PackageManagerService.java revision 002fdbdb950ebbf40331a27de33b80db33e40d30
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_PACKAGE_CHANGED; 51import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 52import static android.content.pm.PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE; 53import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 54import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 55import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 56import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 57import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 58import static android.content.pm.PackageManager.INSTALL_INTERNAL; 59import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK; 62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 65import static android.content.pm.PackageManager.MATCH_ALL; 66import static android.content.pm.PackageManager.MATCH_ANY_USER; 67import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 68import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE; 69import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE; 70import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS; 71import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY; 72import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES; 73import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY; 74import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES; 75import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL; 76import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN; 77import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 78import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 79import static android.content.pm.PackageManager.MOVE_FAILED_LOCKED_USER; 80import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 81import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 82import static android.content.pm.PackageManager.PERMISSION_DENIED; 83import static android.content.pm.PackageManager.PERMISSION_GRANTED; 84import static android.content.pm.PackageParser.isApkFile; 85import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 86import static android.os.storage.StorageManager.FLAG_STORAGE_CE; 87import static android.os.storage.StorageManager.FLAG_STORAGE_DE; 88import static android.system.OsConstants.O_CREAT; 89import static android.system.OsConstants.O_RDWR; 90import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 91import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 92import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 93import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 94import static com.android.internal.util.ArrayUtils.appendInt; 95import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 96import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 97import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 98import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 99import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 100import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason; 101import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter; 102import static com.android.server.pm.PackageManagerServiceUtils.compareSignatures; 103import static com.android.server.pm.PackageManagerServiceUtils.compressedFileExists; 104import static com.android.server.pm.PackageManagerServiceUtils.decompressFile; 105import static com.android.server.pm.PackageManagerServiceUtils.deriveAbiOverride; 106import static com.android.server.pm.PackageManagerServiceUtils.dumpCriticalInfo; 107import static com.android.server.pm.PackageManagerServiceUtils.getCompressedFiles; 108import static com.android.server.pm.PackageManagerServiceUtils.getLastModifiedTime; 109import static com.android.server.pm.PackageManagerServiceUtils.logCriticalInfo; 110import static com.android.server.pm.PackageManagerServiceUtils.verifySignatures; 111import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_FAILURE; 112import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS; 113import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 114import static dalvik.system.DexFile.getNonProfileGuidedCompilerFilter; 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.PackageManager; 167import android.content.pm.PackageManagerInternal; 168import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 169import android.content.pm.PackageManager.PackageInfoFlags; 170import android.content.pm.PackageParser; 171import android.content.pm.PackageParser.ActivityIntentInfo; 172import android.content.pm.PackageParser.Package; 173import android.content.pm.PackageParser.PackageLite; 174import android.content.pm.PackageParser.PackageParserException; 175import android.content.pm.PackageParser.ParseFlags; 176import android.content.pm.PackageStats; 177import android.content.pm.PackageUserState; 178import android.content.pm.ParceledListSlice; 179import android.content.pm.PermissionGroupInfo; 180import android.content.pm.PermissionInfo; 181import android.content.pm.ProviderInfo; 182import android.content.pm.ResolveInfo; 183import android.content.pm.ServiceInfo; 184import android.content.pm.SharedLibraryInfo; 185import android.content.pm.Signature; 186import android.content.pm.UserInfo; 187import android.content.pm.VerifierDeviceIdentity; 188import android.content.pm.VerifierInfo; 189import android.content.pm.VersionedPackage; 190import android.content.res.Resources; 191import android.database.ContentObserver; 192import android.graphics.Bitmap; 193import android.hardware.display.DisplayManager; 194import android.net.Uri; 195import android.os.Binder; 196import android.os.Build; 197import android.os.Bundle; 198import android.os.Debug; 199import android.os.Environment; 200import android.os.Environment.UserEnvironment; 201import android.os.FileUtils; 202import android.os.Handler; 203import android.os.IBinder; 204import android.os.Looper; 205import android.os.Message; 206import android.os.Parcel; 207import android.os.ParcelFileDescriptor; 208import android.os.PatternMatcher; 209import android.os.Process; 210import android.os.RemoteCallbackList; 211import android.os.RemoteException; 212import android.os.ResultReceiver; 213import android.os.SELinux; 214import android.os.ServiceManager; 215import android.os.ShellCallback; 216import android.os.SystemClock; 217import android.os.SystemProperties; 218import android.os.Trace; 219import android.os.UserHandle; 220import android.os.UserManager; 221import android.os.UserManagerInternal; 222import android.os.storage.IStorageManager; 223import android.os.storage.StorageEventListener; 224import android.os.storage.StorageManager; 225import android.os.storage.StorageManagerInternal; 226import android.os.storage.VolumeInfo; 227import android.os.storage.VolumeRecord; 228import android.provider.Settings.Global; 229import android.provider.Settings.Secure; 230import android.security.KeyStore; 231import android.security.SystemKeyStore; 232import android.service.pm.PackageServiceDumpProto; 233import android.system.ErrnoException; 234import android.system.Os; 235import android.text.TextUtils; 236import android.text.format.DateUtils; 237import android.util.ArrayMap; 238import android.util.ArraySet; 239import android.util.Base64; 240import android.util.DisplayMetrics; 241import android.util.EventLog; 242import android.util.ExceptionUtils; 243import android.util.Log; 244import android.util.LogPrinter; 245import android.util.MathUtils; 246import android.util.PackageUtils; 247import android.util.Pair; 248import android.util.PrintStreamPrinter; 249import android.util.Slog; 250import android.util.SparseArray; 251import android.util.SparseBooleanArray; 252import android.util.SparseIntArray; 253import android.util.TimingsTraceLog; 254import android.util.Xml; 255import android.util.jar.StrictJarFile; 256import android.util.proto.ProtoOutputStream; 257import android.view.Display; 258 259import com.android.internal.R; 260import com.android.internal.annotations.GuardedBy; 261import com.android.internal.app.IMediaContainerService; 262import com.android.internal.app.ResolverActivity; 263import com.android.internal.content.NativeLibraryHelper; 264import com.android.internal.content.PackageHelper; 265import com.android.internal.logging.MetricsLogger; 266import com.android.internal.logging.nano.MetricsProto.MetricsEvent; 267import com.android.internal.os.IParcelFileDescriptorFactory; 268import com.android.internal.os.RoSystemProperties; 269import com.android.internal.os.SomeArgs; 270import com.android.internal.os.Zygote; 271import com.android.internal.telephony.CarrierAppUtils; 272import com.android.internal.util.ArrayUtils; 273import com.android.internal.util.ConcurrentUtils; 274import com.android.internal.util.DumpUtils; 275import com.android.internal.util.FastPrintWriter; 276import com.android.internal.util.FastXmlSerializer; 277import com.android.internal.util.IndentingPrintWriter; 278import com.android.internal.util.Preconditions; 279import com.android.internal.util.XmlUtils; 280import com.android.server.AttributeCache; 281import com.android.server.DeviceIdleController; 282import com.android.server.EventLogTags; 283import com.android.server.FgThread; 284import com.android.server.IntentResolver; 285import com.android.server.LocalServices; 286import com.android.server.LockGuard; 287import com.android.server.ServiceThread; 288import com.android.server.SystemConfig; 289import com.android.server.SystemServerInitThreadPool; 290import com.android.server.Watchdog; 291import com.android.server.net.NetworkPolicyManagerInternal; 292import com.android.server.pm.Installer.InstallerException; 293import com.android.server.pm.Settings.DatabaseVersion; 294import com.android.server.pm.Settings.VersionInfo; 295import com.android.server.pm.dex.DexLogger; 296import com.android.server.pm.dex.DexManager; 297import com.android.server.pm.dex.DexoptOptions; 298import com.android.server.pm.dex.PackageDexUsage; 299import com.android.server.pm.permission.BasePermission; 300import com.android.server.pm.permission.DefaultPermissionGrantPolicy; 301import com.android.server.pm.permission.PermissionManagerService; 302import com.android.server.pm.permission.PermissionManagerInternal; 303import com.android.server.pm.permission.DefaultPermissionGrantPolicy.DefaultPermissionGrantedCallback; 304import com.android.server.pm.permission.PermissionManagerInternal.PermissionCallback; 305import com.android.server.pm.permission.PermissionsState; 306import com.android.server.pm.permission.PermissionsState.PermissionState; 307import com.android.server.storage.DeviceStorageMonitorInternal; 308 309import dalvik.system.CloseGuard; 310import dalvik.system.DexFile; 311import dalvik.system.VMRuntime; 312 313import libcore.io.IoUtils; 314import libcore.io.Streams; 315import libcore.util.EmptyArray; 316 317import org.xmlpull.v1.XmlPullParser; 318import org.xmlpull.v1.XmlPullParserException; 319import org.xmlpull.v1.XmlSerializer; 320 321import java.io.BufferedOutputStream; 322import java.io.BufferedReader; 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.FileReader; 330import java.io.FilenameFilter; 331import java.io.IOException; 332import java.io.InputStream; 333import java.io.OutputStream; 334import java.io.PrintWriter; 335import java.lang.annotation.Retention; 336import java.lang.annotation.RetentionPolicy; 337import java.nio.charset.StandardCharsets; 338import java.security.DigestInputStream; 339import java.security.MessageDigest; 340import java.security.NoSuchAlgorithmException; 341import java.security.PublicKey; 342import java.security.SecureRandom; 343import java.security.cert.Certificate; 344import java.security.cert.CertificateEncodingException; 345import java.security.cert.CertificateException; 346import java.text.SimpleDateFormat; 347import java.util.ArrayList; 348import java.util.Arrays; 349import java.util.Collection; 350import java.util.Collections; 351import java.util.Comparator; 352import java.util.Date; 353import java.util.HashMap; 354import java.util.HashSet; 355import java.util.Iterator; 356import java.util.LinkedHashSet; 357import java.util.List; 358import java.util.Map; 359import java.util.Objects; 360import java.util.Set; 361import java.util.concurrent.CountDownLatch; 362import java.util.concurrent.Future; 363import java.util.concurrent.TimeUnit; 364import java.util.concurrent.atomic.AtomicBoolean; 365import java.util.concurrent.atomic.AtomicInteger; 366import java.util.zip.GZIPInputStream; 367 368/** 369 * Keep track of all those APKs everywhere. 370 * <p> 371 * Internally there are two important locks: 372 * <ul> 373 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 374 * and other related state. It is a fine-grained lock that should only be held 375 * momentarily, as it's one of the most contended locks in the system. 376 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 377 * operations typically involve heavy lifting of application data on disk. Since 378 * {@code installd} is single-threaded, and it's operations can often be slow, 379 * this lock should never be acquired while already holding {@link #mPackages}. 380 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 381 * holding {@link #mInstallLock}. 382 * </ul> 383 * Many internal methods rely on the caller to hold the appropriate locks, and 384 * this contract is expressed through method name suffixes: 385 * <ul> 386 * <li>fooLI(): the caller must hold {@link #mInstallLock} 387 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 388 * being modified must be frozen 389 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 390 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 391 * </ul> 392 * <p> 393 * Because this class is very central to the platform's security; please run all 394 * CTS and unit tests whenever making modifications: 395 * 396 * <pre> 397 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 398 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases 399 * </pre> 400 */ 401public class PackageManagerService extends IPackageManager.Stub 402 implements PackageSender { 403 static final String TAG = "PackageManager"; 404 public static final boolean DEBUG_SETTINGS = false; 405 static final boolean DEBUG_PREFERRED = false; 406 static final boolean DEBUG_UPGRADE = false; 407 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 408 private static final boolean DEBUG_BACKUP = false; 409 public static final boolean DEBUG_INSTALL = false; 410 public static final boolean DEBUG_REMOVE = false; 411 private static final boolean DEBUG_BROADCASTS = false; 412 private static final boolean DEBUG_SHOW_INFO = false; 413 private static final boolean DEBUG_PACKAGE_INFO = false; 414 private static final boolean DEBUG_INTENT_MATCHING = false; 415 public static final boolean DEBUG_PACKAGE_SCANNING = false; 416 private static final boolean DEBUG_VERIFY = false; 417 private static final boolean DEBUG_FILTERS = false; 418 public static final boolean DEBUG_PERMISSIONS = false; 419 private static final boolean DEBUG_SHARED_LIBRARIES = false; 420 public static final boolean DEBUG_COMPRESSION = Build.IS_DEBUGGABLE; 421 422 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 423 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 424 // user, but by default initialize to this. 425 public static final boolean DEBUG_DEXOPT = false; 426 427 private static final boolean DEBUG_ABI_SELECTION = false; 428 private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE; 429 private static final boolean DEBUG_TRIAGED_MISSING = false; 430 private static final boolean DEBUG_APP_DATA = false; 431 432 /** REMOVE. According to Svet, this was only used to reset permissions during development. */ 433 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 434 435 private static final boolean HIDE_EPHEMERAL_APIS = false; 436 437 private static final boolean ENABLE_FREE_CACHE_V2 = 438 SystemProperties.getBoolean("fw.free_cache_v2", true); 439 440 private static final int RADIO_UID = Process.PHONE_UID; 441 private static final int LOG_UID = Process.LOG_UID; 442 private static final int NFC_UID = Process.NFC_UID; 443 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 444 private static final int SHELL_UID = Process.SHELL_UID; 445 446 // Suffix used during package installation when copying/moving 447 // package apks to install directory. 448 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 449 450 static final int SCAN_NO_DEX = 1<<0; 451 static final int SCAN_UPDATE_SIGNATURE = 1<<1; 452 static final int SCAN_NEW_INSTALL = 1<<2; 453 static final int SCAN_UPDATE_TIME = 1<<3; 454 static final int SCAN_BOOTING = 1<<4; 455 static final int SCAN_TRUSTED_OVERLAY = 1<<5; 456 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<6; 457 static final int SCAN_REQUIRE_KNOWN = 1<<7; 458 static final int SCAN_MOVE = 1<<8; 459 static final int SCAN_INITIAL = 1<<9; 460 static final int SCAN_CHECK_ONLY = 1<<10; 461 static final int SCAN_DONT_KILL_APP = 1<<11; 462 static final int SCAN_IGNORE_FROZEN = 1<<12; 463 static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<13; 464 static final int SCAN_AS_INSTANT_APP = 1<<14; 465 static final int SCAN_AS_FULL_APP = 1<<15; 466 static final int SCAN_AS_VIRTUAL_PRELOAD = 1<<16; 467 static final int SCAN_AS_SYSTEM = 1<<17; 468 static final int SCAN_AS_PRIVILEGED = 1<<18; 469 static final int SCAN_AS_OEM = 1<<19; 470 static final int SCAN_AS_VENDOR = 1<<20; 471 472 @IntDef(flag = true, prefix = { "SCAN_" }, value = { 473 SCAN_NO_DEX, 474 SCAN_UPDATE_SIGNATURE, 475 SCAN_NEW_INSTALL, 476 SCAN_UPDATE_TIME, 477 SCAN_BOOTING, 478 SCAN_TRUSTED_OVERLAY, 479 SCAN_DELETE_DATA_ON_FAILURES, 480 SCAN_REQUIRE_KNOWN, 481 SCAN_MOVE, 482 SCAN_INITIAL, 483 SCAN_CHECK_ONLY, 484 SCAN_DONT_KILL_APP, 485 SCAN_IGNORE_FROZEN, 486 SCAN_FIRST_BOOT_OR_UPGRADE, 487 SCAN_AS_INSTANT_APP, 488 SCAN_AS_FULL_APP, 489 SCAN_AS_VIRTUAL_PRELOAD, 490 }) 491 @Retention(RetentionPolicy.SOURCE) 492 public @interface ScanFlags {} 493 494 private static final String STATIC_SHARED_LIB_DELIMITER = "_"; 495 /** Extension of the compressed packages */ 496 public final static String COMPRESSED_EXTENSION = ".gz"; 497 /** Suffix of stub packages on the system partition */ 498 public final static String STUB_SUFFIX = "-Stub"; 499 500 private static final int[] EMPTY_INT_ARRAY = new int[0]; 501 502 private static final int TYPE_UNKNOWN = 0; 503 private static final int TYPE_ACTIVITY = 1; 504 private static final int TYPE_RECEIVER = 2; 505 private static final int TYPE_SERVICE = 3; 506 private static final int TYPE_PROVIDER = 4; 507 @IntDef(prefix = { "TYPE_" }, value = { 508 TYPE_UNKNOWN, 509 TYPE_ACTIVITY, 510 TYPE_RECEIVER, 511 TYPE_SERVICE, 512 TYPE_PROVIDER, 513 }) 514 @Retention(RetentionPolicy.SOURCE) 515 public @interface ComponentType {} 516 517 /** 518 * Timeout (in milliseconds) after which the watchdog should declare that 519 * our handler thread is wedged. The usual default for such things is one 520 * minute but we sometimes do very lengthy I/O operations on this thread, 521 * such as installing multi-gigabyte applications, so ours needs to be longer. 522 */ 523 static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 524 525 /** 526 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 527 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 528 * settings entry if available, otherwise we use the hardcoded default. If it's been 529 * more than this long since the last fstrim, we force one during the boot sequence. 530 * 531 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 532 * one gets run at the next available charging+idle time. This final mandatory 533 * no-fstrim check kicks in only of the other scheduling criteria is never met. 534 */ 535 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 536 537 /** 538 * Whether verification is enabled by default. 539 */ 540 private static final boolean DEFAULT_VERIFY_ENABLE = true; 541 542 /** 543 * The default maximum time to wait for the verification agent to return in 544 * milliseconds. 545 */ 546 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 547 548 /** 549 * The default response for package verification timeout. 550 * 551 * This can be either PackageManager.VERIFICATION_ALLOW or 552 * PackageManager.VERIFICATION_REJECT. 553 */ 554 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 555 556 public static final String PLATFORM_PACKAGE_NAME = "android"; 557 558 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 559 560 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 561 DEFAULT_CONTAINER_PACKAGE, 562 "com.android.defcontainer.DefaultContainerService"); 563 564 private static final String KILL_APP_REASON_GIDS_CHANGED = 565 "permission grant or revoke changed gids"; 566 567 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 568 "permissions revoked"; 569 570 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 571 572 private static final String PACKAGE_SCHEME = "package"; 573 574 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 575 576 private static final String PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB = "pm.dexopt.priv-apps-oob"; 577 578 /** Canonical intent used to identify what counts as a "web browser" app */ 579 private static final Intent sBrowserIntent; 580 static { 581 sBrowserIntent = new Intent(); 582 sBrowserIntent.setAction(Intent.ACTION_VIEW); 583 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 584 sBrowserIntent.setData(Uri.parse("http:")); 585 } 586 587 /** 588 * The set of all protected actions [i.e. those actions for which a high priority 589 * intent filter is disallowed]. 590 */ 591 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 592 static { 593 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 594 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 595 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 596 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 597 } 598 599 // Compilation reasons. 600 public static final int REASON_FIRST_BOOT = 0; 601 public static final int REASON_BOOT = 1; 602 public static final int REASON_INSTALL = 2; 603 public static final int REASON_BACKGROUND_DEXOPT = 3; 604 public static final int REASON_AB_OTA = 4; 605 public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5; 606 public static final int REASON_SHARED = 6; 607 608 public static final int REASON_LAST = REASON_SHARED; 609 610 /** 611 * Version number for the package parser cache. Increment this whenever the format or 612 * extent of cached data changes. See {@code PackageParser#setCacheDir}. 613 */ 614 private static final String PACKAGE_PARSER_CACHE_VERSION = "1"; 615 616 /** 617 * Whether the package parser cache is enabled. 618 */ 619 private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true; 620 621 final ServiceThread mHandlerThread; 622 623 final PackageHandler mHandler; 624 625 private final ProcessLoggingHandler mProcessLoggingHandler; 626 627 /** 628 * Messages for {@link #mHandler} that need to wait for system ready before 629 * being dispatched. 630 */ 631 private ArrayList<Message> mPostSystemReadyMessages; 632 633 final int mSdkVersion = Build.VERSION.SDK_INT; 634 635 final Context mContext; 636 final boolean mFactoryTest; 637 final boolean mOnlyCore; 638 final DisplayMetrics mMetrics; 639 final int mDefParseFlags; 640 final String[] mSeparateProcesses; 641 final boolean mIsUpgrade; 642 final boolean mIsPreNUpgrade; 643 final boolean mIsPreNMR1Upgrade; 644 645 // Have we told the Activity Manager to whitelist the default container service by uid yet? 646 @GuardedBy("mPackages") 647 boolean mDefaultContainerWhitelisted = false; 648 649 @GuardedBy("mPackages") 650 private boolean mDexOptDialogShown; 651 652 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 653 // LOCK HELD. Can be called with mInstallLock held. 654 @GuardedBy("mInstallLock") 655 final Installer mInstaller; 656 657 /** Directory where installed third-party apps stored */ 658 final File mAppInstallDir; 659 660 /** 661 * Directory to which applications installed internally have their 662 * 32 bit native libraries copied. 663 */ 664 private File mAppLib32InstallDir; 665 666 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 667 // apps. 668 final File mDrmAppPrivateInstallDir; 669 670 // ---------------------------------------------------------------- 671 672 // Lock for state used when installing and doing other long running 673 // operations. Methods that must be called with this lock held have 674 // the suffix "LI". 675 final Object mInstallLock = new Object(); 676 677 // ---------------------------------------------------------------- 678 679 // Keys are String (package name), values are Package. This also serves 680 // as the lock for the global state. Methods that must be called with 681 // this lock held have the prefix "LP". 682 @GuardedBy("mPackages") 683 final ArrayMap<String, PackageParser.Package> mPackages = 684 new ArrayMap<String, PackageParser.Package>(); 685 686 final ArrayMap<String, Set<String>> mKnownCodebase = 687 new ArrayMap<String, Set<String>>(); 688 689 // Keys are isolated uids and values are the uid of the application 690 // that created the isolated proccess. 691 @GuardedBy("mPackages") 692 final SparseIntArray mIsolatedOwners = new SparseIntArray(); 693 694 /** 695 * Tracks new system packages [received in an OTA] that we expect to 696 * find updated user-installed versions. Keys are package name, values 697 * are package location. 698 */ 699 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 700 /** 701 * Tracks high priority intent filters for protected actions. During boot, certain 702 * filter actions are protected and should never be allowed to have a high priority 703 * intent filter for them. However, there is one, and only one exception -- the 704 * setup wizard. It must be able to define a high priority intent filter for these 705 * actions to ensure there are no escapes from the wizard. We need to delay processing 706 * of these during boot as we need to look at all of the system packages in order 707 * to know which component is the setup wizard. 708 */ 709 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 710 /** 711 * Whether or not processing protected filters should be deferred. 712 */ 713 private boolean mDeferProtectedFilters = true; 714 715 /** 716 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 717 */ 718 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 719 /** 720 * Whether or not system app permissions should be promoted from install to runtime. 721 */ 722 boolean mPromoteSystemApps; 723 724 @GuardedBy("mPackages") 725 final Settings mSettings; 726 727 /** 728 * Set of package names that are currently "frozen", which means active 729 * surgery is being done on the code/data for that package. The platform 730 * will refuse to launch frozen packages to avoid race conditions. 731 * 732 * @see PackageFreezer 733 */ 734 @GuardedBy("mPackages") 735 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 736 737 final ProtectedPackages mProtectedPackages; 738 739 @GuardedBy("mLoadedVolumes") 740 final ArraySet<String> mLoadedVolumes = new ArraySet<>(); 741 742 boolean mFirstBoot; 743 744 PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy; 745 746 @GuardedBy("mAvailableFeatures") 747 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 748 749 // If mac_permissions.xml was found for seinfo labeling. 750 boolean mFoundPolicyFile; 751 752 private final InstantAppRegistry mInstantAppRegistry; 753 754 @GuardedBy("mPackages") 755 int mChangedPackagesSequenceNumber; 756 /** 757 * List of changed [installed, removed or updated] packages. 758 * mapping from user id -> sequence number -> package name 759 */ 760 @GuardedBy("mPackages") 761 final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>(); 762 /** 763 * The sequence number of the last change to a package. 764 * mapping from user id -> package name -> sequence number 765 */ 766 @GuardedBy("mPackages") 767 final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>(); 768 769 class PackageParserCallback implements PackageParser.Callback { 770 @Override public final boolean hasFeature(String feature) { 771 return PackageManagerService.this.hasSystemFeature(feature, 0); 772 } 773 774 final List<PackageParser.Package> getStaticOverlayPackagesLocked( 775 Collection<PackageParser.Package> allPackages, String targetPackageName) { 776 List<PackageParser.Package> overlayPackages = null; 777 for (PackageParser.Package p : allPackages) { 778 if (targetPackageName.equals(p.mOverlayTarget) && p.mIsStaticOverlay) { 779 if (overlayPackages == null) { 780 overlayPackages = new ArrayList<PackageParser.Package>(); 781 } 782 overlayPackages.add(p); 783 } 784 } 785 if (overlayPackages != null) { 786 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 787 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 788 return p1.mOverlayPriority - p2.mOverlayPriority; 789 } 790 }; 791 Collections.sort(overlayPackages, cmp); 792 } 793 return overlayPackages; 794 } 795 796 final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages, 797 String targetPackageName, String targetPath) { 798 if ("android".equals(targetPackageName)) { 799 // Static RROs targeting to "android", ie framework-res.apk, are already applied by 800 // native AssetManager. 801 return null; 802 } 803 List<PackageParser.Package> overlayPackages = 804 getStaticOverlayPackagesLocked(allPackages, targetPackageName); 805 if (overlayPackages == null || overlayPackages.isEmpty()) { 806 return null; 807 } 808 List<String> overlayPathList = null; 809 for (PackageParser.Package overlayPackage : overlayPackages) { 810 if (targetPath == null) { 811 if (overlayPathList == null) { 812 overlayPathList = new ArrayList<String>(); 813 } 814 overlayPathList.add(overlayPackage.baseCodePath); 815 continue; 816 } 817 818 try { 819 // Creates idmaps for system to parse correctly the Android manifest of the 820 // target package. 821 // 822 // OverlayManagerService will update each of them with a correct gid from its 823 // target package app id. 824 mInstaller.idmap(targetPath, overlayPackage.baseCodePath, 825 UserHandle.getSharedAppGid( 826 UserHandle.getUserGid(UserHandle.USER_SYSTEM))); 827 if (overlayPathList == null) { 828 overlayPathList = new ArrayList<String>(); 829 } 830 overlayPathList.add(overlayPackage.baseCodePath); 831 } catch (InstallerException e) { 832 Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " + 833 overlayPackage.baseCodePath); 834 } 835 } 836 return overlayPathList == null ? null : overlayPathList.toArray(new String[0]); 837 } 838 839 String[] getStaticOverlayPaths(String targetPackageName, String targetPath) { 840 synchronized (mPackages) { 841 return getStaticOverlayPathsLocked( 842 mPackages.values(), targetPackageName, targetPath); 843 } 844 } 845 846 @Override public final String[] getOverlayApks(String targetPackageName) { 847 return getStaticOverlayPaths(targetPackageName, null); 848 } 849 850 @Override public final String[] getOverlayPaths(String targetPackageName, 851 String targetPath) { 852 return getStaticOverlayPaths(targetPackageName, targetPath); 853 } 854 } 855 856 class ParallelPackageParserCallback extends PackageParserCallback { 857 List<PackageParser.Package> mOverlayPackages = null; 858 859 void findStaticOverlayPackages() { 860 synchronized (mPackages) { 861 for (PackageParser.Package p : mPackages.values()) { 862 if (p.mIsStaticOverlay) { 863 if (mOverlayPackages == null) { 864 mOverlayPackages = new ArrayList<PackageParser.Package>(); 865 } 866 mOverlayPackages.add(p); 867 } 868 } 869 } 870 } 871 872 @Override 873 synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) { 874 // We can trust mOverlayPackages without holding mPackages because package uninstall 875 // can't happen while running parallel parsing. 876 // Moreover holding mPackages on each parsing thread causes dead-lock. 877 return mOverlayPackages == null ? null : 878 getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath); 879 } 880 } 881 882 final PackageParser.Callback mPackageParserCallback = new PackageParserCallback(); 883 final ParallelPackageParserCallback mParallelPackageParserCallback = 884 new ParallelPackageParserCallback(); 885 886 public static final class SharedLibraryEntry { 887 public final @Nullable String path; 888 public final @Nullable String apk; 889 public final @NonNull SharedLibraryInfo info; 890 891 SharedLibraryEntry(String _path, String _apk, String name, int version, int type, 892 String declaringPackageName, int declaringPackageVersionCode) { 893 path = _path; 894 apk = _apk; 895 info = new SharedLibraryInfo(name, version, type, new VersionedPackage( 896 declaringPackageName, declaringPackageVersionCode), null); 897 } 898 } 899 900 // Currently known shared libraries. 901 final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>(); 902 final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage = 903 new ArrayMap<>(); 904 905 // All available activities, for your resolving pleasure. 906 final ActivityIntentResolver mActivities = 907 new ActivityIntentResolver(); 908 909 // All available receivers, for your resolving pleasure. 910 final ActivityIntentResolver mReceivers = 911 new ActivityIntentResolver(); 912 913 // All available services, for your resolving pleasure. 914 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 915 916 // All available providers, for your resolving pleasure. 917 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 918 919 // Mapping from provider base names (first directory in content URI codePath) 920 // to the provider information. 921 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 922 new ArrayMap<String, PackageParser.Provider>(); 923 924 // Mapping from instrumentation class names to info about them. 925 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 926 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 927 928 // Packages whose data we have transfered into another package, thus 929 // should no longer exist. 930 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 931 932 // Broadcast actions that are only available to the system. 933 @GuardedBy("mProtectedBroadcasts") 934 final ArraySet<String> mProtectedBroadcasts = new ArraySet<>(); 935 936 /** List of packages waiting for verification. */ 937 final SparseArray<PackageVerificationState> mPendingVerification 938 = new SparseArray<PackageVerificationState>(); 939 940 final PackageInstallerService mInstallerService; 941 942 private final PackageDexOptimizer mPackageDexOptimizer; 943 // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package 944 // is used by other apps). 945 private final DexManager mDexManager; 946 947 private AtomicInteger mNextMoveId = new AtomicInteger(); 948 private final MoveCallbacks mMoveCallbacks; 949 950 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 951 952 // Cache of users who need badging. 953 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 954 955 /** Token for keys in mPendingVerification. */ 956 private int mPendingVerificationToken = 0; 957 958 volatile boolean mSystemReady; 959 volatile boolean mSafeMode; 960 volatile boolean mHasSystemUidErrors; 961 private volatile boolean mEphemeralAppsDisabled; 962 963 ApplicationInfo mAndroidApplication; 964 final ActivityInfo mResolveActivity = new ActivityInfo(); 965 final ResolveInfo mResolveInfo = new ResolveInfo(); 966 ComponentName mResolveComponentName; 967 PackageParser.Package mPlatformPackage; 968 ComponentName mCustomResolverComponentName; 969 970 boolean mResolverReplaced = false; 971 972 private final @Nullable ComponentName mIntentFilterVerifierComponent; 973 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 974 975 private int mIntentFilterVerificationToken = 0; 976 977 /** The service connection to the ephemeral resolver */ 978 final EphemeralResolverConnection mInstantAppResolverConnection; 979 /** Component used to show resolver settings for Instant Apps */ 980 final ComponentName mInstantAppResolverSettingsComponent; 981 982 /** Activity used to install instant applications */ 983 ActivityInfo mInstantAppInstallerActivity; 984 final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo(); 985 986 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 987 = new SparseArray<IntentFilterVerificationState>(); 988 989 // TODO remove this and go through mPermissonManager directly 990 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy; 991 private final PermissionManagerInternal mPermissionManager; 992 993 // List of packages names to keep cached, even if they are uninstalled for all users 994 private List<String> mKeepUninstalledPackages; 995 996 private UserManagerInternal mUserManagerInternal; 997 998 private DeviceIdleController.LocalService mDeviceIdleController; 999 1000 private File mCacheDir; 1001 1002 private Future<?> mPrepareAppDataFuture; 1003 1004 private static class IFVerificationParams { 1005 PackageParser.Package pkg; 1006 boolean replacing; 1007 int userId; 1008 int verifierUid; 1009 1010 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 1011 int _userId, int _verifierUid) { 1012 pkg = _pkg; 1013 replacing = _replacing; 1014 userId = _userId; 1015 replacing = _replacing; 1016 verifierUid = _verifierUid; 1017 } 1018 } 1019 1020 private interface IntentFilterVerifier<T extends IntentFilter> { 1021 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 1022 T filter, String packageName); 1023 void startVerifications(int userId); 1024 void receiveVerificationResponse(int verificationId); 1025 } 1026 1027 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 1028 private Context mContext; 1029 private ComponentName mIntentFilterVerifierComponent; 1030 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 1031 1032 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 1033 mContext = context; 1034 mIntentFilterVerifierComponent = verifierComponent; 1035 } 1036 1037 private String getDefaultScheme() { 1038 return IntentFilter.SCHEME_HTTPS; 1039 } 1040 1041 @Override 1042 public void startVerifications(int userId) { 1043 // Launch verifications requests 1044 int count = mCurrentIntentFilterVerifications.size(); 1045 for (int n=0; n<count; n++) { 1046 int verificationId = mCurrentIntentFilterVerifications.get(n); 1047 final IntentFilterVerificationState ivs = 1048 mIntentFilterVerificationStates.get(verificationId); 1049 1050 String packageName = ivs.getPackageName(); 1051 1052 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 1053 final int filterCount = filters.size(); 1054 ArraySet<String> domainsSet = new ArraySet<>(); 1055 for (int m=0; m<filterCount; m++) { 1056 PackageParser.ActivityIntentInfo filter = filters.get(m); 1057 domainsSet.addAll(filter.getHostsList()); 1058 } 1059 synchronized (mPackages) { 1060 if (mSettings.createIntentFilterVerificationIfNeededLPw( 1061 packageName, domainsSet) != null) { 1062 scheduleWriteSettingsLocked(); 1063 } 1064 } 1065 sendVerificationRequest(verificationId, ivs); 1066 } 1067 mCurrentIntentFilterVerifications.clear(); 1068 } 1069 1070 private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) { 1071 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 1072 verificationIntent.putExtra( 1073 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 1074 verificationId); 1075 verificationIntent.putExtra( 1076 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 1077 getDefaultScheme()); 1078 verificationIntent.putExtra( 1079 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 1080 ivs.getHostsString()); 1081 verificationIntent.putExtra( 1082 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 1083 ivs.getPackageName()); 1084 verificationIntent.setComponent(mIntentFilterVerifierComponent); 1085 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 1086 1087 DeviceIdleController.LocalService idleController = getDeviceIdleController(); 1088 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 1089 mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(), 1090 UserHandle.USER_SYSTEM, true, "intent filter verifier"); 1091 1092 mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM); 1093 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1094 "Sending IntentFilter verification broadcast"); 1095 } 1096 1097 public void receiveVerificationResponse(int verificationId) { 1098 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 1099 1100 final boolean verified = ivs.isVerified(); 1101 1102 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 1103 final int count = filters.size(); 1104 if (DEBUG_DOMAIN_VERIFICATION) { 1105 Slog.i(TAG, "Received verification response " + verificationId 1106 + " for " + count + " filters, verified=" + verified); 1107 } 1108 for (int n=0; n<count; n++) { 1109 PackageParser.ActivityIntentInfo filter = filters.get(n); 1110 filter.setVerified(verified); 1111 1112 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 1113 + " verified with result:" + verified + " and hosts:" 1114 + ivs.getHostsString()); 1115 } 1116 1117 mIntentFilterVerificationStates.remove(verificationId); 1118 1119 final String packageName = ivs.getPackageName(); 1120 IntentFilterVerificationInfo ivi = null; 1121 1122 synchronized (mPackages) { 1123 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 1124 } 1125 if (ivi == null) { 1126 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 1127 + verificationId + " packageName:" + packageName); 1128 return; 1129 } 1130 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1131 "Updating IntentFilterVerificationInfo for package " + packageName 1132 +" verificationId:" + verificationId); 1133 1134 synchronized (mPackages) { 1135 if (verified) { 1136 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 1137 } else { 1138 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 1139 } 1140 scheduleWriteSettingsLocked(); 1141 1142 final int userId = ivs.getUserId(); 1143 if (userId != UserHandle.USER_ALL) { 1144 final int userStatus = 1145 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 1146 1147 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 1148 boolean needUpdate = false; 1149 1150 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 1151 // already been set by the User thru the Disambiguation dialog 1152 switch (userStatus) { 1153 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 1154 if (verified) { 1155 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 1156 } else { 1157 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 1158 } 1159 needUpdate = true; 1160 break; 1161 1162 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 1163 if (verified) { 1164 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 1165 needUpdate = true; 1166 } 1167 break; 1168 1169 default: 1170 // Nothing to do 1171 } 1172 1173 if (needUpdate) { 1174 mSettings.updateIntentFilterVerificationStatusLPw( 1175 packageName, updatedStatus, userId); 1176 scheduleWritePackageRestrictionsLocked(userId); 1177 } 1178 } 1179 } 1180 } 1181 1182 @Override 1183 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 1184 ActivityIntentInfo filter, String packageName) { 1185 if (!hasValidDomains(filter)) { 1186 return false; 1187 } 1188 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 1189 if (ivs == null) { 1190 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 1191 packageName); 1192 } 1193 if (DEBUG_DOMAIN_VERIFICATION) { 1194 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 1195 } 1196 ivs.addFilter(filter); 1197 return true; 1198 } 1199 1200 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 1201 int userId, int verificationId, String packageName) { 1202 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 1203 verifierUid, userId, packageName); 1204 ivs.setPendingState(); 1205 synchronized (mPackages) { 1206 mIntentFilterVerificationStates.append(verificationId, ivs); 1207 mCurrentIntentFilterVerifications.add(verificationId); 1208 } 1209 return ivs; 1210 } 1211 } 1212 1213 private static boolean hasValidDomains(ActivityIntentInfo filter) { 1214 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 1215 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 1216 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 1217 } 1218 1219 // Set of pending broadcasts for aggregating enable/disable of components. 1220 static class PendingPackageBroadcasts { 1221 // for each user id, a map of <package name -> components within that package> 1222 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 1223 1224 public PendingPackageBroadcasts() { 1225 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 1226 } 1227 1228 public ArrayList<String> get(int userId, String packageName) { 1229 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1230 return packages.get(packageName); 1231 } 1232 1233 public void put(int userId, String packageName, ArrayList<String> components) { 1234 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1235 packages.put(packageName, components); 1236 } 1237 1238 public void remove(int userId, String packageName) { 1239 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 1240 if (packages != null) { 1241 packages.remove(packageName); 1242 } 1243 } 1244 1245 public void remove(int userId) { 1246 mUidMap.remove(userId); 1247 } 1248 1249 public int userIdCount() { 1250 return mUidMap.size(); 1251 } 1252 1253 public int userIdAt(int n) { 1254 return mUidMap.keyAt(n); 1255 } 1256 1257 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 1258 return mUidMap.get(userId); 1259 } 1260 1261 public int size() { 1262 // total number of pending broadcast entries across all userIds 1263 int num = 0; 1264 for (int i = 0; i< mUidMap.size(); i++) { 1265 num += mUidMap.valueAt(i).size(); 1266 } 1267 return num; 1268 } 1269 1270 public void clear() { 1271 mUidMap.clear(); 1272 } 1273 1274 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1275 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1276 if (map == null) { 1277 map = new ArrayMap<String, ArrayList<String>>(); 1278 mUidMap.put(userId, map); 1279 } 1280 return map; 1281 } 1282 } 1283 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1284 1285 // Service Connection to remote media container service to copy 1286 // package uri's from external media onto secure containers 1287 // or internal storage. 1288 private IMediaContainerService mContainerService = null; 1289 1290 static final int SEND_PENDING_BROADCAST = 1; 1291 static final int MCS_BOUND = 3; 1292 static final int END_COPY = 4; 1293 static final int INIT_COPY = 5; 1294 static final int MCS_UNBIND = 6; 1295 static final int START_CLEANING_PACKAGE = 7; 1296 static final int FIND_INSTALL_LOC = 8; 1297 static final int POST_INSTALL = 9; 1298 static final int MCS_RECONNECT = 10; 1299 static final int MCS_GIVE_UP = 11; 1300 static final int WRITE_SETTINGS = 13; 1301 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1302 static final int PACKAGE_VERIFIED = 15; 1303 static final int CHECK_PENDING_VERIFICATION = 16; 1304 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1305 static final int INTENT_FILTER_VERIFIED = 18; 1306 static final int WRITE_PACKAGE_LIST = 19; 1307 static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20; 1308 1309 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1310 1311 // Delay time in millisecs 1312 static final int BROADCAST_DELAY = 10 * 1000; 1313 1314 private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD = 1315 2 * 60 * 60 * 1000L; /* two hours */ 1316 1317 static UserManagerService sUserManager; 1318 1319 // Stores a list of users whose package restrictions file needs to be updated 1320 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1321 1322 final private DefaultContainerConnection mDefContainerConn = 1323 new DefaultContainerConnection(); 1324 class DefaultContainerConnection implements ServiceConnection { 1325 public void onServiceConnected(ComponentName name, IBinder service) { 1326 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1327 final IMediaContainerService imcs = IMediaContainerService.Stub 1328 .asInterface(Binder.allowBlocking(service)); 1329 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1330 } 1331 1332 public void onServiceDisconnected(ComponentName name) { 1333 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1334 } 1335 } 1336 1337 // Recordkeeping of restore-after-install operations that are currently in flight 1338 // between the Package Manager and the Backup Manager 1339 static class PostInstallData { 1340 public InstallArgs args; 1341 public PackageInstalledInfo res; 1342 1343 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1344 args = _a; 1345 res = _r; 1346 } 1347 } 1348 1349 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1350 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1351 1352 // XML tags for backup/restore of various bits of state 1353 private static final String TAG_PREFERRED_BACKUP = "pa"; 1354 private static final String TAG_DEFAULT_APPS = "da"; 1355 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1356 1357 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1358 private static final String TAG_ALL_GRANTS = "rt-grants"; 1359 private static final String TAG_GRANT = "grant"; 1360 private static final String ATTR_PACKAGE_NAME = "pkg"; 1361 1362 private static final String TAG_PERMISSION = "perm"; 1363 private static final String ATTR_PERMISSION_NAME = "name"; 1364 private static final String ATTR_IS_GRANTED = "g"; 1365 private static final String ATTR_USER_SET = "set"; 1366 private static final String ATTR_USER_FIXED = "fixed"; 1367 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1368 1369 // System/policy permission grants are not backed up 1370 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1371 FLAG_PERMISSION_POLICY_FIXED 1372 | FLAG_PERMISSION_SYSTEM_FIXED 1373 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1374 1375 // And we back up these user-adjusted states 1376 private static final int USER_RUNTIME_GRANT_MASK = 1377 FLAG_PERMISSION_USER_SET 1378 | FLAG_PERMISSION_USER_FIXED 1379 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1380 1381 final @Nullable String mRequiredVerifierPackage; 1382 final @NonNull String mRequiredInstallerPackage; 1383 final @NonNull String mRequiredUninstallerPackage; 1384 final @Nullable String mSetupWizardPackage; 1385 final @Nullable String mStorageManagerPackage; 1386 final @NonNull String mServicesSystemSharedLibraryPackageName; 1387 final @NonNull String mSharedSystemSharedLibraryPackageName; 1388 1389 private final PackageUsage mPackageUsage = new PackageUsage(); 1390 private final CompilerStats mCompilerStats = new CompilerStats(); 1391 1392 class PackageHandler extends Handler { 1393 private boolean mBound = false; 1394 final ArrayList<HandlerParams> mPendingInstalls = 1395 new ArrayList<HandlerParams>(); 1396 1397 private boolean connectToService() { 1398 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1399 " DefaultContainerService"); 1400 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1401 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1402 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1403 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1404 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1405 mBound = true; 1406 return true; 1407 } 1408 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1409 return false; 1410 } 1411 1412 private void disconnectService() { 1413 mContainerService = null; 1414 mBound = false; 1415 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1416 mContext.unbindService(mDefContainerConn); 1417 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1418 } 1419 1420 PackageHandler(Looper looper) { 1421 super(looper); 1422 } 1423 1424 public void handleMessage(Message msg) { 1425 try { 1426 doHandleMessage(msg); 1427 } finally { 1428 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1429 } 1430 } 1431 1432 void doHandleMessage(Message msg) { 1433 switch (msg.what) { 1434 case INIT_COPY: { 1435 HandlerParams params = (HandlerParams) msg.obj; 1436 int idx = mPendingInstalls.size(); 1437 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1438 // If a bind was already initiated we dont really 1439 // need to do anything. The pending install 1440 // will be processed later on. 1441 if (!mBound) { 1442 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1443 System.identityHashCode(mHandler)); 1444 // If this is the only one pending we might 1445 // have to bind to the service again. 1446 if (!connectToService()) { 1447 Slog.e(TAG, "Failed to bind to media container service"); 1448 params.serviceError(); 1449 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1450 System.identityHashCode(mHandler)); 1451 if (params.traceMethod != null) { 1452 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1453 params.traceCookie); 1454 } 1455 return; 1456 } else { 1457 // Once we bind to the service, the first 1458 // pending request will be processed. 1459 mPendingInstalls.add(idx, params); 1460 } 1461 } else { 1462 mPendingInstalls.add(idx, params); 1463 // Already bound to the service. Just make 1464 // sure we trigger off processing the first request. 1465 if (idx == 0) { 1466 mHandler.sendEmptyMessage(MCS_BOUND); 1467 } 1468 } 1469 break; 1470 } 1471 case MCS_BOUND: { 1472 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1473 if (msg.obj != null) { 1474 mContainerService = (IMediaContainerService) msg.obj; 1475 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1476 System.identityHashCode(mHandler)); 1477 } 1478 if (mContainerService == null) { 1479 if (!mBound) { 1480 // Something seriously wrong since we are not bound and we are not 1481 // waiting for connection. Bail out. 1482 Slog.e(TAG, "Cannot bind to media container service"); 1483 for (HandlerParams params : mPendingInstalls) { 1484 // Indicate service bind error 1485 params.serviceError(); 1486 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1487 System.identityHashCode(params)); 1488 if (params.traceMethod != null) { 1489 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1490 params.traceMethod, params.traceCookie); 1491 } 1492 return; 1493 } 1494 mPendingInstalls.clear(); 1495 } else { 1496 Slog.w(TAG, "Waiting to connect to media container service"); 1497 } 1498 } else if (mPendingInstalls.size() > 0) { 1499 HandlerParams params = mPendingInstalls.get(0); 1500 if (params != null) { 1501 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1502 System.identityHashCode(params)); 1503 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1504 if (params.startCopy()) { 1505 // We are done... look for more work or to 1506 // go idle. 1507 if (DEBUG_SD_INSTALL) Log.i(TAG, 1508 "Checking for more work or unbind..."); 1509 // Delete pending install 1510 if (mPendingInstalls.size() > 0) { 1511 mPendingInstalls.remove(0); 1512 } 1513 if (mPendingInstalls.size() == 0) { 1514 if (mBound) { 1515 if (DEBUG_SD_INSTALL) Log.i(TAG, 1516 "Posting delayed MCS_UNBIND"); 1517 removeMessages(MCS_UNBIND); 1518 Message ubmsg = obtainMessage(MCS_UNBIND); 1519 // Unbind after a little delay, to avoid 1520 // continual thrashing. 1521 sendMessageDelayed(ubmsg, 10000); 1522 } 1523 } else { 1524 // There are more pending requests in queue. 1525 // Just post MCS_BOUND message to trigger processing 1526 // of next pending install. 1527 if (DEBUG_SD_INSTALL) Log.i(TAG, 1528 "Posting MCS_BOUND for next work"); 1529 mHandler.sendEmptyMessage(MCS_BOUND); 1530 } 1531 } 1532 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1533 } 1534 } else { 1535 // Should never happen ideally. 1536 Slog.w(TAG, "Empty queue"); 1537 } 1538 break; 1539 } 1540 case MCS_RECONNECT: { 1541 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1542 if (mPendingInstalls.size() > 0) { 1543 if (mBound) { 1544 disconnectService(); 1545 } 1546 if (!connectToService()) { 1547 Slog.e(TAG, "Failed to bind to media container service"); 1548 for (HandlerParams params : mPendingInstalls) { 1549 // Indicate service bind error 1550 params.serviceError(); 1551 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1552 System.identityHashCode(params)); 1553 } 1554 mPendingInstalls.clear(); 1555 } 1556 } 1557 break; 1558 } 1559 case MCS_UNBIND: { 1560 // If there is no actual work left, then time to unbind. 1561 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1562 1563 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1564 if (mBound) { 1565 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1566 1567 disconnectService(); 1568 } 1569 } else if (mPendingInstalls.size() > 0) { 1570 // There are more pending requests in queue. 1571 // Just post MCS_BOUND message to trigger processing 1572 // of next pending install. 1573 mHandler.sendEmptyMessage(MCS_BOUND); 1574 } 1575 1576 break; 1577 } 1578 case MCS_GIVE_UP: { 1579 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1580 HandlerParams params = mPendingInstalls.remove(0); 1581 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1582 System.identityHashCode(params)); 1583 break; 1584 } 1585 case SEND_PENDING_BROADCAST: { 1586 String packages[]; 1587 ArrayList<String> components[]; 1588 int size = 0; 1589 int uids[]; 1590 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1591 synchronized (mPackages) { 1592 if (mPendingBroadcasts == null) { 1593 return; 1594 } 1595 size = mPendingBroadcasts.size(); 1596 if (size <= 0) { 1597 // Nothing to be done. Just return 1598 return; 1599 } 1600 packages = new String[size]; 1601 components = new ArrayList[size]; 1602 uids = new int[size]; 1603 int i = 0; // filling out the above arrays 1604 1605 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1606 int packageUserId = mPendingBroadcasts.userIdAt(n); 1607 Iterator<Map.Entry<String, ArrayList<String>>> it 1608 = mPendingBroadcasts.packagesForUserId(packageUserId) 1609 .entrySet().iterator(); 1610 while (it.hasNext() && i < size) { 1611 Map.Entry<String, ArrayList<String>> ent = it.next(); 1612 packages[i] = ent.getKey(); 1613 components[i] = ent.getValue(); 1614 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1615 uids[i] = (ps != null) 1616 ? UserHandle.getUid(packageUserId, ps.appId) 1617 : -1; 1618 i++; 1619 } 1620 } 1621 size = i; 1622 mPendingBroadcasts.clear(); 1623 } 1624 // Send broadcasts 1625 for (int i = 0; i < size; i++) { 1626 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1627 } 1628 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1629 break; 1630 } 1631 case START_CLEANING_PACKAGE: { 1632 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1633 final String packageName = (String)msg.obj; 1634 final int userId = msg.arg1; 1635 final boolean andCode = msg.arg2 != 0; 1636 synchronized (mPackages) { 1637 if (userId == UserHandle.USER_ALL) { 1638 int[] users = sUserManager.getUserIds(); 1639 for (int user : users) { 1640 mSettings.addPackageToCleanLPw( 1641 new PackageCleanItem(user, packageName, andCode)); 1642 } 1643 } else { 1644 mSettings.addPackageToCleanLPw( 1645 new PackageCleanItem(userId, packageName, andCode)); 1646 } 1647 } 1648 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1649 startCleaningPackages(); 1650 } break; 1651 case POST_INSTALL: { 1652 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1653 1654 PostInstallData data = mRunningInstalls.get(msg.arg1); 1655 final boolean didRestore = (msg.arg2 != 0); 1656 mRunningInstalls.delete(msg.arg1); 1657 1658 if (data != null) { 1659 InstallArgs args = data.args; 1660 PackageInstalledInfo parentRes = data.res; 1661 1662 final boolean grantPermissions = (args.installFlags 1663 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1664 final boolean killApp = (args.installFlags 1665 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1666 final boolean virtualPreload = ((args.installFlags 1667 & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0); 1668 final String[] grantedPermissions = args.installGrantPermissions; 1669 1670 // Handle the parent package 1671 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1672 virtualPreload, grantedPermissions, didRestore, 1673 args.installerPackageName, args.observer); 1674 1675 // Handle the child packages 1676 final int childCount = (parentRes.addedChildPackages != null) 1677 ? parentRes.addedChildPackages.size() : 0; 1678 for (int i = 0; i < childCount; i++) { 1679 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1680 handlePackagePostInstall(childRes, grantPermissions, killApp, 1681 virtualPreload, grantedPermissions, false /*didRestore*/, 1682 args.installerPackageName, args.observer); 1683 } 1684 1685 // Log tracing if needed 1686 if (args.traceMethod != null) { 1687 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1688 args.traceCookie); 1689 } 1690 } else { 1691 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1692 } 1693 1694 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1695 } break; 1696 case WRITE_SETTINGS: { 1697 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1698 synchronized (mPackages) { 1699 removeMessages(WRITE_SETTINGS); 1700 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1701 mSettings.writeLPr(); 1702 mDirtyUsers.clear(); 1703 } 1704 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1705 } break; 1706 case WRITE_PACKAGE_RESTRICTIONS: { 1707 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1708 synchronized (mPackages) { 1709 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1710 for (int userId : mDirtyUsers) { 1711 mSettings.writePackageRestrictionsLPr(userId); 1712 } 1713 mDirtyUsers.clear(); 1714 } 1715 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1716 } break; 1717 case WRITE_PACKAGE_LIST: { 1718 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1719 synchronized (mPackages) { 1720 removeMessages(WRITE_PACKAGE_LIST); 1721 mSettings.writePackageListLPr(msg.arg1); 1722 } 1723 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1724 } break; 1725 case CHECK_PENDING_VERIFICATION: { 1726 final int verificationId = msg.arg1; 1727 final PackageVerificationState state = mPendingVerification.get(verificationId); 1728 1729 if ((state != null) && !state.timeoutExtended()) { 1730 final InstallArgs args = state.getInstallArgs(); 1731 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1732 1733 Slog.i(TAG, "Verification timed out for " + originUri); 1734 mPendingVerification.remove(verificationId); 1735 1736 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1737 1738 final UserHandle user = args.getUser(); 1739 if (getDefaultVerificationResponse(user) 1740 == PackageManager.VERIFICATION_ALLOW) { 1741 Slog.i(TAG, "Continuing with installation of " + originUri); 1742 state.setVerifierResponse(Binder.getCallingUid(), 1743 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1744 broadcastPackageVerified(verificationId, originUri, 1745 PackageManager.VERIFICATION_ALLOW, user); 1746 try { 1747 ret = args.copyApk(mContainerService, true); 1748 } catch (RemoteException e) { 1749 Slog.e(TAG, "Could not contact the ContainerService"); 1750 } 1751 } else { 1752 broadcastPackageVerified(verificationId, originUri, 1753 PackageManager.VERIFICATION_REJECT, user); 1754 } 1755 1756 Trace.asyncTraceEnd( 1757 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1758 1759 processPendingInstall(args, ret); 1760 mHandler.sendEmptyMessage(MCS_UNBIND); 1761 } 1762 break; 1763 } 1764 case PACKAGE_VERIFIED: { 1765 final int verificationId = msg.arg1; 1766 1767 final PackageVerificationState state = mPendingVerification.get(verificationId); 1768 if (state == null) { 1769 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1770 break; 1771 } 1772 1773 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1774 1775 state.setVerifierResponse(response.callerUid, response.code); 1776 1777 if (state.isVerificationComplete()) { 1778 mPendingVerification.remove(verificationId); 1779 1780 final InstallArgs args = state.getInstallArgs(); 1781 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1782 1783 int ret; 1784 if (state.isInstallAllowed()) { 1785 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1786 broadcastPackageVerified(verificationId, originUri, 1787 response.code, state.getInstallArgs().getUser()); 1788 try { 1789 ret = args.copyApk(mContainerService, true); 1790 } catch (RemoteException e) { 1791 Slog.e(TAG, "Could not contact the ContainerService"); 1792 } 1793 } else { 1794 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1795 } 1796 1797 Trace.asyncTraceEnd( 1798 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1799 1800 processPendingInstall(args, ret); 1801 mHandler.sendEmptyMessage(MCS_UNBIND); 1802 } 1803 1804 break; 1805 } 1806 case START_INTENT_FILTER_VERIFICATIONS: { 1807 IFVerificationParams params = (IFVerificationParams) msg.obj; 1808 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1809 params.replacing, params.pkg); 1810 break; 1811 } 1812 case INTENT_FILTER_VERIFIED: { 1813 final int verificationId = msg.arg1; 1814 1815 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1816 verificationId); 1817 if (state == null) { 1818 Slog.w(TAG, "Invalid IntentFilter verification token " 1819 + verificationId + " received"); 1820 break; 1821 } 1822 1823 final int userId = state.getUserId(); 1824 1825 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1826 "Processing IntentFilter verification with token:" 1827 + verificationId + " and userId:" + userId); 1828 1829 final IntentFilterVerificationResponse response = 1830 (IntentFilterVerificationResponse) msg.obj; 1831 1832 state.setVerifierResponse(response.callerUid, response.code); 1833 1834 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1835 "IntentFilter verification with token:" + verificationId 1836 + " and userId:" + userId 1837 + " is settings verifier response with response code:" 1838 + response.code); 1839 1840 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1841 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1842 + response.getFailedDomainsString()); 1843 } 1844 1845 if (state.isVerificationComplete()) { 1846 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1847 } else { 1848 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1849 "IntentFilter verification with token:" + verificationId 1850 + " was not said to be complete"); 1851 } 1852 1853 break; 1854 } 1855 case INSTANT_APP_RESOLUTION_PHASE_TWO: { 1856 InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext, 1857 mInstantAppResolverConnection, 1858 (InstantAppRequest) msg.obj, 1859 mInstantAppInstallerActivity, 1860 mHandler); 1861 } 1862 } 1863 } 1864 } 1865 1866 private PermissionCallback mPermissionCallback = new PermissionCallback() { 1867 @Override 1868 public void onGidsChanged(int appId, int userId) { 1869 mHandler.post(new Runnable() { 1870 @Override 1871 public void run() { 1872 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 1873 } 1874 }); 1875 } 1876 @Override 1877 public void onPermissionGranted(int uid, int userId) { 1878 mOnPermissionChangeListeners.onPermissionsChanged(uid); 1879 1880 // Not critical; if this is lost, the application has to request again. 1881 synchronized (mPackages) { 1882 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 1883 } 1884 } 1885 @Override 1886 public void onInstallPermissionGranted() { 1887 synchronized (mPackages) { 1888 scheduleWriteSettingsLocked(); 1889 } 1890 } 1891 @Override 1892 public void onPermissionRevoked(int uid, int userId) { 1893 mOnPermissionChangeListeners.onPermissionsChanged(uid); 1894 1895 synchronized (mPackages) { 1896 // Critical; after this call the application should never have the permission 1897 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 1898 } 1899 1900 final int appId = UserHandle.getAppId(uid); 1901 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 1902 } 1903 @Override 1904 public void onInstallPermissionRevoked() { 1905 synchronized (mPackages) { 1906 scheduleWriteSettingsLocked(); 1907 } 1908 } 1909 @Override 1910 public void onPermissionUpdated(int[] updatedUserIds, boolean sync) { 1911 synchronized (mPackages) { 1912 for (int userId : updatedUserIds) { 1913 mSettings.writeRuntimePermissionsForUserLPr(userId, sync); 1914 } 1915 } 1916 } 1917 @Override 1918 public void onInstallPermissionUpdated() { 1919 synchronized (mPackages) { 1920 scheduleWriteSettingsLocked(); 1921 } 1922 } 1923 @Override 1924 public void onPermissionRemoved() { 1925 synchronized (mPackages) { 1926 mSettings.writeLPr(); 1927 } 1928 } 1929 }; 1930 1931 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1932 boolean killApp, boolean virtualPreload, String[] grantedPermissions, 1933 boolean launchedForRestore, String installerPackage, 1934 IPackageInstallObserver2 installObserver) { 1935 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1936 // Send the removed broadcasts 1937 if (res.removedInfo != null) { 1938 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1939 } 1940 1941 // Now that we successfully installed the package, grant runtime 1942 // permissions if requested before broadcasting the install. Also 1943 // for legacy apps in permission review mode we clear the permission 1944 // review flag which is used to emulate runtime permissions for 1945 // legacy apps. 1946 if (grantPermissions) { 1947 final int callingUid = Binder.getCallingUid(); 1948 mPermissionManager.grantRequestedRuntimePermissions( 1949 res.pkg, res.newUsers, grantedPermissions, callingUid, 1950 mPermissionCallback); 1951 } 1952 1953 final boolean update = res.removedInfo != null 1954 && res.removedInfo.removedPackage != null; 1955 final String installerPackageName = 1956 res.installerPackageName != null 1957 ? res.installerPackageName 1958 : res.removedInfo != null 1959 ? res.removedInfo.installerPackageName 1960 : null; 1961 1962 // If this is the first time we have child packages for a disabled privileged 1963 // app that had no children, we grant requested runtime permissions to the new 1964 // children if the parent on the system image had them already granted. 1965 if (res.pkg.parentPackage != null) { 1966 final int callingUid = Binder.getCallingUid(); 1967 mPermissionManager.grantRuntimePermissionsGrantedToDisabledPackage( 1968 res.pkg, callingUid, mPermissionCallback); 1969 } 1970 1971 synchronized (mPackages) { 1972 mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers); 1973 } 1974 1975 final String packageName = res.pkg.applicationInfo.packageName; 1976 1977 // Determine the set of users who are adding this package for 1978 // the first time vs. those who are seeing an update. 1979 int[] firstUsers = EMPTY_INT_ARRAY; 1980 int[] updateUsers = 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 if (ps.getInstantApp(newUser)) { 1985 continue; 1986 } 1987 if (allNewUsers) { 1988 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1989 continue; 1990 } 1991 boolean isNew = true; 1992 for (int origUser : res.origUsers) { 1993 if (origUser == newUser) { 1994 isNew = false; 1995 break; 1996 } 1997 } 1998 if (isNew) { 1999 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 2000 } else { 2001 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 2002 } 2003 } 2004 2005 // Send installed broadcasts if the package is not a static shared lib. 2006 if (res.pkg.staticSharedLibName == null) { 2007 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 2008 2009 // Send added for users that see the package for the first time 2010 // sendPackageAddedForNewUsers also deals with system apps 2011 int appId = UserHandle.getAppId(res.uid); 2012 boolean isSystem = res.pkg.applicationInfo.isSystemApp(); 2013 sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload, 2014 virtualPreload /*startReceiver*/, appId, firstUsers); 2015 2016 // Send added for users that don't see the package for the first time 2017 Bundle extras = new Bundle(1); 2018 extras.putInt(Intent.EXTRA_UID, res.uid); 2019 if (update) { 2020 extras.putBoolean(Intent.EXTRA_REPLACING, true); 2021 } 2022 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 2023 extras, 0 /*flags*/, 2024 null /*targetPackage*/, null /*finishedReceiver*/, updateUsers); 2025 if (installerPackageName != null) { 2026 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 2027 extras, 0 /*flags*/, 2028 installerPackageName, null /*finishedReceiver*/, updateUsers); 2029 } 2030 2031 // Send replaced for users that don't see the package for the first time 2032 if (update) { 2033 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 2034 packageName, extras, 0 /*flags*/, 2035 null /*targetPackage*/, null /*finishedReceiver*/, 2036 updateUsers); 2037 if (installerPackageName != null) { 2038 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 2039 extras, 0 /*flags*/, 2040 installerPackageName, null /*finishedReceiver*/, updateUsers); 2041 } 2042 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 2043 null /*package*/, null /*extras*/, 0 /*flags*/, 2044 packageName /*targetPackage*/, 2045 null /*finishedReceiver*/, updateUsers); 2046 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 2047 // First-install and we did a restore, so we're responsible for the 2048 // first-launch broadcast. 2049 if (DEBUG_BACKUP) { 2050 Slog.i(TAG, "Post-restore of " + packageName 2051 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers)); 2052 } 2053 sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers); 2054 } 2055 2056 // Send broadcast package appeared if forward locked/external for all users 2057 // treat asec-hosted packages like removable media on upgrade 2058 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 2059 if (DEBUG_INSTALL) { 2060 Slog.i(TAG, "upgrading pkg " + res.pkg 2061 + " is ASEC-hosted -> AVAILABLE"); 2062 } 2063 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 2064 ArrayList<String> pkgList = new ArrayList<>(1); 2065 pkgList.add(packageName); 2066 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 2067 } 2068 } 2069 2070 // Work that needs to happen on first install within each user 2071 if (firstUsers != null && firstUsers.length > 0) { 2072 synchronized (mPackages) { 2073 for (int userId : firstUsers) { 2074 // If this app is a browser and it's newly-installed for some 2075 // users, clear any default-browser state in those users. The 2076 // app's nature doesn't depend on the user, so we can just check 2077 // its browser nature in any user and generalize. 2078 if (packageIsBrowser(packageName, userId)) { 2079 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 2080 } 2081 2082 // We may also need to apply pending (restored) runtime 2083 // permission grants within these users. 2084 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 2085 } 2086 } 2087 } 2088 2089 // Log current value of "unknown sources" setting 2090 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 2091 getUnknownSourcesSettings()); 2092 2093 // Remove the replaced package's older resources safely now 2094 // We delete after a gc for applications on sdcard. 2095 if (res.removedInfo != null && res.removedInfo.args != null) { 2096 Runtime.getRuntime().gc(); 2097 synchronized (mInstallLock) { 2098 res.removedInfo.args.doPostDeleteLI(true); 2099 } 2100 } else { 2101 // Force a gc to clear up things. Ask for a background one, it's fine to go on 2102 // and not block here. 2103 VMRuntime.getRuntime().requestConcurrentGC(); 2104 } 2105 2106 // Notify DexManager that the package was installed for new users. 2107 // The updated users should already be indexed and the package code paths 2108 // should not change. 2109 // Don't notify the manager for ephemeral apps as they are not expected to 2110 // survive long enough to benefit of background optimizations. 2111 for (int userId : firstUsers) { 2112 PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId); 2113 // There's a race currently where some install events may interleave with an uninstall. 2114 // This can lead to package info being null (b/36642664). 2115 if (info != null) { 2116 mDexManager.notifyPackageInstalled(info, userId); 2117 } 2118 } 2119 } 2120 2121 // If someone is watching installs - notify them 2122 if (installObserver != null) { 2123 try { 2124 Bundle extras = extrasForInstallResult(res); 2125 installObserver.onPackageInstalled(res.name, res.returnCode, 2126 res.returnMsg, extras); 2127 } catch (RemoteException e) { 2128 Slog.i(TAG, "Observer no longer exists."); 2129 } 2130 } 2131 } 2132 2133 private StorageEventListener mStorageListener = new StorageEventListener() { 2134 @Override 2135 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 2136 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 2137 if (vol.state == VolumeInfo.STATE_MOUNTED) { 2138 final String volumeUuid = vol.getFsUuid(); 2139 2140 // Clean up any users or apps that were removed or recreated 2141 // while this volume was missing 2142 sUserManager.reconcileUsers(volumeUuid); 2143 reconcileApps(volumeUuid); 2144 2145 // Clean up any install sessions that expired or were 2146 // cancelled while this volume was missing 2147 mInstallerService.onPrivateVolumeMounted(volumeUuid); 2148 2149 loadPrivatePackages(vol); 2150 2151 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2152 unloadPrivatePackages(vol); 2153 } 2154 } 2155 } 2156 2157 @Override 2158 public void onVolumeForgotten(String fsUuid) { 2159 if (TextUtils.isEmpty(fsUuid)) { 2160 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 2161 return; 2162 } 2163 2164 // Remove any apps installed on the forgotten volume 2165 synchronized (mPackages) { 2166 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 2167 for (PackageSetting ps : packages) { 2168 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 2169 deletePackageVersioned(new VersionedPackage(ps.name, 2170 PackageManager.VERSION_CODE_HIGHEST), 2171 new LegacyPackageDeleteObserver(null).getBinder(), 2172 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 2173 // Try very hard to release any references to this package 2174 // so we don't risk the system server being killed due to 2175 // open FDs 2176 AttributeCache.instance().removePackage(ps.name); 2177 } 2178 2179 mSettings.onVolumeForgotten(fsUuid); 2180 mSettings.writeLPr(); 2181 } 2182 } 2183 }; 2184 2185 Bundle extrasForInstallResult(PackageInstalledInfo res) { 2186 Bundle extras = null; 2187 switch (res.returnCode) { 2188 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 2189 extras = new Bundle(); 2190 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 2191 res.origPermission); 2192 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 2193 res.origPackage); 2194 break; 2195 } 2196 case PackageManager.INSTALL_SUCCEEDED: { 2197 extras = new Bundle(); 2198 extras.putBoolean(Intent.EXTRA_REPLACING, 2199 res.removedInfo != null && res.removedInfo.removedPackage != null); 2200 break; 2201 } 2202 } 2203 return extras; 2204 } 2205 2206 void scheduleWriteSettingsLocked() { 2207 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2208 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2209 } 2210 } 2211 2212 void scheduleWritePackageListLocked(int userId) { 2213 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) { 2214 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST); 2215 msg.arg1 = userId; 2216 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY); 2217 } 2218 } 2219 2220 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2221 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2222 scheduleWritePackageRestrictionsLocked(userId); 2223 } 2224 2225 void scheduleWritePackageRestrictionsLocked(int userId) { 2226 final int[] userIds = (userId == UserHandle.USER_ALL) 2227 ? sUserManager.getUserIds() : new int[]{userId}; 2228 for (int nextUserId : userIds) { 2229 if (!sUserManager.exists(nextUserId)) return; 2230 mDirtyUsers.add(nextUserId); 2231 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2232 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2233 } 2234 } 2235 } 2236 2237 public static PackageManagerService main(Context context, Installer installer, 2238 boolean factoryTest, boolean onlyCore) { 2239 // Self-check for initial settings. 2240 PackageManagerServiceCompilerMapping.checkProperties(); 2241 2242 PackageManagerService m = new PackageManagerService(context, installer, 2243 factoryTest, onlyCore); 2244 m.enableSystemUserPackages(); 2245 ServiceManager.addService("package", m); 2246 final PackageManagerNative pmn = m.new PackageManagerNative(); 2247 ServiceManager.addService("package_native", pmn); 2248 return m; 2249 } 2250 2251 private void enableSystemUserPackages() { 2252 if (!UserManager.isSplitSystemUser()) { 2253 return; 2254 } 2255 // For system user, enable apps based on the following conditions: 2256 // - app is whitelisted or belong to one of these groups: 2257 // -- system app which has no launcher icons 2258 // -- system app which has INTERACT_ACROSS_USERS permission 2259 // -- system IME app 2260 // - app is not in the blacklist 2261 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2262 Set<String> enableApps = new ArraySet<>(); 2263 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2264 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2265 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2266 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2267 enableApps.addAll(wlApps); 2268 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2269 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2270 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2271 enableApps.removeAll(blApps); 2272 Log.i(TAG, "Applications installed for system user: " + enableApps); 2273 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2274 UserHandle.SYSTEM); 2275 final int allAppsSize = allAps.size(); 2276 synchronized (mPackages) { 2277 for (int i = 0; i < allAppsSize; i++) { 2278 String pName = allAps.get(i); 2279 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2280 // Should not happen, but we shouldn't be failing if it does 2281 if (pkgSetting == null) { 2282 continue; 2283 } 2284 boolean install = enableApps.contains(pName); 2285 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2286 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2287 + " for system user"); 2288 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2289 } 2290 } 2291 scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM); 2292 } 2293 } 2294 2295 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2296 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2297 Context.DISPLAY_SERVICE); 2298 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2299 } 2300 2301 /** 2302 * Requests that files preopted on a secondary system partition be copied to the data partition 2303 * if possible. Note that the actual copying of the files is accomplished by init for security 2304 * reasons. This simply requests that the copy takes place and awaits confirmation of its 2305 * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy. 2306 */ 2307 private static void requestCopyPreoptedFiles() { 2308 final int WAIT_TIME_MS = 100; 2309 final String CP_PREOPT_PROPERTY = "sys.cppreopt"; 2310 if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) { 2311 SystemProperties.set(CP_PREOPT_PROPERTY, "requested"); 2312 // We will wait for up to 100 seconds. 2313 final long timeStart = SystemClock.uptimeMillis(); 2314 final long timeEnd = timeStart + 100 * 1000; 2315 long timeNow = timeStart; 2316 while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) { 2317 try { 2318 Thread.sleep(WAIT_TIME_MS); 2319 } catch (InterruptedException e) { 2320 // Do nothing 2321 } 2322 timeNow = SystemClock.uptimeMillis(); 2323 if (timeNow > timeEnd) { 2324 SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out"); 2325 Slog.wtf(TAG, "cppreopt did not finish!"); 2326 break; 2327 } 2328 } 2329 2330 Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms"); 2331 } 2332 } 2333 2334 public PackageManagerService(Context context, Installer installer, 2335 boolean factoryTest, boolean onlyCore) { 2336 LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES); 2337 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager"); 2338 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2339 SystemClock.uptimeMillis()); 2340 2341 if (mSdkVersion <= 0) { 2342 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2343 } 2344 2345 mContext = context; 2346 2347 mFactoryTest = factoryTest; 2348 mOnlyCore = onlyCore; 2349 mMetrics = new DisplayMetrics(); 2350 mInstaller = installer; 2351 2352 // Create sub-components that provide services / data. Order here is important. 2353 synchronized (mInstallLock) { 2354 synchronized (mPackages) { 2355 // Expose private service for system components to use. 2356 LocalServices.addService( 2357 PackageManagerInternal.class, new PackageManagerInternalImpl()); 2358 sUserManager = new UserManagerService(context, this, 2359 new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages); 2360 mPermissionManager = PermissionManagerService.create(context, 2361 new DefaultPermissionGrantedCallback() { 2362 @Override 2363 public void onDefaultRuntimePermissionsGranted(int userId) { 2364 synchronized(mPackages) { 2365 mSettings.onDefaultRuntimePermissionsGrantedLPr(userId); 2366 } 2367 } 2368 }, mPackages /*externalLock*/); 2369 mDefaultPermissionPolicy = mPermissionManager.getDefaultPermissionGrantPolicy(); 2370 mSettings = new Settings(mPermissionManager.getPermissionSettings(), mPackages); 2371 } 2372 } 2373 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2374 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2375 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2376 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2377 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2378 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2379 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2380 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2381 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2382 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2383 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2384 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2385 2386 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2387 if (separateProcesses != null && separateProcesses.length() > 0) { 2388 if ("*".equals(separateProcesses)) { 2389 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2390 mSeparateProcesses = null; 2391 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2392 } else { 2393 mDefParseFlags = 0; 2394 mSeparateProcesses = separateProcesses.split(","); 2395 Slog.w(TAG, "Running with debug.separate_processes: " 2396 + separateProcesses); 2397 } 2398 } else { 2399 mDefParseFlags = 0; 2400 mSeparateProcesses = null; 2401 } 2402 2403 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2404 "*dexopt*"); 2405 DexManager.Listener dexManagerListener = DexLogger.getListener(this, 2406 installer, mInstallLock); 2407 mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock, 2408 dexManagerListener); 2409 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2410 2411 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2412 FgThread.get().getLooper()); 2413 2414 getDefaultDisplayMetrics(context, mMetrics); 2415 2416 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config"); 2417 SystemConfig systemConfig = SystemConfig.getInstance(); 2418 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2419 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2420 2421 mProtectedPackages = new ProtectedPackages(mContext); 2422 2423 synchronized (mInstallLock) { 2424 // writer 2425 synchronized (mPackages) { 2426 mHandlerThread = new ServiceThread(TAG, 2427 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2428 mHandlerThread.start(); 2429 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2430 mProcessLoggingHandler = new ProcessLoggingHandler(); 2431 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2432 mInstantAppRegistry = new InstantAppRegistry(this); 2433 2434 File dataDir = Environment.getDataDirectory(); 2435 mAppInstallDir = new File(dataDir, "app"); 2436 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2437 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2438 2439 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2440 final int builtInLibCount = libConfig.size(); 2441 for (int i = 0; i < builtInLibCount; i++) { 2442 String name = libConfig.keyAt(i); 2443 String path = libConfig.valueAt(i); 2444 addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED, 2445 SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0); 2446 } 2447 2448 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2449 2450 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings"); 2451 mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false)); 2452 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2453 2454 // Clean up orphaned packages for which the code path doesn't exist 2455 // and they are an update to a system app - caused by bug/32321269 2456 final int packageSettingCount = mSettings.mPackages.size(); 2457 for (int i = packageSettingCount - 1; i >= 0; i--) { 2458 PackageSetting ps = mSettings.mPackages.valueAt(i); 2459 if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists()) 2460 && mSettings.getDisabledSystemPkgLPr(ps.name) != null) { 2461 mSettings.mPackages.removeAt(i); 2462 mSettings.enableSystemPackageLPw(ps.name); 2463 } 2464 } 2465 2466 if (mFirstBoot) { 2467 requestCopyPreoptedFiles(); 2468 } 2469 2470 String customResolverActivity = Resources.getSystem().getString( 2471 R.string.config_customResolverActivity); 2472 if (TextUtils.isEmpty(customResolverActivity)) { 2473 customResolverActivity = null; 2474 } else { 2475 mCustomResolverComponentName = ComponentName.unflattenFromString( 2476 customResolverActivity); 2477 } 2478 2479 long startTime = SystemClock.uptimeMillis(); 2480 2481 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2482 startTime); 2483 2484 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2485 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2486 2487 if (bootClassPath == null) { 2488 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2489 } 2490 2491 if (systemServerClassPath == null) { 2492 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2493 } 2494 2495 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2496 2497 final VersionInfo ver = mSettings.getInternalVersion(); 2498 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2499 if (mIsUpgrade) { 2500 logCriticalInfo(Log.INFO, 2501 "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT); 2502 } 2503 2504 // when upgrading from pre-M, promote system app permissions from install to runtime 2505 mPromoteSystemApps = 2506 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2507 2508 // When upgrading from pre-N, we need to handle package extraction like first boot, 2509 // as there is no profiling data available. 2510 mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N; 2511 2512 mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1; 2513 2514 // save off the names of pre-existing system packages prior to scanning; we don't 2515 // want to automatically grant runtime permissions for new system apps 2516 if (mPromoteSystemApps) { 2517 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2518 while (pkgSettingIter.hasNext()) { 2519 PackageSetting ps = pkgSettingIter.next(); 2520 if (isSystemApp(ps)) { 2521 mExistingSystemPackages.add(ps.name); 2522 } 2523 } 2524 } 2525 2526 mCacheDir = preparePackageParserCache(mIsUpgrade); 2527 2528 // Set flag to monitor and not change apk file paths when 2529 // scanning install directories. 2530 int scanFlags = SCAN_BOOTING | SCAN_INITIAL; 2531 2532 if (mIsUpgrade || mFirstBoot) { 2533 scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE; 2534 } 2535 2536 // Collect vendor overlay packages. (Do this before scanning any apps.) 2537 // For security and version matching reason, only consider 2538 // overlay packages if they reside in the right directory. 2539 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), 2540 mDefParseFlags 2541 | PackageParser.PARSE_IS_SYSTEM_DIR, 2542 scanFlags 2543 | SCAN_AS_SYSTEM 2544 | SCAN_TRUSTED_OVERLAY, 2545 0); 2546 2547 mParallelPackageParserCallback.findStaticOverlayPackages(); 2548 2549 // Find base frameworks (resource packages without code). 2550 scanDirTracedLI(frameworkDir, 2551 mDefParseFlags 2552 | PackageParser.PARSE_IS_SYSTEM_DIR, 2553 scanFlags 2554 | SCAN_NO_DEX 2555 | SCAN_AS_SYSTEM 2556 | SCAN_AS_PRIVILEGED, 2557 0); 2558 2559 // Collected privileged system packages. 2560 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2561 scanDirTracedLI(privilegedAppDir, 2562 mDefParseFlags 2563 | PackageParser.PARSE_IS_SYSTEM_DIR, 2564 scanFlags 2565 | SCAN_AS_SYSTEM 2566 | SCAN_AS_PRIVILEGED, 2567 0); 2568 2569 // Collect ordinary system packages. 2570 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2571 scanDirTracedLI(systemAppDir, 2572 mDefParseFlags 2573 | PackageParser.PARSE_IS_SYSTEM_DIR, 2574 scanFlags 2575 | SCAN_AS_SYSTEM, 2576 0); 2577 2578 // Collected privileged vendor packages. 2579 File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), 2580 "priv-app"); 2581 try { 2582 privilegedVendorAppDir = privilegedVendorAppDir.getCanonicalFile(); 2583 } catch (IOException e) { 2584 // failed to look up canonical path, continue with original one 2585 } 2586 scanDirTracedLI(privilegedVendorAppDir, 2587 mDefParseFlags 2588 | PackageParser.PARSE_IS_SYSTEM_DIR, 2589 scanFlags 2590 | SCAN_AS_SYSTEM 2591 | SCAN_AS_VENDOR 2592 | SCAN_AS_PRIVILEGED, 2593 0); 2594 2595 // Collect ordinary vendor packages. 2596 File vendorAppDir = new File(Environment.getVendorDirectory(), "app"); 2597 try { 2598 vendorAppDir = vendorAppDir.getCanonicalFile(); 2599 } catch (IOException e) { 2600 // failed to look up canonical path, continue with original one 2601 } 2602 scanDirTracedLI(vendorAppDir, 2603 mDefParseFlags 2604 | PackageParser.PARSE_IS_SYSTEM_DIR, 2605 scanFlags 2606 | SCAN_AS_SYSTEM 2607 | SCAN_AS_VENDOR, 2608 0); 2609 2610 // Collect all OEM packages. 2611 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2612 scanDirTracedLI(oemAppDir, 2613 mDefParseFlags 2614 | PackageParser.PARSE_IS_SYSTEM_DIR, 2615 scanFlags 2616 | SCAN_AS_SYSTEM 2617 | SCAN_AS_OEM, 2618 0); 2619 2620 // Prune any system packages that no longer exist. 2621 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>(); 2622 // Stub packages must either be replaced with full versions in the /data 2623 // partition or be disabled. 2624 final List<String> stubSystemApps = new ArrayList<>(); 2625 if (!mOnlyCore) { 2626 // do this first before mucking with mPackages for the "expecting better" case 2627 final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator(); 2628 while (pkgIterator.hasNext()) { 2629 final PackageParser.Package pkg = pkgIterator.next(); 2630 if (pkg.isStub) { 2631 stubSystemApps.add(pkg.packageName); 2632 } 2633 } 2634 2635 final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2636 while (psit.hasNext()) { 2637 PackageSetting ps = psit.next(); 2638 2639 /* 2640 * If this is not a system app, it can't be a 2641 * disable system app. 2642 */ 2643 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2644 continue; 2645 } 2646 2647 /* 2648 * If the package is scanned, it's not erased. 2649 */ 2650 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2651 if (scannedPkg != null) { 2652 /* 2653 * If the system app is both scanned and in the 2654 * disabled packages list, then it must have been 2655 * added via OTA. Remove it from the currently 2656 * scanned package so the previously user-installed 2657 * application can be scanned. 2658 */ 2659 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2660 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2661 + ps.name + "; removing system app. Last known codePath=" 2662 + ps.codePathString + ", installStatus=" + ps.installStatus 2663 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2664 + scannedPkg.mVersionCode); 2665 removePackageLI(scannedPkg, true); 2666 mExpectingBetter.put(ps.name, ps.codePath); 2667 } 2668 2669 continue; 2670 } 2671 2672 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2673 psit.remove(); 2674 logCriticalInfo(Log.WARN, "System package " + ps.name 2675 + " no longer exists; it's data will be wiped"); 2676 // Actual deletion of code and data will be handled by later 2677 // reconciliation step 2678 } else { 2679 // we still have a disabled system package, but, it still might have 2680 // been removed. check the code path still exists and check there's 2681 // still a package. the latter can happen if an OTA keeps the same 2682 // code path, but, changes the package name. 2683 final PackageSetting disabledPs = 2684 mSettings.getDisabledSystemPkgLPr(ps.name); 2685 if (disabledPs.codePath == null || !disabledPs.codePath.exists() 2686 || disabledPs.pkg == null) { 2687 possiblyDeletedUpdatedSystemApps.add(ps.name); 2688 } 2689 } 2690 } 2691 } 2692 2693 //look for any incomplete package installations 2694 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2695 for (int i = 0; i < deletePkgsList.size(); i++) { 2696 // Actual deletion of code and data will be handled by later 2697 // reconciliation step 2698 final String packageName = deletePkgsList.get(i).name; 2699 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2700 synchronized (mPackages) { 2701 mSettings.removePackageLPw(packageName); 2702 } 2703 } 2704 2705 //delete tmp files 2706 deleteTempPackageFiles(); 2707 2708 final int cachedSystemApps = PackageParser.sCachedPackageReadCount.get(); 2709 2710 // Remove any shared userIDs that have no associated packages 2711 mSettings.pruneSharedUsersLPw(); 2712 final long systemScanTime = SystemClock.uptimeMillis() - startTime; 2713 final int systemPackagesCount = mPackages.size(); 2714 Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime 2715 + " ms, packageCount: " + systemPackagesCount 2716 + " , timePerPackage: " 2717 + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount) 2718 + " , cached: " + cachedSystemApps); 2719 if (mIsUpgrade && systemPackagesCount > 0) { 2720 MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time", 2721 ((int) systemScanTime) / systemPackagesCount); 2722 } 2723 if (!mOnlyCore) { 2724 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2725 SystemClock.uptimeMillis()); 2726 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2727 2728 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2729 | PackageParser.PARSE_FORWARD_LOCK, 2730 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2731 2732 // Remove disable package settings for updated system apps that were 2733 // removed via an OTA. If the update is no longer present, remove the 2734 // app completely. Otherwise, revoke their system privileges. 2735 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2736 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2737 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2738 2739 final String msg; 2740 if (deletedPkg == null) { 2741 // should have found an update, but, we didn't; remove everything 2742 msg = "Updated system package " + deletedAppName 2743 + " no longer exists; removing its data"; 2744 // Actual deletion of code and data will be handled by later 2745 // reconciliation step 2746 } else { 2747 // found an update; revoke system privileges 2748 msg = "Updated system package + " + deletedAppName 2749 + " no longer exists; revoking system privileges"; 2750 2751 // Don't do anything if a stub is removed from the system image. If 2752 // we were to remove the uncompressed version from the /data partition, 2753 // this is where it'd be done. 2754 2755 final PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2756 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2757 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2758 } 2759 logCriticalInfo(Log.WARN, msg); 2760 } 2761 2762 /* 2763 * Make sure all system apps that we expected to appear on 2764 * the userdata partition actually showed up. If they never 2765 * appeared, crawl back and revive the system version. 2766 */ 2767 for (int i = 0; i < mExpectingBetter.size(); i++) { 2768 final String packageName = mExpectingBetter.keyAt(i); 2769 if (!mPackages.containsKey(packageName)) { 2770 final File scanFile = mExpectingBetter.valueAt(i); 2771 2772 logCriticalInfo(Log.WARN, "Expected better " + packageName 2773 + " but never showed up; reverting to system"); 2774 2775 final @ParseFlags int reparseFlags; 2776 final @ScanFlags int rescanFlags; 2777 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2778 reparseFlags = 2779 mDefParseFlags | 2780 PackageParser.PARSE_IS_SYSTEM_DIR; 2781 rescanFlags = 2782 scanFlags 2783 | SCAN_AS_SYSTEM 2784 | SCAN_AS_PRIVILEGED; 2785 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2786 reparseFlags = 2787 mDefParseFlags | 2788 PackageParser.PARSE_IS_SYSTEM_DIR; 2789 rescanFlags = 2790 scanFlags 2791 | SCAN_AS_SYSTEM; 2792 } else if (FileUtils.contains(privilegedVendorAppDir, scanFile)) { 2793 reparseFlags = 2794 mDefParseFlags | 2795 PackageParser.PARSE_IS_SYSTEM_DIR; 2796 rescanFlags = 2797 scanFlags 2798 | SCAN_AS_SYSTEM 2799 | SCAN_AS_VENDOR 2800 | SCAN_AS_PRIVILEGED; 2801 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2802 reparseFlags = 2803 mDefParseFlags | 2804 PackageParser.PARSE_IS_SYSTEM_DIR; 2805 rescanFlags = 2806 scanFlags 2807 | SCAN_AS_SYSTEM 2808 | SCAN_AS_VENDOR; 2809 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2810 reparseFlags = 2811 mDefParseFlags | 2812 PackageParser.PARSE_IS_SYSTEM_DIR; 2813 rescanFlags = 2814 scanFlags 2815 | SCAN_AS_SYSTEM 2816 | SCAN_AS_OEM; 2817 } else { 2818 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2819 continue; 2820 } 2821 2822 mSettings.enableSystemPackageLPw(packageName); 2823 2824 try { 2825 scanPackageTracedLI(scanFile, reparseFlags, rescanFlags, 0, null); 2826 } catch (PackageManagerException e) { 2827 Slog.e(TAG, "Failed to parse original system package: " 2828 + e.getMessage()); 2829 } 2830 } 2831 } 2832 2833 // Uncompress and install any stubbed system applications. 2834 // This must be done last to ensure all stubs are replaced or disabled. 2835 decompressSystemApplications(stubSystemApps, scanFlags); 2836 2837 final int cachedNonSystemApps = PackageParser.sCachedPackageReadCount.get() 2838 - cachedSystemApps; 2839 2840 final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime; 2841 final int dataPackagesCount = mPackages.size() - systemPackagesCount; 2842 Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime 2843 + " ms, packageCount: " + dataPackagesCount 2844 + " , timePerPackage: " 2845 + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount) 2846 + " , cached: " + cachedNonSystemApps); 2847 if (mIsUpgrade && dataPackagesCount > 0) { 2848 MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time", 2849 ((int) dataScanTime) / dataPackagesCount); 2850 } 2851 } 2852 mExpectingBetter.clear(); 2853 2854 // Resolve the storage manager. 2855 mStorageManagerPackage = getStorageManagerPackageName(); 2856 2857 // Resolve protected action filters. Only the setup wizard is allowed to 2858 // have a high priority filter for these actions. 2859 mSetupWizardPackage = getSetupWizardPackageName(); 2860 if (mProtectedFilters.size() > 0) { 2861 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2862 Slog.i(TAG, "No setup wizard;" 2863 + " All protected intents capped to priority 0"); 2864 } 2865 for (ActivityIntentInfo filter : mProtectedFilters) { 2866 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2867 if (DEBUG_FILTERS) { 2868 Slog.i(TAG, "Found setup wizard;" 2869 + " allow priority " + filter.getPriority() + ";" 2870 + " package: " + filter.activity.info.packageName 2871 + " activity: " + filter.activity.className 2872 + " priority: " + filter.getPriority()); 2873 } 2874 // skip setup wizard; allow it to keep the high priority filter 2875 continue; 2876 } 2877 if (DEBUG_FILTERS) { 2878 Slog.i(TAG, "Protected action; cap priority to 0;" 2879 + " package: " + filter.activity.info.packageName 2880 + " activity: " + filter.activity.className 2881 + " origPrio: " + filter.getPriority()); 2882 } 2883 filter.setPriority(0); 2884 } 2885 } 2886 mDeferProtectedFilters = false; 2887 mProtectedFilters.clear(); 2888 2889 // Now that we know all of the shared libraries, update all clients to have 2890 // the correct library paths. 2891 updateAllSharedLibrariesLPw(null); 2892 2893 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2894 // NOTE: We ignore potential failures here during a system scan (like 2895 // the rest of the commands above) because there's precious little we 2896 // can do about it. A settings error is reported, though. 2897 adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/); 2898 } 2899 2900 // Now that we know all the packages we are keeping, 2901 // read and update their last usage times. 2902 mPackageUsage.read(mPackages); 2903 mCompilerStats.read(); 2904 2905 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2906 SystemClock.uptimeMillis()); 2907 Slog.i(TAG, "Time to scan packages: " 2908 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2909 + " seconds"); 2910 2911 // If the platform SDK has changed since the last time we booted, 2912 // we need to re-grant app permission to catch any new ones that 2913 // appear. This is really a hack, and means that apps can in some 2914 // cases get permissions that the user didn't initially explicitly 2915 // allow... it would be nice to have some better way to handle 2916 // this situation. 2917 final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion); 2918 if (sdkUpdated) { 2919 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2920 + mSdkVersion + "; regranting permissions for internal storage"); 2921 } 2922 mPermissionManager.updateAllPermissions( 2923 StorageManager.UUID_PRIVATE_INTERNAL, sdkUpdated, mPackages.values(), 2924 mPermissionCallback); 2925 ver.sdkVersion = mSdkVersion; 2926 2927 // If this is the first boot or an update from pre-M, and it is a normal 2928 // boot, then we need to initialize the default preferred apps across 2929 // all defined users. 2930 if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) { 2931 for (UserInfo user : sUserManager.getUsers(true)) { 2932 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2933 applyFactoryDefaultBrowserLPw(user.id); 2934 primeDomainVerificationsLPw(user.id); 2935 } 2936 } 2937 2938 // Prepare storage for system user really early during boot, 2939 // since core system apps like SettingsProvider and SystemUI 2940 // can't wait for user to start 2941 final int storageFlags; 2942 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2943 storageFlags = StorageManager.FLAG_STORAGE_DE; 2944 } else { 2945 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2946 } 2947 List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, 2948 UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */, 2949 true /* onlyCoreApps */); 2950 mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> { 2951 TimingsTraceLog traceLog = new TimingsTraceLog("SystemServerTimingAsync", 2952 Trace.TRACE_TAG_PACKAGE_MANAGER); 2953 traceLog.traceBegin("AppDataFixup"); 2954 try { 2955 mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL, 2956 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 2957 } catch (InstallerException e) { 2958 Slog.w(TAG, "Trouble fixing GIDs", e); 2959 } 2960 traceLog.traceEnd(); 2961 2962 traceLog.traceBegin("AppDataPrepare"); 2963 if (deferPackages == null || deferPackages.isEmpty()) { 2964 return; 2965 } 2966 int count = 0; 2967 for (String pkgName : deferPackages) { 2968 PackageParser.Package pkg = null; 2969 synchronized (mPackages) { 2970 PackageSetting ps = mSettings.getPackageLPr(pkgName); 2971 if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) { 2972 pkg = ps.pkg; 2973 } 2974 } 2975 if (pkg != null) { 2976 synchronized (mInstallLock) { 2977 prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags, 2978 true /* maybeMigrateAppData */); 2979 } 2980 count++; 2981 } 2982 } 2983 traceLog.traceEnd(); 2984 Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages"); 2985 }, "prepareAppData"); 2986 2987 // If this is first boot after an OTA, and a normal boot, then 2988 // we need to clear code cache directories. 2989 // Note that we do *not* clear the application profiles. These remain valid 2990 // across OTAs and are used to drive profile verification (post OTA) and 2991 // profile compilation (without waiting to collect a fresh set of profiles). 2992 if (mIsUpgrade && !onlyCore) { 2993 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2994 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2995 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2996 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2997 // No apps are running this early, so no need to freeze 2998 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2999 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 3000 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 3001 } 3002 } 3003 ver.fingerprint = Build.FINGERPRINT; 3004 } 3005 3006 checkDefaultBrowser(); 3007 3008 // clear only after permissions and other defaults have been updated 3009 mExistingSystemPackages.clear(); 3010 mPromoteSystemApps = false; 3011 3012 // All the changes are done during package scanning. 3013 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 3014 3015 // can downgrade to reader 3016 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings"); 3017 mSettings.writeLPr(); 3018 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 3019 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 3020 SystemClock.uptimeMillis()); 3021 3022 if (!mOnlyCore) { 3023 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 3024 mRequiredInstallerPackage = getRequiredInstallerLPr(); 3025 mRequiredUninstallerPackage = getRequiredUninstallerLPr(); 3026 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 3027 if (mIntentFilterVerifierComponent != null) { 3028 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 3029 mIntentFilterVerifierComponent); 3030 } else { 3031 mIntentFilterVerifier = null; 3032 } 3033 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 3034 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES, 3035 SharedLibraryInfo.VERSION_UNDEFINED); 3036 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 3037 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED, 3038 SharedLibraryInfo.VERSION_UNDEFINED); 3039 } else { 3040 mRequiredVerifierPackage = null; 3041 mRequiredInstallerPackage = null; 3042 mRequiredUninstallerPackage = null; 3043 mIntentFilterVerifierComponent = null; 3044 mIntentFilterVerifier = null; 3045 mServicesSystemSharedLibraryPackageName = null; 3046 mSharedSystemSharedLibraryPackageName = null; 3047 } 3048 3049 mInstallerService = new PackageInstallerService(context, this); 3050 final Pair<ComponentName, String> instantAppResolverComponent = 3051 getInstantAppResolverLPr(); 3052 if (instantAppResolverComponent != null) { 3053 if (DEBUG_EPHEMERAL) { 3054 Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent); 3055 } 3056 mInstantAppResolverConnection = new EphemeralResolverConnection( 3057 mContext, instantAppResolverComponent.first, 3058 instantAppResolverComponent.second); 3059 mInstantAppResolverSettingsComponent = 3060 getInstantAppResolverSettingsLPr(instantAppResolverComponent.first); 3061 } else { 3062 mInstantAppResolverConnection = null; 3063 mInstantAppResolverSettingsComponent = null; 3064 } 3065 updateInstantAppInstallerLocked(null); 3066 3067 // Read and update the usage of dex files. 3068 // Do this at the end of PM init so that all the packages have their 3069 // data directory reconciled. 3070 // At this point we know the code paths of the packages, so we can validate 3071 // the disk file and build the internal cache. 3072 // The usage file is expected to be small so loading and verifying it 3073 // should take a fairly small time compare to the other activities (e.g. package 3074 // scanning). 3075 final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>(); 3076 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 3077 for (int userId : currentUserIds) { 3078 userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList()); 3079 } 3080 mDexManager.load(userPackages); 3081 if (mIsUpgrade) { 3082 MetricsLogger.histogram(null, "ota_package_manager_init_time", 3083 (int) (SystemClock.uptimeMillis() - startTime)); 3084 } 3085 } // synchronized (mPackages) 3086 } // synchronized (mInstallLock) 3087 3088 // Now after opening every single application zip, make sure they 3089 // are all flushed. Not really needed, but keeps things nice and 3090 // tidy. 3091 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC"); 3092 Runtime.getRuntime().gc(); 3093 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 3094 3095 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks"); 3096 FallbackCategoryProvider.loadFallbacks(); 3097 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 3098 3099 // The initial scanning above does many calls into installd while 3100 // holding the mPackages lock, but we're mostly interested in yelling 3101 // once we have a booted system. 3102 mInstaller.setWarnIfHeld(mPackages); 3103 3104 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 3105 } 3106 3107 /** 3108 * Uncompress and install stub applications. 3109 * <p>In order to save space on the system partition, some applications are shipped in a 3110 * compressed form. In addition the compressed bits for the full application, the 3111 * system image contains a tiny stub comprised of only the Android manifest. 3112 * <p>During the first boot, attempt to uncompress and install the full application. If 3113 * the application can't be installed for any reason, disable the stub and prevent 3114 * uncompressing the full application during future boots. 3115 * <p>In order to forcefully attempt an installation of a full application, go to app 3116 * settings and enable the application. 3117 */ 3118 private void decompressSystemApplications(@NonNull List<String> stubSystemApps, int scanFlags) { 3119 for (int i = stubSystemApps.size() - 1; i >= 0; --i) { 3120 final String pkgName = stubSystemApps.get(i); 3121 // skip if the system package is already disabled 3122 if (mSettings.isDisabledSystemPackageLPr(pkgName)) { 3123 stubSystemApps.remove(i); 3124 continue; 3125 } 3126 // skip if the package isn't installed (?!); this should never happen 3127 final PackageParser.Package pkg = mPackages.get(pkgName); 3128 if (pkg == null) { 3129 stubSystemApps.remove(i); 3130 continue; 3131 } 3132 // skip if the package has been disabled by the user 3133 final PackageSetting ps = mSettings.mPackages.get(pkgName); 3134 if (ps != null) { 3135 final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM); 3136 if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) { 3137 stubSystemApps.remove(i); 3138 continue; 3139 } 3140 } 3141 3142 if (DEBUG_COMPRESSION) { 3143 Slog.i(TAG, "Uncompressing system stub; pkg: " + pkgName); 3144 } 3145 3146 // uncompress the binary to its eventual destination on /data 3147 final File scanFile = decompressPackage(pkg); 3148 if (scanFile == null) { 3149 continue; 3150 } 3151 3152 // install the package to replace the stub on /system 3153 try { 3154 mSettings.disableSystemPackageLPw(pkgName, true /*replaced*/); 3155 removePackageLI(pkg, true /*chatty*/); 3156 scanPackageTracedLI(scanFile, 0 /*reparseFlags*/, scanFlags, 0, null); 3157 ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT, 3158 UserHandle.USER_SYSTEM, "android"); 3159 stubSystemApps.remove(i); 3160 continue; 3161 } catch (PackageManagerException e) { 3162 Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage()); 3163 } 3164 3165 // any failed attempt to install the package will be cleaned up later 3166 } 3167 3168 // disable any stub still left; these failed to install the full application 3169 for (int i = stubSystemApps.size() - 1; i >= 0; --i) { 3170 final String pkgName = stubSystemApps.get(i); 3171 final PackageSetting ps = mSettings.mPackages.get(pkgName); 3172 ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED, 3173 UserHandle.USER_SYSTEM, "android"); 3174 logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName); 3175 } 3176 } 3177 3178 /** 3179 * Decompresses the given package on the system image onto 3180 * the /data partition. 3181 * @return The directory the package was decompressed into. Otherwise, {@code null}. 3182 */ 3183 private File decompressPackage(PackageParser.Package pkg) { 3184 final File[] compressedFiles = getCompressedFiles(pkg.codePath); 3185 if (compressedFiles == null || compressedFiles.length == 0) { 3186 if (DEBUG_COMPRESSION) { 3187 Slog.i(TAG, "No files to decompress: " + pkg.baseCodePath); 3188 } 3189 return null; 3190 } 3191 final File dstCodePath = 3192 getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName); 3193 int ret = PackageManager.INSTALL_SUCCEEDED; 3194 try { 3195 Os.mkdir(dstCodePath.getAbsolutePath(), 0755); 3196 Os.chmod(dstCodePath.getAbsolutePath(), 0755); 3197 for (File srcFile : compressedFiles) { 3198 final String srcFileName = srcFile.getName(); 3199 final String dstFileName = srcFileName.substring( 3200 0, srcFileName.length() - COMPRESSED_EXTENSION.length()); 3201 final File dstFile = new File(dstCodePath, dstFileName); 3202 ret = decompressFile(srcFile, dstFile); 3203 if (ret != PackageManager.INSTALL_SUCCEEDED) { 3204 logCriticalInfo(Log.ERROR, "Failed to decompress" 3205 + "; pkg: " + pkg.packageName 3206 + ", file: " + dstFileName); 3207 break; 3208 } 3209 } 3210 } catch (ErrnoException e) { 3211 logCriticalInfo(Log.ERROR, "Failed to decompress" 3212 + "; pkg: " + pkg.packageName 3213 + ", err: " + e.errno); 3214 } 3215 if (ret == PackageManager.INSTALL_SUCCEEDED) { 3216 final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME); 3217 NativeLibraryHelper.Handle handle = null; 3218 try { 3219 handle = NativeLibraryHelper.Handle.create(dstCodePath); 3220 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 3221 null /*abiOverride*/); 3222 } catch (IOException e) { 3223 logCriticalInfo(Log.ERROR, "Failed to extract native libraries" 3224 + "; pkg: " + pkg.packageName); 3225 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 3226 } finally { 3227 IoUtils.closeQuietly(handle); 3228 } 3229 } 3230 if (ret != PackageManager.INSTALL_SUCCEEDED) { 3231 if (dstCodePath == null || !dstCodePath.exists()) { 3232 return null; 3233 } 3234 removeCodePathLI(dstCodePath); 3235 return null; 3236 } 3237 3238 return dstCodePath; 3239 } 3240 3241 private void updateInstantAppInstallerLocked(String modifiedPackage) { 3242 // we're only interested in updating the installer appliction when 1) it's not 3243 // already set or 2) the modified package is the installer 3244 if (mInstantAppInstallerActivity != null 3245 && !mInstantAppInstallerActivity.getComponentName().getPackageName() 3246 .equals(modifiedPackage)) { 3247 return; 3248 } 3249 setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr()); 3250 } 3251 3252 private static File preparePackageParserCache(boolean isUpgrade) { 3253 if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) { 3254 return null; 3255 } 3256 3257 // Disable package parsing on eng builds to allow for faster incremental development. 3258 if (Build.IS_ENG) { 3259 return null; 3260 } 3261 3262 if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) { 3263 Slog.i(TAG, "Disabling package parser cache due to system property."); 3264 return null; 3265 } 3266 3267 // The base directory for the package parser cache lives under /data/system/. 3268 final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(), 3269 "package_cache"); 3270 if (cacheBaseDir == null) { 3271 return null; 3272 } 3273 3274 // If this is a system upgrade scenario, delete the contents of the package cache dir. 3275 // This also serves to "GC" unused entries when the package cache version changes (which 3276 // can only happen during upgrades). 3277 if (isUpgrade) { 3278 FileUtils.deleteContents(cacheBaseDir); 3279 } 3280 3281 3282 // Return the versioned package cache directory. This is something like 3283 // "/data/system/package_cache/1" 3284 File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION); 3285 3286 // The following is a workaround to aid development on non-numbered userdebug 3287 // builds or cases where "adb sync" is used on userdebug builds. If we detect that 3288 // the system partition is newer. 3289 // 3290 // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build 3291 // that starts with "eng." to signify that this is an engineering build and not 3292 // destined for release. 3293 if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) { 3294 Slog.w(TAG, "Wiping cache directory because the system partition changed."); 3295 3296 // Heuristic: If the /system directory has been modified recently due to an "adb sync" 3297 // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable 3298 // in general and should not be used for production changes. In this specific case, 3299 // we know that they will work. 3300 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 3301 if (cacheDir.lastModified() < frameworkDir.lastModified()) { 3302 FileUtils.deleteContents(cacheBaseDir); 3303 cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION); 3304 } 3305 } 3306 3307 return cacheDir; 3308 } 3309 3310 @Override 3311 public boolean isFirstBoot() { 3312 // allow instant applications 3313 return mFirstBoot; 3314 } 3315 3316 @Override 3317 public boolean isOnlyCoreApps() { 3318 // allow instant applications 3319 return mOnlyCore; 3320 } 3321 3322 @Override 3323 public boolean isUpgrade() { 3324 // allow instant applications 3325 // The system property allows testing ota flow when upgraded to the same image. 3326 return mIsUpgrade || SystemProperties.getBoolean( 3327 "persist.pm.mock-upgrade", false /* default */); 3328 } 3329 3330 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 3331 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 3332 3333 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 3334 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3335 UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/); 3336 if (matches.size() == 1) { 3337 return matches.get(0).getComponentInfo().packageName; 3338 } else if (matches.size() == 0) { 3339 Log.e(TAG, "There should probably be a verifier, but, none were found"); 3340 return null; 3341 } 3342 throw new RuntimeException("There must be exactly one verifier; found " + matches); 3343 } 3344 3345 private @NonNull String getRequiredSharedLibraryLPr(String name, int version) { 3346 synchronized (mPackages) { 3347 SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version); 3348 if (libraryEntry == null) { 3349 throw new IllegalStateException("Missing required shared library:" + name); 3350 } 3351 return libraryEntry.apk; 3352 } 3353 } 3354 3355 private @NonNull String getRequiredInstallerLPr() { 3356 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 3357 intent.addCategory(Intent.CATEGORY_DEFAULT); 3358 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 3359 3360 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3361 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3362 UserHandle.USER_SYSTEM); 3363 if (matches.size() == 1) { 3364 ResolveInfo resolveInfo = matches.get(0); 3365 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 3366 throw new RuntimeException("The installer must be a privileged app"); 3367 } 3368 return matches.get(0).getComponentInfo().packageName; 3369 } else { 3370 throw new RuntimeException("There must be exactly one installer; found " + matches); 3371 } 3372 } 3373 3374 private @NonNull String getRequiredUninstallerLPr() { 3375 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 3376 intent.addCategory(Intent.CATEGORY_DEFAULT); 3377 intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null)); 3378 3379 final ResolveInfo resolveInfo = resolveIntent(intent, null, 3380 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3381 UserHandle.USER_SYSTEM); 3382 if (resolveInfo == null || 3383 mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) { 3384 throw new RuntimeException("There must be exactly one uninstaller; found " 3385 + resolveInfo); 3386 } 3387 return resolveInfo.getComponentInfo().packageName; 3388 } 3389 3390 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 3391 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 3392 3393 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 3394 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3395 UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/); 3396 ResolveInfo best = null; 3397 final int N = matches.size(); 3398 for (int i = 0; i < N; i++) { 3399 final ResolveInfo cur = matches.get(i); 3400 final String packageName = cur.getComponentInfo().packageName; 3401 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 3402 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 3403 continue; 3404 } 3405 3406 if (best == null || cur.priority > best.priority) { 3407 best = cur; 3408 } 3409 } 3410 3411 if (best != null) { 3412 return best.getComponentInfo().getComponentName(); 3413 } 3414 Slog.w(TAG, "Intent filter verifier not found"); 3415 return null; 3416 } 3417 3418 @Override 3419 public @Nullable ComponentName getInstantAppResolverComponent() { 3420 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 3421 return null; 3422 } 3423 synchronized (mPackages) { 3424 final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr(); 3425 if (instantAppResolver == null) { 3426 return null; 3427 } 3428 return instantAppResolver.first; 3429 } 3430 } 3431 3432 private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() { 3433 final String[] packageArray = 3434 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 3435 if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) { 3436 if (DEBUG_EPHEMERAL) { 3437 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 3438 } 3439 return null; 3440 } 3441 3442 final int callingUid = Binder.getCallingUid(); 3443 final int resolveFlags = 3444 MATCH_DIRECT_BOOT_AWARE 3445 | MATCH_DIRECT_BOOT_UNAWARE 3446 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3447 String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE; 3448 final Intent resolverIntent = new Intent(actionName); 3449 List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 3450 resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/); 3451 // temporarily look for the old action 3452 if (resolvers.size() == 0) { 3453 if (DEBUG_EPHEMERAL) { 3454 Slog.d(TAG, "Ephemeral resolver not found with new action; try old one"); 3455 } 3456 actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE; 3457 resolverIntent.setAction(actionName); 3458 resolvers = queryIntentServicesInternal(resolverIntent, null, 3459 resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/); 3460 } 3461 final int N = resolvers.size(); 3462 if (N == 0) { 3463 if (DEBUG_EPHEMERAL) { 3464 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 3465 } 3466 return null; 3467 } 3468 3469 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 3470 for (int i = 0; i < N; i++) { 3471 final ResolveInfo info = resolvers.get(i); 3472 3473 if (info.serviceInfo == null) { 3474 continue; 3475 } 3476 3477 final String packageName = info.serviceInfo.packageName; 3478 if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) { 3479 if (DEBUG_EPHEMERAL) { 3480 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 3481 + " pkg: " + packageName + ", info:" + info); 3482 } 3483 continue; 3484 } 3485 3486 if (DEBUG_EPHEMERAL) { 3487 Slog.v(TAG, "Ephemeral resolver found;" 3488 + " pkg: " + packageName + ", info:" + info); 3489 } 3490 return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName); 3491 } 3492 if (DEBUG_EPHEMERAL) { 3493 Slog.v(TAG, "Ephemeral resolver NOT found"); 3494 } 3495 return null; 3496 } 3497 3498 private @Nullable ActivityInfo getInstantAppInstallerLPr() { 3499 final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE); 3500 intent.addCategory(Intent.CATEGORY_DEFAULT); 3501 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 3502 3503 final int resolveFlags = 3504 MATCH_DIRECT_BOOT_AWARE 3505 | MATCH_DIRECT_BOOT_UNAWARE 3506 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3507 List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3508 resolveFlags, UserHandle.USER_SYSTEM); 3509 // temporarily look for the old action 3510 if (matches.isEmpty()) { 3511 if (DEBUG_EPHEMERAL) { 3512 Slog.d(TAG, "Ephemeral installer not found with new action; try old one"); 3513 } 3514 intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 3515 matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3516 resolveFlags, UserHandle.USER_SYSTEM); 3517 } 3518 Iterator<ResolveInfo> iter = matches.iterator(); 3519 while (iter.hasNext()) { 3520 final ResolveInfo rInfo = iter.next(); 3521 final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName); 3522 if (ps != null) { 3523 final PermissionsState permissionsState = ps.getPermissionsState(); 3524 if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) { 3525 continue; 3526 } 3527 } 3528 iter.remove(); 3529 } 3530 if (matches.size() == 0) { 3531 return null; 3532 } else if (matches.size() == 1) { 3533 return (ActivityInfo) matches.get(0).getComponentInfo(); 3534 } else { 3535 throw new RuntimeException( 3536 "There must be at most one ephemeral installer; found " + matches); 3537 } 3538 } 3539 3540 private @Nullable ComponentName getInstantAppResolverSettingsLPr( 3541 @NonNull ComponentName resolver) { 3542 final Intent intent = new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS) 3543 .addCategory(Intent.CATEGORY_DEFAULT) 3544 .setPackage(resolver.getPackageName()); 3545 final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3546 List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags, 3547 UserHandle.USER_SYSTEM); 3548 // temporarily look for the old action 3549 if (matches.isEmpty()) { 3550 if (DEBUG_EPHEMERAL) { 3551 Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one"); 3552 } 3553 intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS); 3554 matches = queryIntentActivitiesInternal(intent, null, resolveFlags, 3555 UserHandle.USER_SYSTEM); 3556 } 3557 if (matches.isEmpty()) { 3558 return null; 3559 } 3560 return matches.get(0).getComponentInfo().getComponentName(); 3561 } 3562 3563 private void primeDomainVerificationsLPw(int userId) { 3564 if (DEBUG_DOMAIN_VERIFICATION) { 3565 Slog.d(TAG, "Priming domain verifications in user " + userId); 3566 } 3567 3568 SystemConfig systemConfig = SystemConfig.getInstance(); 3569 ArraySet<String> packages = systemConfig.getLinkedApps(); 3570 3571 for (String packageName : packages) { 3572 PackageParser.Package pkg = mPackages.get(packageName); 3573 if (pkg != null) { 3574 if (!pkg.isSystem()) { 3575 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 3576 continue; 3577 } 3578 3579 ArraySet<String> domains = null; 3580 for (PackageParser.Activity a : pkg.activities) { 3581 for (ActivityIntentInfo filter : a.intents) { 3582 if (hasValidDomains(filter)) { 3583 if (domains == null) { 3584 domains = new ArraySet<String>(); 3585 } 3586 domains.addAll(filter.getHostsList()); 3587 } 3588 } 3589 } 3590 3591 if (domains != null && domains.size() > 0) { 3592 if (DEBUG_DOMAIN_VERIFICATION) { 3593 Slog.v(TAG, " + " + packageName); 3594 } 3595 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 3596 // state w.r.t. the formal app-linkage "no verification attempted" state; 3597 // and then 'always' in the per-user state actually used for intent resolution. 3598 final IntentFilterVerificationInfo ivi; 3599 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains); 3600 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 3601 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 3602 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 3603 } else { 3604 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 3605 + "' does not handle web links"); 3606 } 3607 } else { 3608 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 3609 } 3610 } 3611 3612 scheduleWritePackageRestrictionsLocked(userId); 3613 scheduleWriteSettingsLocked(); 3614 } 3615 3616 private void applyFactoryDefaultBrowserLPw(int userId) { 3617 // The default browser app's package name is stored in a string resource, 3618 // with a product-specific overlay used for vendor customization. 3619 String browserPkg = mContext.getResources().getString( 3620 com.android.internal.R.string.default_browser); 3621 if (!TextUtils.isEmpty(browserPkg)) { 3622 // non-empty string => required to be a known package 3623 PackageSetting ps = mSettings.mPackages.get(browserPkg); 3624 if (ps == null) { 3625 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 3626 browserPkg = null; 3627 } else { 3628 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3629 } 3630 } 3631 3632 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3633 // default. If there's more than one, just leave everything alone. 3634 if (browserPkg == null) { 3635 calculateDefaultBrowserLPw(userId); 3636 } 3637 } 3638 3639 private void calculateDefaultBrowserLPw(int userId) { 3640 List<String> allBrowsers = resolveAllBrowserApps(userId); 3641 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3642 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3643 } 3644 3645 private List<String> resolveAllBrowserApps(int userId) { 3646 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3647 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3648 PackageManager.MATCH_ALL, userId); 3649 3650 final int count = list.size(); 3651 List<String> result = new ArrayList<String>(count); 3652 for (int i=0; i<count; i++) { 3653 ResolveInfo info = list.get(i); 3654 if (info.activityInfo == null 3655 || !info.handleAllWebDataURI 3656 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3657 || result.contains(info.activityInfo.packageName)) { 3658 continue; 3659 } 3660 result.add(info.activityInfo.packageName); 3661 } 3662 3663 return result; 3664 } 3665 3666 private boolean packageIsBrowser(String packageName, int userId) { 3667 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3668 PackageManager.MATCH_ALL, userId); 3669 final int N = list.size(); 3670 for (int i = 0; i < N; i++) { 3671 ResolveInfo info = list.get(i); 3672 if (info.priority >= 0 && packageName.equals(info.activityInfo.packageName)) { 3673 return true; 3674 } 3675 } 3676 return false; 3677 } 3678 3679 private void checkDefaultBrowser() { 3680 final int myUserId = UserHandle.myUserId(); 3681 final String packageName = getDefaultBrowserPackageName(myUserId); 3682 if (packageName != null) { 3683 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3684 if (info == null) { 3685 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3686 synchronized (mPackages) { 3687 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3688 } 3689 } 3690 } 3691 } 3692 3693 @Override 3694 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3695 throws RemoteException { 3696 try { 3697 return super.onTransact(code, data, reply, flags); 3698 } catch (RuntimeException e) { 3699 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3700 Slog.wtf(TAG, "Package Manager Crash", e); 3701 } 3702 throw e; 3703 } 3704 } 3705 3706 static int[] appendInts(int[] cur, int[] add) { 3707 if (add == null) return cur; 3708 if (cur == null) return add; 3709 final int N = add.length; 3710 for (int i=0; i<N; i++) { 3711 cur = appendInt(cur, add[i]); 3712 } 3713 return cur; 3714 } 3715 3716 /** 3717 * Returns whether or not a full application can see an instant application. 3718 * <p> 3719 * Currently, there are three cases in which this can occur: 3720 * <ol> 3721 * <li>The calling application is a "special" process. Special processes 3722 * are those with a UID < {@link Process#FIRST_APPLICATION_UID}.</li> 3723 * <li>The calling application has the permission 3724 * {@link android.Manifest.permission#ACCESS_INSTANT_APPS}.</li> 3725 * <li>The calling application is the default launcher on the 3726 * system partition.</li> 3727 * </ol> 3728 */ 3729 private boolean canViewInstantApps(int callingUid, int userId) { 3730 if (callingUid < Process.FIRST_APPLICATION_UID) { 3731 return true; 3732 } 3733 if (mContext.checkCallingOrSelfPermission( 3734 android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) { 3735 return true; 3736 } 3737 if (mContext.checkCallingOrSelfPermission( 3738 android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) { 3739 final ComponentName homeComponent = getDefaultHomeActivity(userId); 3740 if (homeComponent != null 3741 && isCallerSameApp(homeComponent.getPackageName(), callingUid)) { 3742 return true; 3743 } 3744 } 3745 return false; 3746 } 3747 3748 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3749 if (!sUserManager.exists(userId)) return null; 3750 if (ps == null) { 3751 return null; 3752 } 3753 PackageParser.Package p = ps.pkg; 3754 if (p == null) { 3755 return null; 3756 } 3757 final int callingUid = Binder.getCallingUid(); 3758 // Filter out ephemeral app metadata: 3759 // * The system/shell/root can see metadata for any app 3760 // * An installed app can see metadata for 1) other installed apps 3761 // and 2) ephemeral apps that have explicitly interacted with it 3762 // * Ephemeral apps can only see their own data and exposed installed apps 3763 // * Holding a signature permission allows seeing instant apps 3764 if (filterAppAccessLPr(ps, callingUid, userId)) { 3765 return null; 3766 } 3767 3768 final PermissionsState permissionsState = ps.getPermissionsState(); 3769 3770 // Compute GIDs only if requested 3771 final int[] gids = (flags & PackageManager.GET_GIDS) == 0 3772 ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId); 3773 // Compute granted permissions only if package has requested permissions 3774 final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions) 3775 ? Collections.<String>emptySet() : permissionsState.getPermissions(userId); 3776 final PackageUserState state = ps.readUserState(userId); 3777 3778 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0 3779 && ps.isSystem()) { 3780 flags |= MATCH_ANY_USER; 3781 } 3782 3783 PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags, 3784 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3785 3786 if (packageInfo == null) { 3787 return null; 3788 } 3789 3790 packageInfo.packageName = packageInfo.applicationInfo.packageName = 3791 resolveExternalPackageNameLPr(p); 3792 3793 return packageInfo; 3794 } 3795 3796 @Override 3797 public void checkPackageStartable(String packageName, int userId) { 3798 final int callingUid = Binder.getCallingUid(); 3799 if (getInstantAppPackageName(callingUid) != null) { 3800 throw new SecurityException("Instant applications don't have access to this method"); 3801 } 3802 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3803 synchronized (mPackages) { 3804 final PackageSetting ps = mSettings.mPackages.get(packageName); 3805 if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) { 3806 throw new SecurityException("Package " + packageName + " was not found!"); 3807 } 3808 3809 if (!ps.getInstalled(userId)) { 3810 throw new SecurityException( 3811 "Package " + packageName + " was not installed for user " + userId + "!"); 3812 } 3813 3814 if (mSafeMode && !ps.isSystem()) { 3815 throw new SecurityException("Package " + packageName + " not a system app!"); 3816 } 3817 3818 if (mFrozenPackages.contains(packageName)) { 3819 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3820 } 3821 3822 if (!userKeyUnlocked && !ps.pkg.applicationInfo.isEncryptionAware()) { 3823 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3824 } 3825 } 3826 } 3827 3828 @Override 3829 public boolean isPackageAvailable(String packageName, int userId) { 3830 if (!sUserManager.exists(userId)) return false; 3831 final int callingUid = Binder.getCallingUid(); 3832 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 3833 false /*requireFullPermission*/, false /*checkShell*/, "is package available"); 3834 synchronized (mPackages) { 3835 PackageParser.Package p = mPackages.get(packageName); 3836 if (p != null) { 3837 final PackageSetting ps = (PackageSetting) p.mExtras; 3838 if (filterAppAccessLPr(ps, callingUid, userId)) { 3839 return false; 3840 } 3841 if (ps != null) { 3842 final PackageUserState state = ps.readUserState(userId); 3843 if (state != null) { 3844 return PackageParser.isAvailable(state); 3845 } 3846 } 3847 } 3848 } 3849 return false; 3850 } 3851 3852 @Override 3853 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3854 return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST, 3855 flags, Binder.getCallingUid(), userId); 3856 } 3857 3858 @Override 3859 public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage, 3860 int flags, int userId) { 3861 return getPackageInfoInternal(versionedPackage.getPackageName(), 3862 versionedPackage.getVersionCode(), flags, Binder.getCallingUid(), userId); 3863 } 3864 3865 /** 3866 * Important: The provided filterCallingUid is used exclusively to filter out packages 3867 * that can be seen based on user state. It's typically the original caller uid prior 3868 * to clearing. Because it can only be provided by trusted code, it's value can be 3869 * trusted and will be used as-is; unlike userId which will be validated by this method. 3870 */ 3871 private PackageInfo getPackageInfoInternal(String packageName, int versionCode, 3872 int flags, int filterCallingUid, int userId) { 3873 if (!sUserManager.exists(userId)) return null; 3874 flags = updateFlagsForPackage(flags, userId, packageName); 3875 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 3876 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3877 3878 // reader 3879 synchronized (mPackages) { 3880 // Normalize package name to handle renamed packages and static libs 3881 packageName = resolveInternalPackageNameLPr(packageName, versionCode); 3882 3883 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3884 if (matchFactoryOnly) { 3885 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3886 if (ps != null) { 3887 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 3888 return null; 3889 } 3890 if (filterAppAccessLPr(ps, filterCallingUid, userId)) { 3891 return null; 3892 } 3893 return generatePackageInfo(ps, flags, userId); 3894 } 3895 } 3896 3897 PackageParser.Package p = mPackages.get(packageName); 3898 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3899 return null; 3900 } 3901 if (DEBUG_PACKAGE_INFO) 3902 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3903 if (p != null) { 3904 final PackageSetting ps = (PackageSetting) p.mExtras; 3905 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 3906 return null; 3907 } 3908 if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) { 3909 return null; 3910 } 3911 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3912 } 3913 if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) { 3914 final PackageSetting ps = mSettings.mPackages.get(packageName); 3915 if (ps == null) return null; 3916 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 3917 return null; 3918 } 3919 if (filterAppAccessLPr(ps, filterCallingUid, userId)) { 3920 return null; 3921 } 3922 return generatePackageInfo(ps, flags, userId); 3923 } 3924 } 3925 return null; 3926 } 3927 3928 private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) { 3929 if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) { 3930 return true; 3931 } 3932 if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) { 3933 return true; 3934 } 3935 if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) { 3936 return true; 3937 } 3938 return false; 3939 } 3940 3941 private boolean isComponentVisibleToInstantApp( 3942 @Nullable ComponentName component, @ComponentType int type) { 3943 if (type == TYPE_ACTIVITY) { 3944 final PackageParser.Activity activity = mActivities.mActivities.get(component); 3945 return activity != null 3946 ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0 3947 : false; 3948 } else if (type == TYPE_RECEIVER) { 3949 final PackageParser.Activity activity = mReceivers.mActivities.get(component); 3950 return activity != null 3951 ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0 3952 : false; 3953 } else if (type == TYPE_SERVICE) { 3954 final PackageParser.Service service = mServices.mServices.get(component); 3955 return service != null 3956 ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0 3957 : false; 3958 } else if (type == TYPE_PROVIDER) { 3959 final PackageParser.Provider provider = mProviders.mProviders.get(component); 3960 return provider != null 3961 ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0 3962 : false; 3963 } else if (type == TYPE_UNKNOWN) { 3964 return isComponentVisibleToInstantApp(component); 3965 } 3966 return false; 3967 } 3968 3969 /** 3970 * Returns whether or not access to the application should be filtered. 3971 * <p> 3972 * Access may be limited based upon whether the calling or target applications 3973 * are instant applications. 3974 * 3975 * @see #canAccessInstantApps(int) 3976 */ 3977 private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, 3978 @Nullable ComponentName component, @ComponentType int componentType, int userId) { 3979 // if we're in an isolated process, get the real calling UID 3980 if (Process.isIsolated(callingUid)) { 3981 callingUid = mIsolatedOwners.get(callingUid); 3982 } 3983 final String instantAppPkgName = getInstantAppPackageName(callingUid); 3984 final boolean callerIsInstantApp = instantAppPkgName != null; 3985 if (ps == null) { 3986 if (callerIsInstantApp) { 3987 // pretend the application exists, but, needs to be filtered 3988 return true; 3989 } 3990 return false; 3991 } 3992 // if the target and caller are the same application, don't filter 3993 if (isCallerSameApp(ps.name, callingUid)) { 3994 return false; 3995 } 3996 if (callerIsInstantApp) { 3997 // request for a specific component; if it hasn't been explicitly exposed, filter 3998 if (component != null) { 3999 return !isComponentVisibleToInstantApp(component, componentType); 4000 } 4001 // request for application; if no components have been explicitly exposed, filter 4002 return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps; 4003 } 4004 if (ps.getInstantApp(userId)) { 4005 // caller can see all components of all instant applications, don't filter 4006 if (canViewInstantApps(callingUid, userId)) { 4007 return false; 4008 } 4009 // request for a specific instant application component, filter 4010 if (component != null) { 4011 return true; 4012 } 4013 // request for an instant application; if the caller hasn't been granted access, filter 4014 return !mInstantAppRegistry.isInstantAccessGranted( 4015 userId, UserHandle.getAppId(callingUid), ps.appId); 4016 } 4017 return false; 4018 } 4019 4020 /** 4021 * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int) 4022 */ 4023 private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) { 4024 return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId); 4025 } 4026 4027 private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId, 4028 int flags) { 4029 // Callers can access only the libs they depend on, otherwise they need to explicitly 4030 // ask for the shared libraries given the caller is allowed to access all static libs. 4031 if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) { 4032 // System/shell/root get to see all static libs 4033 final int appId = UserHandle.getAppId(uid); 4034 if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID 4035 || appId == Process.ROOT_UID) { 4036 return false; 4037 } 4038 } 4039 4040 // No package means no static lib as it is always on internal storage 4041 if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) { 4042 return false; 4043 } 4044 4045 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName, 4046 ps.pkg.staticSharedLibVersion); 4047 if (libEntry == null) { 4048 return false; 4049 } 4050 4051 final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid)); 4052 final String[] uidPackageNames = getPackagesForUid(resolvedUid); 4053 if (uidPackageNames == null) { 4054 return true; 4055 } 4056 4057 for (String uidPackageName : uidPackageNames) { 4058 if (ps.name.equals(uidPackageName)) { 4059 return false; 4060 } 4061 PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName); 4062 if (uidPs != null) { 4063 final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries, 4064 libEntry.info.getName()); 4065 if (index < 0) { 4066 continue; 4067 } 4068 if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) { 4069 return false; 4070 } 4071 } 4072 } 4073 return true; 4074 } 4075 4076 @Override 4077 public String[] currentToCanonicalPackageNames(String[] names) { 4078 final int callingUid = Binder.getCallingUid(); 4079 if (getInstantAppPackageName(callingUid) != null) { 4080 return names; 4081 } 4082 final String[] out = new String[names.length]; 4083 // reader 4084 synchronized (mPackages) { 4085 final int callingUserId = UserHandle.getUserId(callingUid); 4086 final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId); 4087 for (int i=names.length-1; i>=0; i--) { 4088 final PackageSetting ps = mSettings.mPackages.get(names[i]); 4089 boolean translateName = false; 4090 if (ps != null && ps.realName != null) { 4091 final boolean targetIsInstantApp = ps.getInstantApp(callingUserId); 4092 translateName = !targetIsInstantApp 4093 || canViewInstantApps 4094 || mInstantAppRegistry.isInstantAccessGranted(callingUserId, 4095 UserHandle.getAppId(callingUid), ps.appId); 4096 } 4097 out[i] = translateName ? ps.realName : names[i]; 4098 } 4099 } 4100 return out; 4101 } 4102 4103 @Override 4104 public String[] canonicalToCurrentPackageNames(String[] names) { 4105 final int callingUid = Binder.getCallingUid(); 4106 if (getInstantAppPackageName(callingUid) != null) { 4107 return names; 4108 } 4109 final String[] out = new String[names.length]; 4110 // reader 4111 synchronized (mPackages) { 4112 final int callingUserId = UserHandle.getUserId(callingUid); 4113 final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId); 4114 for (int i=names.length-1; i>=0; i--) { 4115 final String cur = mSettings.getRenamedPackageLPr(names[i]); 4116 boolean translateName = false; 4117 if (cur != null) { 4118 final PackageSetting ps = mSettings.mPackages.get(names[i]); 4119 final boolean targetIsInstantApp = 4120 ps != null && ps.getInstantApp(callingUserId); 4121 translateName = !targetIsInstantApp 4122 || canViewInstantApps 4123 || mInstantAppRegistry.isInstantAccessGranted(callingUserId, 4124 UserHandle.getAppId(callingUid), ps.appId); 4125 } 4126 out[i] = translateName ? cur : names[i]; 4127 } 4128 } 4129 return out; 4130 } 4131 4132 @Override 4133 public int getPackageUid(String packageName, int flags, int userId) { 4134 if (!sUserManager.exists(userId)) return -1; 4135 final int callingUid = Binder.getCallingUid(); 4136 flags = updateFlagsForPackage(flags, userId, packageName); 4137 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 4138 false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid"); 4139 4140 // reader 4141 synchronized (mPackages) { 4142 final PackageParser.Package p = mPackages.get(packageName); 4143 if (p != null && p.isMatch(flags)) { 4144 PackageSetting ps = (PackageSetting) p.mExtras; 4145 if (filterAppAccessLPr(ps, callingUid, userId)) { 4146 return -1; 4147 } 4148 return UserHandle.getUid(userId, p.applicationInfo.uid); 4149 } 4150 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 4151 final PackageSetting ps = mSettings.mPackages.get(packageName); 4152 if (ps != null && ps.isMatch(flags) 4153 && !filterAppAccessLPr(ps, callingUid, userId)) { 4154 return UserHandle.getUid(userId, ps.appId); 4155 } 4156 } 4157 } 4158 4159 return -1; 4160 } 4161 4162 @Override 4163 public int[] getPackageGids(String packageName, int flags, int userId) { 4164 if (!sUserManager.exists(userId)) return null; 4165 final int callingUid = Binder.getCallingUid(); 4166 flags = updateFlagsForPackage(flags, userId, packageName); 4167 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 4168 false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids"); 4169 4170 // reader 4171 synchronized (mPackages) { 4172 final PackageParser.Package p = mPackages.get(packageName); 4173 if (p != null && p.isMatch(flags)) { 4174 PackageSetting ps = (PackageSetting) p.mExtras; 4175 if (filterAppAccessLPr(ps, callingUid, userId)) { 4176 return null; 4177 } 4178 // TODO: Shouldn't this be checking for package installed state for userId and 4179 // return null? 4180 return ps.getPermissionsState().computeGids(userId); 4181 } 4182 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 4183 final PackageSetting ps = mSettings.mPackages.get(packageName); 4184 if (ps != null && ps.isMatch(flags) 4185 && !filterAppAccessLPr(ps, callingUid, userId)) { 4186 return ps.getPermissionsState().computeGids(userId); 4187 } 4188 } 4189 } 4190 4191 return null; 4192 } 4193 4194 @Override 4195 public PermissionInfo getPermissionInfo(String name, String packageName, int flags) { 4196 return mPermissionManager.getPermissionInfo(name, packageName, flags, getCallingUid()); 4197 } 4198 4199 @Override 4200 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String groupName, 4201 int flags) { 4202 final List<PermissionInfo> permissionList = 4203 mPermissionManager.getPermissionInfoByGroup(groupName, flags, getCallingUid()); 4204 return (permissionList == null) ? null : new ParceledListSlice<>(permissionList); 4205 } 4206 4207 @Override 4208 public PermissionGroupInfo getPermissionGroupInfo(String groupName, int flags) { 4209 return mPermissionManager.getPermissionGroupInfo(groupName, flags, getCallingUid()); 4210 } 4211 4212 @Override 4213 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 4214 final List<PermissionGroupInfo> permissionList = 4215 mPermissionManager.getAllPermissionGroups(flags, getCallingUid()); 4216 return (permissionList == null) 4217 ? ParceledListSlice.emptyList() : new ParceledListSlice<>(permissionList); 4218 } 4219 4220 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 4221 int filterCallingUid, int userId) { 4222 if (!sUserManager.exists(userId)) return null; 4223 PackageSetting ps = mSettings.mPackages.get(packageName); 4224 if (ps != null) { 4225 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 4226 return null; 4227 } 4228 if (filterAppAccessLPr(ps, filterCallingUid, userId)) { 4229 return null; 4230 } 4231 if (ps.pkg == null) { 4232 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 4233 if (pInfo != null) { 4234 return pInfo.applicationInfo; 4235 } 4236 return null; 4237 } 4238 ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 4239 ps.readUserState(userId), userId); 4240 if (ai != null) { 4241 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 4242 } 4243 return ai; 4244 } 4245 return null; 4246 } 4247 4248 @Override 4249 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 4250 return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId); 4251 } 4252 4253 /** 4254 * Important: The provided filterCallingUid is used exclusively to filter out applications 4255 * that can be seen based on user state. It's typically the original caller uid prior 4256 * to clearing. Because it can only be provided by trusted code, it's value can be 4257 * trusted and will be used as-is; unlike userId which will be validated by this method. 4258 */ 4259 private ApplicationInfo getApplicationInfoInternal(String packageName, int flags, 4260 int filterCallingUid, int userId) { 4261 if (!sUserManager.exists(userId)) return null; 4262 flags = updateFlagsForApplication(flags, userId, packageName); 4263 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 4264 false /* requireFullPermission */, false /* checkShell */, "get application info"); 4265 4266 // writer 4267 synchronized (mPackages) { 4268 // Normalize package name to handle renamed packages and static libs 4269 packageName = resolveInternalPackageNameLPr(packageName, 4270 PackageManager.VERSION_CODE_HIGHEST); 4271 4272 PackageParser.Package p = mPackages.get(packageName); 4273 if (DEBUG_PACKAGE_INFO) Log.v( 4274 TAG, "getApplicationInfo " + packageName 4275 + ": " + p); 4276 if (p != null) { 4277 PackageSetting ps = mSettings.mPackages.get(packageName); 4278 if (ps == null) return null; 4279 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 4280 return null; 4281 } 4282 if (filterAppAccessLPr(ps, filterCallingUid, userId)) { 4283 return null; 4284 } 4285 // Note: isEnabledLP() does not apply here - always return info 4286 ApplicationInfo ai = PackageParser.generateApplicationInfo( 4287 p, flags, ps.readUserState(userId), userId); 4288 if (ai != null) { 4289 ai.packageName = resolveExternalPackageNameLPr(p); 4290 } 4291 return ai; 4292 } 4293 if ("android".equals(packageName)||"system".equals(packageName)) { 4294 return mAndroidApplication; 4295 } 4296 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 4297 // Already generates the external package name 4298 return generateApplicationInfoFromSettingsLPw(packageName, 4299 flags, filterCallingUid, userId); 4300 } 4301 } 4302 return null; 4303 } 4304 4305 private String normalizePackageNameLPr(String packageName) { 4306 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 4307 return normalizedPackageName != null ? normalizedPackageName : packageName; 4308 } 4309 4310 @Override 4311 public void deletePreloadsFileCache() { 4312 if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) { 4313 throw new SecurityException("Only system or settings may call deletePreloadsFileCache"); 4314 } 4315 File dir = Environment.getDataPreloadsFileCacheDirectory(); 4316 Slog.i(TAG, "Deleting preloaded file cache " + dir); 4317 FileUtils.deleteContents(dir); 4318 } 4319 4320 @Override 4321 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 4322 final int storageFlags, final IPackageDataObserver observer) { 4323 mContext.enforceCallingOrSelfPermission( 4324 android.Manifest.permission.CLEAR_APP_CACHE, null); 4325 mHandler.post(() -> { 4326 boolean success = false; 4327 try { 4328 freeStorage(volumeUuid, freeStorageSize, storageFlags); 4329 success = true; 4330 } catch (IOException e) { 4331 Slog.w(TAG, e); 4332 } 4333 if (observer != null) { 4334 try { 4335 observer.onRemoveCompleted(null, success); 4336 } catch (RemoteException e) { 4337 Slog.w(TAG, e); 4338 } 4339 } 4340 }); 4341 } 4342 4343 @Override 4344 public void freeStorage(final String volumeUuid, final long freeStorageSize, 4345 final int storageFlags, final IntentSender pi) { 4346 mContext.enforceCallingOrSelfPermission( 4347 android.Manifest.permission.CLEAR_APP_CACHE, TAG); 4348 mHandler.post(() -> { 4349 boolean success = false; 4350 try { 4351 freeStorage(volumeUuid, freeStorageSize, storageFlags); 4352 success = true; 4353 } catch (IOException e) { 4354 Slog.w(TAG, e); 4355 } 4356 if (pi != null) { 4357 try { 4358 pi.sendIntent(null, success ? 1 : 0, null, null, null); 4359 } catch (SendIntentException e) { 4360 Slog.w(TAG, e); 4361 } 4362 } 4363 }); 4364 } 4365 4366 /** 4367 * Blocking call to clear various types of cached data across the system 4368 * until the requested bytes are available. 4369 */ 4370 public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException { 4371 final StorageManager storage = mContext.getSystemService(StorageManager.class); 4372 final File file = storage.findPathForUuid(volumeUuid); 4373 if (file.getUsableSpace() >= bytes) return; 4374 4375 if (ENABLE_FREE_CACHE_V2) { 4376 final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, 4377 volumeUuid); 4378 final boolean aggressive = (storageFlags 4379 & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0; 4380 final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags); 4381 4382 // 1. Pre-flight to determine if we have any chance to succeed 4383 // 2. Consider preloaded data (after 1w honeymoon, unless aggressive) 4384 if (internalVolume && (aggressive || SystemProperties 4385 .getBoolean("persist.sys.preloads.file_cache_expired", false))) { 4386 deletePreloadsFileCache(); 4387 if (file.getUsableSpace() >= bytes) return; 4388 } 4389 4390 // 3. Consider parsed APK data (aggressive only) 4391 if (internalVolume && aggressive) { 4392 FileUtils.deleteContents(mCacheDir); 4393 if (file.getUsableSpace() >= bytes) return; 4394 } 4395 4396 // 4. Consider cached app data (above quotas) 4397 try { 4398 mInstaller.freeCache(volumeUuid, bytes, reservedBytes, 4399 Installer.FLAG_FREE_CACHE_V2); 4400 } catch (InstallerException ignored) { 4401 } 4402 if (file.getUsableSpace() >= bytes) return; 4403 4404 // 5. Consider shared libraries with refcount=0 and age>min cache period 4405 if (internalVolume && pruneUnusedStaticSharedLibraries(bytes, 4406 android.provider.Settings.Global.getLong(mContext.getContentResolver(), 4407 Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD, 4408 DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) { 4409 return; 4410 } 4411 4412 // 6. Consider dexopt output (aggressive only) 4413 // TODO: Implement 4414 4415 // 7. Consider installed instant apps unused longer than min cache period 4416 if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes, 4417 android.provider.Settings.Global.getLong(mContext.getContentResolver(), 4418 Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD, 4419 InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) { 4420 return; 4421 } 4422 4423 // 8. Consider cached app data (below quotas) 4424 try { 4425 mInstaller.freeCache(volumeUuid, bytes, reservedBytes, 4426 Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA); 4427 } catch (InstallerException ignored) { 4428 } 4429 if (file.getUsableSpace() >= bytes) return; 4430 4431 // 9. Consider DropBox entries 4432 // TODO: Implement 4433 4434 // 10. Consider instant meta-data (uninstalled apps) older that min cache period 4435 if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes, 4436 android.provider.Settings.Global.getLong(mContext.getContentResolver(), 4437 Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD, 4438 InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) { 4439 return; 4440 } 4441 } else { 4442 try { 4443 mInstaller.freeCache(volumeUuid, bytes, 0, 0); 4444 } catch (InstallerException ignored) { 4445 } 4446 if (file.getUsableSpace() >= bytes) return; 4447 } 4448 4449 throw new IOException("Failed to free " + bytes + " on storage device at " + file); 4450 } 4451 4452 private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod) 4453 throws IOException { 4454 final StorageManager storage = mContext.getSystemService(StorageManager.class); 4455 final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL); 4456 4457 List<VersionedPackage> packagesToDelete = null; 4458 final long now = System.currentTimeMillis(); 4459 4460 synchronized (mPackages) { 4461 final int[] allUsers = sUserManager.getUserIds(); 4462 final int libCount = mSharedLibraries.size(); 4463 for (int i = 0; i < libCount; i++) { 4464 final SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 4465 if (versionedLib == null) { 4466 continue; 4467 } 4468 final int versionCount = versionedLib.size(); 4469 for (int j = 0; j < versionCount; j++) { 4470 SharedLibraryInfo libInfo = versionedLib.valueAt(j).info; 4471 // Skip packages that are not static shared libs. 4472 if (!libInfo.isStatic()) { 4473 break; 4474 } 4475 // Important: We skip static shared libs used for some user since 4476 // in such a case we need to keep the APK on the device. The check for 4477 // a lib being used for any user is performed by the uninstall call. 4478 final VersionedPackage declaringPackage = libInfo.getDeclaringPackage(); 4479 // Resolve the package name - we use synthetic package names internally 4480 final String internalPackageName = resolveInternalPackageNameLPr( 4481 declaringPackage.getPackageName(), declaringPackage.getVersionCode()); 4482 final PackageSetting ps = mSettings.getPackageLPr(internalPackageName); 4483 // Skip unused static shared libs cached less than the min period 4484 // to prevent pruning a lib needed by a subsequently installed package. 4485 if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) { 4486 continue; 4487 } 4488 if (packagesToDelete == null) { 4489 packagesToDelete = new ArrayList<>(); 4490 } 4491 packagesToDelete.add(new VersionedPackage(internalPackageName, 4492 declaringPackage.getVersionCode())); 4493 } 4494 } 4495 } 4496 4497 if (packagesToDelete != null) { 4498 final int packageCount = packagesToDelete.size(); 4499 for (int i = 0; i < packageCount; i++) { 4500 final VersionedPackage pkgToDelete = packagesToDelete.get(i); 4501 // Delete the package synchronously (will fail of the lib used for any user). 4502 if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getVersionCode(), 4503 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS) 4504 == PackageManager.DELETE_SUCCEEDED) { 4505 if (volume.getUsableSpace() >= neededSpace) { 4506 return true; 4507 } 4508 } 4509 } 4510 } 4511 4512 return false; 4513 } 4514 4515 /** 4516 * Update given flags based on encryption status of current user. 4517 */ 4518 private int updateFlags(int flags, int userId) { 4519 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 4520 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 4521 // Caller expressed an explicit opinion about what encryption 4522 // aware/unaware components they want to see, so fall through and 4523 // give them what they want 4524 } else { 4525 // Caller expressed no opinion, so match based on user state 4526 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 4527 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 4528 } else { 4529 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 4530 } 4531 } 4532 return flags; 4533 } 4534 4535 private UserManagerInternal getUserManagerInternal() { 4536 if (mUserManagerInternal == null) { 4537 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 4538 } 4539 return mUserManagerInternal; 4540 } 4541 4542 private DeviceIdleController.LocalService getDeviceIdleController() { 4543 if (mDeviceIdleController == null) { 4544 mDeviceIdleController = 4545 LocalServices.getService(DeviceIdleController.LocalService.class); 4546 } 4547 return mDeviceIdleController; 4548 } 4549 4550 /** 4551 * Update given flags when being used to request {@link PackageInfo}. 4552 */ 4553 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 4554 final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM; 4555 boolean triaged = true; 4556 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 4557 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 4558 // Caller is asking for component details, so they'd better be 4559 // asking for specific encryption matching behavior, or be triaged 4560 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 4561 | PackageManager.MATCH_DIRECT_BOOT_AWARE 4562 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 4563 triaged = false; 4564 } 4565 } 4566 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 4567 | PackageManager.MATCH_SYSTEM_ONLY 4568 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 4569 triaged = false; 4570 } 4571 if ((flags & PackageManager.MATCH_ANY_USER) != 0) { 4572 mPermissionManager.enforceCrossUserPermission( 4573 Binder.getCallingUid(), userId, false, false, 4574 "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at " 4575 + Debug.getCallers(5)); 4576 } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser 4577 && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) { 4578 // If the caller wants all packages and has a restricted profile associated with it, 4579 // then match all users. This is to make sure that launchers that need to access work 4580 // profile apps don't start breaking. TODO: Remove this hack when launchers stop using 4581 // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380 4582 flags |= PackageManager.MATCH_ANY_USER; 4583 } 4584 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 4585 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 4586 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 4587 } 4588 return updateFlags(flags, userId); 4589 } 4590 4591 /** 4592 * Update given flags when being used to request {@link ApplicationInfo}. 4593 */ 4594 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 4595 return updateFlagsForPackage(flags, userId, cookie); 4596 } 4597 4598 /** 4599 * Update given flags when being used to request {@link ComponentInfo}. 4600 */ 4601 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 4602 if (cookie instanceof Intent) { 4603 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 4604 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 4605 } 4606 } 4607 4608 boolean triaged = true; 4609 // Caller is asking for component details, so they'd better be 4610 // asking for specific encryption matching behavior, or be triaged 4611 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 4612 | PackageManager.MATCH_DIRECT_BOOT_AWARE 4613 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 4614 triaged = false; 4615 } 4616 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 4617 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 4618 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 4619 } 4620 4621 return updateFlags(flags, userId); 4622 } 4623 4624 /** 4625 * Update given intent when being used to request {@link ResolveInfo}. 4626 */ 4627 private Intent updateIntentForResolve(Intent intent) { 4628 if (intent.getSelector() != null) { 4629 intent = intent.getSelector(); 4630 } 4631 if (DEBUG_PREFERRED) { 4632 intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4633 } 4634 return intent; 4635 } 4636 4637 /** 4638 * Update given flags when being used to request {@link ResolveInfo}. 4639 * <p>Instant apps are resolved specially, depending upon context. Minimally, 4640 * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT} 4641 * flag set. However, this flag is only honoured in three circumstances: 4642 * <ul> 4643 * <li>when called from a system process</li> 4644 * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li> 4645 * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW} 4646 * action and a {@code android.intent.category.BROWSABLE} category</li> 4647 * </ul> 4648 */ 4649 int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) { 4650 return updateFlagsForResolve(flags, userId, intent, callingUid, 4651 false /*wantInstantApps*/, false /*onlyExposedExplicitly*/); 4652 } 4653 int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid, 4654 boolean wantInstantApps) { 4655 return updateFlagsForResolve(flags, userId, intent, callingUid, 4656 wantInstantApps, false /*onlyExposedExplicitly*/); 4657 } 4658 int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid, 4659 boolean wantInstantApps, boolean onlyExposedExplicitly) { 4660 // Safe mode means we shouldn't match any third-party components 4661 if (mSafeMode) { 4662 flags |= PackageManager.MATCH_SYSTEM_ONLY; 4663 } 4664 if (getInstantAppPackageName(callingUid) != null) { 4665 // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components 4666 if (onlyExposedExplicitly) { 4667 flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY; 4668 } 4669 flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY; 4670 flags |= PackageManager.MATCH_INSTANT; 4671 } else { 4672 final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0; 4673 final boolean allowMatchInstant = 4674 (wantInstantApps 4675 && Intent.ACTION_VIEW.equals(intent.getAction()) 4676 && hasWebURI(intent)) 4677 || (wantMatchInstant && canViewInstantApps(callingUid, userId)); 4678 flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY 4679 | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY); 4680 if (!allowMatchInstant) { 4681 flags &= ~PackageManager.MATCH_INSTANT; 4682 } 4683 } 4684 return updateFlagsForComponent(flags, userId, intent /*cookie*/); 4685 } 4686 4687 @Override 4688 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 4689 return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId); 4690 } 4691 4692 /** 4693 * Important: The provided filterCallingUid is used exclusively to filter out activities 4694 * that can be seen based on user state. It's typically the original caller uid prior 4695 * to clearing. Because it can only be provided by trusted code, it's value can be 4696 * trusted and will be used as-is; unlike userId which will be validated by this method. 4697 */ 4698 private ActivityInfo getActivityInfoInternal(ComponentName component, int flags, 4699 int filterCallingUid, int userId) { 4700 if (!sUserManager.exists(userId)) return null; 4701 flags = updateFlagsForComponent(flags, userId, component); 4702 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 4703 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 4704 synchronized (mPackages) { 4705 PackageParser.Activity a = mActivities.mActivities.get(component); 4706 4707 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 4708 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 4709 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4710 if (ps == null) return null; 4711 if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) { 4712 return null; 4713 } 4714 return PackageParser.generateActivityInfo( 4715 a, flags, ps.readUserState(userId), userId); 4716 } 4717 if (mResolveComponentName.equals(component)) { 4718 return PackageParser.generateActivityInfo( 4719 mResolveActivity, flags, new PackageUserState(), userId); 4720 } 4721 } 4722 return null; 4723 } 4724 4725 @Override 4726 public boolean activitySupportsIntent(ComponentName component, Intent intent, 4727 String resolvedType) { 4728 synchronized (mPackages) { 4729 if (component.equals(mResolveComponentName)) { 4730 // The resolver supports EVERYTHING! 4731 return true; 4732 } 4733 final int callingUid = Binder.getCallingUid(); 4734 final int callingUserId = UserHandle.getUserId(callingUid); 4735 PackageParser.Activity a = mActivities.mActivities.get(component); 4736 if (a == null) { 4737 return false; 4738 } 4739 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4740 if (ps == null) { 4741 return false; 4742 } 4743 if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) { 4744 return false; 4745 } 4746 for (int i=0; i<a.intents.size(); i++) { 4747 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 4748 intent.getData(), intent.getCategories(), TAG) >= 0) { 4749 return true; 4750 } 4751 } 4752 return false; 4753 } 4754 } 4755 4756 @Override 4757 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 4758 if (!sUserManager.exists(userId)) return null; 4759 final int callingUid = Binder.getCallingUid(); 4760 flags = updateFlagsForComponent(flags, userId, component); 4761 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 4762 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 4763 synchronized (mPackages) { 4764 PackageParser.Activity a = mReceivers.mActivities.get(component); 4765 if (DEBUG_PACKAGE_INFO) Log.v( 4766 TAG, "getReceiverInfo " + component + ": " + a); 4767 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 4768 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4769 if (ps == null) return null; 4770 if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) { 4771 return null; 4772 } 4773 return PackageParser.generateActivityInfo( 4774 a, flags, ps.readUserState(userId), userId); 4775 } 4776 } 4777 return null; 4778 } 4779 4780 @Override 4781 public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName, 4782 int flags, int userId) { 4783 if (!sUserManager.exists(userId)) return null; 4784 Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0"); 4785 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 4786 return null; 4787 } 4788 4789 flags = updateFlagsForPackage(flags, userId, null); 4790 4791 final boolean canSeeStaticLibraries = 4792 mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES) 4793 == PERMISSION_GRANTED 4794 || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES) 4795 == PERMISSION_GRANTED 4796 || canRequestPackageInstallsInternal(packageName, 4797 PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId, 4798 false /* throwIfPermNotDeclared*/) 4799 || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES) 4800 == PERMISSION_GRANTED; 4801 4802 synchronized (mPackages) { 4803 List<SharedLibraryInfo> result = null; 4804 4805 final int libCount = mSharedLibraries.size(); 4806 for (int i = 0; i < libCount; i++) { 4807 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 4808 if (versionedLib == null) { 4809 continue; 4810 } 4811 4812 final int versionCount = versionedLib.size(); 4813 for (int j = 0; j < versionCount; j++) { 4814 SharedLibraryInfo libInfo = versionedLib.valueAt(j).info; 4815 if (!canSeeStaticLibraries && libInfo.isStatic()) { 4816 break; 4817 } 4818 final long identity = Binder.clearCallingIdentity(); 4819 try { 4820 PackageInfo packageInfo = getPackageInfoVersioned( 4821 libInfo.getDeclaringPackage(), flags 4822 | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId); 4823 if (packageInfo == null) { 4824 continue; 4825 } 4826 } finally { 4827 Binder.restoreCallingIdentity(identity); 4828 } 4829 4830 SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(), 4831 libInfo.getVersion(), libInfo.getType(), 4832 libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo, 4833 flags, userId)); 4834 4835 if (result == null) { 4836 result = new ArrayList<>(); 4837 } 4838 result.add(resLibInfo); 4839 } 4840 } 4841 4842 return result != null ? new ParceledListSlice<>(result) : null; 4843 } 4844 } 4845 4846 private List<VersionedPackage> getPackagesUsingSharedLibraryLPr( 4847 SharedLibraryInfo libInfo, int flags, int userId) { 4848 List<VersionedPackage> versionedPackages = null; 4849 final int packageCount = mSettings.mPackages.size(); 4850 for (int i = 0; i < packageCount; i++) { 4851 PackageSetting ps = mSettings.mPackages.valueAt(i); 4852 4853 if (ps == null) { 4854 continue; 4855 } 4856 4857 if (!ps.getUserState().get(userId).isAvailable(flags)) { 4858 continue; 4859 } 4860 4861 final String libName = libInfo.getName(); 4862 if (libInfo.isStatic()) { 4863 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 4864 if (libIdx < 0) { 4865 continue; 4866 } 4867 if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) { 4868 continue; 4869 } 4870 if (versionedPackages == null) { 4871 versionedPackages = new ArrayList<>(); 4872 } 4873 // If the dependent is a static shared lib, use the public package name 4874 String dependentPackageName = ps.name; 4875 if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) { 4876 dependentPackageName = ps.pkg.manifestPackageName; 4877 } 4878 versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode)); 4879 } else if (ps.pkg != null) { 4880 if (ArrayUtils.contains(ps.pkg.usesLibraries, libName) 4881 || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) { 4882 if (versionedPackages == null) { 4883 versionedPackages = new ArrayList<>(); 4884 } 4885 versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode)); 4886 } 4887 } 4888 } 4889 4890 return versionedPackages; 4891 } 4892 4893 @Override 4894 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 4895 if (!sUserManager.exists(userId)) return null; 4896 final int callingUid = Binder.getCallingUid(); 4897 flags = updateFlagsForComponent(flags, userId, component); 4898 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 4899 false /* requireFullPermission */, false /* checkShell */, "get service info"); 4900 synchronized (mPackages) { 4901 PackageParser.Service s = mServices.mServices.get(component); 4902 if (DEBUG_PACKAGE_INFO) Log.v( 4903 TAG, "getServiceInfo " + component + ": " + s); 4904 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 4905 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4906 if (ps == null) return null; 4907 if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) { 4908 return null; 4909 } 4910 return PackageParser.generateServiceInfo( 4911 s, flags, ps.readUserState(userId), userId); 4912 } 4913 } 4914 return null; 4915 } 4916 4917 @Override 4918 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 4919 if (!sUserManager.exists(userId)) return null; 4920 final int callingUid = Binder.getCallingUid(); 4921 flags = updateFlagsForComponent(flags, userId, component); 4922 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 4923 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 4924 synchronized (mPackages) { 4925 PackageParser.Provider p = mProviders.mProviders.get(component); 4926 if (DEBUG_PACKAGE_INFO) Log.v( 4927 TAG, "getProviderInfo " + component + ": " + p); 4928 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 4929 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4930 if (ps == null) return null; 4931 if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) { 4932 return null; 4933 } 4934 return PackageParser.generateProviderInfo( 4935 p, flags, ps.readUserState(userId), userId); 4936 } 4937 } 4938 return null; 4939 } 4940 4941 @Override 4942 public String[] getSystemSharedLibraryNames() { 4943 // allow instant applications 4944 synchronized (mPackages) { 4945 Set<String> libs = null; 4946 final int libCount = mSharedLibraries.size(); 4947 for (int i = 0; i < libCount; i++) { 4948 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 4949 if (versionedLib == null) { 4950 continue; 4951 } 4952 final int versionCount = versionedLib.size(); 4953 for (int j = 0; j < versionCount; j++) { 4954 SharedLibraryEntry libEntry = versionedLib.valueAt(j); 4955 if (!libEntry.info.isStatic()) { 4956 if (libs == null) { 4957 libs = new ArraySet<>(); 4958 } 4959 libs.add(libEntry.info.getName()); 4960 break; 4961 } 4962 PackageSetting ps = mSettings.getPackageLPr(libEntry.apk); 4963 if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(), 4964 UserHandle.getUserId(Binder.getCallingUid()), 4965 PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) { 4966 if (libs == null) { 4967 libs = new ArraySet<>(); 4968 } 4969 libs.add(libEntry.info.getName()); 4970 break; 4971 } 4972 } 4973 } 4974 4975 if (libs != null) { 4976 String[] libsArray = new String[libs.size()]; 4977 libs.toArray(libsArray); 4978 return libsArray; 4979 } 4980 4981 return null; 4982 } 4983 } 4984 4985 @Override 4986 public @NonNull String getServicesSystemSharedLibraryPackageName() { 4987 // allow instant applications 4988 synchronized (mPackages) { 4989 return mServicesSystemSharedLibraryPackageName; 4990 } 4991 } 4992 4993 @Override 4994 public @NonNull String getSharedSystemSharedLibraryPackageName() { 4995 // allow instant applications 4996 synchronized (mPackages) { 4997 return mSharedSystemSharedLibraryPackageName; 4998 } 4999 } 5000 5001 private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) { 5002 for (int i = userList.length - 1; i >= 0; --i) { 5003 final int userId = userList[i]; 5004 // don't add instant app to the list of updates 5005 if (pkgSetting.getInstantApp(userId)) { 5006 continue; 5007 } 5008 SparseArray<String> changedPackages = mChangedPackages.get(userId); 5009 if (changedPackages == null) { 5010 changedPackages = new SparseArray<>(); 5011 mChangedPackages.put(userId, changedPackages); 5012 } 5013 Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId); 5014 if (sequenceNumbers == null) { 5015 sequenceNumbers = new HashMap<>(); 5016 mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers); 5017 } 5018 final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name); 5019 if (sequenceNumber != null) { 5020 changedPackages.remove(sequenceNumber); 5021 } 5022 changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name); 5023 sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber); 5024 } 5025 mChangedPackagesSequenceNumber++; 5026 } 5027 5028 @Override 5029 public ChangedPackages getChangedPackages(int sequenceNumber, int userId) { 5030 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5031 return null; 5032 } 5033 synchronized (mPackages) { 5034 if (sequenceNumber >= mChangedPackagesSequenceNumber) { 5035 return null; 5036 } 5037 final SparseArray<String> changedPackages = mChangedPackages.get(userId); 5038 if (changedPackages == null) { 5039 return null; 5040 } 5041 final List<String> packageNames = 5042 new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber); 5043 for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) { 5044 final String packageName = changedPackages.get(i); 5045 if (packageName != null) { 5046 packageNames.add(packageName); 5047 } 5048 } 5049 return packageNames.isEmpty() 5050 ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames); 5051 } 5052 } 5053 5054 @Override 5055 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 5056 // allow instant applications 5057 ArrayList<FeatureInfo> res; 5058 synchronized (mAvailableFeatures) { 5059 res = new ArrayList<>(mAvailableFeatures.size() + 1); 5060 res.addAll(mAvailableFeatures.values()); 5061 } 5062 final FeatureInfo fi = new FeatureInfo(); 5063 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 5064 FeatureInfo.GL_ES_VERSION_UNDEFINED); 5065 res.add(fi); 5066 5067 return new ParceledListSlice<>(res); 5068 } 5069 5070 @Override 5071 public boolean hasSystemFeature(String name, int version) { 5072 // allow instant applications 5073 synchronized (mAvailableFeatures) { 5074 final FeatureInfo feat = mAvailableFeatures.get(name); 5075 if (feat == null) { 5076 return false; 5077 } else { 5078 return feat.version >= version; 5079 } 5080 } 5081 } 5082 5083 @Override 5084 public int checkPermission(String permName, String pkgName, int userId) { 5085 return mPermissionManager.checkPermission(permName, pkgName, getCallingUid(), userId); 5086 } 5087 5088 @Override 5089 public int checkUidPermission(String permName, int uid) { 5090 return mPermissionManager.checkUidPermission(permName, uid, getCallingUid()); 5091 } 5092 5093 @Override 5094 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 5095 if (UserHandle.getCallingUserId() != userId) { 5096 mContext.enforceCallingPermission( 5097 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5098 "isPermissionRevokedByPolicy for user " + userId); 5099 } 5100 5101 if (checkPermission(permission, packageName, userId) 5102 == PackageManager.PERMISSION_GRANTED) { 5103 return false; 5104 } 5105 5106 final int callingUid = Binder.getCallingUid(); 5107 if (getInstantAppPackageName(callingUid) != null) { 5108 if (!isCallerSameApp(packageName, callingUid)) { 5109 return false; 5110 } 5111 } else { 5112 if (isInstantApp(packageName, userId)) { 5113 return false; 5114 } 5115 } 5116 5117 final long identity = Binder.clearCallingIdentity(); 5118 try { 5119 final int flags = getPermissionFlags(permission, packageName, userId); 5120 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 5121 } finally { 5122 Binder.restoreCallingIdentity(identity); 5123 } 5124 } 5125 5126 @Override 5127 public String getPermissionControllerPackageName() { 5128 synchronized (mPackages) { 5129 return mRequiredInstallerPackage; 5130 } 5131 } 5132 5133 private boolean addDynamicPermission(PermissionInfo info, final boolean async) { 5134 return mPermissionManager.addDynamicPermission( 5135 info, async, getCallingUid(), new PermissionCallback() { 5136 @Override 5137 public void onPermissionChanged() { 5138 if (!async) { 5139 mSettings.writeLPr(); 5140 } else { 5141 scheduleWriteSettingsLocked(); 5142 } 5143 } 5144 }); 5145 } 5146 5147 @Override 5148 public boolean addPermission(PermissionInfo info) { 5149 synchronized (mPackages) { 5150 return addDynamicPermission(info, false); 5151 } 5152 } 5153 5154 @Override 5155 public boolean addPermissionAsync(PermissionInfo info) { 5156 synchronized (mPackages) { 5157 return addDynamicPermission(info, true); 5158 } 5159 } 5160 5161 @Override 5162 public void removePermission(String permName) { 5163 mPermissionManager.removeDynamicPermission(permName, getCallingUid(), mPermissionCallback); 5164 } 5165 5166 @Override 5167 public void grantRuntimePermission(String packageName, String permName, final int userId) { 5168 mPermissionManager.grantRuntimePermission(permName, packageName, false /*overridePolicy*/, 5169 getCallingUid(), userId, mPermissionCallback); 5170 } 5171 5172 @Override 5173 public void revokeRuntimePermission(String packageName, String permName, int userId) { 5174 mPermissionManager.revokeRuntimePermission(permName, packageName, false /*overridePolicy*/, 5175 getCallingUid(), userId, mPermissionCallback); 5176 } 5177 5178 @Override 5179 public void resetRuntimePermissions() { 5180 mContext.enforceCallingOrSelfPermission( 5181 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 5182 "revokeRuntimePermission"); 5183 5184 int callingUid = Binder.getCallingUid(); 5185 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 5186 mContext.enforceCallingOrSelfPermission( 5187 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5188 "resetRuntimePermissions"); 5189 } 5190 5191 synchronized (mPackages) { 5192 mPermissionManager.updateAllPermissions( 5193 StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(), 5194 mPermissionCallback); 5195 for (int userId : UserManagerService.getInstance().getUserIds()) { 5196 final int packageCount = mPackages.size(); 5197 for (int i = 0; i < packageCount; i++) { 5198 PackageParser.Package pkg = mPackages.valueAt(i); 5199 if (!(pkg.mExtras instanceof PackageSetting)) { 5200 continue; 5201 } 5202 PackageSetting ps = (PackageSetting) pkg.mExtras; 5203 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 5204 } 5205 } 5206 } 5207 } 5208 5209 @Override 5210 public int getPermissionFlags(String permName, String packageName, int userId) { 5211 return mPermissionManager.getPermissionFlags( 5212 permName, packageName, getCallingUid(), userId); 5213 } 5214 5215 @Override 5216 public void updatePermissionFlags(String permName, String packageName, int flagMask, 5217 int flagValues, int userId) { 5218 mPermissionManager.updatePermissionFlags( 5219 permName, packageName, flagMask, flagValues, getCallingUid(), userId, 5220 mPermissionCallback); 5221 } 5222 5223 /** 5224 * Update the permission flags for all packages and runtime permissions of a user in order 5225 * to allow device or profile owner to remove POLICY_FIXED. 5226 */ 5227 @Override 5228 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 5229 synchronized (mPackages) { 5230 final boolean changed = mPermissionManager.updatePermissionFlagsForAllApps( 5231 flagMask, flagValues, getCallingUid(), userId, mPackages.values(), 5232 mPermissionCallback); 5233 if (changed) { 5234 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 5235 } 5236 } 5237 } 5238 5239 @Override 5240 public boolean shouldShowRequestPermissionRationale(String permissionName, 5241 String packageName, int userId) { 5242 if (UserHandle.getCallingUserId() != userId) { 5243 mContext.enforceCallingPermission( 5244 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5245 "canShowRequestPermissionRationale for user " + userId); 5246 } 5247 5248 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 5249 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 5250 return false; 5251 } 5252 5253 if (checkPermission(permissionName, packageName, userId) 5254 == PackageManager.PERMISSION_GRANTED) { 5255 return false; 5256 } 5257 5258 final int flags; 5259 5260 final long identity = Binder.clearCallingIdentity(); 5261 try { 5262 flags = getPermissionFlags(permissionName, 5263 packageName, userId); 5264 } finally { 5265 Binder.restoreCallingIdentity(identity); 5266 } 5267 5268 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 5269 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 5270 | PackageManager.FLAG_PERMISSION_USER_FIXED; 5271 5272 if ((flags & fixedFlags) != 0) { 5273 return false; 5274 } 5275 5276 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 5277 } 5278 5279 @Override 5280 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 5281 mContext.enforceCallingOrSelfPermission( 5282 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 5283 "addOnPermissionsChangeListener"); 5284 5285 synchronized (mPackages) { 5286 mOnPermissionChangeListeners.addListenerLocked(listener); 5287 } 5288 } 5289 5290 @Override 5291 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 5292 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5293 throw new SecurityException("Instant applications don't have access to this method"); 5294 } 5295 synchronized (mPackages) { 5296 mOnPermissionChangeListeners.removeListenerLocked(listener); 5297 } 5298 } 5299 5300 @Override 5301 public boolean isProtectedBroadcast(String actionName) { 5302 // allow instant applications 5303 synchronized (mProtectedBroadcasts) { 5304 if (mProtectedBroadcasts.contains(actionName)) { 5305 return true; 5306 } else if (actionName != null) { 5307 // TODO: remove these terrible hacks 5308 if (actionName.startsWith("android.net.netmon.lingerExpired") 5309 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 5310 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 5311 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 5312 return true; 5313 } 5314 } 5315 } 5316 return false; 5317 } 5318 5319 @Override 5320 public int checkSignatures(String pkg1, String pkg2) { 5321 synchronized (mPackages) { 5322 final PackageParser.Package p1 = mPackages.get(pkg1); 5323 final PackageParser.Package p2 = mPackages.get(pkg2); 5324 if (p1 == null || p1.mExtras == null 5325 || p2 == null || p2.mExtras == null) { 5326 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5327 } 5328 final int callingUid = Binder.getCallingUid(); 5329 final int callingUserId = UserHandle.getUserId(callingUid); 5330 final PackageSetting ps1 = (PackageSetting) p1.mExtras; 5331 final PackageSetting ps2 = (PackageSetting) p2.mExtras; 5332 if (filterAppAccessLPr(ps1, callingUid, callingUserId) 5333 || filterAppAccessLPr(ps2, callingUid, callingUserId)) { 5334 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5335 } 5336 return compareSignatures(p1.mSignatures, p2.mSignatures); 5337 } 5338 } 5339 5340 @Override 5341 public int checkUidSignatures(int uid1, int uid2) { 5342 final int callingUid = Binder.getCallingUid(); 5343 final int callingUserId = UserHandle.getUserId(callingUid); 5344 final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null; 5345 // Map to base uids. 5346 uid1 = UserHandle.getAppId(uid1); 5347 uid2 = UserHandle.getAppId(uid2); 5348 // reader 5349 synchronized (mPackages) { 5350 Signature[] s1; 5351 Signature[] s2; 5352 Object obj = mSettings.getUserIdLPr(uid1); 5353 if (obj != null) { 5354 if (obj instanceof SharedUserSetting) { 5355 if (isCallerInstantApp) { 5356 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5357 } 5358 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 5359 } else if (obj instanceof PackageSetting) { 5360 final PackageSetting ps = (PackageSetting) obj; 5361 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 5362 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5363 } 5364 s1 = ps.signatures.mSignatures; 5365 } else { 5366 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5367 } 5368 } else { 5369 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5370 } 5371 obj = mSettings.getUserIdLPr(uid2); 5372 if (obj != null) { 5373 if (obj instanceof SharedUserSetting) { 5374 if (isCallerInstantApp) { 5375 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5376 } 5377 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 5378 } else if (obj instanceof PackageSetting) { 5379 final PackageSetting ps = (PackageSetting) obj; 5380 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 5381 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5382 } 5383 s2 = ps.signatures.mSignatures; 5384 } else { 5385 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5386 } 5387 } else { 5388 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5389 } 5390 return compareSignatures(s1, s2); 5391 } 5392 } 5393 5394 /** 5395 * This method should typically only be used when granting or revoking 5396 * permissions, since the app may immediately restart after this call. 5397 * <p> 5398 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 5399 * guard your work against the app being relaunched. 5400 */ 5401 private void killUid(int appId, int userId, String reason) { 5402 final long identity = Binder.clearCallingIdentity(); 5403 try { 5404 IActivityManager am = ActivityManager.getService(); 5405 if (am != null) { 5406 try { 5407 am.killUid(appId, userId, reason); 5408 } catch (RemoteException e) { 5409 /* ignore - same process */ 5410 } 5411 } 5412 } finally { 5413 Binder.restoreCallingIdentity(identity); 5414 } 5415 } 5416 5417 /** 5418 * If the database version for this type of package (internal storage or 5419 * external storage) is less than the version where package signatures 5420 * were updated, return true. 5421 */ 5422 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 5423 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 5424 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 5425 } 5426 5427 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 5428 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 5429 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 5430 } 5431 5432 @Override 5433 public List<String> getAllPackages() { 5434 final int callingUid = Binder.getCallingUid(); 5435 final int callingUserId = UserHandle.getUserId(callingUid); 5436 synchronized (mPackages) { 5437 if (canViewInstantApps(callingUid, callingUserId)) { 5438 return new ArrayList<String>(mPackages.keySet()); 5439 } 5440 final String instantAppPkgName = getInstantAppPackageName(callingUid); 5441 final List<String> result = new ArrayList<>(); 5442 if (instantAppPkgName != null) { 5443 // caller is an instant application; filter unexposed applications 5444 for (PackageParser.Package pkg : mPackages.values()) { 5445 if (!pkg.visibleToInstantApps) { 5446 continue; 5447 } 5448 result.add(pkg.packageName); 5449 } 5450 } else { 5451 // caller is a normal application; filter instant applications 5452 for (PackageParser.Package pkg : mPackages.values()) { 5453 final PackageSetting ps = 5454 pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null; 5455 if (ps != null 5456 && ps.getInstantApp(callingUserId) 5457 && !mInstantAppRegistry.isInstantAccessGranted( 5458 callingUserId, UserHandle.getAppId(callingUid), ps.appId)) { 5459 continue; 5460 } 5461 result.add(pkg.packageName); 5462 } 5463 } 5464 return result; 5465 } 5466 } 5467 5468 @Override 5469 public String[] getPackagesForUid(int uid) { 5470 final int callingUid = Binder.getCallingUid(); 5471 final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null; 5472 final int userId = UserHandle.getUserId(uid); 5473 uid = UserHandle.getAppId(uid); 5474 // reader 5475 synchronized (mPackages) { 5476 Object obj = mSettings.getUserIdLPr(uid); 5477 if (obj instanceof SharedUserSetting) { 5478 if (isCallerInstantApp) { 5479 return null; 5480 } 5481 final SharedUserSetting sus = (SharedUserSetting) obj; 5482 final int N = sus.packages.size(); 5483 String[] res = new String[N]; 5484 final Iterator<PackageSetting> it = sus.packages.iterator(); 5485 int i = 0; 5486 while (it.hasNext()) { 5487 PackageSetting ps = it.next(); 5488 if (ps.getInstalled(userId)) { 5489 res[i++] = ps.name; 5490 } else { 5491 res = ArrayUtils.removeElement(String.class, res, res[i]); 5492 } 5493 } 5494 return res; 5495 } else if (obj instanceof PackageSetting) { 5496 final PackageSetting ps = (PackageSetting) obj; 5497 if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) { 5498 return new String[]{ps.name}; 5499 } 5500 } 5501 } 5502 return null; 5503 } 5504 5505 @Override 5506 public String getNameForUid(int uid) { 5507 final int callingUid = Binder.getCallingUid(); 5508 if (getInstantAppPackageName(callingUid) != null) { 5509 return null; 5510 } 5511 synchronized (mPackages) { 5512 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5513 if (obj instanceof SharedUserSetting) { 5514 final SharedUserSetting sus = (SharedUserSetting) obj; 5515 return sus.name + ":" + sus.userId; 5516 } else if (obj instanceof PackageSetting) { 5517 final PackageSetting ps = (PackageSetting) obj; 5518 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 5519 return null; 5520 } 5521 return ps.name; 5522 } 5523 return null; 5524 } 5525 } 5526 5527 @Override 5528 public String[] getNamesForUids(int[] uids) { 5529 if (uids == null || uids.length == 0) { 5530 return null; 5531 } 5532 final int callingUid = Binder.getCallingUid(); 5533 if (getInstantAppPackageName(callingUid) != null) { 5534 return null; 5535 } 5536 final String[] names = new String[uids.length]; 5537 synchronized (mPackages) { 5538 for (int i = uids.length - 1; i >= 0; i--) { 5539 final int uid = uids[i]; 5540 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5541 if (obj instanceof SharedUserSetting) { 5542 final SharedUserSetting sus = (SharedUserSetting) obj; 5543 names[i] = "shared:" + sus.name; 5544 } else if (obj instanceof PackageSetting) { 5545 final PackageSetting ps = (PackageSetting) obj; 5546 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 5547 names[i] = null; 5548 } else { 5549 names[i] = ps.name; 5550 } 5551 } else { 5552 names[i] = null; 5553 } 5554 } 5555 } 5556 return names; 5557 } 5558 5559 @Override 5560 public int getUidForSharedUser(String sharedUserName) { 5561 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5562 return -1; 5563 } 5564 if (sharedUserName == null) { 5565 return -1; 5566 } 5567 // reader 5568 synchronized (mPackages) { 5569 SharedUserSetting suid; 5570 try { 5571 suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 5572 if (suid != null) { 5573 return suid.userId; 5574 } 5575 } catch (PackageManagerException ignore) { 5576 // can't happen, but, still need to catch it 5577 } 5578 return -1; 5579 } 5580 } 5581 5582 @Override 5583 public int getFlagsForUid(int uid) { 5584 final int callingUid = Binder.getCallingUid(); 5585 if (getInstantAppPackageName(callingUid) != null) { 5586 return 0; 5587 } 5588 synchronized (mPackages) { 5589 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5590 if (obj instanceof SharedUserSetting) { 5591 final SharedUserSetting sus = (SharedUserSetting) obj; 5592 return sus.pkgFlags; 5593 } else if (obj instanceof PackageSetting) { 5594 final PackageSetting ps = (PackageSetting) obj; 5595 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 5596 return 0; 5597 } 5598 return ps.pkgFlags; 5599 } 5600 } 5601 return 0; 5602 } 5603 5604 @Override 5605 public int getPrivateFlagsForUid(int uid) { 5606 final int callingUid = Binder.getCallingUid(); 5607 if (getInstantAppPackageName(callingUid) != null) { 5608 return 0; 5609 } 5610 synchronized (mPackages) { 5611 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5612 if (obj instanceof SharedUserSetting) { 5613 final SharedUserSetting sus = (SharedUserSetting) obj; 5614 return sus.pkgPrivateFlags; 5615 } else if (obj instanceof PackageSetting) { 5616 final PackageSetting ps = (PackageSetting) obj; 5617 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 5618 return 0; 5619 } 5620 return ps.pkgPrivateFlags; 5621 } 5622 } 5623 return 0; 5624 } 5625 5626 @Override 5627 public boolean isUidPrivileged(int uid) { 5628 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5629 return false; 5630 } 5631 uid = UserHandle.getAppId(uid); 5632 // reader 5633 synchronized (mPackages) { 5634 Object obj = mSettings.getUserIdLPr(uid); 5635 if (obj instanceof SharedUserSetting) { 5636 final SharedUserSetting sus = (SharedUserSetting) obj; 5637 final Iterator<PackageSetting> it = sus.packages.iterator(); 5638 while (it.hasNext()) { 5639 if (it.next().isPrivileged()) { 5640 return true; 5641 } 5642 } 5643 } else if (obj instanceof PackageSetting) { 5644 final PackageSetting ps = (PackageSetting) obj; 5645 return ps.isPrivileged(); 5646 } 5647 } 5648 return false; 5649 } 5650 5651 @Override 5652 public String[] getAppOpPermissionPackages(String permName) { 5653 return mPermissionManager.getAppOpPermissionPackages(permName); 5654 } 5655 5656 @Override 5657 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 5658 int flags, int userId) { 5659 return resolveIntentInternal( 5660 intent, resolvedType, flags, userId, false /*resolveForStart*/); 5661 } 5662 5663 /** 5664 * Normally instant apps can only be resolved when they're visible to the caller. 5665 * However, if {@code resolveForStart} is {@code true}, all instant apps are visible 5666 * since we need to allow the system to start any installed application. 5667 */ 5668 private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType, 5669 int flags, int userId, boolean resolveForStart) { 5670 try { 5671 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 5672 5673 if (!sUserManager.exists(userId)) return null; 5674 final int callingUid = Binder.getCallingUid(); 5675 flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart); 5676 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 5677 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 5678 5679 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5680 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 5681 flags, callingUid, userId, resolveForStart, true /*allowDynamicSplits*/); 5682 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5683 5684 final ResolveInfo bestChoice = 5685 chooseBestActivity(intent, resolvedType, flags, query, userId); 5686 return bestChoice; 5687 } finally { 5688 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5689 } 5690 } 5691 5692 @Override 5693 public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) { 5694 if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) { 5695 throw new SecurityException( 5696 "findPersistentPreferredActivity can only be run by the system"); 5697 } 5698 if (!sUserManager.exists(userId)) { 5699 return null; 5700 } 5701 final int callingUid = Binder.getCallingUid(); 5702 intent = updateIntentForResolve(intent); 5703 final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver()); 5704 final int flags = updateFlagsForResolve( 5705 0, userId, intent, callingUid, false /*includeInstantApps*/); 5706 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5707 userId); 5708 synchronized (mPackages) { 5709 return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false, 5710 userId); 5711 } 5712 } 5713 5714 @Override 5715 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 5716 IntentFilter filter, int match, ComponentName activity) { 5717 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5718 return; 5719 } 5720 final int userId = UserHandle.getCallingUserId(); 5721 if (DEBUG_PREFERRED) { 5722 Log.v(TAG, "setLastChosenActivity intent=" + intent 5723 + " resolvedType=" + resolvedType 5724 + " flags=" + flags 5725 + " filter=" + filter 5726 + " match=" + match 5727 + " activity=" + activity); 5728 filter.dump(new PrintStreamPrinter(System.out), " "); 5729 } 5730 intent.setComponent(null); 5731 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5732 userId); 5733 // Find any earlier preferred or last chosen entries and nuke them 5734 findPreferredActivity(intent, resolvedType, 5735 flags, query, 0, false, true, false, userId); 5736 // Add the new activity as the last chosen for this filter 5737 addPreferredActivityInternal(filter, match, null, activity, false, userId, 5738 "Setting last chosen"); 5739 } 5740 5741 @Override 5742 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 5743 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5744 return null; 5745 } 5746 final int userId = UserHandle.getCallingUserId(); 5747 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 5748 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5749 userId); 5750 return findPreferredActivity(intent, resolvedType, flags, query, 0, 5751 false, false, false, userId); 5752 } 5753 5754 /** 5755 * Returns whether or not instant apps have been disabled remotely. 5756 */ 5757 private boolean isEphemeralDisabled() { 5758 return mEphemeralAppsDisabled; 5759 } 5760 5761 private boolean isInstantAppAllowed( 5762 Intent intent, List<ResolveInfo> resolvedActivities, int userId, 5763 boolean skipPackageCheck) { 5764 if (mInstantAppResolverConnection == null) { 5765 return false; 5766 } 5767 if (mInstantAppInstallerActivity == null) { 5768 return false; 5769 } 5770 if (intent.getComponent() != null) { 5771 return false; 5772 } 5773 if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) { 5774 return false; 5775 } 5776 if (!skipPackageCheck && intent.getPackage() != null) { 5777 return false; 5778 } 5779 final boolean isWebUri = hasWebURI(intent); 5780 if (!isWebUri || intent.getData().getHost() == null) { 5781 return false; 5782 } 5783 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 5784 // Or if there's already an ephemeral app installed that handles the action 5785 synchronized (mPackages) { 5786 final int count = (resolvedActivities == null ? 0 : resolvedActivities.size()); 5787 for (int n = 0; n < count; n++) { 5788 final ResolveInfo info = resolvedActivities.get(n); 5789 final String packageName = info.activityInfo.packageName; 5790 final PackageSetting ps = mSettings.mPackages.get(packageName); 5791 if (ps != null) { 5792 // only check domain verification status if the app is not a browser 5793 if (!info.handleAllWebDataURI) { 5794 // Try to get the status from User settings first 5795 final long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5796 final int status = (int) (packedStatus >> 32); 5797 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 5798 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5799 if (DEBUG_EPHEMERAL) { 5800 Slog.v(TAG, "DENY instant app;" 5801 + " pkg: " + packageName + ", status: " + status); 5802 } 5803 return false; 5804 } 5805 } 5806 if (ps.getInstantApp(userId)) { 5807 if (DEBUG_EPHEMERAL) { 5808 Slog.v(TAG, "DENY instant app installed;" 5809 + " pkg: " + packageName); 5810 } 5811 return false; 5812 } 5813 } 5814 } 5815 } 5816 // We've exhausted all ways to deny ephemeral application; let the system look for them. 5817 return true; 5818 } 5819 5820 private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj, 5821 Intent origIntent, String resolvedType, String callingPackage, 5822 Bundle verificationBundle, int userId) { 5823 final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO, 5824 new InstantAppRequest(responseObj, origIntent, resolvedType, 5825 callingPackage, userId, verificationBundle, false /*resolveForStart*/)); 5826 mHandler.sendMessage(msg); 5827 } 5828 5829 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 5830 int flags, List<ResolveInfo> query, int userId) { 5831 if (query != null) { 5832 final int N = query.size(); 5833 if (N == 1) { 5834 return query.get(0); 5835 } else if (N > 1) { 5836 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 5837 // If there is more than one activity with the same priority, 5838 // then let the user decide between them. 5839 ResolveInfo r0 = query.get(0); 5840 ResolveInfo r1 = query.get(1); 5841 if (DEBUG_INTENT_MATCHING || debug) { 5842 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 5843 + r1.activityInfo.name + "=" + r1.priority); 5844 } 5845 // If the first activity has a higher priority, or a different 5846 // default, then it is always desirable to pick it. 5847 if (r0.priority != r1.priority 5848 || r0.preferredOrder != r1.preferredOrder 5849 || r0.isDefault != r1.isDefault) { 5850 return query.get(0); 5851 } 5852 // If we have saved a preference for a preferred activity for 5853 // this Intent, use that. 5854 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 5855 flags, query, r0.priority, true, false, debug, userId); 5856 if (ri != null) { 5857 return ri; 5858 } 5859 // If we have an ephemeral app, use it 5860 for (int i = 0; i < N; i++) { 5861 ri = query.get(i); 5862 if (ri.activityInfo.applicationInfo.isInstantApp()) { 5863 final String packageName = ri.activityInfo.packageName; 5864 final PackageSetting ps = mSettings.mPackages.get(packageName); 5865 final long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5866 final int status = (int)(packedStatus >> 32); 5867 if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5868 return ri; 5869 } 5870 } 5871 } 5872 ri = new ResolveInfo(mResolveInfo); 5873 ri.activityInfo = new ActivityInfo(ri.activityInfo); 5874 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 5875 // If all of the options come from the same package, show the application's 5876 // label and icon instead of the generic resolver's. 5877 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 5878 // and then throw away the ResolveInfo itself, meaning that the caller loses 5879 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 5880 // a fallback for this case; we only set the target package's resources on 5881 // the ResolveInfo, not the ActivityInfo. 5882 final String intentPackage = intent.getPackage(); 5883 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 5884 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 5885 ri.resolvePackageName = intentPackage; 5886 if (userNeedsBadging(userId)) { 5887 ri.noResourceId = true; 5888 } else { 5889 ri.icon = appi.icon; 5890 } 5891 ri.iconResourceId = appi.icon; 5892 ri.labelRes = appi.labelRes; 5893 } 5894 ri.activityInfo.applicationInfo = new ApplicationInfo( 5895 ri.activityInfo.applicationInfo); 5896 if (userId != 0) { 5897 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 5898 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 5899 } 5900 // Make sure that the resolver is displayable in car mode 5901 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 5902 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 5903 return ri; 5904 } 5905 } 5906 return null; 5907 } 5908 5909 /** 5910 * Return true if the given list is not empty and all of its contents have 5911 * an activityInfo with the given package name. 5912 */ 5913 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 5914 if (ArrayUtils.isEmpty(list)) { 5915 return false; 5916 } 5917 for (int i = 0, N = list.size(); i < N; i++) { 5918 final ResolveInfo ri = list.get(i); 5919 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 5920 if (ai == null || !packageName.equals(ai.packageName)) { 5921 return false; 5922 } 5923 } 5924 return true; 5925 } 5926 5927 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 5928 int flags, List<ResolveInfo> query, boolean debug, int userId) { 5929 final int N = query.size(); 5930 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 5931 .get(userId); 5932 // Get the list of persistent preferred activities that handle the intent 5933 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 5934 List<PersistentPreferredActivity> pprefs = ppir != null 5935 ? ppir.queryIntent(intent, resolvedType, 5936 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 5937 userId) 5938 : null; 5939 if (pprefs != null && pprefs.size() > 0) { 5940 final int M = pprefs.size(); 5941 for (int i=0; i<M; i++) { 5942 final PersistentPreferredActivity ppa = pprefs.get(i); 5943 if (DEBUG_PREFERRED || debug) { 5944 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 5945 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 5946 + "\n component=" + ppa.mComponent); 5947 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5948 } 5949 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 5950 flags | MATCH_DISABLED_COMPONENTS, userId); 5951 if (DEBUG_PREFERRED || debug) { 5952 Slog.v(TAG, "Found persistent preferred activity:"); 5953 if (ai != null) { 5954 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5955 } else { 5956 Slog.v(TAG, " null"); 5957 } 5958 } 5959 if (ai == null) { 5960 // This previously registered persistent preferred activity 5961 // component is no longer known. Ignore it and do NOT remove it. 5962 continue; 5963 } 5964 for (int j=0; j<N; j++) { 5965 final ResolveInfo ri = query.get(j); 5966 if (!ri.activityInfo.applicationInfo.packageName 5967 .equals(ai.applicationInfo.packageName)) { 5968 continue; 5969 } 5970 if (!ri.activityInfo.name.equals(ai.name)) { 5971 continue; 5972 } 5973 // Found a persistent preference that can handle the intent. 5974 if (DEBUG_PREFERRED || debug) { 5975 Slog.v(TAG, "Returning persistent preferred activity: " + 5976 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5977 } 5978 return ri; 5979 } 5980 } 5981 } 5982 return null; 5983 } 5984 5985 // TODO: handle preferred activities missing while user has amnesia 5986 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5987 List<ResolveInfo> query, int priority, boolean always, 5988 boolean removeMatches, boolean debug, int userId) { 5989 if (!sUserManager.exists(userId)) return null; 5990 final int callingUid = Binder.getCallingUid(); 5991 flags = updateFlagsForResolve( 5992 flags, userId, intent, callingUid, false /*includeInstantApps*/); 5993 intent = updateIntentForResolve(intent); 5994 // writer 5995 synchronized (mPackages) { 5996 // Try to find a matching persistent preferred activity. 5997 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5998 debug, userId); 5999 6000 // If a persistent preferred activity matched, use it. 6001 if (pri != null) { 6002 return pri; 6003 } 6004 6005 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 6006 // Get the list of preferred activities that handle the intent 6007 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 6008 List<PreferredActivity> prefs = pir != null 6009 ? pir.queryIntent(intent, resolvedType, 6010 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 6011 userId) 6012 : null; 6013 if (prefs != null && prefs.size() > 0) { 6014 boolean changed = false; 6015 try { 6016 // First figure out how good the original match set is. 6017 // We will only allow preferred activities that came 6018 // from the same match quality. 6019 int match = 0; 6020 6021 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 6022 6023 final int N = query.size(); 6024 for (int j=0; j<N; j++) { 6025 final ResolveInfo ri = query.get(j); 6026 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 6027 + ": 0x" + Integer.toHexString(match)); 6028 if (ri.match > match) { 6029 match = ri.match; 6030 } 6031 } 6032 6033 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 6034 + Integer.toHexString(match)); 6035 6036 match &= IntentFilter.MATCH_CATEGORY_MASK; 6037 final int M = prefs.size(); 6038 for (int i=0; i<M; i++) { 6039 final PreferredActivity pa = prefs.get(i); 6040 if (DEBUG_PREFERRED || debug) { 6041 Slog.v(TAG, "Checking PreferredActivity ds=" 6042 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 6043 + "\n component=" + pa.mPref.mComponent); 6044 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6045 } 6046 if (pa.mPref.mMatch != match) { 6047 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 6048 + Integer.toHexString(pa.mPref.mMatch)); 6049 continue; 6050 } 6051 // If it's not an "always" type preferred activity and that's what we're 6052 // looking for, skip it. 6053 if (always && !pa.mPref.mAlways) { 6054 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 6055 continue; 6056 } 6057 final ActivityInfo ai = getActivityInfo( 6058 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 6059 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 6060 userId); 6061 if (DEBUG_PREFERRED || debug) { 6062 Slog.v(TAG, "Found preferred activity:"); 6063 if (ai != null) { 6064 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6065 } else { 6066 Slog.v(TAG, " null"); 6067 } 6068 } 6069 if (ai == null) { 6070 // This previously registered preferred activity 6071 // component is no longer known. Most likely an update 6072 // to the app was installed and in the new version this 6073 // component no longer exists. Clean it up by removing 6074 // it from the preferred activities list, and skip it. 6075 Slog.w(TAG, "Removing dangling preferred activity: " 6076 + pa.mPref.mComponent); 6077 pir.removeFilter(pa); 6078 changed = true; 6079 continue; 6080 } 6081 for (int j=0; j<N; j++) { 6082 final ResolveInfo ri = query.get(j); 6083 if (!ri.activityInfo.applicationInfo.packageName 6084 .equals(ai.applicationInfo.packageName)) { 6085 continue; 6086 } 6087 if (!ri.activityInfo.name.equals(ai.name)) { 6088 continue; 6089 } 6090 6091 if (removeMatches) { 6092 pir.removeFilter(pa); 6093 changed = true; 6094 if (DEBUG_PREFERRED) { 6095 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 6096 } 6097 break; 6098 } 6099 6100 // Okay we found a previously set preferred or last chosen app. 6101 // If the result set is different from when this 6102 // was created, and is not a subset of the preferred set, we need to 6103 // clear it and re-ask the user their preference, if we're looking for 6104 // an "always" type entry. 6105 if (always && !pa.mPref.sameSet(query)) { 6106 if (pa.mPref.isSuperset(query)) { 6107 // some components of the set are no longer present in 6108 // the query, but the preferred activity can still be reused 6109 if (DEBUG_PREFERRED) { 6110 Slog.i(TAG, "Result set changed, but PreferredActivity is" 6111 + " still valid as only non-preferred components" 6112 + " were removed for " + intent + " type " 6113 + resolvedType); 6114 } 6115 // remove obsolete components and re-add the up-to-date filter 6116 PreferredActivity freshPa = new PreferredActivity(pa, 6117 pa.mPref.mMatch, 6118 pa.mPref.discardObsoleteComponents(query), 6119 pa.mPref.mComponent, 6120 pa.mPref.mAlways); 6121 pir.removeFilter(pa); 6122 pir.addFilter(freshPa); 6123 changed = true; 6124 } else { 6125 Slog.i(TAG, 6126 "Result set changed, dropping preferred activity for " 6127 + intent + " type " + resolvedType); 6128 if (DEBUG_PREFERRED) { 6129 Slog.v(TAG, "Removing preferred activity since set changed " 6130 + pa.mPref.mComponent); 6131 } 6132 pir.removeFilter(pa); 6133 // Re-add the filter as a "last chosen" entry (!always) 6134 PreferredActivity lastChosen = new PreferredActivity( 6135 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 6136 pir.addFilter(lastChosen); 6137 changed = true; 6138 return null; 6139 } 6140 } 6141 6142 // Yay! Either the set matched or we're looking for the last chosen 6143 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 6144 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 6145 return ri; 6146 } 6147 } 6148 } finally { 6149 if (changed) { 6150 if (DEBUG_PREFERRED) { 6151 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 6152 } 6153 scheduleWritePackageRestrictionsLocked(userId); 6154 } 6155 } 6156 } 6157 } 6158 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 6159 return null; 6160 } 6161 6162 /* 6163 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 6164 */ 6165 @Override 6166 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 6167 int targetUserId) { 6168 mContext.enforceCallingOrSelfPermission( 6169 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 6170 List<CrossProfileIntentFilter> matches = 6171 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 6172 if (matches != null) { 6173 int size = matches.size(); 6174 for (int i = 0; i < size; i++) { 6175 if (matches.get(i).getTargetUserId() == targetUserId) return true; 6176 } 6177 } 6178 if (hasWebURI(intent)) { 6179 // cross-profile app linking works only towards the parent. 6180 final int callingUid = Binder.getCallingUid(); 6181 final UserInfo parent = getProfileParent(sourceUserId); 6182 synchronized(mPackages) { 6183 int flags = updateFlagsForResolve(0, parent.id, intent, callingUid, 6184 false /*includeInstantApps*/); 6185 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 6186 intent, resolvedType, flags, sourceUserId, parent.id); 6187 return xpDomainInfo != null; 6188 } 6189 } 6190 return false; 6191 } 6192 6193 private UserInfo getProfileParent(int userId) { 6194 final long identity = Binder.clearCallingIdentity(); 6195 try { 6196 return sUserManager.getProfileParent(userId); 6197 } finally { 6198 Binder.restoreCallingIdentity(identity); 6199 } 6200 } 6201 6202 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 6203 String resolvedType, int userId) { 6204 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 6205 if (resolver != null) { 6206 return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId); 6207 } 6208 return null; 6209 } 6210 6211 @Override 6212 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 6213 String resolvedType, int flags, int userId) { 6214 try { 6215 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 6216 6217 return new ParceledListSlice<>( 6218 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 6219 } finally { 6220 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6221 } 6222 } 6223 6224 /** 6225 * Returns the package name of the calling Uid if it's an instant app. If it isn't 6226 * instant, returns {@code null}. 6227 */ 6228 private String getInstantAppPackageName(int callingUid) { 6229 synchronized (mPackages) { 6230 // If the caller is an isolated app use the owner's uid for the lookup. 6231 if (Process.isIsolated(callingUid)) { 6232 callingUid = mIsolatedOwners.get(callingUid); 6233 } 6234 final int appId = UserHandle.getAppId(callingUid); 6235 final Object obj = mSettings.getUserIdLPr(appId); 6236 if (obj instanceof PackageSetting) { 6237 final PackageSetting ps = (PackageSetting) obj; 6238 final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid)); 6239 return isInstantApp ? ps.pkg.packageName : null; 6240 } 6241 } 6242 return null; 6243 } 6244 6245 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 6246 String resolvedType, int flags, int userId) { 6247 return queryIntentActivitiesInternal( 6248 intent, resolvedType, flags, Binder.getCallingUid(), userId, 6249 false /*resolveForStart*/, true /*allowDynamicSplits*/); 6250 } 6251 6252 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 6253 String resolvedType, int flags, int filterCallingUid, int userId, 6254 boolean resolveForStart, boolean allowDynamicSplits) { 6255 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6256 final String instantAppPkgName = getInstantAppPackageName(filterCallingUid); 6257 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 6258 false /* requireFullPermission */, false /* checkShell */, 6259 "query intent activities"); 6260 final String pkgName = intent.getPackage(); 6261 ComponentName comp = intent.getComponent(); 6262 if (comp == null) { 6263 if (intent.getSelector() != null) { 6264 intent = intent.getSelector(); 6265 comp = intent.getComponent(); 6266 } 6267 } 6268 6269 flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart, 6270 comp != null || pkgName != null /*onlyExposedExplicitly*/); 6271 if (comp != null) { 6272 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6273 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 6274 if (ai != null) { 6275 // When specifying an explicit component, we prevent the activity from being 6276 // used when either 1) the calling package is normal and the activity is within 6277 // an ephemeral application or 2) the calling package is ephemeral and the 6278 // activity is not visible to ephemeral applications. 6279 final boolean matchInstantApp = 6280 (flags & PackageManager.MATCH_INSTANT) != 0; 6281 final boolean matchVisibleToInstantAppOnly = 6282 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 6283 final boolean matchExplicitlyVisibleOnly = 6284 (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0; 6285 final boolean isCallerInstantApp = 6286 instantAppPkgName != null; 6287 final boolean isTargetSameInstantApp = 6288 comp.getPackageName().equals(instantAppPkgName); 6289 final boolean isTargetInstantApp = 6290 (ai.applicationInfo.privateFlags 6291 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 6292 final boolean isTargetVisibleToInstantApp = 6293 (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0; 6294 final boolean isTargetExplicitlyVisibleToInstantApp = 6295 isTargetVisibleToInstantApp 6296 && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0; 6297 final boolean isTargetHiddenFromInstantApp = 6298 !isTargetVisibleToInstantApp 6299 || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp); 6300 final boolean blockResolution = 6301 !isTargetSameInstantApp 6302 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 6303 || (matchVisibleToInstantAppOnly && isCallerInstantApp 6304 && isTargetHiddenFromInstantApp)); 6305 if (!blockResolution) { 6306 final ResolveInfo ri = new ResolveInfo(); 6307 ri.activityInfo = ai; 6308 list.add(ri); 6309 } 6310 } 6311 return applyPostResolutionFilter( 6312 list, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId); 6313 } 6314 6315 // reader 6316 boolean sortResult = false; 6317 boolean addEphemeral = false; 6318 List<ResolveInfo> result; 6319 final boolean ephemeralDisabled = isEphemeralDisabled(); 6320 synchronized (mPackages) { 6321 if (pkgName == null) { 6322 List<CrossProfileIntentFilter> matchingFilters = 6323 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 6324 // Check for results that need to skip the current profile. 6325 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 6326 resolvedType, flags, userId); 6327 if (xpResolveInfo != null) { 6328 List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1); 6329 xpResult.add(xpResolveInfo); 6330 return applyPostResolutionFilter( 6331 filterIfNotSystemUser(xpResult, userId), instantAppPkgName, 6332 allowDynamicSplits, filterCallingUid, userId); 6333 } 6334 6335 // Check for results in the current profile. 6336 result = filterIfNotSystemUser(mActivities.queryIntent( 6337 intent, resolvedType, flags, userId), userId); 6338 addEphemeral = !ephemeralDisabled 6339 && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/); 6340 // Check for cross profile results. 6341 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 6342 xpResolveInfo = queryCrossProfileIntents( 6343 matchingFilters, intent, resolvedType, flags, userId, 6344 hasNonNegativePriorityResult); 6345 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 6346 boolean isVisibleToUser = filterIfNotSystemUser( 6347 Collections.singletonList(xpResolveInfo), userId).size() > 0; 6348 if (isVisibleToUser) { 6349 result.add(xpResolveInfo); 6350 sortResult = true; 6351 } 6352 } 6353 if (hasWebURI(intent)) { 6354 CrossProfileDomainInfo xpDomainInfo = null; 6355 final UserInfo parent = getProfileParent(userId); 6356 if (parent != null) { 6357 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 6358 flags, userId, parent.id); 6359 } 6360 if (xpDomainInfo != null) { 6361 if (xpResolveInfo != null) { 6362 // If we didn't remove it, the cross-profile ResolveInfo would be twice 6363 // in the result. 6364 result.remove(xpResolveInfo); 6365 } 6366 if (result.size() == 0 && !addEphemeral) { 6367 // No result in current profile, but found candidate in parent user. 6368 // And we are not going to add emphemeral app, so we can return the 6369 // result straight away. 6370 result.add(xpDomainInfo.resolveInfo); 6371 return applyPostResolutionFilter(result, instantAppPkgName, 6372 allowDynamicSplits, filterCallingUid, userId); 6373 } 6374 } else if (result.size() <= 1 && !addEphemeral) { 6375 // No result in parent user and <= 1 result in current profile, and we 6376 // are not going to add emphemeral app, so we can return the result without 6377 // further processing. 6378 return applyPostResolutionFilter(result, instantAppPkgName, 6379 allowDynamicSplits, filterCallingUid, userId); 6380 } 6381 // We have more than one candidate (combining results from current and parent 6382 // profile), so we need filtering and sorting. 6383 result = filterCandidatesWithDomainPreferredActivitiesLPr( 6384 intent, flags, result, xpDomainInfo, userId); 6385 sortResult = true; 6386 } 6387 } else { 6388 final PackageParser.Package pkg = mPackages.get(pkgName); 6389 result = null; 6390 if (pkg != null) { 6391 result = filterIfNotSystemUser( 6392 mActivities.queryIntentForPackage( 6393 intent, resolvedType, flags, pkg.activities, userId), 6394 userId); 6395 } 6396 if (result == null || result.size() == 0) { 6397 // the caller wants to resolve for a particular package; however, there 6398 // were no installed results, so, try to find an ephemeral result 6399 addEphemeral = !ephemeralDisabled 6400 && isInstantAppAllowed( 6401 intent, null /*result*/, userId, true /*skipPackageCheck*/); 6402 if (result == null) { 6403 result = new ArrayList<>(); 6404 } 6405 } 6406 } 6407 } 6408 if (addEphemeral) { 6409 result = maybeAddInstantAppInstaller( 6410 result, intent, resolvedType, flags, userId, resolveForStart); 6411 } 6412 if (sortResult) { 6413 Collections.sort(result, mResolvePrioritySorter); 6414 } 6415 return applyPostResolutionFilter( 6416 result, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId); 6417 } 6418 6419 private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent, 6420 String resolvedType, int flags, int userId, boolean resolveForStart) { 6421 // first, check to see if we've got an instant app already installed 6422 final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0; 6423 ResolveInfo localInstantApp = null; 6424 boolean blockResolution = false; 6425 if (!alreadyResolvedLocally) { 6426 final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType, 6427 flags 6428 | PackageManager.GET_RESOLVED_FILTER 6429 | PackageManager.MATCH_INSTANT 6430 | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY, 6431 userId); 6432 for (int i = instantApps.size() - 1; i >= 0; --i) { 6433 final ResolveInfo info = instantApps.get(i); 6434 final String packageName = info.activityInfo.packageName; 6435 final PackageSetting ps = mSettings.mPackages.get(packageName); 6436 if (ps.getInstantApp(userId)) { 6437 final long packedStatus = getDomainVerificationStatusLPr(ps, userId); 6438 final int status = (int)(packedStatus >> 32); 6439 final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 6440 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6441 // there's a local instant application installed, but, the user has 6442 // chosen to never use it; skip resolution and don't acknowledge 6443 // an instant application is even available 6444 if (DEBUG_EPHEMERAL) { 6445 Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName); 6446 } 6447 blockResolution = true; 6448 break; 6449 } else { 6450 // we have a locally installed instant application; skip resolution 6451 // but acknowledge there's an instant application available 6452 if (DEBUG_EPHEMERAL) { 6453 Slog.v(TAG, "Found installed instant app; pkg: " + packageName); 6454 } 6455 localInstantApp = info; 6456 break; 6457 } 6458 } 6459 } 6460 } 6461 // no app installed, let's see if one's available 6462 AuxiliaryResolveInfo auxiliaryResponse = null; 6463 if (!blockResolution) { 6464 if (localInstantApp == null) { 6465 // we don't have an instant app locally, resolve externally 6466 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 6467 final InstantAppRequest requestObject = new InstantAppRequest( 6468 null /*responseObj*/, intent /*origIntent*/, resolvedType, 6469 null /*callingPackage*/, userId, null /*verificationBundle*/, 6470 resolveForStart); 6471 auxiliaryResponse = 6472 InstantAppResolver.doInstantAppResolutionPhaseOne( 6473 mContext, mInstantAppResolverConnection, requestObject); 6474 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6475 } else { 6476 // we have an instant application locally, but, we can't admit that since 6477 // callers shouldn't be able to determine prior browsing. create a dummy 6478 // auxiliary response so the downstream code behaves as if there's an 6479 // instant application available externally. when it comes time to start 6480 // the instant application, we'll do the right thing. 6481 final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo; 6482 auxiliaryResponse = new AuxiliaryResolveInfo( 6483 ai.packageName, null /*splitName*/, null /*failureActivity*/, 6484 ai.versionCode, null /*failureIntent*/); 6485 } 6486 } 6487 if (auxiliaryResponse != null) { 6488 if (DEBUG_EPHEMERAL) { 6489 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 6490 } 6491 final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo); 6492 final PackageSetting ps = 6493 mSettings.mPackages.get(mInstantAppInstallerActivity.packageName); 6494 if (ps != null) { 6495 ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo( 6496 mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId); 6497 ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token; 6498 ephemeralInstaller.auxiliaryInfo = auxiliaryResponse; 6499 // make sure this resolver is the default 6500 ephemeralInstaller.isDefault = true; 6501 ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 6502 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 6503 // add a non-generic filter 6504 ephemeralInstaller.filter = new IntentFilter(intent.getAction()); 6505 ephemeralInstaller.filter.addDataPath( 6506 intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL); 6507 ephemeralInstaller.isInstantAppAvailable = true; 6508 result.add(ephemeralInstaller); 6509 } 6510 } 6511 return result; 6512 } 6513 6514 private static class CrossProfileDomainInfo { 6515 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 6516 ResolveInfo resolveInfo; 6517 /* Best domain verification status of the activities found in the other profile */ 6518 int bestDomainVerificationStatus; 6519 } 6520 6521 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 6522 String resolvedType, int flags, int sourceUserId, int parentUserId) { 6523 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 6524 sourceUserId)) { 6525 return null; 6526 } 6527 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 6528 resolvedType, flags, parentUserId); 6529 6530 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 6531 return null; 6532 } 6533 CrossProfileDomainInfo result = null; 6534 int size = resultTargetUser.size(); 6535 for (int i = 0; i < size; i++) { 6536 ResolveInfo riTargetUser = resultTargetUser.get(i); 6537 // Intent filter verification is only for filters that specify a host. So don't return 6538 // those that handle all web uris. 6539 if (riTargetUser.handleAllWebDataURI) { 6540 continue; 6541 } 6542 String packageName = riTargetUser.activityInfo.packageName; 6543 PackageSetting ps = mSettings.mPackages.get(packageName); 6544 if (ps == null) { 6545 continue; 6546 } 6547 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 6548 int status = (int)(verificationState >> 32); 6549 if (result == null) { 6550 result = new CrossProfileDomainInfo(); 6551 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 6552 sourceUserId, parentUserId); 6553 result.bestDomainVerificationStatus = status; 6554 } else { 6555 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 6556 result.bestDomainVerificationStatus); 6557 } 6558 } 6559 // Don't consider matches with status NEVER across profiles. 6560 if (result != null && result.bestDomainVerificationStatus 6561 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6562 return null; 6563 } 6564 return result; 6565 } 6566 6567 /** 6568 * Verification statuses are ordered from the worse to the best, except for 6569 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 6570 */ 6571 private int bestDomainVerificationStatus(int status1, int status2) { 6572 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6573 return status2; 6574 } 6575 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6576 return status1; 6577 } 6578 return (int) MathUtils.max(status1, status2); 6579 } 6580 6581 private boolean isUserEnabled(int userId) { 6582 long callingId = Binder.clearCallingIdentity(); 6583 try { 6584 UserInfo userInfo = sUserManager.getUserInfo(userId); 6585 return userInfo != null && userInfo.isEnabled(); 6586 } finally { 6587 Binder.restoreCallingIdentity(callingId); 6588 } 6589 } 6590 6591 /** 6592 * Filter out activities with systemUserOnly flag set, when current user is not System. 6593 * 6594 * @return filtered list 6595 */ 6596 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 6597 if (userId == UserHandle.USER_SYSTEM) { 6598 return resolveInfos; 6599 } 6600 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 6601 ResolveInfo info = resolveInfos.get(i); 6602 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 6603 resolveInfos.remove(i); 6604 } 6605 } 6606 return resolveInfos; 6607 } 6608 6609 /** 6610 * Filters out ephemeral activities. 6611 * <p>When resolving for an ephemeral app, only activities that 1) are defined in the 6612 * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned. 6613 * 6614 * @param resolveInfos The pre-filtered list of resolved activities 6615 * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering 6616 * is performed. 6617 * @return A filtered list of resolved activities. 6618 */ 6619 private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos, 6620 String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, int userId) { 6621 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 6622 final ResolveInfo info = resolveInfos.get(i); 6623 // allow activities that are defined in the provided package 6624 if (allowDynamicSplits 6625 && info.activityInfo.splitName != null 6626 && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames, 6627 info.activityInfo.splitName)) { 6628 if (mInstantAppInstallerInfo == null) { 6629 if (DEBUG_INSTALL) { 6630 Slog.v(TAG, "No installer - not adding it to the ResolveInfo list"); 6631 } 6632 resolveInfos.remove(i); 6633 continue; 6634 } 6635 // requested activity is defined in a split that hasn't been installed yet. 6636 // add the installer to the resolve list 6637 if (DEBUG_INSTALL) { 6638 Slog.v(TAG, "Adding installer to the ResolveInfo list"); 6639 } 6640 final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo); 6641 final ComponentName installFailureActivity = findInstallFailureActivity( 6642 info.activityInfo.packageName, filterCallingUid, userId); 6643 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 6644 info.activityInfo.packageName, info.activityInfo.splitName, 6645 installFailureActivity, 6646 info.activityInfo.applicationInfo.versionCode, 6647 null /*failureIntent*/); 6648 installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 6649 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 6650 // add a non-generic filter 6651 installerInfo.filter = new IntentFilter(); 6652 6653 // This resolve info may appear in the chooser UI, so let us make it 6654 // look as the one it replaces as far as the user is concerned which 6655 // requires loading the correct label and icon for the resolve info. 6656 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 6657 installerInfo.labelRes = info.resolveLabelResId(); 6658 installerInfo.icon = info.resolveIconResId(); 6659 6660 // propagate priority/preferred order/default 6661 installerInfo.priority = info.priority; 6662 installerInfo.preferredOrder = info.preferredOrder; 6663 installerInfo.isDefault = info.isDefault; 6664 resolveInfos.set(i, installerInfo); 6665 continue; 6666 } 6667 // caller is a full app, don't need to apply any other filtering 6668 if (ephemeralPkgName == null) { 6669 continue; 6670 } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) { 6671 // caller is same app; don't need to apply any other filtering 6672 continue; 6673 } 6674 // allow activities that have been explicitly exposed to ephemeral apps 6675 final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp(); 6676 if (!isEphemeralApp 6677 && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) { 6678 continue; 6679 } 6680 resolveInfos.remove(i); 6681 } 6682 return resolveInfos; 6683 } 6684 6685 /** 6686 * Returns the activity component that can handle install failures. 6687 * <p>By default, the instant application installer handles failures. However, an 6688 * application may want to handle failures on its own. Applications do this by 6689 * creating an activity with an intent filter that handles the action 6690 * {@link Intent#ACTION_INSTALL_FAILURE}. 6691 */ 6692 private @Nullable ComponentName findInstallFailureActivity( 6693 String packageName, int filterCallingUid, int userId) { 6694 final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE); 6695 failureActivityIntent.setPackage(packageName); 6696 // IMPORTANT: disallow dynamic splits to avoid an infinite loop 6697 final List<ResolveInfo> result = queryIntentActivitiesInternal( 6698 failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId, 6699 false /*resolveForStart*/, false /*allowDynamicSplits*/); 6700 final int NR = result.size(); 6701 if (NR > 0) { 6702 for (int i = 0; i < NR; i++) { 6703 final ResolveInfo info = result.get(i); 6704 if (info.activityInfo.splitName != null) { 6705 continue; 6706 } 6707 return new ComponentName(packageName, info.activityInfo.name); 6708 } 6709 } 6710 return null; 6711 } 6712 6713 /** 6714 * @param resolveInfos list of resolve infos in descending priority order 6715 * @return if the list contains a resolve info with non-negative priority 6716 */ 6717 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 6718 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 6719 } 6720 6721 private static boolean hasWebURI(Intent intent) { 6722 if (intent.getData() == null) { 6723 return false; 6724 } 6725 final String scheme = intent.getScheme(); 6726 if (TextUtils.isEmpty(scheme)) { 6727 return false; 6728 } 6729 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 6730 } 6731 6732 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 6733 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 6734 int userId) { 6735 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 6736 6737 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 6738 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 6739 candidates.size()); 6740 } 6741 6742 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 6743 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 6744 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 6745 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 6746 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 6747 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 6748 6749 synchronized (mPackages) { 6750 final int count = candidates.size(); 6751 // First, try to use linked apps. Partition the candidates into four lists: 6752 // one for the final results, one for the "do not use ever", one for "undefined status" 6753 // and finally one for "browser app type". 6754 for (int n=0; n<count; n++) { 6755 ResolveInfo info = candidates.get(n); 6756 String packageName = info.activityInfo.packageName; 6757 PackageSetting ps = mSettings.mPackages.get(packageName); 6758 if (ps != null) { 6759 // Add to the special match all list (Browser use case) 6760 if (info.handleAllWebDataURI) { 6761 matchAllList.add(info); 6762 continue; 6763 } 6764 // Try to get the status from User settings first 6765 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 6766 int status = (int)(packedStatus >> 32); 6767 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 6768 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 6769 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6770 Slog.i(TAG, " + always: " + info.activityInfo.packageName 6771 + " : linkgen=" + linkGeneration); 6772 } 6773 // Use link-enabled generation as preferredOrder, i.e. 6774 // prefer newly-enabled over earlier-enabled. 6775 info.preferredOrder = linkGeneration; 6776 alwaysList.add(info); 6777 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6778 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6779 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 6780 } 6781 neverList.add(info); 6782 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 6783 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6784 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 6785 } 6786 alwaysAskList.add(info); 6787 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 6788 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 6789 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6790 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 6791 } 6792 undefinedList.add(info); 6793 } 6794 } 6795 } 6796 6797 // We'll want to include browser possibilities in a few cases 6798 boolean includeBrowser = false; 6799 6800 // First try to add the "always" resolution(s) for the current user, if any 6801 if (alwaysList.size() > 0) { 6802 result.addAll(alwaysList); 6803 } else { 6804 // Add all undefined apps as we want them to appear in the disambiguation dialog. 6805 result.addAll(undefinedList); 6806 // Maybe add one for the other profile. 6807 if (xpDomainInfo != null && ( 6808 xpDomainInfo.bestDomainVerificationStatus 6809 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 6810 result.add(xpDomainInfo.resolveInfo); 6811 } 6812 includeBrowser = true; 6813 } 6814 6815 // The presence of any 'always ask' alternatives means we'll also offer browsers. 6816 // If there were 'always' entries their preferred order has been set, so we also 6817 // back that off to make the alternatives equivalent 6818 if (alwaysAskList.size() > 0) { 6819 for (ResolveInfo i : result) { 6820 i.preferredOrder = 0; 6821 } 6822 result.addAll(alwaysAskList); 6823 includeBrowser = true; 6824 } 6825 6826 if (includeBrowser) { 6827 // Also add browsers (all of them or only the default one) 6828 if (DEBUG_DOMAIN_VERIFICATION) { 6829 Slog.v(TAG, " ...including browsers in candidate set"); 6830 } 6831 if ((matchFlags & MATCH_ALL) != 0) { 6832 result.addAll(matchAllList); 6833 } else { 6834 // Browser/generic handling case. If there's a default browser, go straight 6835 // to that (but only if there is no other higher-priority match). 6836 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 6837 int maxMatchPrio = 0; 6838 ResolveInfo defaultBrowserMatch = null; 6839 final int numCandidates = matchAllList.size(); 6840 for (int n = 0; n < numCandidates; n++) { 6841 ResolveInfo info = matchAllList.get(n); 6842 // track the highest overall match priority... 6843 if (info.priority > maxMatchPrio) { 6844 maxMatchPrio = info.priority; 6845 } 6846 // ...and the highest-priority default browser match 6847 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 6848 if (defaultBrowserMatch == null 6849 || (defaultBrowserMatch.priority < info.priority)) { 6850 if (debug) { 6851 Slog.v(TAG, "Considering default browser match " + info); 6852 } 6853 defaultBrowserMatch = info; 6854 } 6855 } 6856 } 6857 if (defaultBrowserMatch != null 6858 && defaultBrowserMatch.priority >= maxMatchPrio 6859 && !TextUtils.isEmpty(defaultBrowserPackageName)) 6860 { 6861 if (debug) { 6862 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 6863 } 6864 result.add(defaultBrowserMatch); 6865 } else { 6866 result.addAll(matchAllList); 6867 } 6868 } 6869 6870 // If there is nothing selected, add all candidates and remove the ones that the user 6871 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 6872 if (result.size() == 0) { 6873 result.addAll(candidates); 6874 result.removeAll(neverList); 6875 } 6876 } 6877 } 6878 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 6879 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 6880 result.size()); 6881 for (ResolveInfo info : result) { 6882 Slog.v(TAG, " + " + info.activityInfo); 6883 } 6884 } 6885 return result; 6886 } 6887 6888 // Returns a packed value as a long: 6889 // 6890 // high 'int'-sized word: link status: undefined/ask/never/always. 6891 // low 'int'-sized word: relative priority among 'always' results. 6892 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 6893 long result = ps.getDomainVerificationStatusForUser(userId); 6894 // if none available, get the master status 6895 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 6896 if (ps.getIntentFilterVerificationInfo() != null) { 6897 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 6898 } 6899 } 6900 return result; 6901 } 6902 6903 private ResolveInfo querySkipCurrentProfileIntents( 6904 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 6905 int flags, int sourceUserId) { 6906 if (matchingFilters != null) { 6907 int size = matchingFilters.size(); 6908 for (int i = 0; i < size; i ++) { 6909 CrossProfileIntentFilter filter = matchingFilters.get(i); 6910 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 6911 // Checking if there are activities in the target user that can handle the 6912 // intent. 6913 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 6914 resolvedType, flags, sourceUserId); 6915 if (resolveInfo != null) { 6916 return resolveInfo; 6917 } 6918 } 6919 } 6920 } 6921 return null; 6922 } 6923 6924 // Return matching ResolveInfo in target user if any. 6925 private ResolveInfo queryCrossProfileIntents( 6926 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 6927 int flags, int sourceUserId, boolean matchInCurrentProfile) { 6928 if (matchingFilters != null) { 6929 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 6930 // match the same intent. For performance reasons, it is better not to 6931 // run queryIntent twice for the same userId 6932 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 6933 int size = matchingFilters.size(); 6934 for (int i = 0; i < size; i++) { 6935 CrossProfileIntentFilter filter = matchingFilters.get(i); 6936 int targetUserId = filter.getTargetUserId(); 6937 boolean skipCurrentProfile = 6938 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 6939 boolean skipCurrentProfileIfNoMatchFound = 6940 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 6941 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 6942 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 6943 // Checking if there are activities in the target user that can handle the 6944 // intent. 6945 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 6946 resolvedType, flags, sourceUserId); 6947 if (resolveInfo != null) return resolveInfo; 6948 alreadyTriedUserIds.put(targetUserId, true); 6949 } 6950 } 6951 } 6952 return null; 6953 } 6954 6955 /** 6956 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 6957 * will forward the intent to the filter's target user. 6958 * Otherwise, returns null. 6959 */ 6960 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 6961 String resolvedType, int flags, int sourceUserId) { 6962 int targetUserId = filter.getTargetUserId(); 6963 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 6964 resolvedType, flags, targetUserId); 6965 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 6966 // If all the matches in the target profile are suspended, return null. 6967 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 6968 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 6969 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 6970 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 6971 targetUserId); 6972 } 6973 } 6974 } 6975 return null; 6976 } 6977 6978 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 6979 int sourceUserId, int targetUserId) { 6980 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 6981 long ident = Binder.clearCallingIdentity(); 6982 boolean targetIsProfile; 6983 try { 6984 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 6985 } finally { 6986 Binder.restoreCallingIdentity(ident); 6987 } 6988 String className; 6989 if (targetIsProfile) { 6990 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 6991 } else { 6992 className = FORWARD_INTENT_TO_PARENT; 6993 } 6994 ComponentName forwardingActivityComponentName = new ComponentName( 6995 mAndroidApplication.packageName, className); 6996 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 6997 sourceUserId); 6998 if (!targetIsProfile) { 6999 forwardingActivityInfo.showUserIcon = targetUserId; 7000 forwardingResolveInfo.noResourceId = true; 7001 } 7002 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 7003 forwardingResolveInfo.priority = 0; 7004 forwardingResolveInfo.preferredOrder = 0; 7005 forwardingResolveInfo.match = 0; 7006 forwardingResolveInfo.isDefault = true; 7007 forwardingResolveInfo.filter = filter; 7008 forwardingResolveInfo.targetUserId = targetUserId; 7009 return forwardingResolveInfo; 7010 } 7011 7012 @Override 7013 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 7014 Intent[] specifics, String[] specificTypes, Intent intent, 7015 String resolvedType, int flags, int userId) { 7016 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 7017 specificTypes, intent, resolvedType, flags, userId)); 7018 } 7019 7020 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 7021 Intent[] specifics, String[] specificTypes, Intent intent, 7022 String resolvedType, int flags, int userId) { 7023 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7024 final int callingUid = Binder.getCallingUid(); 7025 flags = updateFlagsForResolve(flags, userId, intent, callingUid, 7026 false /*includeInstantApps*/); 7027 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 7028 false /*requireFullPermission*/, false /*checkShell*/, 7029 "query intent activity options"); 7030 final String resultsAction = intent.getAction(); 7031 7032 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 7033 | PackageManager.GET_RESOLVED_FILTER, userId); 7034 7035 if (DEBUG_INTENT_MATCHING) { 7036 Log.v(TAG, "Query " + intent + ": " + results); 7037 } 7038 7039 int specificsPos = 0; 7040 int N; 7041 7042 // todo: note that the algorithm used here is O(N^2). This 7043 // isn't a problem in our current environment, but if we start running 7044 // into situations where we have more than 5 or 10 matches then this 7045 // should probably be changed to something smarter... 7046 7047 // First we go through and resolve each of the specific items 7048 // that were supplied, taking care of removing any corresponding 7049 // duplicate items in the generic resolve list. 7050 if (specifics != null) { 7051 for (int i=0; i<specifics.length; i++) { 7052 final Intent sintent = specifics[i]; 7053 if (sintent == null) { 7054 continue; 7055 } 7056 7057 if (DEBUG_INTENT_MATCHING) { 7058 Log.v(TAG, "Specific #" + i + ": " + sintent); 7059 } 7060 7061 String action = sintent.getAction(); 7062 if (resultsAction != null && resultsAction.equals(action)) { 7063 // If this action was explicitly requested, then don't 7064 // remove things that have it. 7065 action = null; 7066 } 7067 7068 ResolveInfo ri = null; 7069 ActivityInfo ai = null; 7070 7071 ComponentName comp = sintent.getComponent(); 7072 if (comp == null) { 7073 ri = resolveIntent( 7074 sintent, 7075 specificTypes != null ? specificTypes[i] : null, 7076 flags, userId); 7077 if (ri == null) { 7078 continue; 7079 } 7080 if (ri == mResolveInfo) { 7081 // ACK! Must do something better with this. 7082 } 7083 ai = ri.activityInfo; 7084 comp = new ComponentName(ai.applicationInfo.packageName, 7085 ai.name); 7086 } else { 7087 ai = getActivityInfo(comp, flags, userId); 7088 if (ai == null) { 7089 continue; 7090 } 7091 } 7092 7093 // Look for any generic query activities that are duplicates 7094 // of this specific one, and remove them from the results. 7095 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 7096 N = results.size(); 7097 int j; 7098 for (j=specificsPos; j<N; j++) { 7099 ResolveInfo sri = results.get(j); 7100 if ((sri.activityInfo.name.equals(comp.getClassName()) 7101 && sri.activityInfo.applicationInfo.packageName.equals( 7102 comp.getPackageName())) 7103 || (action != null && sri.filter.matchAction(action))) { 7104 results.remove(j); 7105 if (DEBUG_INTENT_MATCHING) Log.v( 7106 TAG, "Removing duplicate item from " + j 7107 + " due to specific " + specificsPos); 7108 if (ri == null) { 7109 ri = sri; 7110 } 7111 j--; 7112 N--; 7113 } 7114 } 7115 7116 // Add this specific item to its proper place. 7117 if (ri == null) { 7118 ri = new ResolveInfo(); 7119 ri.activityInfo = ai; 7120 } 7121 results.add(specificsPos, ri); 7122 ri.specificIndex = i; 7123 specificsPos++; 7124 } 7125 } 7126 7127 // Now we go through the remaining generic results and remove any 7128 // duplicate actions that are found here. 7129 N = results.size(); 7130 for (int i=specificsPos; i<N-1; i++) { 7131 final ResolveInfo rii = results.get(i); 7132 if (rii.filter == null) { 7133 continue; 7134 } 7135 7136 // Iterate over all of the actions of this result's intent 7137 // filter... typically this should be just one. 7138 final Iterator<String> it = rii.filter.actionsIterator(); 7139 if (it == null) { 7140 continue; 7141 } 7142 while (it.hasNext()) { 7143 final String action = it.next(); 7144 if (resultsAction != null && resultsAction.equals(action)) { 7145 // If this action was explicitly requested, then don't 7146 // remove things that have it. 7147 continue; 7148 } 7149 for (int j=i+1; j<N; j++) { 7150 final ResolveInfo rij = results.get(j); 7151 if (rij.filter != null && rij.filter.hasAction(action)) { 7152 results.remove(j); 7153 if (DEBUG_INTENT_MATCHING) Log.v( 7154 TAG, "Removing duplicate item from " + j 7155 + " due to action " + action + " at " + i); 7156 j--; 7157 N--; 7158 } 7159 } 7160 } 7161 7162 // If the caller didn't request filter information, drop it now 7163 // so we don't have to marshall/unmarshall it. 7164 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 7165 rii.filter = null; 7166 } 7167 } 7168 7169 // Filter out the caller activity if so requested. 7170 if (caller != null) { 7171 N = results.size(); 7172 for (int i=0; i<N; i++) { 7173 ActivityInfo ainfo = results.get(i).activityInfo; 7174 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 7175 && caller.getClassName().equals(ainfo.name)) { 7176 results.remove(i); 7177 break; 7178 } 7179 } 7180 } 7181 7182 // If the caller didn't request filter information, 7183 // drop them now so we don't have to 7184 // marshall/unmarshall it. 7185 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 7186 N = results.size(); 7187 for (int i=0; i<N; i++) { 7188 results.get(i).filter = null; 7189 } 7190 } 7191 7192 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 7193 return results; 7194 } 7195 7196 @Override 7197 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 7198 String resolvedType, int flags, int userId) { 7199 return new ParceledListSlice<>( 7200 queryIntentReceiversInternal(intent, resolvedType, flags, userId, 7201 false /*allowDynamicSplits*/)); 7202 } 7203 7204 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 7205 String resolvedType, int flags, int userId, boolean allowDynamicSplits) { 7206 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7207 final int callingUid = Binder.getCallingUid(); 7208 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 7209 false /*requireFullPermission*/, false /*checkShell*/, 7210 "query intent receivers"); 7211 final String instantAppPkgName = getInstantAppPackageName(callingUid); 7212 flags = updateFlagsForResolve(flags, userId, intent, callingUid, 7213 false /*includeInstantApps*/); 7214 ComponentName comp = intent.getComponent(); 7215 if (comp == null) { 7216 if (intent.getSelector() != null) { 7217 intent = intent.getSelector(); 7218 comp = intent.getComponent(); 7219 } 7220 } 7221 if (comp != null) { 7222 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7223 final ActivityInfo ai = getReceiverInfo(comp, flags, userId); 7224 if (ai != null) { 7225 // When specifying an explicit component, we prevent the activity from being 7226 // used when either 1) the calling package is normal and the activity is within 7227 // an instant application or 2) the calling package is ephemeral and the 7228 // activity is not visible to instant applications. 7229 final boolean matchInstantApp = 7230 (flags & PackageManager.MATCH_INSTANT) != 0; 7231 final boolean matchVisibleToInstantAppOnly = 7232 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 7233 final boolean matchExplicitlyVisibleOnly = 7234 (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0; 7235 final boolean isCallerInstantApp = 7236 instantAppPkgName != null; 7237 final boolean isTargetSameInstantApp = 7238 comp.getPackageName().equals(instantAppPkgName); 7239 final boolean isTargetInstantApp = 7240 (ai.applicationInfo.privateFlags 7241 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 7242 final boolean isTargetVisibleToInstantApp = 7243 (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0; 7244 final boolean isTargetExplicitlyVisibleToInstantApp = 7245 isTargetVisibleToInstantApp 7246 && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0; 7247 final boolean isTargetHiddenFromInstantApp = 7248 !isTargetVisibleToInstantApp 7249 || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp); 7250 final boolean blockResolution = 7251 !isTargetSameInstantApp 7252 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 7253 || (matchVisibleToInstantAppOnly && isCallerInstantApp 7254 && isTargetHiddenFromInstantApp)); 7255 if (!blockResolution) { 7256 ResolveInfo ri = new ResolveInfo(); 7257 ri.activityInfo = ai; 7258 list.add(ri); 7259 } 7260 } 7261 return applyPostResolutionFilter( 7262 list, instantAppPkgName, allowDynamicSplits, callingUid, userId); 7263 } 7264 7265 // reader 7266 synchronized (mPackages) { 7267 String pkgName = intent.getPackage(); 7268 if (pkgName == null) { 7269 final List<ResolveInfo> result = 7270 mReceivers.queryIntent(intent, resolvedType, flags, userId); 7271 return applyPostResolutionFilter( 7272 result, instantAppPkgName, allowDynamicSplits, callingUid, userId); 7273 } 7274 final PackageParser.Package pkg = mPackages.get(pkgName); 7275 if (pkg != null) { 7276 final List<ResolveInfo> result = mReceivers.queryIntentForPackage( 7277 intent, resolvedType, flags, pkg.receivers, userId); 7278 return applyPostResolutionFilter( 7279 result, instantAppPkgName, allowDynamicSplits, callingUid, userId); 7280 } 7281 return Collections.emptyList(); 7282 } 7283 } 7284 7285 @Override 7286 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 7287 final int callingUid = Binder.getCallingUid(); 7288 return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid); 7289 } 7290 7291 private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags, 7292 int userId, int callingUid) { 7293 if (!sUserManager.exists(userId)) return null; 7294 flags = updateFlagsForResolve( 7295 flags, userId, intent, callingUid, false /*includeInstantApps*/); 7296 List<ResolveInfo> query = queryIntentServicesInternal( 7297 intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/); 7298 if (query != null) { 7299 if (query.size() >= 1) { 7300 // If there is more than one service with the same priority, 7301 // just arbitrarily pick the first one. 7302 return query.get(0); 7303 } 7304 } 7305 return null; 7306 } 7307 7308 @Override 7309 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 7310 String resolvedType, int flags, int userId) { 7311 final int callingUid = Binder.getCallingUid(); 7312 return new ParceledListSlice<>(queryIntentServicesInternal( 7313 intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/)); 7314 } 7315 7316 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 7317 String resolvedType, int flags, int userId, int callingUid, 7318 boolean includeInstantApps) { 7319 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7320 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 7321 false /*requireFullPermission*/, false /*checkShell*/, 7322 "query intent receivers"); 7323 final String instantAppPkgName = getInstantAppPackageName(callingUid); 7324 flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps); 7325 ComponentName comp = intent.getComponent(); 7326 if (comp == null) { 7327 if (intent.getSelector() != null) { 7328 intent = intent.getSelector(); 7329 comp = intent.getComponent(); 7330 } 7331 } 7332 if (comp != null) { 7333 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7334 final ServiceInfo si = getServiceInfo(comp, flags, userId); 7335 if (si != null) { 7336 // When specifying an explicit component, we prevent the service from being 7337 // used when either 1) the service is in an instant application and the 7338 // caller is not the same instant application or 2) the calling package is 7339 // ephemeral and the activity is not visible to ephemeral applications. 7340 final boolean matchInstantApp = 7341 (flags & PackageManager.MATCH_INSTANT) != 0; 7342 final boolean matchVisibleToInstantAppOnly = 7343 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 7344 final boolean isCallerInstantApp = 7345 instantAppPkgName != null; 7346 final boolean isTargetSameInstantApp = 7347 comp.getPackageName().equals(instantAppPkgName); 7348 final boolean isTargetInstantApp = 7349 (si.applicationInfo.privateFlags 7350 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 7351 final boolean isTargetHiddenFromInstantApp = 7352 (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0; 7353 final boolean blockResolution = 7354 !isTargetSameInstantApp 7355 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 7356 || (matchVisibleToInstantAppOnly && isCallerInstantApp 7357 && isTargetHiddenFromInstantApp)); 7358 if (!blockResolution) { 7359 final ResolveInfo ri = new ResolveInfo(); 7360 ri.serviceInfo = si; 7361 list.add(ri); 7362 } 7363 } 7364 return list; 7365 } 7366 7367 // reader 7368 synchronized (mPackages) { 7369 String pkgName = intent.getPackage(); 7370 if (pkgName == null) { 7371 return applyPostServiceResolutionFilter( 7372 mServices.queryIntent(intent, resolvedType, flags, userId), 7373 instantAppPkgName); 7374 } 7375 final PackageParser.Package pkg = mPackages.get(pkgName); 7376 if (pkg != null) { 7377 return applyPostServiceResolutionFilter( 7378 mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 7379 userId), 7380 instantAppPkgName); 7381 } 7382 return Collections.emptyList(); 7383 } 7384 } 7385 7386 private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos, 7387 String instantAppPkgName) { 7388 if (instantAppPkgName == null) { 7389 return resolveInfos; 7390 } 7391 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 7392 final ResolveInfo info = resolveInfos.get(i); 7393 final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp(); 7394 // allow services that are defined in the provided package 7395 if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) { 7396 if (info.serviceInfo.splitName != null 7397 && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames, 7398 info.serviceInfo.splitName)) { 7399 // requested service is defined in a split that hasn't been installed yet. 7400 // add the installer to the resolve list 7401 if (DEBUG_EPHEMERAL) { 7402 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 7403 } 7404 final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo); 7405 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 7406 info.serviceInfo.packageName, info.serviceInfo.splitName, 7407 null /*failureActivity*/, info.serviceInfo.applicationInfo.versionCode, 7408 null /*failureIntent*/); 7409 // make sure this resolver is the default 7410 installerInfo.isDefault = true; 7411 installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 7412 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 7413 // add a non-generic filter 7414 installerInfo.filter = new IntentFilter(); 7415 // load resources from the correct package 7416 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 7417 resolveInfos.set(i, installerInfo); 7418 } 7419 continue; 7420 } 7421 // allow services that have been explicitly exposed to ephemeral apps 7422 if (!isEphemeralApp 7423 && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) { 7424 continue; 7425 } 7426 resolveInfos.remove(i); 7427 } 7428 return resolveInfos; 7429 } 7430 7431 @Override 7432 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 7433 String resolvedType, int flags, int userId) { 7434 return new ParceledListSlice<>( 7435 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 7436 } 7437 7438 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 7439 Intent intent, String resolvedType, int flags, int userId) { 7440 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7441 final int callingUid = Binder.getCallingUid(); 7442 final String instantAppPkgName = getInstantAppPackageName(callingUid); 7443 flags = updateFlagsForResolve(flags, userId, intent, callingUid, 7444 false /*includeInstantApps*/); 7445 ComponentName comp = intent.getComponent(); 7446 if (comp == null) { 7447 if (intent.getSelector() != null) { 7448 intent = intent.getSelector(); 7449 comp = intent.getComponent(); 7450 } 7451 } 7452 if (comp != null) { 7453 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7454 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 7455 if (pi != null) { 7456 // When specifying an explicit component, we prevent the provider from being 7457 // used when either 1) the provider is in an instant application and the 7458 // caller is not the same instant application or 2) the calling package is an 7459 // instant application and the provider is not visible to instant applications. 7460 final boolean matchInstantApp = 7461 (flags & PackageManager.MATCH_INSTANT) != 0; 7462 final boolean matchVisibleToInstantAppOnly = 7463 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 7464 final boolean isCallerInstantApp = 7465 instantAppPkgName != null; 7466 final boolean isTargetSameInstantApp = 7467 comp.getPackageName().equals(instantAppPkgName); 7468 final boolean isTargetInstantApp = 7469 (pi.applicationInfo.privateFlags 7470 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 7471 final boolean isTargetHiddenFromInstantApp = 7472 (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0; 7473 final boolean blockResolution = 7474 !isTargetSameInstantApp 7475 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 7476 || (matchVisibleToInstantAppOnly && isCallerInstantApp 7477 && isTargetHiddenFromInstantApp)); 7478 if (!blockResolution) { 7479 final ResolveInfo ri = new ResolveInfo(); 7480 ri.providerInfo = pi; 7481 list.add(ri); 7482 } 7483 } 7484 return list; 7485 } 7486 7487 // reader 7488 synchronized (mPackages) { 7489 String pkgName = intent.getPackage(); 7490 if (pkgName == null) { 7491 return applyPostContentProviderResolutionFilter( 7492 mProviders.queryIntent(intent, resolvedType, flags, userId), 7493 instantAppPkgName); 7494 } 7495 final PackageParser.Package pkg = mPackages.get(pkgName); 7496 if (pkg != null) { 7497 return applyPostContentProviderResolutionFilter( 7498 mProviders.queryIntentForPackage( 7499 intent, resolvedType, flags, pkg.providers, userId), 7500 instantAppPkgName); 7501 } 7502 return Collections.emptyList(); 7503 } 7504 } 7505 7506 private List<ResolveInfo> applyPostContentProviderResolutionFilter( 7507 List<ResolveInfo> resolveInfos, String instantAppPkgName) { 7508 if (instantAppPkgName == null) { 7509 return resolveInfos; 7510 } 7511 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 7512 final ResolveInfo info = resolveInfos.get(i); 7513 final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp(); 7514 // allow providers that are defined in the provided package 7515 if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) { 7516 if (info.providerInfo.splitName != null 7517 && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames, 7518 info.providerInfo.splitName)) { 7519 // requested provider is defined in a split that hasn't been installed yet. 7520 // add the installer to the resolve list 7521 if (DEBUG_EPHEMERAL) { 7522 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 7523 } 7524 final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo); 7525 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 7526 info.providerInfo.packageName, info.providerInfo.splitName, 7527 null /*failureActivity*/, info.providerInfo.applicationInfo.versionCode, 7528 null /*failureIntent*/); 7529 // make sure this resolver is the default 7530 installerInfo.isDefault = true; 7531 installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 7532 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 7533 // add a non-generic filter 7534 installerInfo.filter = new IntentFilter(); 7535 // load resources from the correct package 7536 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 7537 resolveInfos.set(i, installerInfo); 7538 } 7539 continue; 7540 } 7541 // allow providers that have been explicitly exposed to instant applications 7542 if (!isEphemeralApp 7543 && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) { 7544 continue; 7545 } 7546 resolveInfos.remove(i); 7547 } 7548 return resolveInfos; 7549 } 7550 7551 @Override 7552 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 7553 final int callingUid = Binder.getCallingUid(); 7554 if (getInstantAppPackageName(callingUid) != null) { 7555 return ParceledListSlice.emptyList(); 7556 } 7557 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7558 flags = updateFlagsForPackage(flags, userId, null); 7559 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7560 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 7561 true /* requireFullPermission */, false /* checkShell */, 7562 "get installed packages"); 7563 7564 // writer 7565 synchronized (mPackages) { 7566 ArrayList<PackageInfo> list; 7567 if (listUninstalled) { 7568 list = new ArrayList<>(mSettings.mPackages.size()); 7569 for (PackageSetting ps : mSettings.mPackages.values()) { 7570 if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) { 7571 continue; 7572 } 7573 if (filterAppAccessLPr(ps, callingUid, userId)) { 7574 continue; 7575 } 7576 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 7577 if (pi != null) { 7578 list.add(pi); 7579 } 7580 } 7581 } else { 7582 list = new ArrayList<>(mPackages.size()); 7583 for (PackageParser.Package p : mPackages.values()) { 7584 final PackageSetting ps = (PackageSetting) p.mExtras; 7585 if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) { 7586 continue; 7587 } 7588 if (filterAppAccessLPr(ps, callingUid, userId)) { 7589 continue; 7590 } 7591 final PackageInfo pi = generatePackageInfo((PackageSetting) 7592 p.mExtras, flags, userId); 7593 if (pi != null) { 7594 list.add(pi); 7595 } 7596 } 7597 } 7598 7599 return new ParceledListSlice<>(list); 7600 } 7601 } 7602 7603 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 7604 String[] permissions, boolean[] tmp, int flags, int userId) { 7605 int numMatch = 0; 7606 final PermissionsState permissionsState = ps.getPermissionsState(); 7607 for (int i=0; i<permissions.length; i++) { 7608 final String permission = permissions[i]; 7609 if (permissionsState.hasPermission(permission, userId)) { 7610 tmp[i] = true; 7611 numMatch++; 7612 } else { 7613 tmp[i] = false; 7614 } 7615 } 7616 if (numMatch == 0) { 7617 return; 7618 } 7619 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 7620 7621 // The above might return null in cases of uninstalled apps or install-state 7622 // skew across users/profiles. 7623 if (pi != null) { 7624 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 7625 if (numMatch == permissions.length) { 7626 pi.requestedPermissions = permissions; 7627 } else { 7628 pi.requestedPermissions = new String[numMatch]; 7629 numMatch = 0; 7630 for (int i=0; i<permissions.length; i++) { 7631 if (tmp[i]) { 7632 pi.requestedPermissions[numMatch] = permissions[i]; 7633 numMatch++; 7634 } 7635 } 7636 } 7637 } 7638 list.add(pi); 7639 } 7640 } 7641 7642 @Override 7643 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 7644 String[] permissions, int flags, int userId) { 7645 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7646 flags = updateFlagsForPackage(flags, userId, permissions); 7647 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 7648 true /* requireFullPermission */, false /* checkShell */, 7649 "get packages holding permissions"); 7650 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7651 7652 // writer 7653 synchronized (mPackages) { 7654 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 7655 boolean[] tmpBools = new boolean[permissions.length]; 7656 if (listUninstalled) { 7657 for (PackageSetting ps : mSettings.mPackages.values()) { 7658 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 7659 userId); 7660 } 7661 } else { 7662 for (PackageParser.Package pkg : mPackages.values()) { 7663 PackageSetting ps = (PackageSetting)pkg.mExtras; 7664 if (ps != null) { 7665 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 7666 userId); 7667 } 7668 } 7669 } 7670 7671 return new ParceledListSlice<PackageInfo>(list); 7672 } 7673 } 7674 7675 @Override 7676 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 7677 final int callingUid = Binder.getCallingUid(); 7678 if (getInstantAppPackageName(callingUid) != null) { 7679 return ParceledListSlice.emptyList(); 7680 } 7681 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7682 flags = updateFlagsForApplication(flags, userId, null); 7683 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7684 7685 // writer 7686 synchronized (mPackages) { 7687 ArrayList<ApplicationInfo> list; 7688 if (listUninstalled) { 7689 list = new ArrayList<>(mSettings.mPackages.size()); 7690 for (PackageSetting ps : mSettings.mPackages.values()) { 7691 ApplicationInfo ai; 7692 int effectiveFlags = flags; 7693 if (ps.isSystem()) { 7694 effectiveFlags |= PackageManager.MATCH_ANY_USER; 7695 } 7696 if (ps.pkg != null) { 7697 if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) { 7698 continue; 7699 } 7700 if (filterAppAccessLPr(ps, callingUid, userId)) { 7701 continue; 7702 } 7703 ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags, 7704 ps.readUserState(userId), userId); 7705 if (ai != null) { 7706 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 7707 } 7708 } else { 7709 // Shared lib filtering done in generateApplicationInfoFromSettingsLPw 7710 // and already converts to externally visible package name 7711 ai = generateApplicationInfoFromSettingsLPw(ps.name, 7712 callingUid, effectiveFlags, userId); 7713 } 7714 if (ai != null) { 7715 list.add(ai); 7716 } 7717 } 7718 } else { 7719 list = new ArrayList<>(mPackages.size()); 7720 for (PackageParser.Package p : mPackages.values()) { 7721 if (p.mExtras != null) { 7722 PackageSetting ps = (PackageSetting) p.mExtras; 7723 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) { 7724 continue; 7725 } 7726 if (filterAppAccessLPr(ps, callingUid, userId)) { 7727 continue; 7728 } 7729 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 7730 ps.readUserState(userId), userId); 7731 if (ai != null) { 7732 ai.packageName = resolveExternalPackageNameLPr(p); 7733 list.add(ai); 7734 } 7735 } 7736 } 7737 } 7738 7739 return new ParceledListSlice<>(list); 7740 } 7741 } 7742 7743 @Override 7744 public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) { 7745 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7746 return null; 7747 } 7748 if (!canViewInstantApps(Binder.getCallingUid(), userId)) { 7749 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS, 7750 "getEphemeralApplications"); 7751 } 7752 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 7753 true /* requireFullPermission */, false /* checkShell */, 7754 "getEphemeralApplications"); 7755 synchronized (mPackages) { 7756 List<InstantAppInfo> instantApps = mInstantAppRegistry 7757 .getInstantAppsLPr(userId); 7758 if (instantApps != null) { 7759 return new ParceledListSlice<>(instantApps); 7760 } 7761 } 7762 return null; 7763 } 7764 7765 @Override 7766 public boolean isInstantApp(String packageName, int userId) { 7767 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 7768 true /* requireFullPermission */, false /* checkShell */, 7769 "isInstantApp"); 7770 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7771 return false; 7772 } 7773 7774 synchronized (mPackages) { 7775 int callingUid = Binder.getCallingUid(); 7776 if (Process.isIsolated(callingUid)) { 7777 callingUid = mIsolatedOwners.get(callingUid); 7778 } 7779 final PackageSetting ps = mSettings.mPackages.get(packageName); 7780 PackageParser.Package pkg = mPackages.get(packageName); 7781 final boolean returnAllowed = 7782 ps != null 7783 && (isCallerSameApp(packageName, callingUid) 7784 || canViewInstantApps(callingUid, userId) 7785 || mInstantAppRegistry.isInstantAccessGranted( 7786 userId, UserHandle.getAppId(callingUid), ps.appId)); 7787 if (returnAllowed) { 7788 return ps.getInstantApp(userId); 7789 } 7790 } 7791 return false; 7792 } 7793 7794 @Override 7795 public byte[] getInstantAppCookie(String packageName, int userId) { 7796 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7797 return null; 7798 } 7799 7800 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 7801 true /* requireFullPermission */, false /* checkShell */, 7802 "getInstantAppCookie"); 7803 if (!isCallerSameApp(packageName, Binder.getCallingUid())) { 7804 return null; 7805 } 7806 synchronized (mPackages) { 7807 return mInstantAppRegistry.getInstantAppCookieLPw( 7808 packageName, userId); 7809 } 7810 } 7811 7812 @Override 7813 public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) { 7814 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7815 return true; 7816 } 7817 7818 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 7819 true /* requireFullPermission */, true /* checkShell */, 7820 "setInstantAppCookie"); 7821 if (!isCallerSameApp(packageName, Binder.getCallingUid())) { 7822 return false; 7823 } 7824 synchronized (mPackages) { 7825 return mInstantAppRegistry.setInstantAppCookieLPw( 7826 packageName, cookie, userId); 7827 } 7828 } 7829 7830 @Override 7831 public Bitmap getInstantAppIcon(String packageName, int userId) { 7832 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7833 return null; 7834 } 7835 7836 if (!canViewInstantApps(Binder.getCallingUid(), userId)) { 7837 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS, 7838 "getInstantAppIcon"); 7839 } 7840 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 7841 true /* requireFullPermission */, false /* checkShell */, 7842 "getInstantAppIcon"); 7843 7844 synchronized (mPackages) { 7845 return mInstantAppRegistry.getInstantAppIconLPw( 7846 packageName, userId); 7847 } 7848 } 7849 7850 private boolean isCallerSameApp(String packageName, int uid) { 7851 PackageParser.Package pkg = mPackages.get(packageName); 7852 return pkg != null 7853 && UserHandle.getAppId(uid) == pkg.applicationInfo.uid; 7854 } 7855 7856 @Override 7857 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 7858 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 7859 return ParceledListSlice.emptyList(); 7860 } 7861 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 7862 } 7863 7864 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 7865 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 7866 7867 // reader 7868 synchronized (mPackages) { 7869 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 7870 final int userId = UserHandle.getCallingUserId(); 7871 while (i.hasNext()) { 7872 final PackageParser.Package p = i.next(); 7873 if (p.applicationInfo == null) continue; 7874 7875 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 7876 && !p.applicationInfo.isDirectBootAware(); 7877 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 7878 && p.applicationInfo.isDirectBootAware(); 7879 7880 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 7881 && (!mSafeMode || isSystemApp(p)) 7882 && (matchesUnaware || matchesAware)) { 7883 PackageSetting ps = mSettings.mPackages.get(p.packageName); 7884 if (ps != null) { 7885 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 7886 ps.readUserState(userId), userId); 7887 if (ai != null) { 7888 finalList.add(ai); 7889 } 7890 } 7891 } 7892 } 7893 } 7894 7895 return finalList; 7896 } 7897 7898 @Override 7899 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 7900 return resolveContentProviderInternal(name, flags, userId); 7901 } 7902 7903 private ProviderInfo resolveContentProviderInternal(String name, int flags, int userId) { 7904 if (!sUserManager.exists(userId)) return null; 7905 flags = updateFlagsForComponent(flags, userId, name); 7906 final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid()); 7907 // reader 7908 synchronized (mPackages) { 7909 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 7910 PackageSetting ps = provider != null 7911 ? mSettings.mPackages.get(provider.owner.packageName) 7912 : null; 7913 if (ps != null) { 7914 final boolean isInstantApp = ps.getInstantApp(userId); 7915 // normal application; filter out instant application provider 7916 if (instantAppPkgName == null && isInstantApp) { 7917 return null; 7918 } 7919 // instant application; filter out other instant applications 7920 if (instantAppPkgName != null 7921 && isInstantApp 7922 && !provider.owner.packageName.equals(instantAppPkgName)) { 7923 return null; 7924 } 7925 // instant application; filter out non-exposed provider 7926 if (instantAppPkgName != null 7927 && !isInstantApp 7928 && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) { 7929 return null; 7930 } 7931 // provider not enabled 7932 if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) { 7933 return null; 7934 } 7935 return PackageParser.generateProviderInfo( 7936 provider, flags, ps.readUserState(userId), userId); 7937 } 7938 return null; 7939 } 7940 } 7941 7942 /** 7943 * @deprecated 7944 */ 7945 @Deprecated 7946 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 7947 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 7948 return; 7949 } 7950 // reader 7951 synchronized (mPackages) { 7952 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 7953 .entrySet().iterator(); 7954 final int userId = UserHandle.getCallingUserId(); 7955 while (i.hasNext()) { 7956 Map.Entry<String, PackageParser.Provider> entry = i.next(); 7957 PackageParser.Provider p = entry.getValue(); 7958 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 7959 7960 if (ps != null && p.syncable 7961 && (!mSafeMode || (p.info.applicationInfo.flags 7962 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 7963 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 7964 ps.readUserState(userId), userId); 7965 if (info != null) { 7966 outNames.add(entry.getKey()); 7967 outInfo.add(info); 7968 } 7969 } 7970 } 7971 } 7972 } 7973 7974 @Override 7975 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 7976 int uid, int flags, String metaDataKey) { 7977 final int callingUid = Binder.getCallingUid(); 7978 final int userId = processName != null ? UserHandle.getUserId(uid) 7979 : UserHandle.getCallingUserId(); 7980 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7981 flags = updateFlagsForComponent(flags, userId, processName); 7982 ArrayList<ProviderInfo> finalList = null; 7983 // reader 7984 synchronized (mPackages) { 7985 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 7986 while (i.hasNext()) { 7987 final PackageParser.Provider p = i.next(); 7988 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 7989 if (ps != null && p.info.authority != null 7990 && (processName == null 7991 || (p.info.processName.equals(processName) 7992 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 7993 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 7994 7995 // See PM.queryContentProviders()'s javadoc for why we have the metaData 7996 // parameter. 7997 if (metaDataKey != null 7998 && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) { 7999 continue; 8000 } 8001 final ComponentName component = 8002 new ComponentName(p.info.packageName, p.info.name); 8003 if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) { 8004 continue; 8005 } 8006 if (finalList == null) { 8007 finalList = new ArrayList<ProviderInfo>(3); 8008 } 8009 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 8010 ps.readUserState(userId), userId); 8011 if (info != null) { 8012 finalList.add(info); 8013 } 8014 } 8015 } 8016 } 8017 8018 if (finalList != null) { 8019 Collections.sort(finalList, mProviderInitOrderSorter); 8020 return new ParceledListSlice<ProviderInfo>(finalList); 8021 } 8022 8023 return ParceledListSlice.emptyList(); 8024 } 8025 8026 @Override 8027 public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) { 8028 // reader 8029 synchronized (mPackages) { 8030 final int callingUid = Binder.getCallingUid(); 8031 final int callingUserId = UserHandle.getUserId(callingUid); 8032 final PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 8033 if (ps == null) return null; 8034 if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) { 8035 return null; 8036 } 8037 final PackageParser.Instrumentation i = mInstrumentation.get(component); 8038 return PackageParser.generateInstrumentationInfo(i, flags); 8039 } 8040 } 8041 8042 @Override 8043 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 8044 String targetPackage, int flags) { 8045 final int callingUid = Binder.getCallingUid(); 8046 final int callingUserId = UserHandle.getUserId(callingUid); 8047 final PackageSetting ps = mSettings.mPackages.get(targetPackage); 8048 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 8049 return ParceledListSlice.emptyList(); 8050 } 8051 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 8052 } 8053 8054 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 8055 int flags) { 8056 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 8057 8058 // reader 8059 synchronized (mPackages) { 8060 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 8061 while (i.hasNext()) { 8062 final PackageParser.Instrumentation p = i.next(); 8063 if (targetPackage == null 8064 || targetPackage.equals(p.info.targetPackage)) { 8065 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 8066 flags); 8067 if (ii != null) { 8068 finalList.add(ii); 8069 } 8070 } 8071 } 8072 } 8073 8074 return finalList; 8075 } 8076 8077 private void scanDirTracedLI(File scanDir, final int parseFlags, int scanFlags, long currentTime) { 8078 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + scanDir.getAbsolutePath() + "]"); 8079 try { 8080 scanDirLI(scanDir, parseFlags, scanFlags, currentTime); 8081 } finally { 8082 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8083 } 8084 } 8085 8086 private void scanDirLI(File scanDir, int parseFlags, int scanFlags, long currentTime) { 8087 final File[] files = scanDir.listFiles(); 8088 if (ArrayUtils.isEmpty(files)) { 8089 Log.d(TAG, "No files in app dir " + scanDir); 8090 return; 8091 } 8092 8093 if (DEBUG_PACKAGE_SCANNING) { 8094 Log.d(TAG, "Scanning app dir " + scanDir + " scanFlags=" + scanFlags 8095 + " flags=0x" + Integer.toHexString(parseFlags)); 8096 } 8097 try (ParallelPackageParser parallelPackageParser = new ParallelPackageParser( 8098 mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir, 8099 mParallelPackageParserCallback)) { 8100 // Submit files for parsing in parallel 8101 int fileCount = 0; 8102 for (File file : files) { 8103 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 8104 && !PackageInstallerService.isStageName(file.getName()); 8105 if (!isPackage) { 8106 // Ignore entries which are not packages 8107 continue; 8108 } 8109 parallelPackageParser.submit(file, parseFlags); 8110 fileCount++; 8111 } 8112 8113 // Process results one by one 8114 for (; fileCount > 0; fileCount--) { 8115 ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take(); 8116 Throwable throwable = parseResult.throwable; 8117 int errorCode = PackageManager.INSTALL_SUCCEEDED; 8118 8119 if (throwable == null) { 8120 // Static shared libraries have synthetic package names 8121 if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) { 8122 renameStaticSharedLibraryPackage(parseResult.pkg); 8123 } 8124 try { 8125 if (errorCode == PackageManager.INSTALL_SUCCEEDED) { 8126 scanPackageChildLI(parseResult.pkg, parseFlags, scanFlags, 8127 currentTime, null); 8128 } 8129 } catch (PackageManagerException e) { 8130 errorCode = e.error; 8131 Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage()); 8132 } 8133 } else if (throwable instanceof PackageParser.PackageParserException) { 8134 PackageParser.PackageParserException e = (PackageParser.PackageParserException) 8135 throwable; 8136 errorCode = e.error; 8137 Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage()); 8138 } else { 8139 throw new IllegalStateException("Unexpected exception occurred while parsing " 8140 + parseResult.scanFile, throwable); 8141 } 8142 8143 // Delete invalid userdata apps 8144 if ((scanFlags & SCAN_AS_SYSTEM) == 0 && 8145 errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) { 8146 logCriticalInfo(Log.WARN, 8147 "Deleting invalid package at " + parseResult.scanFile); 8148 removeCodePathLI(parseResult.scanFile); 8149 } 8150 } 8151 } 8152 } 8153 8154 public static void reportSettingsProblem(int priority, String msg) { 8155 logCriticalInfo(priority, msg); 8156 } 8157 8158 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, 8159 final @ParseFlags int parseFlags) throws PackageManagerException { 8160 // When upgrading from pre-N MR1, verify the package time stamp using the package 8161 // directory and not the APK file. 8162 final long lastModifiedTime = mIsPreNMR1Upgrade 8163 ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg); 8164 if (ps != null 8165 && ps.codePathString.equals(pkg.codePath) 8166 && ps.timeStamp == lastModifiedTime 8167 && !isCompatSignatureUpdateNeeded(pkg) 8168 && !isRecoverSignatureUpdateNeeded(pkg)) { 8169 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 8170 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 8171 ArraySet<PublicKey> signingKs; 8172 synchronized (mPackages) { 8173 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 8174 } 8175 if (ps.signatures.mSignatures != null 8176 && ps.signatures.mSignatures.length != 0 8177 && signingKs != null) { 8178 // Optimization: reuse the existing cached certificates 8179 // if the package appears to be unchanged. 8180 pkg.mSignatures = ps.signatures.mSignatures; 8181 pkg.mSigningKeys = signingKs; 8182 return; 8183 } 8184 8185 Slog.w(TAG, "PackageSetting for " + ps.name 8186 + " is missing signatures. Collecting certs again to recover them."); 8187 } else { 8188 Slog.i(TAG, toString() + " changed; collecting certs"); 8189 } 8190 8191 try { 8192 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 8193 PackageParser.collectCertificates(pkg, parseFlags); 8194 } catch (PackageParserException e) { 8195 throw PackageManagerException.from(e); 8196 } finally { 8197 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8198 } 8199 } 8200 8201 /** 8202 * Traces a package scan. 8203 * @see #scanPackageLI(File, int, int, long, UserHandle) 8204 */ 8205 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 8206 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 8207 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]"); 8208 try { 8209 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 8210 } finally { 8211 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8212 } 8213 } 8214 8215 /** 8216 * Scans a package and returns the newly parsed package. 8217 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 8218 */ 8219 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 8220 long currentTime, UserHandle user) throws PackageManagerException { 8221 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 8222 PackageParser pp = new PackageParser(); 8223 pp.setSeparateProcesses(mSeparateProcesses); 8224 pp.setOnlyCoreApps(mOnlyCore); 8225 pp.setDisplayMetrics(mMetrics); 8226 pp.setCallback(mPackageParserCallback); 8227 8228 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 8229 final PackageParser.Package pkg; 8230 try { 8231 pkg = pp.parsePackage(scanFile, parseFlags); 8232 } catch (PackageParserException e) { 8233 throw PackageManagerException.from(e); 8234 } finally { 8235 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8236 } 8237 8238 // Static shared libraries have synthetic package names 8239 if (pkg.applicationInfo.isStaticSharedLibrary()) { 8240 renameStaticSharedLibraryPackage(pkg); 8241 } 8242 8243 return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user); 8244 } 8245 8246 /** 8247 * Scans a package and returns the newly parsed package. 8248 * @throws PackageManagerException on a parse error. 8249 */ 8250 private PackageParser.Package scanPackageChildLI(PackageParser.Package pkg, 8251 final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime, 8252 @Nullable UserHandle user) 8253 throws PackageManagerException { 8254 // If the package has children and this is the first dive in the function 8255 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 8256 // packages (parent and children) would be successfully scanned before the 8257 // actual scan since scanning mutates internal state and we want to atomically 8258 // install the package and its children. 8259 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8260 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 8261 scanFlags |= SCAN_CHECK_ONLY; 8262 } 8263 } else { 8264 scanFlags &= ~SCAN_CHECK_ONLY; 8265 } 8266 8267 // Scan the parent 8268 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, parseFlags, 8269 scanFlags, currentTime, user); 8270 8271 // Scan the children 8272 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8273 for (int i = 0; i < childCount; i++) { 8274 PackageParser.Package childPackage = pkg.childPackages.get(i); 8275 scanPackageInternalLI(childPackage, parseFlags, scanFlags, 8276 currentTime, user); 8277 } 8278 8279 8280 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8281 return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user); 8282 } 8283 8284 return scannedPkg; 8285 } 8286 8287 /** 8288 * Scans a package and returns the newly parsed package. 8289 * @throws PackageManagerException on a parse error. 8290 */ 8291 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, 8292 @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime, 8293 @Nullable UserHandle user) 8294 throws PackageManagerException { 8295 PackageSetting ps = null; 8296 PackageSetting updatedPs; 8297 // reader 8298 synchronized (mPackages) { 8299 // Look to see if we already know about this package. 8300 String oldName = mSettings.getRenamedPackageLPr(pkg.packageName); 8301 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 8302 // This package has been renamed to its original name. Let's 8303 // use that. 8304 ps = mSettings.getPackageLPr(oldName); 8305 } 8306 // If there was no original package, see one for the real package name. 8307 if (ps == null) { 8308 ps = mSettings.getPackageLPr(pkg.packageName); 8309 } 8310 // Check to see if this package could be hiding/updating a system 8311 // package. Must look for it either under the original or real 8312 // package name depending on our state. 8313 updatedPs = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 8314 if (DEBUG_INSTALL && updatedPs != null) Slog.d(TAG, "updatedPkg = " + updatedPs); 8315 8316 // If this is a package we don't know about on the system partition, we 8317 // may need to remove disabled child packages on the system partition 8318 // or may need to not add child packages if the parent apk is updated 8319 // on the data partition and no longer defines this child package. 8320 if ((scanFlags & SCAN_AS_SYSTEM) != 0) { 8321 // If this is a parent package for an updated system app and this system 8322 // app got an OTA update which no longer defines some of the child packages 8323 // we have to prune them from the disabled system packages. 8324 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 8325 if (disabledPs != null) { 8326 final int scannedChildCount = (pkg.childPackages != null) 8327 ? pkg.childPackages.size() : 0; 8328 final int disabledChildCount = disabledPs.childPackageNames != null 8329 ? disabledPs.childPackageNames.size() : 0; 8330 for (int i = 0; i < disabledChildCount; i++) { 8331 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 8332 boolean disabledPackageAvailable = false; 8333 for (int j = 0; j < scannedChildCount; j++) { 8334 PackageParser.Package childPkg = pkg.childPackages.get(j); 8335 if (childPkg.packageName.equals(disabledChildPackageName)) { 8336 disabledPackageAvailable = true; 8337 break; 8338 } 8339 } 8340 if (!disabledPackageAvailable) { 8341 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 8342 } 8343 } 8344 } 8345 } 8346 } 8347 8348 final boolean isUpdatedPkg = updatedPs != null; 8349 final boolean isUpdatedSystemPkg = isUpdatedPkg && (scanFlags & SCAN_AS_SYSTEM) != 0; 8350 boolean isUpdatedPkgBetter = false; 8351 // First check if this is a system package that may involve an update 8352 if (isUpdatedSystemPkg) { 8353 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 8354 // it needs to drop FLAG_PRIVILEGED. 8355 if (locationIsPrivileged(pkg.codePath)) { 8356 updatedPs.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 8357 } else { 8358 updatedPs.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 8359 } 8360 // If new package is not located in "/oem" (e.g. due to an OTA), 8361 // it needs to drop FLAG_OEM. 8362 if (locationIsOem(pkg.codePath)) { 8363 updatedPs.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM; 8364 } else { 8365 updatedPs.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_OEM; 8366 } 8367 // If new package is not located in "/vendor" (e.g. due to an OTA), 8368 // it needs to drop FLAG_VENDOR. 8369 if (locationIsVendor(pkg.codePath)) { 8370 updatedPs.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_VENDOR; 8371 } else { 8372 updatedPs.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_VENDOR; 8373 } 8374 8375 if (ps != null && !ps.codePathString.equals(pkg.codePath)) { 8376 // The path has changed from what was last scanned... check the 8377 // version of the new path against what we have stored to determine 8378 // what to do. 8379 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 8380 if (pkg.mVersionCode <= ps.versionCode) { 8381 // The system package has been updated and the code path does not match 8382 // Ignore entry. Skip it. 8383 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + pkg.codePath 8384 + " ignored: updated version " + ps.versionCode 8385 + " better than this " + pkg.mVersionCode); 8386 if (!updatedPs.codePathString.equals(pkg.codePath)) { 8387 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 8388 + ps.name + " changing from " + updatedPs.codePathString 8389 + " to " + pkg.codePath); 8390 final File codePath = new File(pkg.codePath); 8391 updatedPs.codePath = codePath; 8392 updatedPs.codePathString = pkg.codePath; 8393 updatedPs.resourcePath = codePath; 8394 updatedPs.resourcePathString = pkg.codePath; 8395 } 8396 updatedPs.pkg = pkg; 8397 updatedPs.versionCode = pkg.mVersionCode; 8398 8399 // Update the disabled system child packages to point to the package too. 8400 final int childCount = updatedPs.childPackageNames != null 8401 ? updatedPs.childPackageNames.size() : 0; 8402 for (int i = 0; i < childCount; i++) { 8403 String childPackageName = updatedPs.childPackageNames.get(i); 8404 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 8405 childPackageName); 8406 if (updatedChildPkg != null) { 8407 updatedChildPkg.pkg = pkg; 8408 updatedChildPkg.versionCode = pkg.mVersionCode; 8409 } 8410 } 8411 } else { 8412 // The current app on the system partition is better than 8413 // what we have updated to on the data partition; switch 8414 // back to the system partition version. 8415 // At this point, its safely assumed that package installation for 8416 // apps in system partition will go through. If not there won't be a working 8417 // version of the app 8418 // writer 8419 synchronized (mPackages) { 8420 // Just remove the loaded entries from package lists. 8421 mPackages.remove(ps.name); 8422 } 8423 8424 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + pkg.codePath 8425 + " reverting from " + ps.codePathString 8426 + ": new version " + pkg.mVersionCode 8427 + " better than installed " + ps.versionCode); 8428 8429 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 8430 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 8431 synchronized (mInstallLock) { 8432 args.cleanUpResourcesLI(); 8433 } 8434 synchronized (mPackages) { 8435 mSettings.enableSystemPackageLPw(ps.name); 8436 } 8437 isUpdatedPkgBetter = true; 8438 } 8439 } 8440 } 8441 8442 String resourcePath = null; 8443 String baseResourcePath = null; 8444 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !isUpdatedPkgBetter) { 8445 if (ps != null && ps.resourcePathString != null) { 8446 resourcePath = ps.resourcePathString; 8447 baseResourcePath = ps.resourcePathString; 8448 } else { 8449 // Should not happen at all. Just log an error. 8450 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 8451 } 8452 } else { 8453 resourcePath = pkg.codePath; 8454 baseResourcePath = pkg.baseCodePath; 8455 } 8456 8457 // Set application objects path explicitly. 8458 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 8459 pkg.setApplicationInfoCodePath(pkg.codePath); 8460 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 8461 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 8462 pkg.setApplicationInfoResourcePath(resourcePath); 8463 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 8464 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 8465 8466 // throw an exception if we have an update to a system application, but, it's not more 8467 // recent than the package we've already scanned 8468 if (isUpdatedSystemPkg && !isUpdatedPkgBetter) { 8469 // Set CPU Abis to application info. 8470 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) { 8471 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, updatedPs); 8472 derivePackageAbi(pkg, cpuAbiOverride, false, mAppLib32InstallDir); 8473 } else { 8474 pkg.applicationInfo.primaryCpuAbi = updatedPs.primaryCpuAbiString; 8475 pkg.applicationInfo.secondaryCpuAbi = updatedPs.secondaryCpuAbiString; 8476 } 8477 pkg.mExtras = updatedPs; 8478 8479 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 8480 + pkg.codePath + " ignored: updated version " + ps.versionCode 8481 + " better than this " + pkg.mVersionCode); 8482 } 8483 8484 if (isUpdatedPkg) { 8485 // updated system applications don't initially have the SCAN_AS_SYSTEM flag set 8486 scanFlags |= SCAN_AS_SYSTEM; 8487 8488 // An updated privileged application will not have the PARSE_IS_PRIVILEGED 8489 // flag set initially 8490 if ((updatedPs.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 8491 scanFlags |= SCAN_AS_PRIVILEGED; 8492 } 8493 8494 // An updated OEM app will not have the SCAN_AS_OEM 8495 // flag set initially 8496 if ((updatedPs.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0) { 8497 scanFlags |= SCAN_AS_OEM; 8498 } 8499 8500 // An updated vendor app will not have the SCAN_AS_VENDOR 8501 // flag set initially 8502 if ((updatedPs.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0) { 8503 scanFlags |= SCAN_AS_VENDOR; 8504 } 8505 } 8506 8507 // Verify certificates against what was last scanned 8508 collectCertificatesLI(ps, pkg, parseFlags); 8509 8510 /* 8511 * A new system app appeared, but we already had a non-system one of the 8512 * same name installed earlier. 8513 */ 8514 boolean shouldHideSystemApp = false; 8515 if (!isUpdatedPkg && ps != null 8516 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 8517 /* 8518 * Check to make sure the signatures match first. If they don't, 8519 * wipe the installed application and its data. 8520 */ 8521 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 8522 != PackageManager.SIGNATURE_MATCH) { 8523 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 8524 + " signatures don't match existing userdata copy; removing"); 8525 try (PackageFreezer freezer = freezePackage(pkg.packageName, 8526 "scanPackageInternalLI")) { 8527 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 8528 } 8529 ps = null; 8530 } else { 8531 /* 8532 * If the newly-added system app is an older version than the 8533 * already installed version, hide it. It will be scanned later 8534 * and re-added like an update. 8535 */ 8536 if (pkg.mVersionCode <= ps.versionCode) { 8537 shouldHideSystemApp = true; 8538 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + pkg.codePath 8539 + " but new version " + pkg.mVersionCode + " better than installed " 8540 + ps.versionCode + "; hiding system"); 8541 } else { 8542 /* 8543 * The newly found system app is a newer version that the 8544 * one previously installed. Simply remove the 8545 * already-installed application and replace it with our own 8546 * while keeping the application data. 8547 */ 8548 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + pkg.codePath 8549 + " reverting from " + ps.codePathString + ": new version " 8550 + pkg.mVersionCode + " better than installed " + ps.versionCode); 8551 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 8552 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 8553 synchronized (mInstallLock) { 8554 args.cleanUpResourcesLI(); 8555 } 8556 } 8557 } 8558 } 8559 8560 // The apk is forward locked (not public) if its code and resources 8561 // are kept in different files. (except for app in either system or 8562 // vendor path). 8563 // TODO grab this value from PackageSettings 8564 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8565 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 8566 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 8567 } 8568 } 8569 8570 final int userId = ((user == null) ? 0 : user.getIdentifier()); 8571 if (ps != null && ps.getInstantApp(userId)) { 8572 scanFlags |= SCAN_AS_INSTANT_APP; 8573 } 8574 if (ps != null && ps.getVirtulalPreload(userId)) { 8575 scanFlags |= SCAN_AS_VIRTUAL_PRELOAD; 8576 } 8577 8578 // Note that we invoke the following method only if we are about to unpack an application 8579 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 8580 | SCAN_UPDATE_SIGNATURE, currentTime, user); 8581 8582 /* 8583 * If the system app should be overridden by a previously installed 8584 * data, hide the system app now and let the /data/app scan pick it up 8585 * again. 8586 */ 8587 if (shouldHideSystemApp) { 8588 synchronized (mPackages) { 8589 mSettings.disableSystemPackageLPw(pkg.packageName, true); 8590 } 8591 } 8592 8593 return scannedPkg; 8594 } 8595 8596 private static void renameStaticSharedLibraryPackage(PackageParser.Package pkg) { 8597 // Derive the new package synthetic package name 8598 pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER 8599 + pkg.staticSharedLibVersion); 8600 } 8601 8602 private static String fixProcessName(String defProcessName, 8603 String processName) { 8604 if (processName == null) { 8605 return defProcessName; 8606 } 8607 return processName; 8608 } 8609 8610 /** 8611 * Enforces that only the system UID or root's UID can call a method exposed 8612 * via Binder. 8613 * 8614 * @param message used as message if SecurityException is thrown 8615 * @throws SecurityException if the caller is not system or root 8616 */ 8617 private static final void enforceSystemOrRoot(String message) { 8618 final int uid = Binder.getCallingUid(); 8619 if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) { 8620 throw new SecurityException(message); 8621 } 8622 } 8623 8624 @Override 8625 public void performFstrimIfNeeded() { 8626 enforceSystemOrRoot("Only the system can request fstrim"); 8627 8628 // Before everything else, see whether we need to fstrim. 8629 try { 8630 IStorageManager sm = PackageHelper.getStorageManager(); 8631 if (sm != null) { 8632 boolean doTrim = false; 8633 final long interval = android.provider.Settings.Global.getLong( 8634 mContext.getContentResolver(), 8635 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 8636 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 8637 if (interval > 0) { 8638 final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance(); 8639 if (timeSinceLast > interval) { 8640 doTrim = true; 8641 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 8642 + "; running immediately"); 8643 } 8644 } 8645 if (doTrim) { 8646 final boolean dexOptDialogShown; 8647 synchronized (mPackages) { 8648 dexOptDialogShown = mDexOptDialogShown; 8649 } 8650 if (!isFirstBoot() && dexOptDialogShown) { 8651 try { 8652 ActivityManager.getService().showBootMessage( 8653 mContext.getResources().getString( 8654 R.string.android_upgrading_fstrim), true); 8655 } catch (RemoteException e) { 8656 } 8657 } 8658 sm.runMaintenance(); 8659 } 8660 } else { 8661 Slog.e(TAG, "storageManager service unavailable!"); 8662 } 8663 } catch (RemoteException e) { 8664 // Can't happen; StorageManagerService is local 8665 } 8666 } 8667 8668 @Override 8669 public void updatePackagesIfNeeded() { 8670 enforceSystemOrRoot("Only the system can request package update"); 8671 8672 // We need to re-extract after an OTA. 8673 boolean causeUpgrade = isUpgrade(); 8674 8675 // First boot or factory reset. 8676 // Note: we also handle devices that are upgrading to N right now as if it is their 8677 // first boot, as they do not have profile data. 8678 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 8679 8680 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 8681 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 8682 8683 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 8684 return; 8685 } 8686 8687 List<PackageParser.Package> pkgs; 8688 synchronized (mPackages) { 8689 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 8690 } 8691 8692 final long startTime = System.nanoTime(); 8693 final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */, 8694 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT), 8695 false /* bootComplete */); 8696 8697 final int elapsedTimeSeconds = 8698 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 8699 8700 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]); 8701 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]); 8702 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]); 8703 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 8704 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 8705 } 8706 8707 /* 8708 * Return the prebuilt profile path given a package base code path. 8709 */ 8710 private static String getPrebuildProfilePath(PackageParser.Package pkg) { 8711 return pkg.baseCodePath + ".prof"; 8712 } 8713 8714 /** 8715 * Performs dexopt on the set of packages in {@code packages} and returns an int array 8716 * containing statistics about the invocation. The array consists of three elements, 8717 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped} 8718 * and {@code numberOfPackagesFailed}. 8719 */ 8720 private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog, 8721 final String compilerFilter, boolean bootComplete) { 8722 8723 int numberOfPackagesVisited = 0; 8724 int numberOfPackagesOptimized = 0; 8725 int numberOfPackagesSkipped = 0; 8726 int numberOfPackagesFailed = 0; 8727 final int numberOfPackagesToDexopt = pkgs.size(); 8728 8729 for (PackageParser.Package pkg : pkgs) { 8730 numberOfPackagesVisited++; 8731 8732 boolean useProfileForDexopt = false; 8733 8734 if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) { 8735 // Copy over initial preopt profiles since we won't get any JIT samples for methods 8736 // that are already compiled. 8737 File profileFile = new File(getPrebuildProfilePath(pkg)); 8738 // Copy profile if it exists. 8739 if (profileFile.exists()) { 8740 try { 8741 // We could also do this lazily before calling dexopt in 8742 // PackageDexOptimizer to prevent this happening on first boot. The issue 8743 // is that we don't have a good way to say "do this only once". 8744 if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(), 8745 pkg.applicationInfo.uid, pkg.packageName)) { 8746 Log.e(TAG, "Installer failed to copy system profile!"); 8747 } else { 8748 // Disabled as this causes speed-profile compilation during first boot 8749 // even if things are already compiled. 8750 // useProfileForDexopt = true; 8751 } 8752 } catch (Exception e) { 8753 Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ", 8754 e); 8755 } 8756 } else { 8757 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 8758 // Handle compressed APKs in this path. Only do this for stubs with profiles to 8759 // minimize the number off apps being speed-profile compiled during first boot. 8760 // The other paths will not change the filter. 8761 if (disabledPs != null && disabledPs.pkg.isStub) { 8762 // The package is the stub one, remove the stub suffix to get the normal 8763 // package and APK names. 8764 String systemProfilePath = 8765 getPrebuildProfilePath(disabledPs.pkg).replace(STUB_SUFFIX, ""); 8766 profileFile = new File(systemProfilePath); 8767 // If we have a profile for a compressed APK, copy it to the reference 8768 // location. 8769 // Note that copying the profile here will cause it to override the 8770 // reference profile every OTA even though the existing reference profile 8771 // may have more data. We can't copy during decompression since the 8772 // directories are not set up at that point. 8773 if (profileFile.exists()) { 8774 try { 8775 // We could also do this lazily before calling dexopt in 8776 // PackageDexOptimizer to prevent this happening on first boot. The 8777 // issue is that we don't have a good way to say "do this only 8778 // once". 8779 if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(), 8780 pkg.applicationInfo.uid, pkg.packageName)) { 8781 Log.e(TAG, "Failed to copy system profile for stub package!"); 8782 } else { 8783 useProfileForDexopt = true; 8784 } 8785 } catch (Exception e) { 8786 Log.e(TAG, "Failed to copy profile " + 8787 profileFile.getAbsolutePath() + " ", e); 8788 } 8789 } 8790 } 8791 } 8792 } 8793 8794 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 8795 if (DEBUG_DEXOPT) { 8796 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 8797 } 8798 numberOfPackagesSkipped++; 8799 continue; 8800 } 8801 8802 if (DEBUG_DEXOPT) { 8803 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 8804 numberOfPackagesToDexopt + ": " + pkg.packageName); 8805 } 8806 8807 if (showDialog) { 8808 try { 8809 ActivityManager.getService().showBootMessage( 8810 mContext.getResources().getString(R.string.android_upgrading_apk, 8811 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 8812 } catch (RemoteException e) { 8813 } 8814 synchronized (mPackages) { 8815 mDexOptDialogShown = true; 8816 } 8817 } 8818 8819 String pkgCompilerFilter = compilerFilter; 8820 if (useProfileForDexopt) { 8821 // Use background dexopt mode to try and use the profile. Note that this does not 8822 // guarantee usage of the profile. 8823 pkgCompilerFilter = 8824 PackageManagerServiceCompilerMapping.getCompilerFilterForReason( 8825 PackageManagerService.REASON_BACKGROUND_DEXOPT); 8826 } 8827 8828 // checkProfiles is false to avoid merging profiles during boot which 8829 // might interfere with background compilation (b/28612421). 8830 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 8831 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 8832 // trade-off worth doing to save boot time work. 8833 int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0; 8834 int primaryDexOptStaus = performDexOptTraced(new DexoptOptions( 8835 pkg.packageName, 8836 pkgCompilerFilter, 8837 dexoptFlags)); 8838 8839 switch (primaryDexOptStaus) { 8840 case PackageDexOptimizer.DEX_OPT_PERFORMED: 8841 numberOfPackagesOptimized++; 8842 break; 8843 case PackageDexOptimizer.DEX_OPT_SKIPPED: 8844 numberOfPackagesSkipped++; 8845 break; 8846 case PackageDexOptimizer.DEX_OPT_FAILED: 8847 numberOfPackagesFailed++; 8848 break; 8849 default: 8850 Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus); 8851 break; 8852 } 8853 } 8854 8855 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped, 8856 numberOfPackagesFailed }; 8857 } 8858 8859 @Override 8860 public void notifyPackageUse(String packageName, int reason) { 8861 synchronized (mPackages) { 8862 final int callingUid = Binder.getCallingUid(); 8863 final int callingUserId = UserHandle.getUserId(callingUid); 8864 if (getInstantAppPackageName(callingUid) != null) { 8865 if (!isCallerSameApp(packageName, callingUid)) { 8866 return; 8867 } 8868 } else { 8869 if (isInstantApp(packageName, callingUserId)) { 8870 return; 8871 } 8872 } 8873 notifyPackageUseLocked(packageName, reason); 8874 } 8875 } 8876 8877 private void notifyPackageUseLocked(String packageName, int reason) { 8878 final PackageParser.Package p = mPackages.get(packageName); 8879 if (p == null) { 8880 return; 8881 } 8882 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 8883 } 8884 8885 @Override 8886 public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames, 8887 List<String> classPaths, String loaderIsa) { 8888 int userId = UserHandle.getCallingUserId(); 8889 ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId); 8890 if (ai == null) { 8891 Slog.w(TAG, "Loading a package that does not exist for the calling user. package=" 8892 + loadingPackageName + ", user=" + userId); 8893 return; 8894 } 8895 mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId); 8896 } 8897 8898 @Override 8899 public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule, 8900 IDexModuleRegisterCallback callback) { 8901 int userId = UserHandle.getCallingUserId(); 8902 ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId); 8903 DexManager.RegisterDexModuleResult result; 8904 if (ai == null) { 8905 Slog.w(TAG, "Registering a dex module for a package that does not exist for the" + 8906 " calling user. package=" + packageName + ", user=" + userId); 8907 result = new DexManager.RegisterDexModuleResult(false, "Package not installed"); 8908 } else { 8909 result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId); 8910 } 8911 8912 if (callback != null) { 8913 mHandler.post(() -> { 8914 try { 8915 callback.onDexModuleRegistered(dexModulePath, result.success, result.message); 8916 } catch (RemoteException e) { 8917 Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e); 8918 } 8919 }); 8920 } 8921 } 8922 8923 /** 8924 * Ask the package manager to perform a dex-opt with the given compiler filter. 8925 * 8926 * Note: exposed only for the shell command to allow moving packages explicitly to a 8927 * definite state. 8928 */ 8929 @Override 8930 public boolean performDexOptMode(String packageName, 8931 boolean checkProfiles, String targetCompilerFilter, boolean force, 8932 boolean bootComplete, String splitName) { 8933 int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) | 8934 (force ? DexoptOptions.DEXOPT_FORCE : 0) | 8935 (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0); 8936 return performDexOpt(new DexoptOptions(packageName, targetCompilerFilter, 8937 splitName, flags)); 8938 } 8939 8940 /** 8941 * Ask the package manager to perform a dex-opt with the given compiler filter on the 8942 * secondary dex files belonging to the given package. 8943 * 8944 * Note: exposed only for the shell command to allow moving packages explicitly to a 8945 * definite state. 8946 */ 8947 @Override 8948 public boolean performDexOptSecondary(String packageName, String compilerFilter, 8949 boolean force) { 8950 int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX | 8951 DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES | 8952 DexoptOptions.DEXOPT_BOOT_COMPLETE | 8953 (force ? DexoptOptions.DEXOPT_FORCE : 0); 8954 return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags)); 8955 } 8956 8957 /*package*/ boolean performDexOpt(DexoptOptions options) { 8958 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 8959 return false; 8960 } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) { 8961 return false; 8962 } 8963 8964 if (options.isDexoptOnlySecondaryDex()) { 8965 return mDexManager.dexoptSecondaryDex(options); 8966 } else { 8967 int dexoptStatus = performDexOptWithStatus(options); 8968 return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 8969 } 8970 } 8971 8972 /** 8973 * Perform dexopt on the given package and return one of following result: 8974 * {@link PackageDexOptimizer#DEX_OPT_SKIPPED} 8975 * {@link PackageDexOptimizer#DEX_OPT_PERFORMED} 8976 * {@link PackageDexOptimizer#DEX_OPT_FAILED} 8977 */ 8978 /* package */ int performDexOptWithStatus(DexoptOptions options) { 8979 return performDexOptTraced(options); 8980 } 8981 8982 private int performDexOptTraced(DexoptOptions options) { 8983 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 8984 try { 8985 return performDexOptInternal(options); 8986 } finally { 8987 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8988 } 8989 } 8990 8991 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 8992 // if the package can now be considered up to date for the given filter. 8993 private int performDexOptInternal(DexoptOptions options) { 8994 PackageParser.Package p; 8995 synchronized (mPackages) { 8996 p = mPackages.get(options.getPackageName()); 8997 if (p == null) { 8998 // Package could not be found. Report failure. 8999 return PackageDexOptimizer.DEX_OPT_FAILED; 9000 } 9001 mPackageUsage.maybeWriteAsync(mPackages); 9002 mCompilerStats.maybeWriteAsync(); 9003 } 9004 long callingId = Binder.clearCallingIdentity(); 9005 try { 9006 synchronized (mInstallLock) { 9007 return performDexOptInternalWithDependenciesLI(p, options); 9008 } 9009 } finally { 9010 Binder.restoreCallingIdentity(callingId); 9011 } 9012 } 9013 9014 public ArraySet<String> getOptimizablePackages() { 9015 ArraySet<String> pkgs = new ArraySet<String>(); 9016 synchronized (mPackages) { 9017 for (PackageParser.Package p : mPackages.values()) { 9018 if (PackageDexOptimizer.canOptimizePackage(p)) { 9019 pkgs.add(p.packageName); 9020 } 9021 } 9022 } 9023 return pkgs; 9024 } 9025 9026 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 9027 DexoptOptions options) { 9028 // Select the dex optimizer based on the force parameter. 9029 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 9030 // allocate an object here. 9031 PackageDexOptimizer pdo = options.isForce() 9032 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 9033 : mPackageDexOptimizer; 9034 9035 // Dexopt all dependencies first. Note: we ignore the return value and march on 9036 // on errors. 9037 // Note that we are going to call performDexOpt on those libraries as many times as 9038 // they are referenced in packages. When we do a batch of performDexOpt (for example 9039 // at boot, or background job), the passed 'targetCompilerFilter' stays the same, 9040 // and the first package that uses the library will dexopt it. The 9041 // others will see that the compiled code for the library is up to date. 9042 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 9043 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 9044 if (!deps.isEmpty()) { 9045 DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(), 9046 options.getCompilerFilter(), options.getSplitName(), 9047 options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY); 9048 for (PackageParser.Package depPackage : deps) { 9049 // TODO: Analyze and investigate if we (should) profile libraries. 9050 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 9051 getOrCreateCompilerPackageStats(depPackage), 9052 mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions); 9053 } 9054 } 9055 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, 9056 getOrCreateCompilerPackageStats(p), 9057 mDexManager.getPackageUseInfoOrDefault(p.packageName), options); 9058 } 9059 9060 /** 9061 * Reconcile the information we have about the secondary dex files belonging to 9062 * {@code packagName} and the actual dex files. For all dex files that were 9063 * deleted, update the internal records and delete the generated oat files. 9064 */ 9065 @Override 9066 public void reconcileSecondaryDexFiles(String packageName) { 9067 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 9068 return; 9069 } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) { 9070 return; 9071 } 9072 mDexManager.reconcileSecondaryDexFiles(packageName); 9073 } 9074 9075 // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject 9076 // a reference there. 9077 /*package*/ DexManager getDexManager() { 9078 return mDexManager; 9079 } 9080 9081 /** 9082 * Execute the background dexopt job immediately. 9083 */ 9084 @Override 9085 public boolean runBackgroundDexoptJob(@Nullable List<String> packageNames) { 9086 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 9087 return false; 9088 } 9089 return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext, packageNames); 9090 } 9091 9092 List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 9093 if (p.usesLibraries != null || p.usesOptionalLibraries != null 9094 || p.usesStaticLibraries != null) { 9095 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 9096 Set<String> collectedNames = new HashSet<>(); 9097 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 9098 9099 retValue.remove(p); 9100 9101 return retValue; 9102 } else { 9103 return Collections.emptyList(); 9104 } 9105 } 9106 9107 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 9108 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) { 9109 if (!collectedNames.contains(p.packageName)) { 9110 collectedNames.add(p.packageName); 9111 collected.add(p); 9112 9113 if (p.usesLibraries != null) { 9114 findSharedNonSystemLibrariesRecursive(p.usesLibraries, 9115 null, collected, collectedNames); 9116 } 9117 if (p.usesOptionalLibraries != null) { 9118 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, 9119 null, collected, collectedNames); 9120 } 9121 if (p.usesStaticLibraries != null) { 9122 findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries, 9123 p.usesStaticLibrariesVersions, collected, collectedNames); 9124 } 9125 } 9126 } 9127 9128 private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions, 9129 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) { 9130 final int libNameCount = libs.size(); 9131 for (int i = 0; i < libNameCount; i++) { 9132 String libName = libs.get(i); 9133 int version = (versions != null && versions.length == libNameCount) 9134 ? versions[i] : PackageManager.VERSION_CODE_HIGHEST; 9135 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version); 9136 if (libPkg != null) { 9137 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 9138 } 9139 } 9140 } 9141 9142 private PackageParser.Package findSharedNonSystemLibrary(String name, int version) { 9143 synchronized (mPackages) { 9144 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version); 9145 if (libEntry != null) { 9146 return mPackages.get(libEntry.apk); 9147 } 9148 return null; 9149 } 9150 } 9151 9152 private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) { 9153 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 9154 if (versionedLib == null) { 9155 return null; 9156 } 9157 return versionedLib.get(version); 9158 } 9159 9160 private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) { 9161 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get( 9162 pkg.staticSharedLibName); 9163 if (versionedLib == null) { 9164 return null; 9165 } 9166 int previousLibVersion = -1; 9167 final int versionCount = versionedLib.size(); 9168 for (int i = 0; i < versionCount; i++) { 9169 final int libVersion = versionedLib.keyAt(i); 9170 if (libVersion < pkg.staticSharedLibVersion) { 9171 previousLibVersion = Math.max(previousLibVersion, libVersion); 9172 } 9173 } 9174 if (previousLibVersion >= 0) { 9175 return versionedLib.get(previousLibVersion); 9176 } 9177 return null; 9178 } 9179 9180 public void shutdown() { 9181 mPackageUsage.writeNow(mPackages); 9182 mCompilerStats.writeNow(); 9183 mDexManager.writePackageDexUsageNow(); 9184 } 9185 9186 @Override 9187 public void dumpProfiles(String packageName) { 9188 PackageParser.Package pkg; 9189 synchronized (mPackages) { 9190 pkg = mPackages.get(packageName); 9191 if (pkg == null) { 9192 throw new IllegalArgumentException("Unknown package: " + packageName); 9193 } 9194 } 9195 /* Only the shell, root, or the app user should be able to dump profiles. */ 9196 int callingUid = Binder.getCallingUid(); 9197 if (callingUid != Process.SHELL_UID && 9198 callingUid != Process.ROOT_UID && 9199 callingUid != pkg.applicationInfo.uid) { 9200 throw new SecurityException("dumpProfiles"); 9201 } 9202 9203 synchronized (mInstallLock) { 9204 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles"); 9205 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 9206 try { 9207 List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly(); 9208 String codePaths = TextUtils.join(";", allCodePaths); 9209 mInstaller.dumpProfiles(sharedGid, packageName, codePaths); 9210 } catch (InstallerException e) { 9211 Slog.w(TAG, "Failed to dump profiles", e); 9212 } 9213 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9214 } 9215 } 9216 9217 @Override 9218 public void forceDexOpt(String packageName) { 9219 enforceSystemOrRoot("forceDexOpt"); 9220 9221 PackageParser.Package pkg; 9222 synchronized (mPackages) { 9223 pkg = mPackages.get(packageName); 9224 if (pkg == null) { 9225 throw new IllegalArgumentException("Unknown package: " + packageName); 9226 } 9227 } 9228 9229 synchronized (mInstallLock) { 9230 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 9231 9232 // Whoever is calling forceDexOpt wants a compiled package. 9233 // Don't use profiles since that may cause compilation to be skipped. 9234 final int res = performDexOptInternalWithDependenciesLI( 9235 pkg, 9236 new DexoptOptions(packageName, 9237 getDefaultCompilerFilter(), 9238 DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE)); 9239 9240 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9241 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 9242 throw new IllegalStateException("Failed to dexopt: " + res); 9243 } 9244 } 9245 } 9246 9247 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 9248 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 9249 Slog.w(TAG, "Unable to update from " + oldPkg.name 9250 + " to " + newPkg.packageName 9251 + ": old package not in system partition"); 9252 return false; 9253 } else if (mPackages.get(oldPkg.name) != null) { 9254 Slog.w(TAG, "Unable to update from " + oldPkg.name 9255 + " to " + newPkg.packageName 9256 + ": old package still exists"); 9257 return false; 9258 } 9259 return true; 9260 } 9261 9262 void removeCodePathLI(File codePath) { 9263 if (codePath.isDirectory()) { 9264 try { 9265 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 9266 } catch (InstallerException e) { 9267 Slog.w(TAG, "Failed to remove code path", e); 9268 } 9269 } else { 9270 codePath.delete(); 9271 } 9272 } 9273 9274 private int[] resolveUserIds(int userId) { 9275 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 9276 } 9277 9278 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 9279 if (pkg == null) { 9280 Slog.wtf(TAG, "Package was null!", new Throwable()); 9281 return; 9282 } 9283 clearAppDataLeafLIF(pkg, userId, flags); 9284 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9285 for (int i = 0; i < childCount; i++) { 9286 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 9287 } 9288 } 9289 9290 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 9291 final PackageSetting ps; 9292 synchronized (mPackages) { 9293 ps = mSettings.mPackages.get(pkg.packageName); 9294 } 9295 for (int realUserId : resolveUserIds(userId)) { 9296 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 9297 try { 9298 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 9299 ceDataInode); 9300 } catch (InstallerException e) { 9301 Slog.w(TAG, String.valueOf(e)); 9302 } 9303 } 9304 } 9305 9306 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 9307 if (pkg == null) { 9308 Slog.wtf(TAG, "Package was null!", new Throwable()); 9309 return; 9310 } 9311 destroyAppDataLeafLIF(pkg, userId, flags); 9312 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9313 for (int i = 0; i < childCount; i++) { 9314 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 9315 } 9316 } 9317 9318 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 9319 final PackageSetting ps; 9320 synchronized (mPackages) { 9321 ps = mSettings.mPackages.get(pkg.packageName); 9322 } 9323 for (int realUserId : resolveUserIds(userId)) { 9324 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 9325 try { 9326 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 9327 ceDataInode); 9328 } catch (InstallerException e) { 9329 Slog.w(TAG, String.valueOf(e)); 9330 } 9331 mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId); 9332 } 9333 } 9334 9335 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 9336 if (pkg == null) { 9337 Slog.wtf(TAG, "Package was null!", new Throwable()); 9338 return; 9339 } 9340 destroyAppProfilesLeafLIF(pkg); 9341 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9342 for (int i = 0; i < childCount; i++) { 9343 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 9344 } 9345 } 9346 9347 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 9348 try { 9349 mInstaller.destroyAppProfiles(pkg.packageName); 9350 } catch (InstallerException e) { 9351 Slog.w(TAG, String.valueOf(e)); 9352 } 9353 } 9354 9355 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 9356 if (pkg == null) { 9357 Slog.wtf(TAG, "Package was null!", new Throwable()); 9358 return; 9359 } 9360 clearAppProfilesLeafLIF(pkg); 9361 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9362 for (int i = 0; i < childCount; i++) { 9363 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 9364 } 9365 } 9366 9367 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 9368 try { 9369 mInstaller.clearAppProfiles(pkg.packageName); 9370 } catch (InstallerException e) { 9371 Slog.w(TAG, String.valueOf(e)); 9372 } 9373 } 9374 9375 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 9376 long lastUpdateTime) { 9377 // Set parent install/update time 9378 PackageSetting ps = (PackageSetting) pkg.mExtras; 9379 if (ps != null) { 9380 ps.firstInstallTime = firstInstallTime; 9381 ps.lastUpdateTime = lastUpdateTime; 9382 } 9383 // Set children install/update time 9384 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9385 for (int i = 0; i < childCount; i++) { 9386 PackageParser.Package childPkg = pkg.childPackages.get(i); 9387 ps = (PackageSetting) childPkg.mExtras; 9388 if (ps != null) { 9389 ps.firstInstallTime = firstInstallTime; 9390 ps.lastUpdateTime = lastUpdateTime; 9391 } 9392 } 9393 } 9394 9395 private void addSharedLibraryLPr(Set<String> usesLibraryFiles, 9396 SharedLibraryEntry file, 9397 PackageParser.Package changingLib) { 9398 if (file.path != null) { 9399 usesLibraryFiles.add(file.path); 9400 return; 9401 } 9402 PackageParser.Package p = mPackages.get(file.apk); 9403 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 9404 // If we are doing this while in the middle of updating a library apk, 9405 // then we need to make sure to use that new apk for determining the 9406 // dependencies here. (We haven't yet finished committing the new apk 9407 // to the package manager state.) 9408 if (p == null || p.packageName.equals(changingLib.packageName)) { 9409 p = changingLib; 9410 } 9411 } 9412 if (p != null) { 9413 usesLibraryFiles.addAll(p.getAllCodePaths()); 9414 if (p.usesLibraryFiles != null) { 9415 Collections.addAll(usesLibraryFiles, p.usesLibraryFiles); 9416 } 9417 } 9418 } 9419 9420 private void updateSharedLibrariesLPr(PackageParser.Package pkg, 9421 PackageParser.Package changingLib) throws PackageManagerException { 9422 if (pkg == null) { 9423 return; 9424 } 9425 // The collection used here must maintain the order of addition (so 9426 // that libraries are searched in the correct order) and must have no 9427 // duplicates. 9428 Set<String> usesLibraryFiles = null; 9429 if (pkg.usesLibraries != null) { 9430 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries, 9431 null, null, pkg.packageName, changingLib, true, 9432 pkg.applicationInfo.targetSdkVersion, null); 9433 } 9434 if (pkg.usesStaticLibraries != null) { 9435 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries, 9436 pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests, 9437 pkg.packageName, changingLib, true, 9438 pkg.applicationInfo.targetSdkVersion, usesLibraryFiles); 9439 } 9440 if (pkg.usesOptionalLibraries != null) { 9441 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries, 9442 null, null, pkg.packageName, changingLib, false, 9443 pkg.applicationInfo.targetSdkVersion, usesLibraryFiles); 9444 } 9445 if (!ArrayUtils.isEmpty(usesLibraryFiles)) { 9446 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]); 9447 } else { 9448 pkg.usesLibraryFiles = null; 9449 } 9450 } 9451 9452 private Set<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries, 9453 @Nullable int[] requiredVersions, @Nullable String[][] requiredCertDigests, 9454 @NonNull String packageName, @Nullable PackageParser.Package changingLib, 9455 boolean required, int targetSdk, @Nullable Set<String> outUsedLibraries) 9456 throws PackageManagerException { 9457 final int libCount = requestedLibraries.size(); 9458 for (int i = 0; i < libCount; i++) { 9459 final String libName = requestedLibraries.get(i); 9460 final int libVersion = requiredVersions != null ? requiredVersions[i] 9461 : SharedLibraryInfo.VERSION_UNDEFINED; 9462 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion); 9463 if (libEntry == null) { 9464 if (required) { 9465 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9466 "Package " + packageName + " requires unavailable shared library " 9467 + libName + "; failing!"); 9468 } else if (DEBUG_SHARED_LIBRARIES) { 9469 Slog.i(TAG, "Package " + packageName 9470 + " desires unavailable shared library " 9471 + libName + "; ignoring!"); 9472 } 9473 } else { 9474 if (requiredVersions != null && requiredCertDigests != null) { 9475 if (libEntry.info.getVersion() != requiredVersions[i]) { 9476 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9477 "Package " + packageName + " requires unavailable static shared" 9478 + " library " + libName + " version " 9479 + libEntry.info.getVersion() + "; failing!"); 9480 } 9481 9482 PackageParser.Package libPkg = mPackages.get(libEntry.apk); 9483 if (libPkg == null) { 9484 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9485 "Package " + packageName + " requires unavailable static shared" 9486 + " library; failing!"); 9487 } 9488 9489 final String[] expectedCertDigests = requiredCertDigests[i]; 9490 // For apps targeting O MR1 we require explicit enumeration of all certs. 9491 final String[] libCertDigests = (targetSdk > Build.VERSION_CODES.O) 9492 ? PackageUtils.computeSignaturesSha256Digests(libPkg.mSignatures) 9493 : PackageUtils.computeSignaturesSha256Digests( 9494 new Signature[]{libPkg.mSignatures[0]}); 9495 9496 // Take a shortcut if sizes don't match. Note that if an app doesn't 9497 // target O we don't parse the "additional-certificate" tags similarly 9498 // how we only consider all certs only for apps targeting O (see above). 9499 // Therefore, the size check is safe to make. 9500 if (expectedCertDigests.length != libCertDigests.length) { 9501 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9502 "Package " + packageName + " requires differently signed" + 9503 " static sDexLoadReporter.java:45.19hared library; failing!"); 9504 } 9505 9506 // Use a predictable order as signature order may vary 9507 Arrays.sort(libCertDigests); 9508 Arrays.sort(expectedCertDigests); 9509 9510 final int certCount = libCertDigests.length; 9511 for (int j = 0; j < certCount; j++) { 9512 if (!libCertDigests[j].equalsIgnoreCase(expectedCertDigests[j])) { 9513 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9514 "Package " + packageName + " requires differently signed" + 9515 " static shared library; failing!"); 9516 } 9517 } 9518 } 9519 9520 if (outUsedLibraries == null) { 9521 // Use LinkedHashSet to preserve the order of files added to 9522 // usesLibraryFiles while eliminating duplicates. 9523 outUsedLibraries = new LinkedHashSet<>(); 9524 } 9525 addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib); 9526 } 9527 } 9528 return outUsedLibraries; 9529 } 9530 9531 private static boolean hasString(List<String> list, List<String> which) { 9532 if (list == null) { 9533 return false; 9534 } 9535 for (int i=list.size()-1; i>=0; i--) { 9536 for (int j=which.size()-1; j>=0; j--) { 9537 if (which.get(j).equals(list.get(i))) { 9538 return true; 9539 } 9540 } 9541 } 9542 return false; 9543 } 9544 9545 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 9546 PackageParser.Package changingPkg) { 9547 ArrayList<PackageParser.Package> res = null; 9548 for (PackageParser.Package pkg : mPackages.values()) { 9549 if (changingPkg != null 9550 && !hasString(pkg.usesLibraries, changingPkg.libraryNames) 9551 && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames) 9552 && !ArrayUtils.contains(pkg.usesStaticLibraries, 9553 changingPkg.staticSharedLibName)) { 9554 return null; 9555 } 9556 if (res == null) { 9557 res = new ArrayList<>(); 9558 } 9559 res.add(pkg); 9560 try { 9561 updateSharedLibrariesLPr(pkg, changingPkg); 9562 } catch (PackageManagerException e) { 9563 // If a system app update or an app and a required lib missing we 9564 // delete the package and for updated system apps keep the data as 9565 // it is better for the user to reinstall than to be in an limbo 9566 // state. Also libs disappearing under an app should never happen 9567 // - just in case. 9568 if (!pkg.isSystem() || pkg.isUpdatedSystemApp()) { 9569 final int flags = pkg.isUpdatedSystemApp() 9570 ? PackageManager.DELETE_KEEP_DATA : 0; 9571 deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(), 9572 flags , null, true, null); 9573 } 9574 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 9575 } 9576 } 9577 return res; 9578 } 9579 9580 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 9581 final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime, 9582 @Nullable UserHandle user) throws PackageManagerException { 9583 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 9584 // If the package has children and this is the first dive in the function 9585 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 9586 // whether all packages (parent and children) would be successfully scanned 9587 // before the actual scan since scanning mutates internal state and we want 9588 // to atomically install the package and its children. 9589 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 9590 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 9591 scanFlags |= SCAN_CHECK_ONLY; 9592 } 9593 } else { 9594 scanFlags &= ~SCAN_CHECK_ONLY; 9595 } 9596 9597 final PackageParser.Package scannedPkg; 9598 try { 9599 // Scan the parent 9600 scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user); 9601 // Scan the children 9602 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9603 for (int i = 0; i < childCount; i++) { 9604 PackageParser.Package childPkg = pkg.childPackages.get(i); 9605 scanPackageLI(childPkg, parseFlags, 9606 scanFlags, currentTime, user); 9607 } 9608 } finally { 9609 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9610 } 9611 9612 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 9613 return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user); 9614 } 9615 9616 return scannedPkg; 9617 } 9618 9619 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, 9620 final @ParseFlags int parseFlags, final @ScanFlags int scanFlags, long currentTime, 9621 @Nullable UserHandle user) throws PackageManagerException { 9622 boolean success = false; 9623 try { 9624 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 9625 currentTime, user); 9626 success = true; 9627 return res; 9628 } finally { 9629 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 9630 // DELETE_DATA_ON_FAILURES is only used by frozen paths 9631 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 9632 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 9633 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 9634 } 9635 } 9636 } 9637 9638 /** 9639 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 9640 */ 9641 private static boolean apkHasCode(String fileName) { 9642 StrictJarFile jarFile = null; 9643 try { 9644 jarFile = new StrictJarFile(fileName, 9645 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 9646 return jarFile.findEntry("classes.dex") != null; 9647 } catch (IOException ignore) { 9648 } finally { 9649 try { 9650 if (jarFile != null) { 9651 jarFile.close(); 9652 } 9653 } catch (IOException ignore) {} 9654 } 9655 return false; 9656 } 9657 9658 /** 9659 * Enforces code policy for the package. This ensures that if an APK has 9660 * declared hasCode="true" in its manifest that the APK actually contains 9661 * code. 9662 * 9663 * @throws PackageManagerException If bytecode could not be found when it should exist 9664 */ 9665 private static void assertCodePolicy(PackageParser.Package pkg) 9666 throws PackageManagerException { 9667 final boolean shouldHaveCode = 9668 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 9669 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 9670 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 9671 "Package " + pkg.baseCodePath + " code is missing"); 9672 } 9673 9674 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 9675 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 9676 final boolean splitShouldHaveCode = 9677 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 9678 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 9679 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 9680 "Package " + pkg.splitCodePaths[i] + " code is missing"); 9681 } 9682 } 9683 } 9684 } 9685 9686 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 9687 final @ParseFlags int parseFlags, final @ScanFlags int scanFlags, long currentTime, 9688 @Nullable UserHandle user) 9689 throws PackageManagerException { 9690 if (DEBUG_PACKAGE_SCANNING) { 9691 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 9692 Log.d(TAG, "Scanning package " + pkg.packageName); 9693 } 9694 9695 applyPolicy(pkg, parseFlags, scanFlags); 9696 9697 assertPackageIsValid(pkg, parseFlags, scanFlags); 9698 9699 if (Build.IS_DEBUGGABLE && 9700 pkg.isPrivileged() && 9701 SystemProperties.getBoolean(PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB, false)) { 9702 PackageManagerServiceUtils.logPackageHasUncompressedCode(pkg); 9703 } 9704 9705 // Initialize package source and resource directories 9706 final File scanFile = new File(pkg.codePath); 9707 final File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 9708 final File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 9709 9710 SharedUserSetting suid = null; 9711 PackageSetting pkgSetting = null; 9712 9713 // Getting the package setting may have a side-effect, so if we 9714 // are only checking if scan would succeed, stash a copy of the 9715 // old setting to restore at the end. 9716 PackageSetting nonMutatedPs = null; 9717 9718 // We keep references to the derived CPU Abis from settings in oder to reuse 9719 // them in the case where we're not upgrading or booting for the first time. 9720 String primaryCpuAbiFromSettings = null; 9721 String secondaryCpuAbiFromSettings = null; 9722 9723 // writer 9724 synchronized (mPackages) { 9725 if (pkg.mSharedUserId != null) { 9726 // SIDE EFFECTS; may potentially allocate a new shared user 9727 suid = mSettings.getSharedUserLPw( 9728 pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/); 9729 if (DEBUG_PACKAGE_SCANNING) { 9730 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 9731 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 9732 + "): packages=" + suid.packages); 9733 } 9734 } 9735 9736 // Check if we are renaming from an original package name. 9737 PackageSetting origPackage = null; 9738 String realName = null; 9739 if (pkg.mOriginalPackages != null) { 9740 // This package may need to be renamed to a previously 9741 // installed name. Let's check on that... 9742 final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage); 9743 if (pkg.mOriginalPackages.contains(renamed)) { 9744 // This package had originally been installed as the 9745 // original name, and we have already taken care of 9746 // transitioning to the new one. Just update the new 9747 // one to continue using the old name. 9748 realName = pkg.mRealPackage; 9749 if (!pkg.packageName.equals(renamed)) { 9750 // Callers into this function may have already taken 9751 // care of renaming the package; only do it here if 9752 // it is not already done. 9753 pkg.setPackageName(renamed); 9754 } 9755 } else { 9756 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 9757 if ((origPackage = mSettings.getPackageLPr( 9758 pkg.mOriginalPackages.get(i))) != null) { 9759 // We do have the package already installed under its 9760 // original name... should we use it? 9761 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 9762 // New package is not compatible with original. 9763 origPackage = null; 9764 continue; 9765 } else if (origPackage.sharedUser != null) { 9766 // Make sure uid is compatible between packages. 9767 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 9768 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 9769 + " to " + pkg.packageName + ": old uid " 9770 + origPackage.sharedUser.name 9771 + " differs from " + pkg.mSharedUserId); 9772 origPackage = null; 9773 continue; 9774 } 9775 // TODO: Add case when shared user id is added [b/28144775] 9776 } else { 9777 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 9778 + pkg.packageName + " to old name " + origPackage.name); 9779 } 9780 break; 9781 } 9782 } 9783 } 9784 } 9785 9786 if (mTransferedPackages.contains(pkg.packageName)) { 9787 Slog.w(TAG, "Package " + pkg.packageName 9788 + " was transferred to another, but its .apk remains"); 9789 } 9790 9791 // See comments in nonMutatedPs declaration 9792 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 9793 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName); 9794 if (foundPs != null) { 9795 nonMutatedPs = new PackageSetting(foundPs); 9796 } 9797 } 9798 9799 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) { 9800 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName); 9801 if (foundPs != null) { 9802 primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString; 9803 secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString; 9804 } 9805 } 9806 9807 pkgSetting = mSettings.getPackageLPr(pkg.packageName); 9808 if (pkgSetting != null && pkgSetting.sharedUser != suid) { 9809 PackageManagerService.reportSettingsProblem(Log.WARN, 9810 "Package " + pkg.packageName + " shared user changed from " 9811 + (pkgSetting.sharedUser != null 9812 ? pkgSetting.sharedUser.name : "<nothing>") 9813 + " to " 9814 + (suid != null ? suid.name : "<nothing>") 9815 + "; replacing with new"); 9816 pkgSetting = null; 9817 } 9818 final PackageSetting oldPkgSetting = 9819 pkgSetting == null ? null : new PackageSetting(pkgSetting); 9820 final PackageSetting disabledPkgSetting = 9821 mSettings.getDisabledSystemPkgLPr(pkg.packageName); 9822 9823 String[] usesStaticLibraries = null; 9824 if (pkg.usesStaticLibraries != null) { 9825 usesStaticLibraries = new String[pkg.usesStaticLibraries.size()]; 9826 pkg.usesStaticLibraries.toArray(usesStaticLibraries); 9827 } 9828 9829 if (pkgSetting == null) { 9830 final String parentPackageName = (pkg.parentPackage != null) 9831 ? pkg.parentPackage.packageName : null; 9832 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 9833 final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0; 9834 // REMOVE SharedUserSetting from method; update in a separate call 9835 pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage, 9836 disabledPkgSetting, realName, suid, destCodeFile, destResourceFile, 9837 pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi, 9838 pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode, 9839 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user, 9840 true /*allowInstall*/, instantApp, virtualPreload, 9841 parentPackageName, pkg.getChildPackageNames(), 9842 UserManagerService.getInstance(), usesStaticLibraries, 9843 pkg.usesStaticLibrariesVersions); 9844 // SIDE EFFECTS; updates system state; move elsewhere 9845 if (origPackage != null) { 9846 mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name); 9847 } 9848 mSettings.addUserToSettingLPw(pkgSetting); 9849 } else { 9850 // REMOVE SharedUserSetting from method; update in a separate call. 9851 // 9852 // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi, 9853 // secondaryCpuAbi are not known at this point so we always update them 9854 // to null here, only to reset them at a later point. 9855 Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile, 9856 pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi, 9857 pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags, 9858 pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(), 9859 UserManagerService.getInstance(), usesStaticLibraries, 9860 pkg.usesStaticLibrariesVersions); 9861 } 9862 // SIDE EFFECTS; persists system state to files on disk; move elsewhere 9863 mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting); 9864 9865 // SIDE EFFECTS; modifies system state; move elsewhere 9866 if (pkgSetting.origPackage != null) { 9867 // If we are first transitioning from an original package, 9868 // fix up the new package's name now. We need to do this after 9869 // looking up the package under its new name, so getPackageLP 9870 // can take care of fiddling things correctly. 9871 pkg.setPackageName(origPackage.name); 9872 9873 // File a report about this. 9874 String msg = "New package " + pkgSetting.realName 9875 + " renamed to replace old package " + pkgSetting.name; 9876 reportSettingsProblem(Log.WARN, msg); 9877 9878 // Make a note of it. 9879 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 9880 mTransferedPackages.add(origPackage.name); 9881 } 9882 9883 // No longer need to retain this. 9884 pkgSetting.origPackage = null; 9885 } 9886 9887 // SIDE EFFECTS; modifies system state; move elsewhere 9888 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 9889 // Make a note of it. 9890 mTransferedPackages.add(pkg.packageName); 9891 } 9892 9893 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 9894 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 9895 } 9896 9897 if ((scanFlags & SCAN_BOOTING) == 0 9898 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 9899 // Check all shared libraries and map to their actual file path. 9900 // We only do this here for apps not on a system dir, because those 9901 // are the only ones that can fail an install due to this. We 9902 // will take care of the system apps by updating all of their 9903 // library paths after the scan is done. Also during the initial 9904 // scan don't update any libs as we do this wholesale after all 9905 // apps are scanned to avoid dependency based scanning. 9906 updateSharedLibrariesLPr(pkg, null); 9907 } 9908 9909 if (mFoundPolicyFile) { 9910 SELinuxMMAC.assignSeInfoValue(pkg); 9911 } 9912 pkg.applicationInfo.uid = pkgSetting.appId; 9913 pkg.mExtras = pkgSetting; 9914 9915 9916 // Static shared libs have same package with different versions where 9917 // we internally use a synthetic package name to allow multiple versions 9918 // of the same package, therefore we need to compare signatures against 9919 // the package setting for the latest library version. 9920 PackageSetting signatureCheckPs = pkgSetting; 9921 if (pkg.applicationInfo.isStaticSharedLibrary()) { 9922 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg); 9923 if (libraryEntry != null) { 9924 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk); 9925 } 9926 } 9927 9928 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 9929 if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) { 9930 if (ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) { 9931 // We just determined the app is signed correctly, so bring 9932 // over the latest parsed certs. 9933 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9934 } else { 9935 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 9936 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 9937 "Package " + pkg.packageName + " upgrade keys do not match the " 9938 + "previously installed version"); 9939 } else { 9940 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9941 String msg = "System package " + pkg.packageName 9942 + " signature changed; retaining data."; 9943 reportSettingsProblem(Log.WARN, msg); 9944 } 9945 } 9946 } else { 9947 try { 9948 final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg); 9949 final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg); 9950 final boolean compatMatch = verifySignatures(signatureCheckPs, pkg.mSignatures, 9951 compareCompat, compareRecover); 9952 // The new KeySets will be re-added later in the scanning process. 9953 if (compatMatch) { 9954 synchronized (mPackages) { 9955 ksms.removeAppKeySetDataLPw(pkg.packageName); 9956 } 9957 } 9958 // We just determined the app is signed correctly, so bring 9959 // over the latest parsed certs. 9960 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9961 } catch (PackageManagerException e) { 9962 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 9963 throw e; 9964 } 9965 // The signature has changed, but this package is in the system 9966 // image... let's recover! 9967 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9968 // However... if this package is part of a shared user, but it 9969 // doesn't match the signature of the shared user, let's fail. 9970 // What this means is that you can't change the signatures 9971 // associated with an overall shared user, which doesn't seem all 9972 // that unreasonable. 9973 if (signatureCheckPs.sharedUser != null) { 9974 if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures, 9975 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 9976 throw new PackageManagerException( 9977 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 9978 "Signature mismatch for shared user: " 9979 + pkgSetting.sharedUser); 9980 } 9981 } 9982 // File a report about this. 9983 String msg = "System package " + pkg.packageName 9984 + " signature changed; retaining data."; 9985 reportSettingsProblem(Log.WARN, msg); 9986 } 9987 } 9988 9989 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 9990 // This package wants to adopt ownership of permissions from 9991 // another package. 9992 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 9993 final String origName = pkg.mAdoptPermissions.get(i); 9994 final PackageSetting orig = mSettings.getPackageLPr(origName); 9995 if (orig != null) { 9996 if (verifyPackageUpdateLPr(orig, pkg)) { 9997 Slog.i(TAG, "Adopting permissions from " + origName + " to " 9998 + pkg.packageName); 9999 // SIDE EFFECTS; updates permissions system state; move elsewhere 10000 mSettings.mPermissions.transferPermissions(origName, pkg.packageName); 10001 } 10002 } 10003 } 10004 } 10005 } 10006 10007 pkg.applicationInfo.processName = fixProcessName( 10008 pkg.applicationInfo.packageName, 10009 pkg.applicationInfo.processName); 10010 10011 if (pkg != mPlatformPackage) { 10012 // Get all of our default paths setup 10013 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 10014 } 10015 10016 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 10017 10018 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 10019 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) { 10020 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi"); 10021 final boolean extractNativeLibs = !pkg.isLibrary(); 10022 derivePackageAbi(pkg, cpuAbiOverride, extractNativeLibs, mAppLib32InstallDir); 10023 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10024 10025 // Some system apps still use directory structure for native libraries 10026 // in which case we might end up not detecting abi solely based on apk 10027 // structure. Try to detect abi based on directory structure. 10028 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 10029 pkg.applicationInfo.primaryCpuAbi == null) { 10030 setBundledAppAbisAndRoots(pkg, pkgSetting); 10031 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 10032 } 10033 } else { 10034 // This is not a first boot or an upgrade, don't bother deriving the 10035 // ABI during the scan. Instead, trust the value that was stored in the 10036 // package setting. 10037 pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings; 10038 pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings; 10039 10040 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 10041 10042 if (DEBUG_ABI_SELECTION) { 10043 Slog.i(TAG, "Using ABIS and native lib paths from settings : " + 10044 pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " + 10045 pkg.applicationInfo.secondaryCpuAbi); 10046 } 10047 } 10048 } else { 10049 if ((scanFlags & SCAN_MOVE) != 0) { 10050 // We haven't run dex-opt for this move (since we've moved the compiled output too) 10051 // but we already have this packages package info in the PackageSetting. We just 10052 // use that and derive the native library path based on the new codepath. 10053 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 10054 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 10055 } 10056 10057 // Set native library paths again. For moves, the path will be updated based on the 10058 // ABIs we've determined above. For non-moves, the path will be updated based on the 10059 // ABIs we determined during compilation, but the path will depend on the final 10060 // package path (after the rename away from the stage path). 10061 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 10062 } 10063 10064 // This is a special case for the "system" package, where the ABI is 10065 // dictated by the zygote configuration (and init.rc). We should keep track 10066 // of this ABI so that we can deal with "normal" applications that run under 10067 // the same UID correctly. 10068 if (mPlatformPackage == pkg) { 10069 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 10070 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 10071 } 10072 10073 // If there's a mismatch between the abi-override in the package setting 10074 // and the abiOverride specified for the install. Warn about this because we 10075 // would've already compiled the app without taking the package setting into 10076 // account. 10077 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 10078 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 10079 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 10080 " for package " + pkg.packageName); 10081 } 10082 } 10083 10084 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 10085 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 10086 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 10087 10088 // Copy the derived override back to the parsed package, so that we can 10089 // update the package settings accordingly. 10090 pkg.cpuAbiOverride = cpuAbiOverride; 10091 10092 if (DEBUG_ABI_SELECTION) { 10093 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 10094 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 10095 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 10096 } 10097 10098 // Push the derived path down into PackageSettings so we know what to 10099 // clean up at uninstall time. 10100 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 10101 10102 if (DEBUG_ABI_SELECTION) { 10103 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 10104 " primary=" + pkg.applicationInfo.primaryCpuAbi + 10105 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 10106 } 10107 10108 // SIDE EFFECTS; removes DEX files from disk; move elsewhere 10109 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 10110 // We don't do this here during boot because we can do it all 10111 // at once after scanning all existing packages. 10112 // 10113 // We also do this *before* we perform dexopt on this package, so that 10114 // we can avoid redundant dexopts, and also to make sure we've got the 10115 // code and package path correct. 10116 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg); 10117 } 10118 10119 if (mFactoryTest && pkg.requestedPermissions.contains( 10120 android.Manifest.permission.FACTORY_TEST)) { 10121 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 10122 } 10123 10124 if (isSystemApp(pkg)) { 10125 pkgSetting.isOrphaned = true; 10126 } 10127 10128 // Take care of first install / last update times. 10129 final long scanFileTime = getLastModifiedTime(pkg); 10130 if (currentTime != 0) { 10131 if (pkgSetting.firstInstallTime == 0) { 10132 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 10133 } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) { 10134 pkgSetting.lastUpdateTime = currentTime; 10135 } 10136 } else if (pkgSetting.firstInstallTime == 0) { 10137 // We need *something*. Take time time stamp of the file. 10138 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 10139 } else if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 10140 if (scanFileTime != pkgSetting.timeStamp) { 10141 // A package on the system image has changed; consider this 10142 // to be an update. 10143 pkgSetting.lastUpdateTime = scanFileTime; 10144 } 10145 } 10146 pkgSetting.setTimeStamp(scanFileTime); 10147 10148 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 10149 if (nonMutatedPs != null) { 10150 synchronized (mPackages) { 10151 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 10152 } 10153 } 10154 } else { 10155 final int userId = user == null ? 0 : user.getIdentifier(); 10156 // Modify state for the given package setting 10157 commitPackageSettings(pkg, pkgSetting, user, scanFlags, 10158 (parseFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/); 10159 if (pkgSetting.getInstantApp(userId)) { 10160 mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId); 10161 } 10162 } 10163 return pkg; 10164 } 10165 10166 /** 10167 * Applies policy to the parsed package based upon the given policy flags. 10168 * Ensures the package is in a good state. 10169 * <p> 10170 * Implementation detail: This method must NOT have any side effect. It would 10171 * ideally be static, but, it requires locks to read system state. 10172 */ 10173 private void applyPolicy(PackageParser.Package pkg, final @ParseFlags int parseFlags, 10174 final @ScanFlags int scanFlags) { 10175 if ((scanFlags & SCAN_AS_SYSTEM) != 0) { 10176 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 10177 if (pkg.applicationInfo.isDirectBootAware()) { 10178 // we're direct boot aware; set for all components 10179 for (PackageParser.Service s : pkg.services) { 10180 s.info.encryptionAware = s.info.directBootAware = true; 10181 } 10182 for (PackageParser.Provider p : pkg.providers) { 10183 p.info.encryptionAware = p.info.directBootAware = true; 10184 } 10185 for (PackageParser.Activity a : pkg.activities) { 10186 a.info.encryptionAware = a.info.directBootAware = true; 10187 } 10188 for (PackageParser.Activity r : pkg.receivers) { 10189 r.info.encryptionAware = r.info.directBootAware = true; 10190 } 10191 } 10192 if (compressedFileExists(pkg.codePath)) { 10193 pkg.isStub = true; 10194 } 10195 } else { 10196 // non system apps can't be flagged as core 10197 pkg.coreApp = false; 10198 // clear flags not applicable to regular apps 10199 pkg.applicationInfo.flags &= 10200 ~ApplicationInfo.FLAG_PERSISTENT; 10201 pkg.applicationInfo.privateFlags &= 10202 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 10203 pkg.applicationInfo.privateFlags &= 10204 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 10205 // clear protected broadcasts 10206 pkg.protectedBroadcasts = null; 10207 // cap permission priorities 10208 if (pkg.permissionGroups != null && pkg.permissionGroups.size() > 0) { 10209 for (int i = pkg.permissionGroups.size() - 1; i >= 0; --i) { 10210 pkg.permissionGroups.get(i).info.priority = 0; 10211 } 10212 } 10213 } 10214 if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) { 10215 // ignore export request for single user receivers 10216 if (pkg.receivers != null) { 10217 for (int i = pkg.receivers.size() - 1; i >= 0; --i) { 10218 final PackageParser.Activity receiver = pkg.receivers.get(i); 10219 if ((receiver.info.flags & ActivityInfo.FLAG_SINGLE_USER) != 0) { 10220 receiver.info.exported = false; 10221 } 10222 } 10223 } 10224 // ignore export request for single user services 10225 if (pkg.services != null) { 10226 for (int i = pkg.services.size() - 1; i >= 0; --i) { 10227 final PackageParser.Service service = pkg.services.get(i); 10228 if ((service.info.flags & ServiceInfo.FLAG_SINGLE_USER) != 0) { 10229 service.info.exported = false; 10230 } 10231 } 10232 } 10233 // ignore export request for single user providers 10234 if (pkg.providers != null) { 10235 for (int i = pkg.providers.size() - 1; i >= 0; --i) { 10236 final PackageParser.Provider provider = pkg.providers.get(i); 10237 if ((provider.info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0) { 10238 provider.info.exported = false; 10239 } 10240 } 10241 } 10242 } 10243 pkg.mTrustedOverlay = (scanFlags & SCAN_TRUSTED_OVERLAY) != 0; 10244 10245 if ((scanFlags & SCAN_AS_PRIVILEGED) != 0) { 10246 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 10247 } 10248 10249 if ((scanFlags & SCAN_AS_OEM) != 0) { 10250 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM; 10251 } 10252 10253 if ((scanFlags & SCAN_AS_VENDOR) != 0) { 10254 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_VENDOR; 10255 } 10256 10257 if (!isSystemApp(pkg)) { 10258 // Only system apps can use these features. 10259 pkg.mOriginalPackages = null; 10260 pkg.mRealPackage = null; 10261 pkg.mAdoptPermissions = null; 10262 } 10263 } 10264 10265 /** 10266 * Asserts the parsed package is valid according to the given policy. If the 10267 * package is invalid, for whatever reason, throws {@link PackageManagerException}. 10268 * <p> 10269 * Implementation detail: This method must NOT have any side effects. It would 10270 * ideally be static, but, it requires locks to read system state. 10271 * 10272 * @throws PackageManagerException If the package fails any of the validation checks 10273 */ 10274 private void assertPackageIsValid(PackageParser.Package pkg, final @ParseFlags int parseFlags, 10275 final @ScanFlags int scanFlags) 10276 throws PackageManagerException { 10277 if ((parseFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 10278 assertCodePolicy(pkg); 10279 } 10280 10281 if (pkg.applicationInfo.getCodePath() == null || 10282 pkg.applicationInfo.getResourcePath() == null) { 10283 // Bail out. The resource and code paths haven't been set. 10284 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 10285 "Code and resource paths haven't been set correctly"); 10286 } 10287 10288 // Make sure we're not adding any bogus keyset info 10289 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 10290 ksms.assertScannedPackageValid(pkg); 10291 10292 synchronized (mPackages) { 10293 // The special "android" package can only be defined once 10294 if (pkg.packageName.equals("android")) { 10295 if (mAndroidApplication != null) { 10296 Slog.w(TAG, "*************************************************"); 10297 Slog.w(TAG, "Core android package being redefined. Skipping."); 10298 Slog.w(TAG, " codePath=" + pkg.codePath); 10299 Slog.w(TAG, "*************************************************"); 10300 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 10301 "Core android package being redefined. Skipping."); 10302 } 10303 } 10304 10305 // A package name must be unique; don't allow duplicates 10306 if (mPackages.containsKey(pkg.packageName)) { 10307 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 10308 "Application package " + pkg.packageName 10309 + " already installed. Skipping duplicate."); 10310 } 10311 10312 if (pkg.applicationInfo.isStaticSharedLibrary()) { 10313 // Static libs have a synthetic package name containing the version 10314 // but we still want the base name to be unique. 10315 if (mPackages.containsKey(pkg.manifestPackageName)) { 10316 throw new PackageManagerException( 10317 "Duplicate static shared lib provider package"); 10318 } 10319 10320 // Static shared libraries should have at least O target SDK 10321 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) { 10322 throw new PackageManagerException( 10323 "Packages declaring static-shared libs must target O SDK or higher"); 10324 } 10325 10326 // Package declaring static a shared lib cannot be instant apps 10327 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 10328 throw new PackageManagerException( 10329 "Packages declaring static-shared libs cannot be instant apps"); 10330 } 10331 10332 // Package declaring static a shared lib cannot be renamed since the package 10333 // name is synthetic and apps can't code around package manager internals. 10334 if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) { 10335 throw new PackageManagerException( 10336 "Packages declaring static-shared libs cannot be renamed"); 10337 } 10338 10339 // Package declaring static a shared lib cannot declare child packages 10340 if (!ArrayUtils.isEmpty(pkg.childPackages)) { 10341 throw new PackageManagerException( 10342 "Packages declaring static-shared libs cannot have child packages"); 10343 } 10344 10345 // Package declaring static a shared lib cannot declare dynamic libs 10346 if (!ArrayUtils.isEmpty(pkg.libraryNames)) { 10347 throw new PackageManagerException( 10348 "Packages declaring static-shared libs cannot declare dynamic libs"); 10349 } 10350 10351 // Package declaring static a shared lib cannot declare shared users 10352 if (pkg.mSharedUserId != null) { 10353 throw new PackageManagerException( 10354 "Packages declaring static-shared libs cannot declare shared users"); 10355 } 10356 10357 // Static shared libs cannot declare activities 10358 if (!pkg.activities.isEmpty()) { 10359 throw new PackageManagerException( 10360 "Static shared libs cannot declare activities"); 10361 } 10362 10363 // Static shared libs cannot declare services 10364 if (!pkg.services.isEmpty()) { 10365 throw new PackageManagerException( 10366 "Static shared libs cannot declare services"); 10367 } 10368 10369 // Static shared libs cannot declare providers 10370 if (!pkg.providers.isEmpty()) { 10371 throw new PackageManagerException( 10372 "Static shared libs cannot declare content providers"); 10373 } 10374 10375 // Static shared libs cannot declare receivers 10376 if (!pkg.receivers.isEmpty()) { 10377 throw new PackageManagerException( 10378 "Static shared libs cannot declare broadcast receivers"); 10379 } 10380 10381 // Static shared libs cannot declare permission groups 10382 if (!pkg.permissionGroups.isEmpty()) { 10383 throw new PackageManagerException( 10384 "Static shared libs cannot declare permission groups"); 10385 } 10386 10387 // Static shared libs cannot declare permissions 10388 if (!pkg.permissions.isEmpty()) { 10389 throw new PackageManagerException( 10390 "Static shared libs cannot declare permissions"); 10391 } 10392 10393 // Static shared libs cannot declare protected broadcasts 10394 if (pkg.protectedBroadcasts != null) { 10395 throw new PackageManagerException( 10396 "Static shared libs cannot declare protected broadcasts"); 10397 } 10398 10399 // Static shared libs cannot be overlay targets 10400 if (pkg.mOverlayTarget != null) { 10401 throw new PackageManagerException( 10402 "Static shared libs cannot be overlay targets"); 10403 } 10404 10405 // The version codes must be ordered as lib versions 10406 int minVersionCode = Integer.MIN_VALUE; 10407 int maxVersionCode = Integer.MAX_VALUE; 10408 10409 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get( 10410 pkg.staticSharedLibName); 10411 if (versionedLib != null) { 10412 final int versionCount = versionedLib.size(); 10413 for (int i = 0; i < versionCount; i++) { 10414 SharedLibraryInfo libInfo = versionedLib.valueAt(i).info; 10415 final int libVersionCode = libInfo.getDeclaringPackage() 10416 .getVersionCode(); 10417 if (libInfo.getVersion() < pkg.staticSharedLibVersion) { 10418 minVersionCode = Math.max(minVersionCode, libVersionCode + 1); 10419 } else if (libInfo.getVersion() > pkg.staticSharedLibVersion) { 10420 maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1); 10421 } else { 10422 minVersionCode = maxVersionCode = libVersionCode; 10423 break; 10424 } 10425 } 10426 } 10427 if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) { 10428 throw new PackageManagerException("Static shared" 10429 + " lib version codes must be ordered as lib versions"); 10430 } 10431 } 10432 10433 // Only privileged apps and updated privileged apps can add child packages. 10434 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 10435 if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) { 10436 throw new PackageManagerException("Only privileged apps can add child " 10437 + "packages. Ignoring package " + pkg.packageName); 10438 } 10439 final int childCount = pkg.childPackages.size(); 10440 for (int i = 0; i < childCount; i++) { 10441 PackageParser.Package childPkg = pkg.childPackages.get(i); 10442 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 10443 childPkg.packageName)) { 10444 throw new PackageManagerException("Can't override child of " 10445 + "another disabled app. Ignoring package " + pkg.packageName); 10446 } 10447 } 10448 } 10449 10450 // If we're only installing presumed-existing packages, require that the 10451 // scanned APK is both already known and at the path previously established 10452 // for it. Previously unknown packages we pick up normally, but if we have an 10453 // a priori expectation about this package's install presence, enforce it. 10454 // With a singular exception for new system packages. When an OTA contains 10455 // a new system package, we allow the codepath to change from a system location 10456 // to the user-installed location. If we don't allow this change, any newer, 10457 // user-installed version of the application will be ignored. 10458 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 10459 if (mExpectingBetter.containsKey(pkg.packageName)) { 10460 logCriticalInfo(Log.WARN, 10461 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 10462 } else { 10463 PackageSetting known = mSettings.getPackageLPr(pkg.packageName); 10464 if (known != null) { 10465 if (DEBUG_PACKAGE_SCANNING) { 10466 Log.d(TAG, "Examining " + pkg.codePath 10467 + " and requiring known paths " + known.codePathString 10468 + " & " + known.resourcePathString); 10469 } 10470 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 10471 || !pkg.applicationInfo.getResourcePath().equals( 10472 known.resourcePathString)) { 10473 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 10474 "Application package " + pkg.packageName 10475 + " found at " + pkg.applicationInfo.getCodePath() 10476 + " but expected at " + known.codePathString 10477 + "; ignoring."); 10478 } 10479 } else { 10480 throw new PackageManagerException(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 10481 "Application package " + pkg.packageName 10482 + " not found; ignoring."); 10483 } 10484 } 10485 } 10486 10487 // Verify that this new package doesn't have any content providers 10488 // that conflict with existing packages. Only do this if the 10489 // package isn't already installed, since we don't want to break 10490 // things that are installed. 10491 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 10492 final int N = pkg.providers.size(); 10493 int i; 10494 for (i=0; i<N; i++) { 10495 PackageParser.Provider p = pkg.providers.get(i); 10496 if (p.info.authority != null) { 10497 String names[] = p.info.authority.split(";"); 10498 for (int j = 0; j < names.length; j++) { 10499 if (mProvidersByAuthority.containsKey(names[j])) { 10500 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 10501 final String otherPackageName = 10502 ((other != null && other.getComponentName() != null) ? 10503 other.getComponentName().getPackageName() : "?"); 10504 throw new PackageManagerException( 10505 INSTALL_FAILED_CONFLICTING_PROVIDER, 10506 "Can't install because provider name " + names[j] 10507 + " (in package " + pkg.applicationInfo.packageName 10508 + ") is already used by " + otherPackageName); 10509 } 10510 } 10511 } 10512 } 10513 } 10514 } 10515 } 10516 10517 private boolean addSharedLibraryLPw(String path, String apk, String name, int version, 10518 int type, String declaringPackageName, int declaringVersionCode) { 10519 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 10520 if (versionedLib == null) { 10521 versionedLib = new SparseArray<>(); 10522 mSharedLibraries.put(name, versionedLib); 10523 if (type == SharedLibraryInfo.TYPE_STATIC) { 10524 mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib); 10525 } 10526 } else if (versionedLib.indexOfKey(version) >= 0) { 10527 return false; 10528 } 10529 SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name, 10530 version, type, declaringPackageName, declaringVersionCode); 10531 versionedLib.put(version, libEntry); 10532 return true; 10533 } 10534 10535 private boolean removeSharedLibraryLPw(String name, int version) { 10536 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 10537 if (versionedLib == null) { 10538 return false; 10539 } 10540 final int libIdx = versionedLib.indexOfKey(version); 10541 if (libIdx < 0) { 10542 return false; 10543 } 10544 SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx); 10545 versionedLib.remove(version); 10546 if (versionedLib.size() <= 0) { 10547 mSharedLibraries.remove(name); 10548 if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) { 10549 mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage() 10550 .getPackageName()); 10551 } 10552 } 10553 return true; 10554 } 10555 10556 /** 10557 * Adds a scanned package to the system. When this method is finished, the package will 10558 * be available for query, resolution, etc... 10559 */ 10560 private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting, 10561 UserHandle user, final @ScanFlags int scanFlags, boolean chatty) 10562 throws PackageManagerException { 10563 final String pkgName = pkg.packageName; 10564 if (mCustomResolverComponentName != null && 10565 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 10566 setUpCustomResolverActivity(pkg); 10567 } 10568 10569 if (pkg.packageName.equals("android")) { 10570 synchronized (mPackages) { 10571 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 10572 // Set up information for our fall-back user intent resolution activity. 10573 mPlatformPackage = pkg; 10574 pkg.mVersionCode = mSdkVersion; 10575 mAndroidApplication = pkg.applicationInfo; 10576 if (!mResolverReplaced) { 10577 mResolveActivity.applicationInfo = mAndroidApplication; 10578 mResolveActivity.name = ResolverActivity.class.getName(); 10579 mResolveActivity.packageName = mAndroidApplication.packageName; 10580 mResolveActivity.processName = "system:ui"; 10581 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 10582 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 10583 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 10584 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 10585 mResolveActivity.exported = true; 10586 mResolveActivity.enabled = true; 10587 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 10588 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 10589 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 10590 | ActivityInfo.CONFIG_SCREEN_LAYOUT 10591 | ActivityInfo.CONFIG_ORIENTATION 10592 | ActivityInfo.CONFIG_KEYBOARD 10593 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 10594 mResolveInfo.activityInfo = mResolveActivity; 10595 mResolveInfo.priority = 0; 10596 mResolveInfo.preferredOrder = 0; 10597 mResolveInfo.match = 0; 10598 mResolveComponentName = new ComponentName( 10599 mAndroidApplication.packageName, mResolveActivity.name); 10600 } 10601 } 10602 } 10603 } 10604 10605 ArrayList<PackageParser.Package> clientLibPkgs = null; 10606 // writer 10607 synchronized (mPackages) { 10608 boolean hasStaticSharedLibs = false; 10609 10610 // Any app can add new static shared libraries 10611 if (pkg.staticSharedLibName != null) { 10612 // Static shared libs don't allow renaming as they have synthetic package 10613 // names to allow install of multiple versions, so use name from manifest. 10614 if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName, 10615 pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC, 10616 pkg.manifestPackageName, pkg.mVersionCode)) { 10617 hasStaticSharedLibs = true; 10618 } else { 10619 Slog.w(TAG, "Package " + pkg.packageName + " library " 10620 + pkg.staticSharedLibName + " already exists; skipping"); 10621 } 10622 // Static shared libs cannot be updated once installed since they 10623 // use synthetic package name which includes the version code, so 10624 // not need to update other packages's shared lib dependencies. 10625 } 10626 10627 if (!hasStaticSharedLibs 10628 && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 10629 // Only system apps can add new dynamic shared libraries. 10630 if (pkg.libraryNames != null) { 10631 for (int i = 0; i < pkg.libraryNames.size(); i++) { 10632 String name = pkg.libraryNames.get(i); 10633 boolean allowed = false; 10634 if (pkg.isUpdatedSystemApp()) { 10635 // New library entries can only be added through the 10636 // system image. This is important to get rid of a lot 10637 // of nasty edge cases: for example if we allowed a non- 10638 // system update of the app to add a library, then uninstalling 10639 // the update would make the library go away, and assumptions 10640 // we made such as through app install filtering would now 10641 // have allowed apps on the device which aren't compatible 10642 // with it. Better to just have the restriction here, be 10643 // conservative, and create many fewer cases that can negatively 10644 // impact the user experience. 10645 final PackageSetting sysPs = mSettings 10646 .getDisabledSystemPkgLPr(pkg.packageName); 10647 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 10648 for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) { 10649 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 10650 allowed = true; 10651 break; 10652 } 10653 } 10654 } 10655 } else { 10656 allowed = true; 10657 } 10658 if (allowed) { 10659 if (!addSharedLibraryLPw(null, pkg.packageName, name, 10660 SharedLibraryInfo.VERSION_UNDEFINED, 10661 SharedLibraryInfo.TYPE_DYNAMIC, 10662 pkg.packageName, pkg.mVersionCode)) { 10663 Slog.w(TAG, "Package " + pkg.packageName + " library " 10664 + name + " already exists; skipping"); 10665 } 10666 } else { 10667 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 10668 + name + " that is not declared on system image; skipping"); 10669 } 10670 } 10671 10672 if ((scanFlags & SCAN_BOOTING) == 0) { 10673 // If we are not booting, we need to update any applications 10674 // that are clients of our shared library. If we are booting, 10675 // this will all be done once the scan is complete. 10676 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 10677 } 10678 } 10679 } 10680 } 10681 10682 if ((scanFlags & SCAN_BOOTING) != 0) { 10683 // No apps can run during boot scan, so they don't need to be frozen 10684 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 10685 // Caller asked to not kill app, so it's probably not frozen 10686 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 10687 // Caller asked us to ignore frozen check for some reason; they 10688 // probably didn't know the package name 10689 } else { 10690 // We're doing major surgery on this package, so it better be frozen 10691 // right now to keep it from launching 10692 checkPackageFrozen(pkgName); 10693 } 10694 10695 // Also need to kill any apps that are dependent on the library. 10696 if (clientLibPkgs != null) { 10697 for (int i=0; i<clientLibPkgs.size(); i++) { 10698 PackageParser.Package clientPkg = clientLibPkgs.get(i); 10699 killApplication(clientPkg.applicationInfo.packageName, 10700 clientPkg.applicationInfo.uid, "update lib"); 10701 } 10702 } 10703 10704 // writer 10705 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 10706 10707 synchronized (mPackages) { 10708 // We don't expect installation to fail beyond this point 10709 10710 // Add the new setting to mSettings 10711 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 10712 // Add the new setting to mPackages 10713 mPackages.put(pkg.applicationInfo.packageName, pkg); 10714 // Make sure we don't accidentally delete its data. 10715 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 10716 while (iter.hasNext()) { 10717 PackageCleanItem item = iter.next(); 10718 if (pkgName.equals(item.packageName)) { 10719 iter.remove(); 10720 } 10721 } 10722 10723 // Add the package's KeySets to the global KeySetManagerService 10724 KeySetManagerService ksms = mSettings.mKeySetManagerService; 10725 ksms.addScannedPackageLPw(pkg); 10726 10727 int N = pkg.providers.size(); 10728 StringBuilder r = null; 10729 int i; 10730 for (i=0; i<N; i++) { 10731 PackageParser.Provider p = pkg.providers.get(i); 10732 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 10733 p.info.processName); 10734 mProviders.addProvider(p); 10735 p.syncable = p.info.isSyncable; 10736 if (p.info.authority != null) { 10737 String names[] = p.info.authority.split(";"); 10738 p.info.authority = null; 10739 for (int j = 0; j < names.length; j++) { 10740 if (j == 1 && p.syncable) { 10741 // We only want the first authority for a provider to possibly be 10742 // syncable, so if we already added this provider using a different 10743 // authority clear the syncable flag. We copy the provider before 10744 // changing it because the mProviders object contains a reference 10745 // to a provider that we don't want to change. 10746 // Only do this for the second authority since the resulting provider 10747 // object can be the same for all future authorities for this provider. 10748 p = new PackageParser.Provider(p); 10749 p.syncable = false; 10750 } 10751 if (!mProvidersByAuthority.containsKey(names[j])) { 10752 mProvidersByAuthority.put(names[j], p); 10753 if (p.info.authority == null) { 10754 p.info.authority = names[j]; 10755 } else { 10756 p.info.authority = p.info.authority + ";" + names[j]; 10757 } 10758 if (DEBUG_PACKAGE_SCANNING) { 10759 if (chatty) 10760 Log.d(TAG, "Registered content provider: " + names[j] 10761 + ", className = " + p.info.name + ", isSyncable = " 10762 + p.info.isSyncable); 10763 } 10764 } else { 10765 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 10766 Slog.w(TAG, "Skipping provider name " + names[j] + 10767 " (in package " + pkg.applicationInfo.packageName + 10768 "): name already used by " 10769 + ((other != null && other.getComponentName() != null) 10770 ? other.getComponentName().getPackageName() : "?")); 10771 } 10772 } 10773 } 10774 if (chatty) { 10775 if (r == null) { 10776 r = new StringBuilder(256); 10777 } else { 10778 r.append(' '); 10779 } 10780 r.append(p.info.name); 10781 } 10782 } 10783 if (r != null) { 10784 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 10785 } 10786 10787 N = pkg.services.size(); 10788 r = null; 10789 for (i=0; i<N; i++) { 10790 PackageParser.Service s = pkg.services.get(i); 10791 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 10792 s.info.processName); 10793 mServices.addService(s); 10794 if (chatty) { 10795 if (r == null) { 10796 r = new StringBuilder(256); 10797 } else { 10798 r.append(' '); 10799 } 10800 r.append(s.info.name); 10801 } 10802 } 10803 if (r != null) { 10804 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 10805 } 10806 10807 N = pkg.receivers.size(); 10808 r = null; 10809 for (i=0; i<N; i++) { 10810 PackageParser.Activity a = pkg.receivers.get(i); 10811 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 10812 a.info.processName); 10813 mReceivers.addActivity(a, "receiver"); 10814 if (chatty) { 10815 if (r == null) { 10816 r = new StringBuilder(256); 10817 } else { 10818 r.append(' '); 10819 } 10820 r.append(a.info.name); 10821 } 10822 } 10823 if (r != null) { 10824 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 10825 } 10826 10827 N = pkg.activities.size(); 10828 r = null; 10829 for (i=0; i<N; i++) { 10830 PackageParser.Activity a = pkg.activities.get(i); 10831 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 10832 a.info.processName); 10833 mActivities.addActivity(a, "activity"); 10834 if (chatty) { 10835 if (r == null) { 10836 r = new StringBuilder(256); 10837 } else { 10838 r.append(' '); 10839 } 10840 r.append(a.info.name); 10841 } 10842 } 10843 if (r != null) { 10844 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 10845 } 10846 10847 // Don't allow ephemeral applications to define new permissions groups. 10848 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 10849 Slog.w(TAG, "Permission groups from package " + pkg.packageName 10850 + " ignored: instant apps cannot define new permission groups."); 10851 } else { 10852 mPermissionManager.addAllPermissionGroups(pkg, chatty); 10853 } 10854 10855 // Don't allow ephemeral applications to define new permissions. 10856 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 10857 Slog.w(TAG, "Permissions from package " + pkg.packageName 10858 + " ignored: instant apps cannot define new permissions."); 10859 } else { 10860 mPermissionManager.addAllPermissions(pkg, chatty); 10861 } 10862 10863 N = pkg.instrumentation.size(); 10864 r = null; 10865 for (i=0; i<N; i++) { 10866 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 10867 a.info.packageName = pkg.applicationInfo.packageName; 10868 a.info.sourceDir = pkg.applicationInfo.sourceDir; 10869 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 10870 a.info.splitNames = pkg.splitNames; 10871 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 10872 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 10873 a.info.splitDependencies = pkg.applicationInfo.splitDependencies; 10874 a.info.dataDir = pkg.applicationInfo.dataDir; 10875 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 10876 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 10877 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 10878 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 10879 mInstrumentation.put(a.getComponentName(), a); 10880 if (chatty) { 10881 if (r == null) { 10882 r = new StringBuilder(256); 10883 } else { 10884 r.append(' '); 10885 } 10886 r.append(a.info.name); 10887 } 10888 } 10889 if (r != null) { 10890 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 10891 } 10892 10893 if (pkg.protectedBroadcasts != null) { 10894 N = pkg.protectedBroadcasts.size(); 10895 synchronized (mProtectedBroadcasts) { 10896 for (i = 0; i < N; i++) { 10897 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 10898 } 10899 } 10900 } 10901 } 10902 10903 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10904 } 10905 10906 /** 10907 * Derive the ABI of a non-system package located at {@code scanFile}. This information 10908 * is derived purely on the basis of the contents of {@code scanFile} and 10909 * {@code cpuAbiOverride}. 10910 * 10911 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 10912 */ 10913 private static void derivePackageAbi(PackageParser.Package pkg, String cpuAbiOverride, 10914 boolean extractLibs, File appLib32InstallDir) 10915 throws PackageManagerException { 10916 // Give ourselves some initial paths; we'll come back for another 10917 // pass once we've determined ABI below. 10918 setNativeLibraryPaths(pkg, appLib32InstallDir); 10919 10920 // We would never need to extract libs for forward-locked and external packages, 10921 // since the container service will do it for us. We shouldn't attempt to 10922 // extract libs from system app when it was not updated. 10923 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 10924 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 10925 extractLibs = false; 10926 } 10927 10928 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 10929 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 10930 10931 NativeLibraryHelper.Handle handle = null; 10932 try { 10933 handle = NativeLibraryHelper.Handle.create(pkg); 10934 // TODO(multiArch): This can be null for apps that didn't go through the 10935 // usual installation process. We can calculate it again, like we 10936 // do during install time. 10937 // 10938 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 10939 // unnecessary. 10940 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 10941 10942 // Null out the abis so that they can be recalculated. 10943 pkg.applicationInfo.primaryCpuAbi = null; 10944 pkg.applicationInfo.secondaryCpuAbi = null; 10945 if (isMultiArch(pkg.applicationInfo)) { 10946 // Warn if we've set an abiOverride for multi-lib packages.. 10947 // By definition, we need to copy both 32 and 64 bit libraries for 10948 // such packages. 10949 if (pkg.cpuAbiOverride != null 10950 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 10951 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 10952 } 10953 10954 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 10955 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 10956 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 10957 if (extractLibs) { 10958 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 10959 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 10960 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 10961 useIsaSpecificSubdirs); 10962 } else { 10963 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 10964 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 10965 } 10966 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10967 } 10968 10969 // Shared library native code should be in the APK zip aligned 10970 if (abi32 >= 0 && pkg.isLibrary() && extractLibs) { 10971 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 10972 "Shared library native lib extraction not supported"); 10973 } 10974 10975 maybeThrowExceptionForMultiArchCopy( 10976 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 10977 10978 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 10979 if (extractLibs) { 10980 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 10981 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 10982 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 10983 useIsaSpecificSubdirs); 10984 } else { 10985 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 10986 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 10987 } 10988 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10989 } 10990 10991 maybeThrowExceptionForMultiArchCopy( 10992 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 10993 10994 if (abi64 >= 0) { 10995 // Shared library native libs should be in the APK zip aligned 10996 if (extractLibs && pkg.isLibrary()) { 10997 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 10998 "Shared library native lib extraction not supported"); 10999 } 11000 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 11001 } 11002 11003 if (abi32 >= 0) { 11004 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 11005 if (abi64 >= 0) { 11006 if (pkg.use32bitAbi) { 11007 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 11008 pkg.applicationInfo.primaryCpuAbi = abi; 11009 } else { 11010 pkg.applicationInfo.secondaryCpuAbi = abi; 11011 } 11012 } else { 11013 pkg.applicationInfo.primaryCpuAbi = abi; 11014 } 11015 } 11016 } else { 11017 String[] abiList = (cpuAbiOverride != null) ? 11018 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 11019 11020 // Enable gross and lame hacks for apps that are built with old 11021 // SDK tools. We must scan their APKs for renderscript bitcode and 11022 // not launch them if it's present. Don't bother checking on devices 11023 // that don't have 64 bit support. 11024 boolean needsRenderScriptOverride = false; 11025 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 11026 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 11027 abiList = Build.SUPPORTED_32_BIT_ABIS; 11028 needsRenderScriptOverride = true; 11029 } 11030 11031 final int copyRet; 11032 if (extractLibs) { 11033 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 11034 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 11035 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 11036 } else { 11037 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 11038 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 11039 } 11040 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11041 11042 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 11043 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 11044 "Error unpackaging native libs for app, errorCode=" + copyRet); 11045 } 11046 11047 if (copyRet >= 0) { 11048 // Shared libraries that have native libs must be multi-architecture 11049 if (pkg.isLibrary()) { 11050 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 11051 "Shared library with native libs must be multiarch"); 11052 } 11053 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 11054 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 11055 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 11056 } else if (needsRenderScriptOverride) { 11057 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 11058 } 11059 } 11060 } catch (IOException ioe) { 11061 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 11062 } finally { 11063 IoUtils.closeQuietly(handle); 11064 } 11065 11066 // Now that we've calculated the ABIs and determined if it's an internal app, 11067 // we will go ahead and populate the nativeLibraryPath. 11068 setNativeLibraryPaths(pkg, appLib32InstallDir); 11069 } 11070 11071 /** 11072 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 11073 * i.e, so that all packages can be run inside a single process if required. 11074 * 11075 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 11076 * this function will either try and make the ABI for all packages in {@code packagesForUser} 11077 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 11078 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 11079 * updating a package that belongs to a shared user. 11080 * 11081 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 11082 * adds unnecessary complexity. 11083 */ 11084 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 11085 PackageParser.Package scannedPackage) { 11086 String requiredInstructionSet = null; 11087 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 11088 requiredInstructionSet = VMRuntime.getInstructionSet( 11089 scannedPackage.applicationInfo.primaryCpuAbi); 11090 } 11091 11092 PackageSetting requirer = null; 11093 for (PackageSetting ps : packagesForUser) { 11094 // If packagesForUser contains scannedPackage, we skip it. This will happen 11095 // when scannedPackage is an update of an existing package. Without this check, 11096 // we will never be able to change the ABI of any package belonging to a shared 11097 // user, even if it's compatible with other packages. 11098 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 11099 if (ps.primaryCpuAbiString == null) { 11100 continue; 11101 } 11102 11103 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 11104 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 11105 // We have a mismatch between instruction sets (say arm vs arm64) warn about 11106 // this but there's not much we can do. 11107 String errorMessage = "Instruction set mismatch, " 11108 + ((requirer == null) ? "[caller]" : requirer) 11109 + " requires " + requiredInstructionSet + " whereas " + ps 11110 + " requires " + instructionSet; 11111 Slog.w(TAG, errorMessage); 11112 } 11113 11114 if (requiredInstructionSet == null) { 11115 requiredInstructionSet = instructionSet; 11116 requirer = ps; 11117 } 11118 } 11119 } 11120 11121 if (requiredInstructionSet != null) { 11122 String adjustedAbi; 11123 if (requirer != null) { 11124 // requirer != null implies that either scannedPackage was null or that scannedPackage 11125 // did not require an ABI, in which case we have to adjust scannedPackage to match 11126 // the ABI of the set (which is the same as requirer's ABI) 11127 adjustedAbi = requirer.primaryCpuAbiString; 11128 if (scannedPackage != null) { 11129 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 11130 } 11131 } else { 11132 // requirer == null implies that we're updating all ABIs in the set to 11133 // match scannedPackage. 11134 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 11135 } 11136 11137 for (PackageSetting ps : packagesForUser) { 11138 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 11139 if (ps.primaryCpuAbiString != null) { 11140 continue; 11141 } 11142 11143 ps.primaryCpuAbiString = adjustedAbi; 11144 if (ps.pkg != null && ps.pkg.applicationInfo != null && 11145 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 11146 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 11147 if (DEBUG_ABI_SELECTION) { 11148 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 11149 + " (requirer=" 11150 + (requirer != null ? requirer.pkg : "null") 11151 + ", scannedPackage=" 11152 + (scannedPackage != null ? scannedPackage : "null") 11153 + ")"); 11154 } 11155 try { 11156 mInstaller.rmdex(ps.codePathString, 11157 getDexCodeInstructionSet(getPreferredInstructionSet())); 11158 } catch (InstallerException ignored) { 11159 } 11160 } 11161 } 11162 } 11163 } 11164 } 11165 11166 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 11167 synchronized (mPackages) { 11168 mResolverReplaced = true; 11169 // Set up information for custom user intent resolution activity. 11170 mResolveActivity.applicationInfo = pkg.applicationInfo; 11171 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 11172 mResolveActivity.packageName = pkg.applicationInfo.packageName; 11173 mResolveActivity.processName = pkg.applicationInfo.packageName; 11174 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 11175 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 11176 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 11177 mResolveActivity.theme = 0; 11178 mResolveActivity.exported = true; 11179 mResolveActivity.enabled = true; 11180 mResolveInfo.activityInfo = mResolveActivity; 11181 mResolveInfo.priority = 0; 11182 mResolveInfo.preferredOrder = 0; 11183 mResolveInfo.match = 0; 11184 mResolveComponentName = mCustomResolverComponentName; 11185 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 11186 mResolveComponentName); 11187 } 11188 } 11189 11190 private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) { 11191 if (installerActivity == null) { 11192 if (DEBUG_EPHEMERAL) { 11193 Slog.d(TAG, "Clear ephemeral installer activity"); 11194 } 11195 mInstantAppInstallerActivity = null; 11196 return; 11197 } 11198 11199 if (DEBUG_EPHEMERAL) { 11200 Slog.d(TAG, "Set ephemeral installer activity: " 11201 + installerActivity.getComponentName()); 11202 } 11203 // Set up information for ephemeral installer activity 11204 mInstantAppInstallerActivity = installerActivity; 11205 mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS 11206 | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 11207 mInstantAppInstallerActivity.exported = true; 11208 mInstantAppInstallerActivity.enabled = true; 11209 mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity; 11210 mInstantAppInstallerInfo.priority = 0; 11211 mInstantAppInstallerInfo.preferredOrder = 1; 11212 mInstantAppInstallerInfo.isDefault = true; 11213 mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 11214 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 11215 } 11216 11217 private static String calculateBundledApkRoot(final String codePathString) { 11218 final File codePath = new File(codePathString); 11219 final File codeRoot; 11220 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 11221 codeRoot = Environment.getRootDirectory(); 11222 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 11223 codeRoot = Environment.getOemDirectory(); 11224 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 11225 codeRoot = Environment.getVendorDirectory(); 11226 } else { 11227 // Unrecognized code path; take its top real segment as the apk root: 11228 // e.g. /something/app/blah.apk => /something 11229 try { 11230 File f = codePath.getCanonicalFile(); 11231 File parent = f.getParentFile(); // non-null because codePath is a file 11232 File tmp; 11233 while ((tmp = parent.getParentFile()) != null) { 11234 f = parent; 11235 parent = tmp; 11236 } 11237 codeRoot = f; 11238 Slog.w(TAG, "Unrecognized code path " 11239 + codePath + " - using " + codeRoot); 11240 } catch (IOException e) { 11241 // Can't canonicalize the code path -- shenanigans? 11242 Slog.w(TAG, "Can't canonicalize code path " + codePath); 11243 return Environment.getRootDirectory().getPath(); 11244 } 11245 } 11246 return codeRoot.getPath(); 11247 } 11248 11249 /** 11250 * Derive and set the location of native libraries for the given package, 11251 * which varies depending on where and how the package was installed. 11252 */ 11253 private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) { 11254 final ApplicationInfo info = pkg.applicationInfo; 11255 final String codePath = pkg.codePath; 11256 final File codeFile = new File(codePath); 11257 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 11258 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 11259 11260 info.nativeLibraryRootDir = null; 11261 info.nativeLibraryRootRequiresIsa = false; 11262 info.nativeLibraryDir = null; 11263 info.secondaryNativeLibraryDir = null; 11264 11265 if (isApkFile(codeFile)) { 11266 // Monolithic install 11267 if (bundledApp) { 11268 // If "/system/lib64/apkname" exists, assume that is the per-package 11269 // native library directory to use; otherwise use "/system/lib/apkname". 11270 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 11271 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 11272 getPrimaryInstructionSet(info)); 11273 11274 // This is a bundled system app so choose the path based on the ABI. 11275 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 11276 // is just the default path. 11277 final String apkName = deriveCodePathName(codePath); 11278 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 11279 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 11280 apkName).getAbsolutePath(); 11281 11282 if (info.secondaryCpuAbi != null) { 11283 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 11284 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 11285 secondaryLibDir, apkName).getAbsolutePath(); 11286 } 11287 } else if (asecApp) { 11288 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 11289 .getAbsolutePath(); 11290 } else { 11291 final String apkName = deriveCodePathName(codePath); 11292 info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName) 11293 .getAbsolutePath(); 11294 } 11295 11296 info.nativeLibraryRootRequiresIsa = false; 11297 info.nativeLibraryDir = info.nativeLibraryRootDir; 11298 } else { 11299 // Cluster install 11300 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 11301 info.nativeLibraryRootRequiresIsa = true; 11302 11303 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 11304 getPrimaryInstructionSet(info)).getAbsolutePath(); 11305 11306 if (info.secondaryCpuAbi != null) { 11307 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 11308 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 11309 } 11310 } 11311 } 11312 11313 /** 11314 * Calculate the abis and roots for a bundled app. These can uniquely 11315 * be determined from the contents of the system partition, i.e whether 11316 * it contains 64 or 32 bit shared libraries etc. We do not validate any 11317 * of this information, and instead assume that the system was built 11318 * sensibly. 11319 */ 11320 private static void setBundledAppAbisAndRoots(PackageParser.Package pkg, 11321 PackageSetting pkgSetting) { 11322 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 11323 11324 // If "/system/lib64/apkname" exists, assume that is the per-package 11325 // native library directory to use; otherwise use "/system/lib/apkname". 11326 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 11327 setBundledAppAbi(pkg, apkRoot, apkName); 11328 // pkgSetting might be null during rescan following uninstall of updates 11329 // to a bundled app, so accommodate that possibility. The settings in 11330 // that case will be established later from the parsed package. 11331 // 11332 // If the settings aren't null, sync them up with what we've just derived. 11333 // note that apkRoot isn't stored in the package settings. 11334 if (pkgSetting != null) { 11335 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 11336 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 11337 } 11338 } 11339 11340 /** 11341 * Deduces the ABI of a bundled app and sets the relevant fields on the 11342 * parsed pkg object. 11343 * 11344 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 11345 * under which system libraries are installed. 11346 * @param apkName the name of the installed package. 11347 */ 11348 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 11349 final File codeFile = new File(pkg.codePath); 11350 11351 final boolean has64BitLibs; 11352 final boolean has32BitLibs; 11353 if (isApkFile(codeFile)) { 11354 // Monolithic install 11355 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 11356 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 11357 } else { 11358 // Cluster install 11359 final File rootDir = new File(codeFile, LIB_DIR_NAME); 11360 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 11361 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 11362 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 11363 has64BitLibs = (new File(rootDir, isa)).exists(); 11364 } else { 11365 has64BitLibs = false; 11366 } 11367 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 11368 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 11369 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 11370 has32BitLibs = (new File(rootDir, isa)).exists(); 11371 } else { 11372 has32BitLibs = false; 11373 } 11374 } 11375 11376 if (has64BitLibs && !has32BitLibs) { 11377 // The package has 64 bit libs, but not 32 bit libs. Its primary 11378 // ABI should be 64 bit. We can safely assume here that the bundled 11379 // native libraries correspond to the most preferred ABI in the list. 11380 11381 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 11382 pkg.applicationInfo.secondaryCpuAbi = null; 11383 } else if (has32BitLibs && !has64BitLibs) { 11384 // The package has 32 bit libs but not 64 bit libs. Its primary 11385 // ABI should be 32 bit. 11386 11387 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 11388 pkg.applicationInfo.secondaryCpuAbi = null; 11389 } else if (has32BitLibs && has64BitLibs) { 11390 // The application has both 64 and 32 bit bundled libraries. We check 11391 // here that the app declares multiArch support, and warn if it doesn't. 11392 // 11393 // We will be lenient here and record both ABIs. The primary will be the 11394 // ABI that's higher on the list, i.e, a device that's configured to prefer 11395 // 64 bit apps will see a 64 bit primary ABI, 11396 11397 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 11398 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 11399 } 11400 11401 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 11402 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 11403 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 11404 } else { 11405 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 11406 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 11407 } 11408 } else { 11409 pkg.applicationInfo.primaryCpuAbi = null; 11410 pkg.applicationInfo.secondaryCpuAbi = null; 11411 } 11412 } 11413 11414 private void killApplication(String pkgName, int appId, String reason) { 11415 killApplication(pkgName, appId, UserHandle.USER_ALL, reason); 11416 } 11417 11418 private void killApplication(String pkgName, int appId, int userId, String reason) { 11419 // Request the ActivityManager to kill the process(only for existing packages) 11420 // so that we do not end up in a confused state while the user is still using the older 11421 // version of the application while the new one gets installed. 11422 final long token = Binder.clearCallingIdentity(); 11423 try { 11424 IActivityManager am = ActivityManager.getService(); 11425 if (am != null) { 11426 try { 11427 am.killApplication(pkgName, appId, userId, reason); 11428 } catch (RemoteException e) { 11429 } 11430 } 11431 } finally { 11432 Binder.restoreCallingIdentity(token); 11433 } 11434 } 11435 11436 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 11437 // Remove the parent package setting 11438 PackageSetting ps = (PackageSetting) pkg.mExtras; 11439 if (ps != null) { 11440 removePackageLI(ps, chatty); 11441 } 11442 // Remove the child package setting 11443 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 11444 for (int i = 0; i < childCount; i++) { 11445 PackageParser.Package childPkg = pkg.childPackages.get(i); 11446 ps = (PackageSetting) childPkg.mExtras; 11447 if (ps != null) { 11448 removePackageLI(ps, chatty); 11449 } 11450 } 11451 } 11452 11453 void removePackageLI(PackageSetting ps, boolean chatty) { 11454 if (DEBUG_INSTALL) { 11455 if (chatty) 11456 Log.d(TAG, "Removing package " + ps.name); 11457 } 11458 11459 // writer 11460 synchronized (mPackages) { 11461 mPackages.remove(ps.name); 11462 final PackageParser.Package pkg = ps.pkg; 11463 if (pkg != null) { 11464 cleanPackageDataStructuresLILPw(pkg, chatty); 11465 } 11466 } 11467 } 11468 11469 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 11470 if (DEBUG_INSTALL) { 11471 if (chatty) 11472 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 11473 } 11474 11475 // writer 11476 synchronized (mPackages) { 11477 // Remove the parent package 11478 mPackages.remove(pkg.applicationInfo.packageName); 11479 cleanPackageDataStructuresLILPw(pkg, chatty); 11480 11481 // Remove the child packages 11482 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 11483 for (int i = 0; i < childCount; i++) { 11484 PackageParser.Package childPkg = pkg.childPackages.get(i); 11485 mPackages.remove(childPkg.applicationInfo.packageName); 11486 cleanPackageDataStructuresLILPw(childPkg, chatty); 11487 } 11488 } 11489 } 11490 11491 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 11492 int N = pkg.providers.size(); 11493 StringBuilder r = null; 11494 int i; 11495 for (i=0; i<N; i++) { 11496 PackageParser.Provider p = pkg.providers.get(i); 11497 mProviders.removeProvider(p); 11498 if (p.info.authority == null) { 11499 11500 /* There was another ContentProvider with this authority when 11501 * this app was installed so this authority is null, 11502 * Ignore it as we don't have to unregister the provider. 11503 */ 11504 continue; 11505 } 11506 String names[] = p.info.authority.split(";"); 11507 for (int j = 0; j < names.length; j++) { 11508 if (mProvidersByAuthority.get(names[j]) == p) { 11509 mProvidersByAuthority.remove(names[j]); 11510 if (DEBUG_REMOVE) { 11511 if (chatty) 11512 Log.d(TAG, "Unregistered content provider: " + names[j] 11513 + ", className = " + p.info.name + ", isSyncable = " 11514 + p.info.isSyncable); 11515 } 11516 } 11517 } 11518 if (DEBUG_REMOVE && chatty) { 11519 if (r == null) { 11520 r = new StringBuilder(256); 11521 } else { 11522 r.append(' '); 11523 } 11524 r.append(p.info.name); 11525 } 11526 } 11527 if (r != null) { 11528 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 11529 } 11530 11531 N = pkg.services.size(); 11532 r = null; 11533 for (i=0; i<N; i++) { 11534 PackageParser.Service s = pkg.services.get(i); 11535 mServices.removeService(s); 11536 if (chatty) { 11537 if (r == null) { 11538 r = new StringBuilder(256); 11539 } else { 11540 r.append(' '); 11541 } 11542 r.append(s.info.name); 11543 } 11544 } 11545 if (r != null) { 11546 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 11547 } 11548 11549 N = pkg.receivers.size(); 11550 r = null; 11551 for (i=0; i<N; i++) { 11552 PackageParser.Activity a = pkg.receivers.get(i); 11553 mReceivers.removeActivity(a, "receiver"); 11554 if (DEBUG_REMOVE && chatty) { 11555 if (r == null) { 11556 r = new StringBuilder(256); 11557 } else { 11558 r.append(' '); 11559 } 11560 r.append(a.info.name); 11561 } 11562 } 11563 if (r != null) { 11564 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 11565 } 11566 11567 N = pkg.activities.size(); 11568 r = null; 11569 for (i=0; i<N; i++) { 11570 PackageParser.Activity a = pkg.activities.get(i); 11571 mActivities.removeActivity(a, "activity"); 11572 if (DEBUG_REMOVE && chatty) { 11573 if (r == null) { 11574 r = new StringBuilder(256); 11575 } else { 11576 r.append(' '); 11577 } 11578 r.append(a.info.name); 11579 } 11580 } 11581 if (r != null) { 11582 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 11583 } 11584 11585 mPermissionManager.removeAllPermissions(pkg, chatty); 11586 11587 N = pkg.instrumentation.size(); 11588 r = null; 11589 for (i=0; i<N; i++) { 11590 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 11591 mInstrumentation.remove(a.getComponentName()); 11592 if (DEBUG_REMOVE && chatty) { 11593 if (r == null) { 11594 r = new StringBuilder(256); 11595 } else { 11596 r.append(' '); 11597 } 11598 r.append(a.info.name); 11599 } 11600 } 11601 if (r != null) { 11602 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 11603 } 11604 11605 r = null; 11606 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 11607 // Only system apps can hold shared libraries. 11608 if (pkg.libraryNames != null) { 11609 for (i = 0; i < pkg.libraryNames.size(); i++) { 11610 String name = pkg.libraryNames.get(i); 11611 if (removeSharedLibraryLPw(name, 0)) { 11612 if (DEBUG_REMOVE && chatty) { 11613 if (r == null) { 11614 r = new StringBuilder(256); 11615 } else { 11616 r.append(' '); 11617 } 11618 r.append(name); 11619 } 11620 } 11621 } 11622 } 11623 } 11624 11625 r = null; 11626 11627 // Any package can hold static shared libraries. 11628 if (pkg.staticSharedLibName != null) { 11629 if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) { 11630 if (DEBUG_REMOVE && chatty) { 11631 if (r == null) { 11632 r = new StringBuilder(256); 11633 } else { 11634 r.append(' '); 11635 } 11636 r.append(pkg.staticSharedLibName); 11637 } 11638 } 11639 } 11640 11641 if (r != null) { 11642 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 11643 } 11644 } 11645 11646 11647 final class ActivityIntentResolver 11648 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 11649 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 11650 boolean defaultOnly, int userId) { 11651 if (!sUserManager.exists(userId)) return null; 11652 mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0); 11653 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 11654 } 11655 11656 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 11657 int userId) { 11658 if (!sUserManager.exists(userId)) return null; 11659 mFlags = flags; 11660 return super.queryIntent(intent, resolvedType, 11661 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 11662 userId); 11663 } 11664 11665 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 11666 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 11667 if (!sUserManager.exists(userId)) return null; 11668 if (packageActivities == null) { 11669 return null; 11670 } 11671 mFlags = flags; 11672 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 11673 final int N = packageActivities.size(); 11674 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 11675 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 11676 11677 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 11678 for (int i = 0; i < N; ++i) { 11679 intentFilters = packageActivities.get(i).intents; 11680 if (intentFilters != null && intentFilters.size() > 0) { 11681 PackageParser.ActivityIntentInfo[] array = 11682 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 11683 intentFilters.toArray(array); 11684 listCut.add(array); 11685 } 11686 } 11687 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 11688 } 11689 11690 /** 11691 * Finds a privileged activity that matches the specified activity names. 11692 */ 11693 private PackageParser.Activity findMatchingActivity( 11694 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 11695 for (PackageParser.Activity sysActivity : activityList) { 11696 if (sysActivity.info.name.equals(activityInfo.name)) { 11697 return sysActivity; 11698 } 11699 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 11700 return sysActivity; 11701 } 11702 if (sysActivity.info.targetActivity != null) { 11703 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 11704 return sysActivity; 11705 } 11706 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 11707 return sysActivity; 11708 } 11709 } 11710 } 11711 return null; 11712 } 11713 11714 public class IterGenerator<E> { 11715 public Iterator<E> generate(ActivityIntentInfo info) { 11716 return null; 11717 } 11718 } 11719 11720 public class ActionIterGenerator extends IterGenerator<String> { 11721 @Override 11722 public Iterator<String> generate(ActivityIntentInfo info) { 11723 return info.actionsIterator(); 11724 } 11725 } 11726 11727 public class CategoriesIterGenerator extends IterGenerator<String> { 11728 @Override 11729 public Iterator<String> generate(ActivityIntentInfo info) { 11730 return info.categoriesIterator(); 11731 } 11732 } 11733 11734 public class SchemesIterGenerator extends IterGenerator<String> { 11735 @Override 11736 public Iterator<String> generate(ActivityIntentInfo info) { 11737 return info.schemesIterator(); 11738 } 11739 } 11740 11741 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 11742 @Override 11743 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 11744 return info.authoritiesIterator(); 11745 } 11746 } 11747 11748 /** 11749 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 11750 * MODIFIED. Do not pass in a list that should not be changed. 11751 */ 11752 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 11753 IterGenerator<T> generator, Iterator<T> searchIterator) { 11754 // loop through the set of actions; every one must be found in the intent filter 11755 while (searchIterator.hasNext()) { 11756 // we must have at least one filter in the list to consider a match 11757 if (intentList.size() == 0) { 11758 break; 11759 } 11760 11761 final T searchAction = searchIterator.next(); 11762 11763 // loop through the set of intent filters 11764 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 11765 while (intentIter.hasNext()) { 11766 final ActivityIntentInfo intentInfo = intentIter.next(); 11767 boolean selectionFound = false; 11768 11769 // loop through the intent filter's selection criteria; at least one 11770 // of them must match the searched criteria 11771 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 11772 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 11773 final T intentSelection = intentSelectionIter.next(); 11774 if (intentSelection != null && intentSelection.equals(searchAction)) { 11775 selectionFound = true; 11776 break; 11777 } 11778 } 11779 11780 // the selection criteria wasn't found in this filter's set; this filter 11781 // is not a potential match 11782 if (!selectionFound) { 11783 intentIter.remove(); 11784 } 11785 } 11786 } 11787 } 11788 11789 private boolean isProtectedAction(ActivityIntentInfo filter) { 11790 final Iterator<String> actionsIter = filter.actionsIterator(); 11791 while (actionsIter != null && actionsIter.hasNext()) { 11792 final String filterAction = actionsIter.next(); 11793 if (PROTECTED_ACTIONS.contains(filterAction)) { 11794 return true; 11795 } 11796 } 11797 return false; 11798 } 11799 11800 /** 11801 * Adjusts the priority of the given intent filter according to policy. 11802 * <p> 11803 * <ul> 11804 * <li>The priority for non privileged applications is capped to '0'</li> 11805 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 11806 * <li>The priority for unbundled updates to privileged applications is capped to the 11807 * priority defined on the system partition</li> 11808 * </ul> 11809 * <p> 11810 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 11811 * allowed to obtain any priority on any action. 11812 */ 11813 private void adjustPriority( 11814 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 11815 // nothing to do; priority is fine as-is 11816 if (intent.getPriority() <= 0) { 11817 return; 11818 } 11819 11820 final ActivityInfo activityInfo = intent.activity.info; 11821 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 11822 11823 final boolean privilegedApp = 11824 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 11825 if (!privilegedApp) { 11826 // non-privileged applications can never define a priority >0 11827 if (DEBUG_FILTERS) { 11828 Slog.i(TAG, "Non-privileged app; cap priority to 0;" 11829 + " package: " + applicationInfo.packageName 11830 + " activity: " + intent.activity.className 11831 + " origPrio: " + intent.getPriority()); 11832 } 11833 intent.setPriority(0); 11834 return; 11835 } 11836 11837 if (systemActivities == null) { 11838 // the system package is not disabled; we're parsing the system partition 11839 if (isProtectedAction(intent)) { 11840 if (mDeferProtectedFilters) { 11841 // We can't deal with these just yet. No component should ever obtain a 11842 // >0 priority for a protected actions, with ONE exception -- the setup 11843 // wizard. The setup wizard, however, cannot be known until we're able to 11844 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 11845 // until all intent filters have been processed. Chicken, meet egg. 11846 // Let the filter temporarily have a high priority and rectify the 11847 // priorities after all system packages have been scanned. 11848 mProtectedFilters.add(intent); 11849 if (DEBUG_FILTERS) { 11850 Slog.i(TAG, "Protected action; save for later;" 11851 + " package: " + applicationInfo.packageName 11852 + " activity: " + intent.activity.className 11853 + " origPrio: " + intent.getPriority()); 11854 } 11855 return; 11856 } else { 11857 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 11858 Slog.i(TAG, "No setup wizard;" 11859 + " All protected intents capped to priority 0"); 11860 } 11861 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 11862 if (DEBUG_FILTERS) { 11863 Slog.i(TAG, "Found setup wizard;" 11864 + " allow priority " + intent.getPriority() + ";" 11865 + " package: " + intent.activity.info.packageName 11866 + " activity: " + intent.activity.className 11867 + " priority: " + intent.getPriority()); 11868 } 11869 // setup wizard gets whatever it wants 11870 return; 11871 } 11872 if (DEBUG_FILTERS) { 11873 Slog.i(TAG, "Protected action; cap priority to 0;" 11874 + " package: " + intent.activity.info.packageName 11875 + " activity: " + intent.activity.className 11876 + " origPrio: " + intent.getPriority()); 11877 } 11878 intent.setPriority(0); 11879 return; 11880 } 11881 } 11882 // privileged apps on the system image get whatever priority they request 11883 return; 11884 } 11885 11886 // privileged app unbundled update ... try to find the same activity 11887 final PackageParser.Activity foundActivity = 11888 findMatchingActivity(systemActivities, activityInfo); 11889 if (foundActivity == null) { 11890 // this is a new activity; it cannot obtain >0 priority 11891 if (DEBUG_FILTERS) { 11892 Slog.i(TAG, "New activity; cap priority to 0;" 11893 + " package: " + applicationInfo.packageName 11894 + " activity: " + intent.activity.className 11895 + " origPrio: " + intent.getPriority()); 11896 } 11897 intent.setPriority(0); 11898 return; 11899 } 11900 11901 // found activity, now check for filter equivalence 11902 11903 // a shallow copy is enough; we modify the list, not its contents 11904 final List<ActivityIntentInfo> intentListCopy = 11905 new ArrayList<>(foundActivity.intents); 11906 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 11907 11908 // find matching action subsets 11909 final Iterator<String> actionsIterator = intent.actionsIterator(); 11910 if (actionsIterator != null) { 11911 getIntentListSubset( 11912 intentListCopy, new ActionIterGenerator(), actionsIterator); 11913 if (intentListCopy.size() == 0) { 11914 // no more intents to match; we're not equivalent 11915 if (DEBUG_FILTERS) { 11916 Slog.i(TAG, "Mismatched action; cap priority to 0;" 11917 + " package: " + applicationInfo.packageName 11918 + " activity: " + intent.activity.className 11919 + " origPrio: " + intent.getPriority()); 11920 } 11921 intent.setPriority(0); 11922 return; 11923 } 11924 } 11925 11926 // find matching category subsets 11927 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 11928 if (categoriesIterator != null) { 11929 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 11930 categoriesIterator); 11931 if (intentListCopy.size() == 0) { 11932 // no more intents to match; we're not equivalent 11933 if (DEBUG_FILTERS) { 11934 Slog.i(TAG, "Mismatched category; cap priority to 0;" 11935 + " package: " + applicationInfo.packageName 11936 + " activity: " + intent.activity.className 11937 + " origPrio: " + intent.getPriority()); 11938 } 11939 intent.setPriority(0); 11940 return; 11941 } 11942 } 11943 11944 // find matching schemes subsets 11945 final Iterator<String> schemesIterator = intent.schemesIterator(); 11946 if (schemesIterator != null) { 11947 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 11948 schemesIterator); 11949 if (intentListCopy.size() == 0) { 11950 // no more intents to match; we're not equivalent 11951 if (DEBUG_FILTERS) { 11952 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 11953 + " package: " + applicationInfo.packageName 11954 + " activity: " + intent.activity.className 11955 + " origPrio: " + intent.getPriority()); 11956 } 11957 intent.setPriority(0); 11958 return; 11959 } 11960 } 11961 11962 // find matching authorities subsets 11963 final Iterator<IntentFilter.AuthorityEntry> 11964 authoritiesIterator = intent.authoritiesIterator(); 11965 if (authoritiesIterator != null) { 11966 getIntentListSubset(intentListCopy, 11967 new AuthoritiesIterGenerator(), 11968 authoritiesIterator); 11969 if (intentListCopy.size() == 0) { 11970 // no more intents to match; we're not equivalent 11971 if (DEBUG_FILTERS) { 11972 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 11973 + " package: " + applicationInfo.packageName 11974 + " activity: " + intent.activity.className 11975 + " origPrio: " + intent.getPriority()); 11976 } 11977 intent.setPriority(0); 11978 return; 11979 } 11980 } 11981 11982 // we found matching filter(s); app gets the max priority of all intents 11983 int cappedPriority = 0; 11984 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 11985 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 11986 } 11987 if (intent.getPriority() > cappedPriority) { 11988 if (DEBUG_FILTERS) { 11989 Slog.i(TAG, "Found matching filter(s);" 11990 + " cap priority to " + cappedPriority + ";" 11991 + " package: " + applicationInfo.packageName 11992 + " activity: " + intent.activity.className 11993 + " origPrio: " + intent.getPriority()); 11994 } 11995 intent.setPriority(cappedPriority); 11996 return; 11997 } 11998 // all this for nothing; the requested priority was <= what was on the system 11999 } 12000 12001 public final void addActivity(PackageParser.Activity a, String type) { 12002 mActivities.put(a.getComponentName(), a); 12003 if (DEBUG_SHOW_INFO) 12004 Log.v( 12005 TAG, " " + type + " " + 12006 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 12007 if (DEBUG_SHOW_INFO) 12008 Log.v(TAG, " Class=" + a.info.name); 12009 final int NI = a.intents.size(); 12010 for (int j=0; j<NI; j++) { 12011 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 12012 if ("activity".equals(type)) { 12013 final PackageSetting ps = 12014 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 12015 final List<PackageParser.Activity> systemActivities = 12016 ps != null && ps.pkg != null ? ps.pkg.activities : null; 12017 adjustPriority(systemActivities, intent); 12018 } 12019 if (DEBUG_SHOW_INFO) { 12020 Log.v(TAG, " IntentFilter:"); 12021 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12022 } 12023 if (!intent.debugCheck()) { 12024 Log.w(TAG, "==> For Activity " + a.info.name); 12025 } 12026 addFilter(intent); 12027 } 12028 } 12029 12030 public final void removeActivity(PackageParser.Activity a, String type) { 12031 mActivities.remove(a.getComponentName()); 12032 if (DEBUG_SHOW_INFO) { 12033 Log.v(TAG, " " + type + " " 12034 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 12035 : a.info.name) + ":"); 12036 Log.v(TAG, " Class=" + a.info.name); 12037 } 12038 final int NI = a.intents.size(); 12039 for (int j=0; j<NI; j++) { 12040 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 12041 if (DEBUG_SHOW_INFO) { 12042 Log.v(TAG, " IntentFilter:"); 12043 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12044 } 12045 removeFilter(intent); 12046 } 12047 } 12048 12049 @Override 12050 protected boolean allowFilterResult( 12051 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 12052 ActivityInfo filterAi = filter.activity.info; 12053 for (int i=dest.size()-1; i>=0; i--) { 12054 ActivityInfo destAi = dest.get(i).activityInfo; 12055 if (destAi.name == filterAi.name 12056 && destAi.packageName == filterAi.packageName) { 12057 return false; 12058 } 12059 } 12060 return true; 12061 } 12062 12063 @Override 12064 protected ActivityIntentInfo[] newArray(int size) { 12065 return new ActivityIntentInfo[size]; 12066 } 12067 12068 @Override 12069 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 12070 if (!sUserManager.exists(userId)) return true; 12071 PackageParser.Package p = filter.activity.owner; 12072 if (p != null) { 12073 PackageSetting ps = (PackageSetting)p.mExtras; 12074 if (ps != null) { 12075 // System apps are never considered stopped for purposes of 12076 // filtering, because there may be no way for the user to 12077 // actually re-launch them. 12078 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 12079 && ps.getStopped(userId); 12080 } 12081 } 12082 return false; 12083 } 12084 12085 @Override 12086 protected boolean isPackageForFilter(String packageName, 12087 PackageParser.ActivityIntentInfo info) { 12088 return packageName.equals(info.activity.owner.packageName); 12089 } 12090 12091 @Override 12092 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 12093 int match, int userId) { 12094 if (!sUserManager.exists(userId)) return null; 12095 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 12096 return null; 12097 } 12098 final PackageParser.Activity activity = info.activity; 12099 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 12100 if (ps == null) { 12101 return null; 12102 } 12103 final PackageUserState userState = ps.readUserState(userId); 12104 ActivityInfo ai = 12105 PackageParser.generateActivityInfo(activity, mFlags, userState, userId); 12106 if (ai == null) { 12107 return null; 12108 } 12109 final boolean matchExplicitlyVisibleOnly = 12110 (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0; 12111 final boolean matchVisibleToInstantApp = 12112 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 12113 final boolean componentVisible = 12114 matchVisibleToInstantApp 12115 && info.isVisibleToInstantApp() 12116 && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp()); 12117 final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 12118 // throw out filters that aren't visible to ephemeral apps 12119 if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) { 12120 return null; 12121 } 12122 // throw out instant app filters if we're not explicitly requesting them 12123 if (!matchInstantApp && userState.instantApp) { 12124 return null; 12125 } 12126 // throw out instant app filters if updates are available; will trigger 12127 // instant app resolution 12128 if (userState.instantApp && ps.isUpdateAvailable()) { 12129 return null; 12130 } 12131 final ResolveInfo res = new ResolveInfo(); 12132 res.activityInfo = ai; 12133 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 12134 res.filter = info; 12135 } 12136 if (info != null) { 12137 res.handleAllWebDataURI = info.handleAllWebDataURI(); 12138 } 12139 res.priority = info.getPriority(); 12140 res.preferredOrder = activity.owner.mPreferredOrder; 12141 //System.out.println("Result: " + res.activityInfo.className + 12142 // " = " + res.priority); 12143 res.match = match; 12144 res.isDefault = info.hasDefault; 12145 res.labelRes = info.labelRes; 12146 res.nonLocalizedLabel = info.nonLocalizedLabel; 12147 if (userNeedsBadging(userId)) { 12148 res.noResourceId = true; 12149 } else { 12150 res.icon = info.icon; 12151 } 12152 res.iconResourceId = info.icon; 12153 res.system = res.activityInfo.applicationInfo.isSystemApp(); 12154 res.isInstantAppAvailable = userState.instantApp; 12155 return res; 12156 } 12157 12158 @Override 12159 protected void sortResults(List<ResolveInfo> results) { 12160 Collections.sort(results, mResolvePrioritySorter); 12161 } 12162 12163 @Override 12164 protected void dumpFilter(PrintWriter out, String prefix, 12165 PackageParser.ActivityIntentInfo filter) { 12166 out.print(prefix); out.print( 12167 Integer.toHexString(System.identityHashCode(filter.activity))); 12168 out.print(' '); 12169 filter.activity.printComponentShortName(out); 12170 out.print(" filter "); 12171 out.println(Integer.toHexString(System.identityHashCode(filter))); 12172 } 12173 12174 @Override 12175 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 12176 return filter.activity; 12177 } 12178 12179 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12180 PackageParser.Activity activity = (PackageParser.Activity)label; 12181 out.print(prefix); out.print( 12182 Integer.toHexString(System.identityHashCode(activity))); 12183 out.print(' '); 12184 activity.printComponentShortName(out); 12185 if (count > 1) { 12186 out.print(" ("); out.print(count); out.print(" filters)"); 12187 } 12188 out.println(); 12189 } 12190 12191 // Keys are String (activity class name), values are Activity. 12192 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 12193 = new ArrayMap<ComponentName, PackageParser.Activity>(); 12194 private int mFlags; 12195 } 12196 12197 private final class ServiceIntentResolver 12198 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 12199 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12200 boolean defaultOnly, int userId) { 12201 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 12202 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 12203 } 12204 12205 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12206 int userId) { 12207 if (!sUserManager.exists(userId)) return null; 12208 mFlags = flags; 12209 return super.queryIntent(intent, resolvedType, 12210 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12211 userId); 12212 } 12213 12214 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12215 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 12216 if (!sUserManager.exists(userId)) return null; 12217 if (packageServices == null) { 12218 return null; 12219 } 12220 mFlags = flags; 12221 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 12222 final int N = packageServices.size(); 12223 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 12224 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 12225 12226 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 12227 for (int i = 0; i < N; ++i) { 12228 intentFilters = packageServices.get(i).intents; 12229 if (intentFilters != null && intentFilters.size() > 0) { 12230 PackageParser.ServiceIntentInfo[] array = 12231 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 12232 intentFilters.toArray(array); 12233 listCut.add(array); 12234 } 12235 } 12236 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 12237 } 12238 12239 public final void addService(PackageParser.Service s) { 12240 mServices.put(s.getComponentName(), s); 12241 if (DEBUG_SHOW_INFO) { 12242 Log.v(TAG, " " 12243 + (s.info.nonLocalizedLabel != null 12244 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 12245 Log.v(TAG, " Class=" + s.info.name); 12246 } 12247 final int NI = s.intents.size(); 12248 int j; 12249 for (j=0; j<NI; j++) { 12250 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 12251 if (DEBUG_SHOW_INFO) { 12252 Log.v(TAG, " IntentFilter:"); 12253 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12254 } 12255 if (!intent.debugCheck()) { 12256 Log.w(TAG, "==> For Service " + s.info.name); 12257 } 12258 addFilter(intent); 12259 } 12260 } 12261 12262 public final void removeService(PackageParser.Service s) { 12263 mServices.remove(s.getComponentName()); 12264 if (DEBUG_SHOW_INFO) { 12265 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 12266 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 12267 Log.v(TAG, " Class=" + s.info.name); 12268 } 12269 final int NI = s.intents.size(); 12270 int j; 12271 for (j=0; j<NI; j++) { 12272 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 12273 if (DEBUG_SHOW_INFO) { 12274 Log.v(TAG, " IntentFilter:"); 12275 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12276 } 12277 removeFilter(intent); 12278 } 12279 } 12280 12281 @Override 12282 protected boolean allowFilterResult( 12283 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 12284 ServiceInfo filterSi = filter.service.info; 12285 for (int i=dest.size()-1; i>=0; i--) { 12286 ServiceInfo destAi = dest.get(i).serviceInfo; 12287 if (destAi.name == filterSi.name 12288 && destAi.packageName == filterSi.packageName) { 12289 return false; 12290 } 12291 } 12292 return true; 12293 } 12294 12295 @Override 12296 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 12297 return new PackageParser.ServiceIntentInfo[size]; 12298 } 12299 12300 @Override 12301 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 12302 if (!sUserManager.exists(userId)) return true; 12303 PackageParser.Package p = filter.service.owner; 12304 if (p != null) { 12305 PackageSetting ps = (PackageSetting)p.mExtras; 12306 if (ps != null) { 12307 // System apps are never considered stopped for purposes of 12308 // filtering, because there may be no way for the user to 12309 // actually re-launch them. 12310 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 12311 && ps.getStopped(userId); 12312 } 12313 } 12314 return false; 12315 } 12316 12317 @Override 12318 protected boolean isPackageForFilter(String packageName, 12319 PackageParser.ServiceIntentInfo info) { 12320 return packageName.equals(info.service.owner.packageName); 12321 } 12322 12323 @Override 12324 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 12325 int match, int userId) { 12326 if (!sUserManager.exists(userId)) return null; 12327 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 12328 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 12329 return null; 12330 } 12331 final PackageParser.Service service = info.service; 12332 PackageSetting ps = (PackageSetting) service.owner.mExtras; 12333 if (ps == null) { 12334 return null; 12335 } 12336 final PackageUserState userState = ps.readUserState(userId); 12337 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 12338 userState, userId); 12339 if (si == null) { 12340 return null; 12341 } 12342 final boolean matchVisibleToInstantApp = 12343 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 12344 final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 12345 // throw out filters that aren't visible to ephemeral apps 12346 if (matchVisibleToInstantApp 12347 && !(info.isVisibleToInstantApp() || userState.instantApp)) { 12348 return null; 12349 } 12350 // throw out ephemeral filters if we're not explicitly requesting them 12351 if (!isInstantApp && userState.instantApp) { 12352 return null; 12353 } 12354 // throw out instant app filters if updates are available; will trigger 12355 // instant app resolution 12356 if (userState.instantApp && ps.isUpdateAvailable()) { 12357 return null; 12358 } 12359 final ResolveInfo res = new ResolveInfo(); 12360 res.serviceInfo = si; 12361 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 12362 res.filter = filter; 12363 } 12364 res.priority = info.getPriority(); 12365 res.preferredOrder = service.owner.mPreferredOrder; 12366 res.match = match; 12367 res.isDefault = info.hasDefault; 12368 res.labelRes = info.labelRes; 12369 res.nonLocalizedLabel = info.nonLocalizedLabel; 12370 res.icon = info.icon; 12371 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 12372 return res; 12373 } 12374 12375 @Override 12376 protected void sortResults(List<ResolveInfo> results) { 12377 Collections.sort(results, mResolvePrioritySorter); 12378 } 12379 12380 @Override 12381 protected void dumpFilter(PrintWriter out, String prefix, 12382 PackageParser.ServiceIntentInfo filter) { 12383 out.print(prefix); out.print( 12384 Integer.toHexString(System.identityHashCode(filter.service))); 12385 out.print(' '); 12386 filter.service.printComponentShortName(out); 12387 out.print(" filter "); 12388 out.println(Integer.toHexString(System.identityHashCode(filter))); 12389 } 12390 12391 @Override 12392 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 12393 return filter.service; 12394 } 12395 12396 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12397 PackageParser.Service service = (PackageParser.Service)label; 12398 out.print(prefix); out.print( 12399 Integer.toHexString(System.identityHashCode(service))); 12400 out.print(' '); 12401 service.printComponentShortName(out); 12402 if (count > 1) { 12403 out.print(" ("); out.print(count); out.print(" filters)"); 12404 } 12405 out.println(); 12406 } 12407 12408// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 12409// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 12410// final List<ResolveInfo> retList = Lists.newArrayList(); 12411// while (i.hasNext()) { 12412// final ResolveInfo resolveInfo = (ResolveInfo) i; 12413// if (isEnabledLP(resolveInfo.serviceInfo)) { 12414// retList.add(resolveInfo); 12415// } 12416// } 12417// return retList; 12418// } 12419 12420 // Keys are String (activity class name), values are Activity. 12421 private final ArrayMap<ComponentName, PackageParser.Service> mServices 12422 = new ArrayMap<ComponentName, PackageParser.Service>(); 12423 private int mFlags; 12424 } 12425 12426 private final class ProviderIntentResolver 12427 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 12428 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12429 boolean defaultOnly, int userId) { 12430 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 12431 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 12432 } 12433 12434 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12435 int userId) { 12436 if (!sUserManager.exists(userId)) 12437 return null; 12438 mFlags = flags; 12439 return super.queryIntent(intent, resolvedType, 12440 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12441 userId); 12442 } 12443 12444 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12445 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 12446 if (!sUserManager.exists(userId)) 12447 return null; 12448 if (packageProviders == null) { 12449 return null; 12450 } 12451 mFlags = flags; 12452 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 12453 final int N = packageProviders.size(); 12454 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 12455 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 12456 12457 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 12458 for (int i = 0; i < N; ++i) { 12459 intentFilters = packageProviders.get(i).intents; 12460 if (intentFilters != null && intentFilters.size() > 0) { 12461 PackageParser.ProviderIntentInfo[] array = 12462 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 12463 intentFilters.toArray(array); 12464 listCut.add(array); 12465 } 12466 } 12467 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 12468 } 12469 12470 public final void addProvider(PackageParser.Provider p) { 12471 if (mProviders.containsKey(p.getComponentName())) { 12472 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 12473 return; 12474 } 12475 12476 mProviders.put(p.getComponentName(), p); 12477 if (DEBUG_SHOW_INFO) { 12478 Log.v(TAG, " " 12479 + (p.info.nonLocalizedLabel != null 12480 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 12481 Log.v(TAG, " Class=" + p.info.name); 12482 } 12483 final int NI = p.intents.size(); 12484 int j; 12485 for (j = 0; j < NI; j++) { 12486 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 12487 if (DEBUG_SHOW_INFO) { 12488 Log.v(TAG, " IntentFilter:"); 12489 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12490 } 12491 if (!intent.debugCheck()) { 12492 Log.w(TAG, "==> For Provider " + p.info.name); 12493 } 12494 addFilter(intent); 12495 } 12496 } 12497 12498 public final void removeProvider(PackageParser.Provider p) { 12499 mProviders.remove(p.getComponentName()); 12500 if (DEBUG_SHOW_INFO) { 12501 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 12502 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 12503 Log.v(TAG, " Class=" + p.info.name); 12504 } 12505 final int NI = p.intents.size(); 12506 int j; 12507 for (j = 0; j < NI; j++) { 12508 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 12509 if (DEBUG_SHOW_INFO) { 12510 Log.v(TAG, " IntentFilter:"); 12511 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12512 } 12513 removeFilter(intent); 12514 } 12515 } 12516 12517 @Override 12518 protected boolean allowFilterResult( 12519 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 12520 ProviderInfo filterPi = filter.provider.info; 12521 for (int i = dest.size() - 1; i >= 0; i--) { 12522 ProviderInfo destPi = dest.get(i).providerInfo; 12523 if (destPi.name == filterPi.name 12524 && destPi.packageName == filterPi.packageName) { 12525 return false; 12526 } 12527 } 12528 return true; 12529 } 12530 12531 @Override 12532 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 12533 return new PackageParser.ProviderIntentInfo[size]; 12534 } 12535 12536 @Override 12537 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 12538 if (!sUserManager.exists(userId)) 12539 return true; 12540 PackageParser.Package p = filter.provider.owner; 12541 if (p != null) { 12542 PackageSetting ps = (PackageSetting) p.mExtras; 12543 if (ps != null) { 12544 // System apps are never considered stopped for purposes of 12545 // filtering, because there may be no way for the user to 12546 // actually re-launch them. 12547 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 12548 && ps.getStopped(userId); 12549 } 12550 } 12551 return false; 12552 } 12553 12554 @Override 12555 protected boolean isPackageForFilter(String packageName, 12556 PackageParser.ProviderIntentInfo info) { 12557 return packageName.equals(info.provider.owner.packageName); 12558 } 12559 12560 @Override 12561 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 12562 int match, int userId) { 12563 if (!sUserManager.exists(userId)) 12564 return null; 12565 final PackageParser.ProviderIntentInfo info = filter; 12566 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 12567 return null; 12568 } 12569 final PackageParser.Provider provider = info.provider; 12570 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 12571 if (ps == null) { 12572 return null; 12573 } 12574 final PackageUserState userState = ps.readUserState(userId); 12575 final boolean matchVisibleToInstantApp = 12576 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 12577 final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 12578 // throw out filters that aren't visible to instant applications 12579 if (matchVisibleToInstantApp 12580 && !(info.isVisibleToInstantApp() || userState.instantApp)) { 12581 return null; 12582 } 12583 // throw out instant application filters if we're not explicitly requesting them 12584 if (!isInstantApp && userState.instantApp) { 12585 return null; 12586 } 12587 // throw out instant application filters if updates are available; will trigger 12588 // instant application resolution 12589 if (userState.instantApp && ps.isUpdateAvailable()) { 12590 return null; 12591 } 12592 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 12593 userState, userId); 12594 if (pi == null) { 12595 return null; 12596 } 12597 final ResolveInfo res = new ResolveInfo(); 12598 res.providerInfo = pi; 12599 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 12600 res.filter = filter; 12601 } 12602 res.priority = info.getPriority(); 12603 res.preferredOrder = provider.owner.mPreferredOrder; 12604 res.match = match; 12605 res.isDefault = info.hasDefault; 12606 res.labelRes = info.labelRes; 12607 res.nonLocalizedLabel = info.nonLocalizedLabel; 12608 res.icon = info.icon; 12609 res.system = res.providerInfo.applicationInfo.isSystemApp(); 12610 return res; 12611 } 12612 12613 @Override 12614 protected void sortResults(List<ResolveInfo> results) { 12615 Collections.sort(results, mResolvePrioritySorter); 12616 } 12617 12618 @Override 12619 protected void dumpFilter(PrintWriter out, String prefix, 12620 PackageParser.ProviderIntentInfo filter) { 12621 out.print(prefix); 12622 out.print( 12623 Integer.toHexString(System.identityHashCode(filter.provider))); 12624 out.print(' '); 12625 filter.provider.printComponentShortName(out); 12626 out.print(" filter "); 12627 out.println(Integer.toHexString(System.identityHashCode(filter))); 12628 } 12629 12630 @Override 12631 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 12632 return filter.provider; 12633 } 12634 12635 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12636 PackageParser.Provider provider = (PackageParser.Provider)label; 12637 out.print(prefix); out.print( 12638 Integer.toHexString(System.identityHashCode(provider))); 12639 out.print(' '); 12640 provider.printComponentShortName(out); 12641 if (count > 1) { 12642 out.print(" ("); out.print(count); out.print(" filters)"); 12643 } 12644 out.println(); 12645 } 12646 12647 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 12648 = new ArrayMap<ComponentName, PackageParser.Provider>(); 12649 private int mFlags; 12650 } 12651 12652 static final class EphemeralIntentResolver 12653 extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> { 12654 /** 12655 * The result that has the highest defined order. Ordering applies on a 12656 * per-package basis. Mapping is from package name to Pair of order and 12657 * EphemeralResolveInfo. 12658 * <p> 12659 * NOTE: This is implemented as a field variable for convenience and efficiency. 12660 * By having a field variable, we're able to track filter ordering as soon as 12661 * a non-zero order is defined. Otherwise, multiple loops across the result set 12662 * would be needed to apply ordering. If the intent resolver becomes re-entrant, 12663 * this needs to be contained entirely within {@link #filterResults}. 12664 */ 12665 final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>(); 12666 12667 @Override 12668 protected AuxiliaryResolveInfo[] newArray(int size) { 12669 return new AuxiliaryResolveInfo[size]; 12670 } 12671 12672 @Override 12673 protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) { 12674 return true; 12675 } 12676 12677 @Override 12678 protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match, 12679 int userId) { 12680 if (!sUserManager.exists(userId)) { 12681 return null; 12682 } 12683 final String packageName = responseObj.resolveInfo.getPackageName(); 12684 final Integer order = responseObj.getOrder(); 12685 final Pair<Integer, InstantAppResolveInfo> lastOrderResult = 12686 mOrderResult.get(packageName); 12687 // ordering is enabled and this item's order isn't high enough 12688 if (lastOrderResult != null && lastOrderResult.first >= order) { 12689 return null; 12690 } 12691 final InstantAppResolveInfo res = responseObj.resolveInfo; 12692 if (order > 0) { 12693 // non-zero order, enable ordering 12694 mOrderResult.put(packageName, new Pair<>(order, res)); 12695 } 12696 return responseObj; 12697 } 12698 12699 @Override 12700 protected void filterResults(List<AuxiliaryResolveInfo> results) { 12701 // only do work if ordering is enabled [most of the time it won't be] 12702 if (mOrderResult.size() == 0) { 12703 return; 12704 } 12705 int resultSize = results.size(); 12706 for (int i = 0; i < resultSize; i++) { 12707 final InstantAppResolveInfo info = results.get(i).resolveInfo; 12708 final String packageName = info.getPackageName(); 12709 final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName); 12710 if (savedInfo == null) { 12711 // package doesn't having ordering 12712 continue; 12713 } 12714 if (savedInfo.second == info) { 12715 // circled back to the highest ordered item; remove from order list 12716 mOrderResult.remove(packageName); 12717 if (mOrderResult.size() == 0) { 12718 // no more ordered items 12719 break; 12720 } 12721 continue; 12722 } 12723 // item has a worse order, remove it from the result list 12724 results.remove(i); 12725 resultSize--; 12726 i--; 12727 } 12728 } 12729 } 12730 12731 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 12732 new Comparator<ResolveInfo>() { 12733 public int compare(ResolveInfo r1, ResolveInfo r2) { 12734 int v1 = r1.priority; 12735 int v2 = r2.priority; 12736 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 12737 if (v1 != v2) { 12738 return (v1 > v2) ? -1 : 1; 12739 } 12740 v1 = r1.preferredOrder; 12741 v2 = r2.preferredOrder; 12742 if (v1 != v2) { 12743 return (v1 > v2) ? -1 : 1; 12744 } 12745 if (r1.isDefault != r2.isDefault) { 12746 return r1.isDefault ? -1 : 1; 12747 } 12748 v1 = r1.match; 12749 v2 = r2.match; 12750 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 12751 if (v1 != v2) { 12752 return (v1 > v2) ? -1 : 1; 12753 } 12754 if (r1.system != r2.system) { 12755 return r1.system ? -1 : 1; 12756 } 12757 if (r1.activityInfo != null) { 12758 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 12759 } 12760 if (r1.serviceInfo != null) { 12761 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 12762 } 12763 if (r1.providerInfo != null) { 12764 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 12765 } 12766 return 0; 12767 } 12768 }; 12769 12770 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 12771 new Comparator<ProviderInfo>() { 12772 public int compare(ProviderInfo p1, ProviderInfo p2) { 12773 final int v1 = p1.initOrder; 12774 final int v2 = p2.initOrder; 12775 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 12776 } 12777 }; 12778 12779 public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 12780 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 12781 final int[] userIds) { 12782 mHandler.post(new Runnable() { 12783 @Override 12784 public void run() { 12785 try { 12786 final IActivityManager am = ActivityManager.getService(); 12787 if (am == null) return; 12788 final int[] resolvedUserIds; 12789 if (userIds == null) { 12790 resolvedUserIds = am.getRunningUserIds(); 12791 } else { 12792 resolvedUserIds = userIds; 12793 } 12794 for (int id : resolvedUserIds) { 12795 final Intent intent = new Intent(action, 12796 pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null); 12797 if (extras != null) { 12798 intent.putExtras(extras); 12799 } 12800 if (targetPkg != null) { 12801 intent.setPackage(targetPkg); 12802 } 12803 // Modify the UID when posting to other users 12804 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 12805 if (uid > 0 && UserHandle.getUserId(uid) != id) { 12806 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 12807 intent.putExtra(Intent.EXTRA_UID, uid); 12808 } 12809 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 12810 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 12811 if (DEBUG_BROADCASTS) { 12812 RuntimeException here = new RuntimeException("here"); 12813 here.fillInStackTrace(); 12814 Slog.d(TAG, "Sending to user " + id + ": " 12815 + intent.toShortString(false, true, false, false) 12816 + " " + intent.getExtras(), here); 12817 } 12818 am.broadcastIntent(null, intent, null, finishedReceiver, 12819 0, null, null, null, android.app.AppOpsManager.OP_NONE, 12820 null, finishedReceiver != null, false, id); 12821 } 12822 } catch (RemoteException ex) { 12823 } 12824 } 12825 }); 12826 } 12827 12828 /** 12829 * Check if the external storage media is available. This is true if there 12830 * is a mounted external storage medium or if the external storage is 12831 * emulated. 12832 */ 12833 private boolean isExternalMediaAvailable() { 12834 return mMediaMounted || Environment.isExternalStorageEmulated(); 12835 } 12836 12837 @Override 12838 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 12839 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 12840 return null; 12841 } 12842 // writer 12843 synchronized (mPackages) { 12844 if (!isExternalMediaAvailable()) { 12845 // If the external storage is no longer mounted at this point, 12846 // the caller may not have been able to delete all of this 12847 // packages files and can not delete any more. Bail. 12848 return null; 12849 } 12850 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 12851 if (lastPackage != null) { 12852 pkgs.remove(lastPackage); 12853 } 12854 if (pkgs.size() > 0) { 12855 return pkgs.get(0); 12856 } 12857 } 12858 return null; 12859 } 12860 12861 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 12862 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 12863 userId, andCode ? 1 : 0, packageName); 12864 if (mSystemReady) { 12865 msg.sendToTarget(); 12866 } else { 12867 if (mPostSystemReadyMessages == null) { 12868 mPostSystemReadyMessages = new ArrayList<>(); 12869 } 12870 mPostSystemReadyMessages.add(msg); 12871 } 12872 } 12873 12874 void startCleaningPackages() { 12875 // reader 12876 if (!isExternalMediaAvailable()) { 12877 return; 12878 } 12879 synchronized (mPackages) { 12880 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 12881 return; 12882 } 12883 } 12884 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 12885 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 12886 IActivityManager am = ActivityManager.getService(); 12887 if (am != null) { 12888 int dcsUid = -1; 12889 synchronized (mPackages) { 12890 if (!mDefaultContainerWhitelisted) { 12891 mDefaultContainerWhitelisted = true; 12892 PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE); 12893 dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId); 12894 } 12895 } 12896 try { 12897 if (dcsUid > 0) { 12898 am.backgroundWhitelistUid(dcsUid); 12899 } 12900 am.startService(null, intent, null, false, mContext.getOpPackageName(), 12901 UserHandle.USER_SYSTEM); 12902 } catch (RemoteException e) { 12903 } 12904 } 12905 } 12906 12907 @Override 12908 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 12909 int installFlags, String installerPackageName, int userId) { 12910 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 12911 12912 final int callingUid = Binder.getCallingUid(); 12913 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 12914 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 12915 12916 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 12917 try { 12918 if (observer != null) { 12919 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 12920 } 12921 } catch (RemoteException re) { 12922 } 12923 return; 12924 } 12925 12926 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 12927 installFlags |= PackageManager.INSTALL_FROM_ADB; 12928 12929 } else { 12930 // Caller holds INSTALL_PACKAGES permission, so we're less strict 12931 // about installerPackageName. 12932 12933 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 12934 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 12935 } 12936 12937 UserHandle user; 12938 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 12939 user = UserHandle.ALL; 12940 } else { 12941 user = new UserHandle(userId); 12942 } 12943 12944 // Only system components can circumvent runtime permissions when installing. 12945 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 12946 && mContext.checkCallingOrSelfPermission(Manifest.permission 12947 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 12948 throw new SecurityException("You need the " 12949 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 12950 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 12951 } 12952 12953 if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0 12954 || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 12955 throw new IllegalArgumentException( 12956 "New installs into ASEC containers no longer supported"); 12957 } 12958 12959 final File originFile = new File(originPath); 12960 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 12961 12962 final Message msg = mHandler.obtainMessage(INIT_COPY); 12963 final VerificationInfo verificationInfo = new VerificationInfo( 12964 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 12965 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 12966 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 12967 null /*packageAbiOverride*/, null /*grantedPermissions*/, 12968 null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN); 12969 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 12970 msg.obj = params; 12971 12972 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 12973 System.identityHashCode(msg.obj)); 12974 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 12975 System.identityHashCode(msg.obj)); 12976 12977 mHandler.sendMessage(msg); 12978 } 12979 12980 12981 /** 12982 * Ensure that the install reason matches what we know about the package installer (e.g. whether 12983 * it is acting on behalf on an enterprise or the user). 12984 * 12985 * Note that the ordering of the conditionals in this method is important. The checks we perform 12986 * are as follows, in this order: 12987 * 12988 * 1) If the install is being performed by a system app, we can trust the app to have set the 12989 * install reason correctly. Thus, we pass through the install reason unchanged, no matter 12990 * what it is. 12991 * 2) If the install is being performed by a device or profile owner app, the install reason 12992 * should be enterprise policy. However, we cannot be sure that the device or profile owner 12993 * set the install reason correctly. If the app targets an older SDK version where install 12994 * reasons did not exist yet, or if the app author simply forgot, the install reason may be 12995 * unset or wrong. Thus, we force the install reason to be enterprise policy. 12996 * 3) In all other cases, the install is being performed by a regular app that is neither part 12997 * of the system nor a device or profile owner. We have no reason to believe that this app is 12998 * acting on behalf of the enterprise admin. Thus, we check whether the install reason was 12999 * set to enterprise policy and if so, change it to unknown instead. 13000 */ 13001 private int fixUpInstallReason(String installerPackageName, int installerUid, 13002 int installReason) { 13003 if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid) 13004 == PERMISSION_GRANTED) { 13005 // If the install is being performed by a system app, we trust that app to have set the 13006 // install reason correctly. 13007 return installReason; 13008 } 13009 13010 final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 13011 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 13012 if (dpm != null) { 13013 ComponentName owner = null; 13014 try { 13015 owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */); 13016 if (owner == null) { 13017 owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid)); 13018 } 13019 } catch (RemoteException e) { 13020 } 13021 if (owner != null && owner.getPackageName().equals(installerPackageName)) { 13022 // If the install is being performed by a device or profile owner, the install 13023 // reason should be enterprise policy. 13024 return PackageManager.INSTALL_REASON_POLICY; 13025 } 13026 } 13027 13028 if (installReason == PackageManager.INSTALL_REASON_POLICY) { 13029 // If the install is being performed by a regular app (i.e. neither system app nor 13030 // device or profile owner), we have no reason to believe that the app is acting on 13031 // behalf of an enterprise. If the app set the install reason to enterprise policy, 13032 // change it to unknown instead. 13033 return PackageManager.INSTALL_REASON_UNKNOWN; 13034 } 13035 13036 // If the install is being performed by a regular app and the install reason was set to any 13037 // value but enterprise policy, leave the install reason unchanged. 13038 return installReason; 13039 } 13040 13041 void installStage(String packageName, File stagedDir, 13042 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 13043 String installerPackageName, int installerUid, UserHandle user, 13044 Certificate[][] certificates) { 13045 if (DEBUG_EPHEMERAL) { 13046 if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) { 13047 Slog.d(TAG, "Ephemeral install of " + packageName); 13048 } 13049 } 13050 final VerificationInfo verificationInfo = new VerificationInfo( 13051 sessionParams.originatingUri, sessionParams.referrerUri, 13052 sessionParams.originatingUid, installerUid); 13053 13054 final OriginInfo origin = OriginInfo.fromStagedFile(stagedDir); 13055 13056 final Message msg = mHandler.obtainMessage(INIT_COPY); 13057 final int installReason = fixUpInstallReason(installerPackageName, installerUid, 13058 sessionParams.installReason); 13059 final InstallParams params = new InstallParams(origin, null, observer, 13060 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 13061 verificationInfo, user, sessionParams.abiOverride, 13062 sessionParams.grantedRuntimePermissions, certificates, installReason); 13063 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 13064 msg.obj = params; 13065 13066 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 13067 System.identityHashCode(msg.obj)); 13068 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 13069 System.identityHashCode(msg.obj)); 13070 13071 mHandler.sendMessage(msg); 13072 } 13073 13074 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 13075 int userId) { 13076 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 13077 sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/, 13078 false /*startReceiver*/, pkgSetting.appId, userId); 13079 13080 // Send a session commit broadcast 13081 final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo(); 13082 info.installReason = pkgSetting.getInstallReason(userId); 13083 info.appPackageName = packageName; 13084 sendSessionCommitBroadcast(info, userId); 13085 } 13086 13087 public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted, 13088 boolean includeStopped, int appId, int... userIds) { 13089 if (ArrayUtils.isEmpty(userIds)) { 13090 return; 13091 } 13092 Bundle extras = new Bundle(1); 13093 // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast 13094 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId)); 13095 13096 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 13097 packageName, extras, 0, null, null, userIds); 13098 if (sendBootCompleted) { 13099 mHandler.post(() -> { 13100 for (int userId : userIds) { 13101 sendBootCompletedBroadcastToSystemApp( 13102 packageName, includeStopped, userId); 13103 } 13104 } 13105 ); 13106 } 13107 } 13108 13109 /** 13110 * The just-installed/enabled app is bundled on the system, so presumed to be able to run 13111 * automatically without needing an explicit launch. 13112 * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones. 13113 */ 13114 private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped, 13115 int userId) { 13116 // If user is not running, the app didn't miss any broadcast 13117 if (!mUserManagerInternal.isUserRunning(userId)) { 13118 return; 13119 } 13120 final IActivityManager am = ActivityManager.getService(); 13121 try { 13122 // Deliver LOCKED_BOOT_COMPLETED first 13123 Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED) 13124 .setPackage(packageName); 13125 if (includeStopped) { 13126 lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); 13127 } 13128 final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED}; 13129 am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions, 13130 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 13131 13132 // Deliver BOOT_COMPLETED only if user is unlocked 13133 if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) { 13134 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName); 13135 if (includeStopped) { 13136 bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); 13137 } 13138 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions, 13139 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 13140 } 13141 } catch (RemoteException e) { 13142 throw e.rethrowFromSystemServer(); 13143 } 13144 } 13145 13146 @Override 13147 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 13148 int userId) { 13149 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13150 PackageSetting pkgSetting; 13151 final int callingUid = Binder.getCallingUid(); 13152 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 13153 true /* requireFullPermission */, true /* checkShell */, 13154 "setApplicationHiddenSetting for user " + userId); 13155 13156 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 13157 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 13158 return false; 13159 } 13160 13161 long callingId = Binder.clearCallingIdentity(); 13162 try { 13163 boolean sendAdded = false; 13164 boolean sendRemoved = false; 13165 // writer 13166 synchronized (mPackages) { 13167 pkgSetting = mSettings.mPackages.get(packageName); 13168 if (pkgSetting == null) { 13169 return false; 13170 } 13171 if (filterAppAccessLPr(pkgSetting, callingUid, userId)) { 13172 return false; 13173 } 13174 // Do not allow "android" is being disabled 13175 if ("android".equals(packageName)) { 13176 Slog.w(TAG, "Cannot hide package: android"); 13177 return false; 13178 } 13179 // Cannot hide static shared libs as they are considered 13180 // a part of the using app (emulating static linking). Also 13181 // static libs are installed always on internal storage. 13182 PackageParser.Package pkg = mPackages.get(packageName); 13183 if (pkg != null && pkg.staticSharedLibName != null) { 13184 Slog.w(TAG, "Cannot hide package: " + packageName 13185 + " providing static shared library: " 13186 + pkg.staticSharedLibName); 13187 return false; 13188 } 13189 // Only allow protected packages to hide themselves. 13190 if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId) 13191 && mProtectedPackages.isPackageStateProtected(userId, packageName)) { 13192 Slog.w(TAG, "Not hiding protected package: " + packageName); 13193 return false; 13194 } 13195 13196 if (pkgSetting.getHidden(userId) != hidden) { 13197 pkgSetting.setHidden(hidden, userId); 13198 mSettings.writePackageRestrictionsLPr(userId); 13199 if (hidden) { 13200 sendRemoved = true; 13201 } else { 13202 sendAdded = true; 13203 } 13204 } 13205 } 13206 if (sendAdded) { 13207 sendPackageAddedForUser(packageName, pkgSetting, userId); 13208 return true; 13209 } 13210 if (sendRemoved) { 13211 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 13212 "hiding pkg"); 13213 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 13214 return true; 13215 } 13216 } finally { 13217 Binder.restoreCallingIdentity(callingId); 13218 } 13219 return false; 13220 } 13221 13222 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 13223 int userId) { 13224 final PackageRemovedInfo info = new PackageRemovedInfo(this); 13225 info.removedPackage = packageName; 13226 info.installerPackageName = pkgSetting.installerPackageName; 13227 info.removedUsers = new int[] {userId}; 13228 info.broadcastUsers = new int[] {userId}; 13229 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 13230 info.sendPackageRemovedBroadcasts(true /*killApp*/); 13231 } 13232 13233 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 13234 if (pkgList.length > 0) { 13235 Bundle extras = new Bundle(1); 13236 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 13237 13238 sendPackageBroadcast( 13239 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 13240 : Intent.ACTION_PACKAGES_UNSUSPENDED, 13241 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 13242 new int[] {userId}); 13243 } 13244 } 13245 13246 /** 13247 * Returns true if application is not found or there was an error. Otherwise it returns 13248 * the hidden state of the package for the given user. 13249 */ 13250 @Override 13251 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 13252 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13253 final int callingUid = Binder.getCallingUid(); 13254 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 13255 true /* requireFullPermission */, false /* checkShell */, 13256 "getApplicationHidden for user " + userId); 13257 PackageSetting ps; 13258 long callingId = Binder.clearCallingIdentity(); 13259 try { 13260 // writer 13261 synchronized (mPackages) { 13262 ps = mSettings.mPackages.get(packageName); 13263 if (ps == null) { 13264 return true; 13265 } 13266 if (filterAppAccessLPr(ps, callingUid, userId)) { 13267 return true; 13268 } 13269 return ps.getHidden(userId); 13270 } 13271 } finally { 13272 Binder.restoreCallingIdentity(callingId); 13273 } 13274 } 13275 13276 /** 13277 * @hide 13278 */ 13279 @Override 13280 public int installExistingPackageAsUser(String packageName, int userId, int installFlags, 13281 int installReason) { 13282 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 13283 null); 13284 PackageSetting pkgSetting; 13285 final int callingUid = Binder.getCallingUid(); 13286 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 13287 true /* requireFullPermission */, true /* checkShell */, 13288 "installExistingPackage for user " + userId); 13289 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 13290 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 13291 } 13292 13293 long callingId = Binder.clearCallingIdentity(); 13294 try { 13295 boolean installed = false; 13296 final boolean instantApp = 13297 (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 13298 final boolean fullApp = 13299 (installFlags & PackageManager.INSTALL_FULL_APP) != 0; 13300 13301 // writer 13302 synchronized (mPackages) { 13303 pkgSetting = mSettings.mPackages.get(packageName); 13304 if (pkgSetting == null) { 13305 return PackageManager.INSTALL_FAILED_INVALID_URI; 13306 } 13307 if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) { 13308 // only allow the existing package to be used if it's installed as a full 13309 // application for at least one user 13310 boolean installAllowed = false; 13311 for (int checkUserId : sUserManager.getUserIds()) { 13312 installAllowed = !pkgSetting.getInstantApp(checkUserId); 13313 if (installAllowed) { 13314 break; 13315 } 13316 } 13317 if (!installAllowed) { 13318 return PackageManager.INSTALL_FAILED_INVALID_URI; 13319 } 13320 } 13321 if (!pkgSetting.getInstalled(userId)) { 13322 pkgSetting.setInstalled(true, userId); 13323 pkgSetting.setHidden(false, userId); 13324 pkgSetting.setInstallReason(installReason, userId); 13325 mSettings.writePackageRestrictionsLPr(userId); 13326 mSettings.writeKernelMappingLPr(pkgSetting); 13327 installed = true; 13328 } else if (fullApp && pkgSetting.getInstantApp(userId)) { 13329 // upgrade app from instant to full; we don't allow app downgrade 13330 installed = true; 13331 } 13332 setInstantAppForUser(pkgSetting, userId, instantApp, fullApp); 13333 } 13334 13335 if (installed) { 13336 if (pkgSetting.pkg != null) { 13337 synchronized (mInstallLock) { 13338 // We don't need to freeze for a brand new install 13339 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 13340 } 13341 } 13342 sendPackageAddedForUser(packageName, pkgSetting, userId); 13343 synchronized (mPackages) { 13344 updateSequenceNumberLP(pkgSetting, new int[]{ userId }); 13345 } 13346 } 13347 } finally { 13348 Binder.restoreCallingIdentity(callingId); 13349 } 13350 13351 return PackageManager.INSTALL_SUCCEEDED; 13352 } 13353 13354 void setInstantAppForUser(PackageSetting pkgSetting, int userId, 13355 boolean instantApp, boolean fullApp) { 13356 // no state specified; do nothing 13357 if (!instantApp && !fullApp) { 13358 return; 13359 } 13360 if (userId != UserHandle.USER_ALL) { 13361 if (instantApp && !pkgSetting.getInstantApp(userId)) { 13362 pkgSetting.setInstantApp(true /*instantApp*/, userId); 13363 } else if (fullApp && pkgSetting.getInstantApp(userId)) { 13364 pkgSetting.setInstantApp(false /*instantApp*/, userId); 13365 } 13366 } else { 13367 for (int currentUserId : sUserManager.getUserIds()) { 13368 if (instantApp && !pkgSetting.getInstantApp(currentUserId)) { 13369 pkgSetting.setInstantApp(true /*instantApp*/, currentUserId); 13370 } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) { 13371 pkgSetting.setInstantApp(false /*instantApp*/, currentUserId); 13372 } 13373 } 13374 } 13375 } 13376 13377 boolean isUserRestricted(int userId, String restrictionKey) { 13378 Bundle restrictions = sUserManager.getUserRestrictions(userId); 13379 if (restrictions.getBoolean(restrictionKey, false)) { 13380 Log.w(TAG, "User is restricted: " + restrictionKey); 13381 return true; 13382 } 13383 return false; 13384 } 13385 13386 @Override 13387 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 13388 int userId) { 13389 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13390 final int callingUid = Binder.getCallingUid(); 13391 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 13392 true /* requireFullPermission */, true /* checkShell */, 13393 "setPackagesSuspended for user " + userId); 13394 13395 if (ArrayUtils.isEmpty(packageNames)) { 13396 return packageNames; 13397 } 13398 13399 // List of package names for whom the suspended state has changed. 13400 List<String> changedPackages = new ArrayList<>(packageNames.length); 13401 // List of package names for whom the suspended state is not set as requested in this 13402 // method. 13403 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 13404 long callingId = Binder.clearCallingIdentity(); 13405 try { 13406 for (int i = 0; i < packageNames.length; i++) { 13407 String packageName = packageNames[i]; 13408 boolean changed = false; 13409 final int appId; 13410 synchronized (mPackages) { 13411 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 13412 if (pkgSetting == null 13413 || filterAppAccessLPr(pkgSetting, callingUid, userId)) { 13414 Slog.w(TAG, "Could not find package setting for package \"" + packageName 13415 + "\". Skipping suspending/un-suspending."); 13416 unactionedPackages.add(packageName); 13417 continue; 13418 } 13419 appId = pkgSetting.appId; 13420 if (pkgSetting.getSuspended(userId) != suspended) { 13421 if (!canSuspendPackageForUserLocked(packageName, userId)) { 13422 unactionedPackages.add(packageName); 13423 continue; 13424 } 13425 pkgSetting.setSuspended(suspended, userId); 13426 mSettings.writePackageRestrictionsLPr(userId); 13427 changed = true; 13428 changedPackages.add(packageName); 13429 } 13430 } 13431 13432 if (changed && suspended) { 13433 killApplication(packageName, UserHandle.getUid(userId, appId), 13434 "suspending package"); 13435 } 13436 } 13437 } finally { 13438 Binder.restoreCallingIdentity(callingId); 13439 } 13440 13441 if (!changedPackages.isEmpty()) { 13442 sendPackagesSuspendedForUser(changedPackages.toArray( 13443 new String[changedPackages.size()]), userId, suspended); 13444 } 13445 13446 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 13447 } 13448 13449 @Override 13450 public boolean isPackageSuspendedForUser(String packageName, int userId) { 13451 final int callingUid = Binder.getCallingUid(); 13452 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 13453 true /* requireFullPermission */, false /* checkShell */, 13454 "isPackageSuspendedForUser for user " + userId); 13455 synchronized (mPackages) { 13456 final PackageSetting ps = mSettings.mPackages.get(packageName); 13457 if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) { 13458 throw new IllegalArgumentException("Unknown target package: " + packageName); 13459 } 13460 return ps.getSuspended(userId); 13461 } 13462 } 13463 13464 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 13465 if (isPackageDeviceAdmin(packageName, userId)) { 13466 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13467 + "\": has an active device admin"); 13468 return false; 13469 } 13470 13471 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 13472 if (packageName.equals(activeLauncherPackageName)) { 13473 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13474 + "\": contains the active launcher"); 13475 return false; 13476 } 13477 13478 if (packageName.equals(mRequiredInstallerPackage)) { 13479 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13480 + "\": required for package installation"); 13481 return false; 13482 } 13483 13484 if (packageName.equals(mRequiredUninstallerPackage)) { 13485 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13486 + "\": required for package uninstallation"); 13487 return false; 13488 } 13489 13490 if (packageName.equals(mRequiredVerifierPackage)) { 13491 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13492 + "\": required for package verification"); 13493 return false; 13494 } 13495 13496 if (packageName.equals(getDefaultDialerPackageName(userId))) { 13497 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13498 + "\": is the default dialer"); 13499 return false; 13500 } 13501 13502 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 13503 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13504 + "\": protected package"); 13505 return false; 13506 } 13507 13508 // Cannot suspend static shared libs as they are considered 13509 // a part of the using app (emulating static linking). Also 13510 // static libs are installed always on internal storage. 13511 PackageParser.Package pkg = mPackages.get(packageName); 13512 if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) { 13513 Slog.w(TAG, "Cannot suspend package: " + packageName 13514 + " providing static shared library: " 13515 + pkg.staticSharedLibName); 13516 return false; 13517 } 13518 13519 return true; 13520 } 13521 13522 private String getActiveLauncherPackageName(int userId) { 13523 Intent intent = new Intent(Intent.ACTION_MAIN); 13524 intent.addCategory(Intent.CATEGORY_HOME); 13525 ResolveInfo resolveInfo = resolveIntent( 13526 intent, 13527 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 13528 PackageManager.MATCH_DEFAULT_ONLY, 13529 userId); 13530 13531 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 13532 } 13533 13534 private String getDefaultDialerPackageName(int userId) { 13535 synchronized (mPackages) { 13536 return mSettings.getDefaultDialerPackageNameLPw(userId); 13537 } 13538 } 13539 13540 @Override 13541 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 13542 mContext.enforceCallingOrSelfPermission( 13543 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13544 "Only package verification agents can verify applications"); 13545 13546 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 13547 final PackageVerificationResponse response = new PackageVerificationResponse( 13548 verificationCode, Binder.getCallingUid()); 13549 msg.arg1 = id; 13550 msg.obj = response; 13551 mHandler.sendMessage(msg); 13552 } 13553 13554 @Override 13555 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 13556 long millisecondsToDelay) { 13557 mContext.enforceCallingOrSelfPermission( 13558 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13559 "Only package verification agents can extend verification timeouts"); 13560 13561 final PackageVerificationState state = mPendingVerification.get(id); 13562 final PackageVerificationResponse response = new PackageVerificationResponse( 13563 verificationCodeAtTimeout, Binder.getCallingUid()); 13564 13565 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 13566 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 13567 } 13568 if (millisecondsToDelay < 0) { 13569 millisecondsToDelay = 0; 13570 } 13571 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 13572 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 13573 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 13574 } 13575 13576 if ((state != null) && !state.timeoutExtended()) { 13577 state.extendTimeout(); 13578 13579 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 13580 msg.arg1 = id; 13581 msg.obj = response; 13582 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 13583 } 13584 } 13585 13586 private void broadcastPackageVerified(int verificationId, Uri packageUri, 13587 int verificationCode, UserHandle user) { 13588 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 13589 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 13590 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 13591 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 13592 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 13593 13594 mContext.sendBroadcastAsUser(intent, user, 13595 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 13596 } 13597 13598 private ComponentName matchComponentForVerifier(String packageName, 13599 List<ResolveInfo> receivers) { 13600 ActivityInfo targetReceiver = null; 13601 13602 final int NR = receivers.size(); 13603 for (int i = 0; i < NR; i++) { 13604 final ResolveInfo info = receivers.get(i); 13605 if (info.activityInfo == null) { 13606 continue; 13607 } 13608 13609 if (packageName.equals(info.activityInfo.packageName)) { 13610 targetReceiver = info.activityInfo; 13611 break; 13612 } 13613 } 13614 13615 if (targetReceiver == null) { 13616 return null; 13617 } 13618 13619 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 13620 } 13621 13622 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 13623 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 13624 if (pkgInfo.verifiers.length == 0) { 13625 return null; 13626 } 13627 13628 final int N = pkgInfo.verifiers.length; 13629 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 13630 for (int i = 0; i < N; i++) { 13631 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 13632 13633 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 13634 receivers); 13635 if (comp == null) { 13636 continue; 13637 } 13638 13639 final int verifierUid = getUidForVerifier(verifierInfo); 13640 if (verifierUid == -1) { 13641 continue; 13642 } 13643 13644 if (DEBUG_VERIFY) { 13645 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 13646 + " with the correct signature"); 13647 } 13648 sufficientVerifiers.add(comp); 13649 verificationState.addSufficientVerifier(verifierUid); 13650 } 13651 13652 return sufficientVerifiers; 13653 } 13654 13655 private int getUidForVerifier(VerifierInfo verifierInfo) { 13656 synchronized (mPackages) { 13657 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 13658 if (pkg == null) { 13659 return -1; 13660 } else if (pkg.mSignatures.length != 1) { 13661 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 13662 + " has more than one signature; ignoring"); 13663 return -1; 13664 } 13665 13666 /* 13667 * If the public key of the package's signature does not match 13668 * our expected public key, then this is a different package and 13669 * we should skip. 13670 */ 13671 13672 final byte[] expectedPublicKey; 13673 try { 13674 final Signature verifierSig = pkg.mSignatures[0]; 13675 final PublicKey publicKey = verifierSig.getPublicKey(); 13676 expectedPublicKey = publicKey.getEncoded(); 13677 } catch (CertificateException e) { 13678 return -1; 13679 } 13680 13681 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 13682 13683 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 13684 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 13685 + " does not have the expected public key; ignoring"); 13686 return -1; 13687 } 13688 13689 return pkg.applicationInfo.uid; 13690 } 13691 } 13692 13693 @Override 13694 public void finishPackageInstall(int token, boolean didLaunch) { 13695 enforceSystemOrRoot("Only the system is allowed to finish installs"); 13696 13697 if (DEBUG_INSTALL) { 13698 Slog.v(TAG, "BM finishing package install for " + token); 13699 } 13700 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 13701 13702 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 13703 mHandler.sendMessage(msg); 13704 } 13705 13706 /** 13707 * Get the verification agent timeout. Used for both the APK verifier and the 13708 * intent filter verifier. 13709 * 13710 * @return verification timeout in milliseconds 13711 */ 13712 private long getVerificationTimeout() { 13713 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 13714 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 13715 DEFAULT_VERIFICATION_TIMEOUT); 13716 } 13717 13718 /** 13719 * Get the default verification agent response code. 13720 * 13721 * @return default verification response code 13722 */ 13723 private int getDefaultVerificationResponse(UserHandle user) { 13724 if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) { 13725 return PackageManager.VERIFICATION_REJECT; 13726 } 13727 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13728 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 13729 DEFAULT_VERIFICATION_RESPONSE); 13730 } 13731 13732 /** 13733 * Check whether or not package verification has been enabled. 13734 * 13735 * @return true if verification should be performed 13736 */ 13737 private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) { 13738 if (!DEFAULT_VERIFY_ENABLE) { 13739 return false; 13740 } 13741 13742 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 13743 13744 // Check if installing from ADB 13745 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 13746 // Do not run verification in a test harness environment 13747 if (ActivityManager.isRunningInTestHarness()) { 13748 return false; 13749 } 13750 if (ensureVerifyAppsEnabled) { 13751 return true; 13752 } 13753 // Check if the developer does not want package verification for ADB installs 13754 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13755 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 13756 return false; 13757 } 13758 } else { 13759 // only when not installed from ADB, skip verification for instant apps when 13760 // the installer and verifier are the same. 13761 if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) { 13762 if (mInstantAppInstallerActivity != null 13763 && mInstantAppInstallerActivity.packageName.equals( 13764 mRequiredVerifierPackage)) { 13765 try { 13766 mContext.getSystemService(AppOpsManager.class) 13767 .checkPackage(installerUid, mRequiredVerifierPackage); 13768 if (DEBUG_VERIFY) { 13769 Slog.i(TAG, "disable verification for instant app"); 13770 } 13771 return false; 13772 } catch (SecurityException ignore) { } 13773 } 13774 } 13775 } 13776 13777 if (ensureVerifyAppsEnabled) { 13778 return true; 13779 } 13780 13781 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13782 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 13783 } 13784 13785 @Override 13786 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 13787 throws RemoteException { 13788 mContext.enforceCallingOrSelfPermission( 13789 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 13790 "Only intentfilter verification agents can verify applications"); 13791 13792 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 13793 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 13794 Binder.getCallingUid(), verificationCode, failedDomains); 13795 msg.arg1 = id; 13796 msg.obj = response; 13797 mHandler.sendMessage(msg); 13798 } 13799 13800 @Override 13801 public int getIntentVerificationStatus(String packageName, int userId) { 13802 final int callingUid = Binder.getCallingUid(); 13803 if (UserHandle.getUserId(callingUid) != userId) { 13804 mContext.enforceCallingOrSelfPermission( 13805 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 13806 "getIntentVerificationStatus" + userId); 13807 } 13808 if (getInstantAppPackageName(callingUid) != null) { 13809 return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 13810 } 13811 synchronized (mPackages) { 13812 final PackageSetting ps = mSettings.mPackages.get(packageName); 13813 if (ps == null 13814 || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 13815 return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 13816 } 13817 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 13818 } 13819 } 13820 13821 @Override 13822 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 13823 mContext.enforceCallingOrSelfPermission( 13824 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13825 13826 boolean result = false; 13827 synchronized (mPackages) { 13828 final PackageSetting ps = mSettings.mPackages.get(packageName); 13829 if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) { 13830 return false; 13831 } 13832 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 13833 } 13834 if (result) { 13835 scheduleWritePackageRestrictionsLocked(userId); 13836 } 13837 return result; 13838 } 13839 13840 @Override 13841 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 13842 String packageName) { 13843 final int callingUid = Binder.getCallingUid(); 13844 if (getInstantAppPackageName(callingUid) != null) { 13845 return ParceledListSlice.emptyList(); 13846 } 13847 synchronized (mPackages) { 13848 final PackageSetting ps = mSettings.mPackages.get(packageName); 13849 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 13850 return ParceledListSlice.emptyList(); 13851 } 13852 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 13853 } 13854 } 13855 13856 @Override 13857 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 13858 if (TextUtils.isEmpty(packageName)) { 13859 return ParceledListSlice.emptyList(); 13860 } 13861 final int callingUid = Binder.getCallingUid(); 13862 final int callingUserId = UserHandle.getUserId(callingUid); 13863 synchronized (mPackages) { 13864 PackageParser.Package pkg = mPackages.get(packageName); 13865 if (pkg == null || pkg.activities == null) { 13866 return ParceledListSlice.emptyList(); 13867 } 13868 if (pkg.mExtras == null) { 13869 return ParceledListSlice.emptyList(); 13870 } 13871 final PackageSetting ps = (PackageSetting) pkg.mExtras; 13872 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 13873 return ParceledListSlice.emptyList(); 13874 } 13875 final int count = pkg.activities.size(); 13876 ArrayList<IntentFilter> result = new ArrayList<>(); 13877 for (int n=0; n<count; n++) { 13878 PackageParser.Activity activity = pkg.activities.get(n); 13879 if (activity.intents != null && activity.intents.size() > 0) { 13880 result.addAll(activity.intents); 13881 } 13882 } 13883 return new ParceledListSlice<>(result); 13884 } 13885 } 13886 13887 @Override 13888 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 13889 mContext.enforceCallingOrSelfPermission( 13890 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13891 if (UserHandle.getCallingUserId() != userId) { 13892 mContext.enforceCallingOrSelfPermission( 13893 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 13894 } 13895 13896 synchronized (mPackages) { 13897 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 13898 if (packageName != null) { 13899 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowser( 13900 packageName, userId); 13901 } 13902 return result; 13903 } 13904 } 13905 13906 @Override 13907 public String getDefaultBrowserPackageName(int userId) { 13908 if (UserHandle.getCallingUserId() != userId) { 13909 mContext.enforceCallingOrSelfPermission( 13910 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 13911 } 13912 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 13913 return null; 13914 } 13915 synchronized (mPackages) { 13916 return mSettings.getDefaultBrowserPackageNameLPw(userId); 13917 } 13918 } 13919 13920 /** 13921 * Get the "allow unknown sources" setting. 13922 * 13923 * @return the current "allow unknown sources" setting 13924 */ 13925 private int getUnknownSourcesSettings() { 13926 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 13927 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 13928 -1); 13929 } 13930 13931 @Override 13932 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 13933 final int callingUid = Binder.getCallingUid(); 13934 if (getInstantAppPackageName(callingUid) != null) { 13935 return; 13936 } 13937 // writer 13938 synchronized (mPackages) { 13939 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 13940 if (targetPackageSetting == null 13941 || filterAppAccessLPr( 13942 targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) { 13943 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 13944 } 13945 13946 PackageSetting installerPackageSetting; 13947 if (installerPackageName != null) { 13948 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 13949 if (installerPackageSetting == null) { 13950 throw new IllegalArgumentException("Unknown installer package: " 13951 + installerPackageName); 13952 } 13953 } else { 13954 installerPackageSetting = null; 13955 } 13956 13957 Signature[] callerSignature; 13958 Object obj = mSettings.getUserIdLPr(callingUid); 13959 if (obj != null) { 13960 if (obj instanceof SharedUserSetting) { 13961 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 13962 } else if (obj instanceof PackageSetting) { 13963 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 13964 } else { 13965 throw new SecurityException("Bad object " + obj + " for uid " + callingUid); 13966 } 13967 } else { 13968 throw new SecurityException("Unknown calling UID: " + callingUid); 13969 } 13970 13971 // Verify: can't set installerPackageName to a package that is 13972 // not signed with the same cert as the caller. 13973 if (installerPackageSetting != null) { 13974 if (compareSignatures(callerSignature, 13975 installerPackageSetting.signatures.mSignatures) 13976 != PackageManager.SIGNATURE_MATCH) { 13977 throw new SecurityException( 13978 "Caller does not have same cert as new installer package " 13979 + installerPackageName); 13980 } 13981 } 13982 13983 // Verify: if target already has an installer package, it must 13984 // be signed with the same cert as the caller. 13985 if (targetPackageSetting.installerPackageName != null) { 13986 PackageSetting setting = mSettings.mPackages.get( 13987 targetPackageSetting.installerPackageName); 13988 // If the currently set package isn't valid, then it's always 13989 // okay to change it. 13990 if (setting != null) { 13991 if (compareSignatures(callerSignature, 13992 setting.signatures.mSignatures) 13993 != PackageManager.SIGNATURE_MATCH) { 13994 throw new SecurityException( 13995 "Caller does not have same cert as old installer package " 13996 + targetPackageSetting.installerPackageName); 13997 } 13998 } 13999 } 14000 14001 // Okay! 14002 targetPackageSetting.installerPackageName = installerPackageName; 14003 if (installerPackageName != null) { 14004 mSettings.mInstallerPackages.add(installerPackageName); 14005 } 14006 scheduleWriteSettingsLocked(); 14007 } 14008 } 14009 14010 @Override 14011 public void setApplicationCategoryHint(String packageName, int categoryHint, 14012 String callerPackageName) { 14013 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 14014 throw new SecurityException("Instant applications don't have access to this method"); 14015 } 14016 mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(), 14017 callerPackageName); 14018 synchronized (mPackages) { 14019 PackageSetting ps = mSettings.mPackages.get(packageName); 14020 if (ps == null) { 14021 throw new IllegalArgumentException("Unknown target package " + packageName); 14022 } 14023 if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) { 14024 throw new IllegalArgumentException("Unknown target package " + packageName); 14025 } 14026 if (!Objects.equals(callerPackageName, ps.installerPackageName)) { 14027 throw new IllegalArgumentException("Calling package " + callerPackageName 14028 + " is not installer for " + packageName); 14029 } 14030 14031 if (ps.categoryHint != categoryHint) { 14032 ps.categoryHint = categoryHint; 14033 scheduleWriteSettingsLocked(); 14034 } 14035 } 14036 } 14037 14038 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 14039 // Queue up an async operation since the package installation may take a little while. 14040 mHandler.post(new Runnable() { 14041 public void run() { 14042 mHandler.removeCallbacks(this); 14043 // Result object to be returned 14044 PackageInstalledInfo res = new PackageInstalledInfo(); 14045 res.setReturnCode(currentStatus); 14046 res.uid = -1; 14047 res.pkg = null; 14048 res.removedInfo = null; 14049 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14050 args.doPreInstall(res.returnCode); 14051 synchronized (mInstallLock) { 14052 installPackageTracedLI(args, res); 14053 } 14054 args.doPostInstall(res.returnCode, res.uid); 14055 } 14056 14057 // A restore should be performed at this point if (a) the install 14058 // succeeded, (b) the operation is not an update, and (c) the new 14059 // package has not opted out of backup participation. 14060 final boolean update = res.removedInfo != null 14061 && res.removedInfo.removedPackage != null; 14062 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 14063 boolean doRestore = !update 14064 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 14065 14066 // Set up the post-install work request bookkeeping. This will be used 14067 // and cleaned up by the post-install event handling regardless of whether 14068 // there's a restore pass performed. Token values are >= 1. 14069 int token; 14070 if (mNextInstallToken < 0) mNextInstallToken = 1; 14071 token = mNextInstallToken++; 14072 14073 PostInstallData data = new PostInstallData(args, res); 14074 mRunningInstalls.put(token, data); 14075 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 14076 14077 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 14078 // Pass responsibility to the Backup Manager. It will perform a 14079 // restore if appropriate, then pass responsibility back to the 14080 // Package Manager to run the post-install observer callbacks 14081 // and broadcasts. 14082 IBackupManager bm = IBackupManager.Stub.asInterface( 14083 ServiceManager.getService(Context.BACKUP_SERVICE)); 14084 if (bm != null) { 14085 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 14086 + " to BM for possible restore"); 14087 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 14088 try { 14089 // TODO: http://b/22388012 14090 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 14091 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 14092 } else { 14093 doRestore = false; 14094 } 14095 } catch (RemoteException e) { 14096 // can't happen; the backup manager is local 14097 } catch (Exception e) { 14098 Slog.e(TAG, "Exception trying to enqueue restore", e); 14099 doRestore = false; 14100 } 14101 } else { 14102 Slog.e(TAG, "Backup Manager not found!"); 14103 doRestore = false; 14104 } 14105 } 14106 14107 if (!doRestore) { 14108 // No restore possible, or the Backup Manager was mysteriously not 14109 // available -- just fire the post-install work request directly. 14110 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 14111 14112 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 14113 14114 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 14115 mHandler.sendMessage(msg); 14116 } 14117 } 14118 }); 14119 } 14120 14121 /** 14122 * Callback from PackageSettings whenever an app is first transitioned out of the 14123 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 14124 * the app was "launched" for a restoreAtInstall operation. Therefore we check 14125 * here whether the app is the target of an ongoing install, and only send the 14126 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 14127 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 14128 * handling. 14129 */ 14130 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 14131 // Serialize this with the rest of the install-process message chain. In the 14132 // restore-at-install case, this Runnable will necessarily run before the 14133 // POST_INSTALL message is processed, so the contents of mRunningInstalls 14134 // are coherent. In the non-restore case, the app has already completed install 14135 // and been launched through some other means, so it is not in a problematic 14136 // state for observers to see the FIRST_LAUNCH signal. 14137 mHandler.post(new Runnable() { 14138 @Override 14139 public void run() { 14140 for (int i = 0; i < mRunningInstalls.size(); i++) { 14141 final PostInstallData data = mRunningInstalls.valueAt(i); 14142 if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14143 continue; 14144 } 14145 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 14146 // right package; but is it for the right user? 14147 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 14148 if (userId == data.res.newUsers[uIndex]) { 14149 if (DEBUG_BACKUP) { 14150 Slog.i(TAG, "Package " + pkgName 14151 + " being restored so deferring FIRST_LAUNCH"); 14152 } 14153 return; 14154 } 14155 } 14156 } 14157 } 14158 // didn't find it, so not being restored 14159 if (DEBUG_BACKUP) { 14160 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 14161 } 14162 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 14163 } 14164 }); 14165 } 14166 14167 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 14168 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 14169 installerPkg, null, userIds); 14170 } 14171 14172 private abstract class HandlerParams { 14173 private static final int MAX_RETRIES = 4; 14174 14175 /** 14176 * Number of times startCopy() has been attempted and had a non-fatal 14177 * error. 14178 */ 14179 private int mRetries = 0; 14180 14181 /** User handle for the user requesting the information or installation. */ 14182 private final UserHandle mUser; 14183 String traceMethod; 14184 int traceCookie; 14185 14186 HandlerParams(UserHandle user) { 14187 mUser = user; 14188 } 14189 14190 UserHandle getUser() { 14191 return mUser; 14192 } 14193 14194 HandlerParams setTraceMethod(String traceMethod) { 14195 this.traceMethod = traceMethod; 14196 return this; 14197 } 14198 14199 HandlerParams setTraceCookie(int traceCookie) { 14200 this.traceCookie = traceCookie; 14201 return this; 14202 } 14203 14204 final boolean startCopy() { 14205 boolean res; 14206 try { 14207 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 14208 14209 if (++mRetries > MAX_RETRIES) { 14210 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 14211 mHandler.sendEmptyMessage(MCS_GIVE_UP); 14212 handleServiceError(); 14213 return false; 14214 } else { 14215 handleStartCopy(); 14216 res = true; 14217 } 14218 } catch (RemoteException e) { 14219 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 14220 mHandler.sendEmptyMessage(MCS_RECONNECT); 14221 res = false; 14222 } 14223 handleReturnCode(); 14224 return res; 14225 } 14226 14227 final void serviceError() { 14228 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 14229 handleServiceError(); 14230 handleReturnCode(); 14231 } 14232 14233 abstract void handleStartCopy() throws RemoteException; 14234 abstract void handleServiceError(); 14235 abstract void handleReturnCode(); 14236 } 14237 14238 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 14239 for (File path : paths) { 14240 try { 14241 mcs.clearDirectory(path.getAbsolutePath()); 14242 } catch (RemoteException e) { 14243 } 14244 } 14245 } 14246 14247 static class OriginInfo { 14248 /** 14249 * Location where install is coming from, before it has been 14250 * copied/renamed into place. This could be a single monolithic APK 14251 * file, or a cluster directory. This location may be untrusted. 14252 */ 14253 final File file; 14254 14255 /** 14256 * Flag indicating that {@link #file} or {@link #cid} has already been 14257 * staged, meaning downstream users don't need to defensively copy the 14258 * contents. 14259 */ 14260 final boolean staged; 14261 14262 /** 14263 * Flag indicating that {@link #file} or {@link #cid} is an already 14264 * installed app that is being moved. 14265 */ 14266 final boolean existing; 14267 14268 final String resolvedPath; 14269 final File resolvedFile; 14270 14271 static OriginInfo fromNothing() { 14272 return new OriginInfo(null, false, false); 14273 } 14274 14275 static OriginInfo fromUntrustedFile(File file) { 14276 return new OriginInfo(file, false, false); 14277 } 14278 14279 static OriginInfo fromExistingFile(File file) { 14280 return new OriginInfo(file, false, true); 14281 } 14282 14283 static OriginInfo fromStagedFile(File file) { 14284 return new OriginInfo(file, true, false); 14285 } 14286 14287 private OriginInfo(File file, boolean staged, boolean existing) { 14288 this.file = file; 14289 this.staged = staged; 14290 this.existing = existing; 14291 14292 if (file != null) { 14293 resolvedPath = file.getAbsolutePath(); 14294 resolvedFile = file; 14295 } else { 14296 resolvedPath = null; 14297 resolvedFile = null; 14298 } 14299 } 14300 } 14301 14302 static class MoveInfo { 14303 final int moveId; 14304 final String fromUuid; 14305 final String toUuid; 14306 final String packageName; 14307 final String dataAppName; 14308 final int appId; 14309 final String seinfo; 14310 final int targetSdkVersion; 14311 14312 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 14313 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 14314 this.moveId = moveId; 14315 this.fromUuid = fromUuid; 14316 this.toUuid = toUuid; 14317 this.packageName = packageName; 14318 this.dataAppName = dataAppName; 14319 this.appId = appId; 14320 this.seinfo = seinfo; 14321 this.targetSdkVersion = targetSdkVersion; 14322 } 14323 } 14324 14325 static class VerificationInfo { 14326 /** A constant used to indicate that a uid value is not present. */ 14327 public static final int NO_UID = -1; 14328 14329 /** URI referencing where the package was downloaded from. */ 14330 final Uri originatingUri; 14331 14332 /** HTTP referrer URI associated with the originatingURI. */ 14333 final Uri referrer; 14334 14335 /** UID of the application that the install request originated from. */ 14336 final int originatingUid; 14337 14338 /** UID of application requesting the install */ 14339 final int installerUid; 14340 14341 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 14342 this.originatingUri = originatingUri; 14343 this.referrer = referrer; 14344 this.originatingUid = originatingUid; 14345 this.installerUid = installerUid; 14346 } 14347 } 14348 14349 class InstallParams extends HandlerParams { 14350 final OriginInfo origin; 14351 final MoveInfo move; 14352 final IPackageInstallObserver2 observer; 14353 int installFlags; 14354 final String installerPackageName; 14355 final String volumeUuid; 14356 private InstallArgs mArgs; 14357 private int mRet; 14358 final String packageAbiOverride; 14359 final String[] grantedRuntimePermissions; 14360 final VerificationInfo verificationInfo; 14361 final Certificate[][] certificates; 14362 final int installReason; 14363 14364 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 14365 int installFlags, String installerPackageName, String volumeUuid, 14366 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 14367 String[] grantedPermissions, Certificate[][] certificates, int installReason) { 14368 super(user); 14369 this.origin = origin; 14370 this.move = move; 14371 this.observer = observer; 14372 this.installFlags = installFlags; 14373 this.installerPackageName = installerPackageName; 14374 this.volumeUuid = volumeUuid; 14375 this.verificationInfo = verificationInfo; 14376 this.packageAbiOverride = packageAbiOverride; 14377 this.grantedRuntimePermissions = grantedPermissions; 14378 this.certificates = certificates; 14379 this.installReason = installReason; 14380 } 14381 14382 @Override 14383 public String toString() { 14384 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 14385 + " file=" + origin.file + "}"; 14386 } 14387 14388 private int installLocationPolicy(PackageInfoLite pkgLite) { 14389 String packageName = pkgLite.packageName; 14390 int installLocation = pkgLite.installLocation; 14391 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14392 // reader 14393 synchronized (mPackages) { 14394 // Currently installed package which the new package is attempting to replace or 14395 // null if no such package is installed. 14396 PackageParser.Package installedPkg = mPackages.get(packageName); 14397 // Package which currently owns the data which the new package will own if installed. 14398 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 14399 // will be null whereas dataOwnerPkg will contain information about the package 14400 // which was uninstalled while keeping its data. 14401 PackageParser.Package dataOwnerPkg = installedPkg; 14402 if (dataOwnerPkg == null) { 14403 PackageSetting ps = mSettings.mPackages.get(packageName); 14404 if (ps != null) { 14405 dataOwnerPkg = ps.pkg; 14406 } 14407 } 14408 14409 if (dataOwnerPkg != null) { 14410 // If installed, the package will get access to data left on the device by its 14411 // predecessor. As a security measure, this is permited only if this is not a 14412 // version downgrade or if the predecessor package is marked as debuggable and 14413 // a downgrade is explicitly requested. 14414 // 14415 // On debuggable platform builds, downgrades are permitted even for 14416 // non-debuggable packages to make testing easier. Debuggable platform builds do 14417 // not offer security guarantees and thus it's OK to disable some security 14418 // mechanisms to make debugging/testing easier on those builds. However, even on 14419 // debuggable builds downgrades of packages are permitted only if requested via 14420 // installFlags. This is because we aim to keep the behavior of debuggable 14421 // platform builds as close as possible to the behavior of non-debuggable 14422 // platform builds. 14423 final boolean downgradeRequested = 14424 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 14425 final boolean packageDebuggable = 14426 (dataOwnerPkg.applicationInfo.flags 14427 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 14428 final boolean downgradePermitted = 14429 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 14430 if (!downgradePermitted) { 14431 try { 14432 checkDowngrade(dataOwnerPkg, pkgLite); 14433 } catch (PackageManagerException e) { 14434 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 14435 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 14436 } 14437 } 14438 } 14439 14440 if (installedPkg != null) { 14441 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14442 // Check for updated system application. 14443 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 14444 if (onSd) { 14445 Slog.w(TAG, "Cannot install update to system app on sdcard"); 14446 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 14447 } 14448 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14449 } else { 14450 if (onSd) { 14451 // Install flag overrides everything. 14452 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14453 } 14454 // If current upgrade specifies particular preference 14455 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 14456 // Application explicitly specified internal. 14457 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14458 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 14459 // App explictly prefers external. Let policy decide 14460 } else { 14461 // Prefer previous location 14462 if (isExternal(installedPkg)) { 14463 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14464 } 14465 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14466 } 14467 } 14468 } else { 14469 // Invalid install. Return error code 14470 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 14471 } 14472 } 14473 } 14474 // All the special cases have been taken care of. 14475 // Return result based on recommended install location. 14476 if (onSd) { 14477 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14478 } 14479 return pkgLite.recommendedInstallLocation; 14480 } 14481 14482 /* 14483 * Invoke remote method to get package information and install 14484 * location values. Override install location based on default 14485 * policy if needed and then create install arguments based 14486 * on the install location. 14487 */ 14488 public void handleStartCopy() throws RemoteException { 14489 int ret = PackageManager.INSTALL_SUCCEEDED; 14490 14491 // If we're already staged, we've firmly committed to an install location 14492 if (origin.staged) { 14493 if (origin.file != null) { 14494 installFlags |= PackageManager.INSTALL_INTERNAL; 14495 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 14496 } else { 14497 throw new IllegalStateException("Invalid stage location"); 14498 } 14499 } 14500 14501 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14502 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 14503 final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 14504 PackageInfoLite pkgLite = null; 14505 14506 if (onInt && onSd) { 14507 // Check if both bits are set. 14508 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 14509 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14510 } else if (onSd && ephemeral) { 14511 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 14512 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14513 } else { 14514 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 14515 packageAbiOverride); 14516 14517 if (DEBUG_EPHEMERAL && ephemeral) { 14518 Slog.v(TAG, "pkgLite for install: " + pkgLite); 14519 } 14520 14521 /* 14522 * If we have too little free space, try to free cache 14523 * before giving up. 14524 */ 14525 if (!origin.staged && pkgLite.recommendedInstallLocation 14526 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 14527 // TODO: focus freeing disk space on the target device 14528 final StorageManager storage = StorageManager.from(mContext); 14529 final long lowThreshold = storage.getStorageLowBytes( 14530 Environment.getDataDirectory()); 14531 14532 final long sizeBytes = mContainerService.calculateInstalledSize( 14533 origin.resolvedPath, packageAbiOverride); 14534 14535 try { 14536 mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0); 14537 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 14538 installFlags, packageAbiOverride); 14539 } catch (InstallerException e) { 14540 Slog.w(TAG, "Failed to free cache", e); 14541 } 14542 14543 /* 14544 * The cache free must have deleted the file we 14545 * downloaded to install. 14546 * 14547 * TODO: fix the "freeCache" call to not delete 14548 * the file we care about. 14549 */ 14550 if (pkgLite.recommendedInstallLocation 14551 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 14552 pkgLite.recommendedInstallLocation 14553 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 14554 } 14555 } 14556 } 14557 14558 if (ret == PackageManager.INSTALL_SUCCEEDED) { 14559 int loc = pkgLite.recommendedInstallLocation; 14560 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 14561 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14562 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 14563 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 14564 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 14565 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 14566 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 14567 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 14568 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 14569 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 14570 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 14571 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 14572 } else { 14573 // Override with defaults if needed. 14574 loc = installLocationPolicy(pkgLite); 14575 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 14576 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 14577 } else if (!onSd && !onInt) { 14578 // Override install location with flags 14579 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 14580 // Set the flag to install on external media. 14581 installFlags |= PackageManager.INSTALL_EXTERNAL; 14582 installFlags &= ~PackageManager.INSTALL_INTERNAL; 14583 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 14584 if (DEBUG_EPHEMERAL) { 14585 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 14586 } 14587 installFlags |= PackageManager.INSTALL_INSTANT_APP; 14588 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 14589 |PackageManager.INSTALL_INTERNAL); 14590 } else { 14591 // Make sure the flag for installing on external 14592 // media is unset 14593 installFlags |= PackageManager.INSTALL_INTERNAL; 14594 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 14595 } 14596 } 14597 } 14598 } 14599 14600 final InstallArgs args = createInstallArgs(this); 14601 mArgs = args; 14602 14603 if (ret == PackageManager.INSTALL_SUCCEEDED) { 14604 // TODO: http://b/22976637 14605 // Apps installed for "all" users use the device owner to verify the app 14606 UserHandle verifierUser = getUser(); 14607 if (verifierUser == UserHandle.ALL) { 14608 verifierUser = UserHandle.SYSTEM; 14609 } 14610 14611 /* 14612 * Determine if we have any installed package verifiers. If we 14613 * do, then we'll defer to them to verify the packages. 14614 */ 14615 final int requiredUid = mRequiredVerifierPackage == null ? -1 14616 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 14617 verifierUser.getIdentifier()); 14618 final int installerUid = 14619 verificationInfo == null ? -1 : verificationInfo.installerUid; 14620 if (!origin.existing && requiredUid != -1 14621 && isVerificationEnabled( 14622 verifierUser.getIdentifier(), installFlags, installerUid)) { 14623 final Intent verification = new Intent( 14624 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 14625 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 14626 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 14627 PACKAGE_MIME_TYPE); 14628 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 14629 14630 // Query all live verifiers based on current user state 14631 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 14632 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(), 14633 false /*allowDynamicSplits*/); 14634 14635 if (DEBUG_VERIFY) { 14636 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 14637 + verification.toString() + " with " + pkgLite.verifiers.length 14638 + " optional verifiers"); 14639 } 14640 14641 final int verificationId = mPendingVerificationToken++; 14642 14643 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 14644 14645 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 14646 installerPackageName); 14647 14648 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 14649 installFlags); 14650 14651 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 14652 pkgLite.packageName); 14653 14654 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 14655 pkgLite.versionCode); 14656 14657 if (verificationInfo != null) { 14658 if (verificationInfo.originatingUri != null) { 14659 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 14660 verificationInfo.originatingUri); 14661 } 14662 if (verificationInfo.referrer != null) { 14663 verification.putExtra(Intent.EXTRA_REFERRER, 14664 verificationInfo.referrer); 14665 } 14666 if (verificationInfo.originatingUid >= 0) { 14667 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 14668 verificationInfo.originatingUid); 14669 } 14670 if (verificationInfo.installerUid >= 0) { 14671 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 14672 verificationInfo.installerUid); 14673 } 14674 } 14675 14676 final PackageVerificationState verificationState = new PackageVerificationState( 14677 requiredUid, args); 14678 14679 mPendingVerification.append(verificationId, verificationState); 14680 14681 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 14682 receivers, verificationState); 14683 14684 DeviceIdleController.LocalService idleController = getDeviceIdleController(); 14685 final long idleDuration = getVerificationTimeout(); 14686 14687 /* 14688 * If any sufficient verifiers were listed in the package 14689 * manifest, attempt to ask them. 14690 */ 14691 if (sufficientVerifiers != null) { 14692 final int N = sufficientVerifiers.size(); 14693 if (N == 0) { 14694 Slog.i(TAG, "Additional verifiers required, but none installed."); 14695 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 14696 } else { 14697 for (int i = 0; i < N; i++) { 14698 final ComponentName verifierComponent = sufficientVerifiers.get(i); 14699 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 14700 verifierComponent.getPackageName(), idleDuration, 14701 verifierUser.getIdentifier(), false, "package verifier"); 14702 14703 final Intent sufficientIntent = new Intent(verification); 14704 sufficientIntent.setComponent(verifierComponent); 14705 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 14706 } 14707 } 14708 } 14709 14710 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 14711 mRequiredVerifierPackage, receivers); 14712 if (ret == PackageManager.INSTALL_SUCCEEDED 14713 && mRequiredVerifierPackage != null) { 14714 Trace.asyncTraceBegin( 14715 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 14716 /* 14717 * Send the intent to the required verification agent, 14718 * but only start the verification timeout after the 14719 * target BroadcastReceivers have run. 14720 */ 14721 verification.setComponent(requiredVerifierComponent); 14722 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 14723 mRequiredVerifierPackage, idleDuration, 14724 verifierUser.getIdentifier(), false, "package verifier"); 14725 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 14726 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 14727 new BroadcastReceiver() { 14728 @Override 14729 public void onReceive(Context context, Intent intent) { 14730 final Message msg = mHandler 14731 .obtainMessage(CHECK_PENDING_VERIFICATION); 14732 msg.arg1 = verificationId; 14733 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 14734 } 14735 }, null, 0, null, null); 14736 14737 /* 14738 * We don't want the copy to proceed until verification 14739 * succeeds, so null out this field. 14740 */ 14741 mArgs = null; 14742 } 14743 } else { 14744 /* 14745 * No package verification is enabled, so immediately start 14746 * the remote call to initiate copy using temporary file. 14747 */ 14748 ret = args.copyApk(mContainerService, true); 14749 } 14750 } 14751 14752 mRet = ret; 14753 } 14754 14755 @Override 14756 void handleReturnCode() { 14757 // If mArgs is null, then MCS couldn't be reached. When it 14758 // reconnects, it will try again to install. At that point, this 14759 // will succeed. 14760 if (mArgs != null) { 14761 processPendingInstall(mArgs, mRet); 14762 } 14763 } 14764 14765 @Override 14766 void handleServiceError() { 14767 mArgs = createInstallArgs(this); 14768 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 14769 } 14770 } 14771 14772 private InstallArgs createInstallArgs(InstallParams params) { 14773 if (params.move != null) { 14774 return new MoveInstallArgs(params); 14775 } else { 14776 return new FileInstallArgs(params); 14777 } 14778 } 14779 14780 /** 14781 * Create args that describe an existing installed package. Typically used 14782 * when cleaning up old installs, or used as a move source. 14783 */ 14784 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 14785 String resourcePath, String[] instructionSets) { 14786 return new FileInstallArgs(codePath, resourcePath, instructionSets); 14787 } 14788 14789 static abstract class InstallArgs { 14790 /** @see InstallParams#origin */ 14791 final OriginInfo origin; 14792 /** @see InstallParams#move */ 14793 final MoveInfo move; 14794 14795 final IPackageInstallObserver2 observer; 14796 // Always refers to PackageManager flags only 14797 final int installFlags; 14798 final String installerPackageName; 14799 final String volumeUuid; 14800 final UserHandle user; 14801 final String abiOverride; 14802 final String[] installGrantPermissions; 14803 /** If non-null, drop an async trace when the install completes */ 14804 final String traceMethod; 14805 final int traceCookie; 14806 final Certificate[][] certificates; 14807 final int installReason; 14808 14809 // The list of instruction sets supported by this app. This is currently 14810 // only used during the rmdex() phase to clean up resources. We can get rid of this 14811 // if we move dex files under the common app path. 14812 /* nullable */ String[] instructionSets; 14813 14814 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 14815 int installFlags, String installerPackageName, String volumeUuid, 14816 UserHandle user, String[] instructionSets, 14817 String abiOverride, String[] installGrantPermissions, 14818 String traceMethod, int traceCookie, Certificate[][] certificates, 14819 int installReason) { 14820 this.origin = origin; 14821 this.move = move; 14822 this.installFlags = installFlags; 14823 this.observer = observer; 14824 this.installerPackageName = installerPackageName; 14825 this.volumeUuid = volumeUuid; 14826 this.user = user; 14827 this.instructionSets = instructionSets; 14828 this.abiOverride = abiOverride; 14829 this.installGrantPermissions = installGrantPermissions; 14830 this.traceMethod = traceMethod; 14831 this.traceCookie = traceCookie; 14832 this.certificates = certificates; 14833 this.installReason = installReason; 14834 } 14835 14836 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 14837 abstract int doPreInstall(int status); 14838 14839 /** 14840 * Rename package into final resting place. All paths on the given 14841 * scanned package should be updated to reflect the rename. 14842 */ 14843 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 14844 abstract int doPostInstall(int status, int uid); 14845 14846 /** @see PackageSettingBase#codePathString */ 14847 abstract String getCodePath(); 14848 /** @see PackageSettingBase#resourcePathString */ 14849 abstract String getResourcePath(); 14850 14851 // Need installer lock especially for dex file removal. 14852 abstract void cleanUpResourcesLI(); 14853 abstract boolean doPostDeleteLI(boolean delete); 14854 14855 /** 14856 * Called before the source arguments are copied. This is used mostly 14857 * for MoveParams when it needs to read the source file to put it in the 14858 * destination. 14859 */ 14860 int doPreCopy() { 14861 return PackageManager.INSTALL_SUCCEEDED; 14862 } 14863 14864 /** 14865 * Called after the source arguments are copied. This is used mostly for 14866 * MoveParams when it needs to read the source file to put it in the 14867 * destination. 14868 */ 14869 int doPostCopy(int uid) { 14870 return PackageManager.INSTALL_SUCCEEDED; 14871 } 14872 14873 protected boolean isFwdLocked() { 14874 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 14875 } 14876 14877 protected boolean isExternalAsec() { 14878 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14879 } 14880 14881 protected boolean isEphemeral() { 14882 return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 14883 } 14884 14885 UserHandle getUser() { 14886 return user; 14887 } 14888 } 14889 14890 void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 14891 if (!allCodePaths.isEmpty()) { 14892 if (instructionSets == null) { 14893 throw new IllegalStateException("instructionSet == null"); 14894 } 14895 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 14896 for (String codePath : allCodePaths) { 14897 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 14898 try { 14899 mInstaller.rmdex(codePath, dexCodeInstructionSet); 14900 } catch (InstallerException ignored) { 14901 } 14902 } 14903 } 14904 } 14905 } 14906 14907 /** 14908 * Logic to handle installation of non-ASEC applications, including copying 14909 * and renaming logic. 14910 */ 14911 class FileInstallArgs extends InstallArgs { 14912 private File codeFile; 14913 private File resourceFile; 14914 14915 // Example topology: 14916 // /data/app/com.example/base.apk 14917 // /data/app/com.example/split_foo.apk 14918 // /data/app/com.example/lib/arm/libfoo.so 14919 // /data/app/com.example/lib/arm64/libfoo.so 14920 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 14921 14922 /** New install */ 14923 FileInstallArgs(InstallParams params) { 14924 super(params.origin, params.move, params.observer, params.installFlags, 14925 params.installerPackageName, params.volumeUuid, 14926 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 14927 params.grantedRuntimePermissions, 14928 params.traceMethod, params.traceCookie, params.certificates, 14929 params.installReason); 14930 if (isFwdLocked()) { 14931 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 14932 } 14933 } 14934 14935 /** Existing install */ 14936 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 14937 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 14938 null, null, null, 0, null /*certificates*/, 14939 PackageManager.INSTALL_REASON_UNKNOWN); 14940 this.codeFile = (codePath != null) ? new File(codePath) : null; 14941 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 14942 } 14943 14944 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 14945 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 14946 try { 14947 return doCopyApk(imcs, temp); 14948 } finally { 14949 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14950 } 14951 } 14952 14953 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 14954 if (origin.staged) { 14955 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 14956 codeFile = origin.file; 14957 resourceFile = origin.file; 14958 return PackageManager.INSTALL_SUCCEEDED; 14959 } 14960 14961 try { 14962 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 14963 final File tempDir = 14964 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 14965 codeFile = tempDir; 14966 resourceFile = tempDir; 14967 } catch (IOException e) { 14968 Slog.w(TAG, "Failed to create copy file: " + e); 14969 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 14970 } 14971 14972 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 14973 @Override 14974 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 14975 if (!FileUtils.isValidExtFilename(name)) { 14976 throw new IllegalArgumentException("Invalid filename: " + name); 14977 } 14978 try { 14979 final File file = new File(codeFile, name); 14980 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 14981 O_RDWR | O_CREAT, 0644); 14982 Os.chmod(file.getAbsolutePath(), 0644); 14983 return new ParcelFileDescriptor(fd); 14984 } catch (ErrnoException e) { 14985 throw new RemoteException("Failed to open: " + e.getMessage()); 14986 } 14987 } 14988 }; 14989 14990 int ret = PackageManager.INSTALL_SUCCEEDED; 14991 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 14992 if (ret != PackageManager.INSTALL_SUCCEEDED) { 14993 Slog.e(TAG, "Failed to copy package"); 14994 return ret; 14995 } 14996 14997 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 14998 NativeLibraryHelper.Handle handle = null; 14999 try { 15000 handle = NativeLibraryHelper.Handle.create(codeFile); 15001 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 15002 abiOverride); 15003 } catch (IOException e) { 15004 Slog.e(TAG, "Copying native libraries failed", e); 15005 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15006 } finally { 15007 IoUtils.closeQuietly(handle); 15008 } 15009 15010 return ret; 15011 } 15012 15013 int doPreInstall(int status) { 15014 if (status != PackageManager.INSTALL_SUCCEEDED) { 15015 cleanUp(); 15016 } 15017 return status; 15018 } 15019 15020 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15021 if (status != PackageManager.INSTALL_SUCCEEDED) { 15022 cleanUp(); 15023 return false; 15024 } 15025 15026 final File targetDir = codeFile.getParentFile(); 15027 final File beforeCodeFile = codeFile; 15028 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 15029 15030 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 15031 try { 15032 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 15033 } catch (ErrnoException e) { 15034 Slog.w(TAG, "Failed to rename", e); 15035 return false; 15036 } 15037 15038 if (!SELinux.restoreconRecursive(afterCodeFile)) { 15039 Slog.w(TAG, "Failed to restorecon"); 15040 return false; 15041 } 15042 15043 // Reflect the rename internally 15044 codeFile = afterCodeFile; 15045 resourceFile = afterCodeFile; 15046 15047 // Reflect the rename in scanned details 15048 try { 15049 pkg.setCodePath(afterCodeFile.getCanonicalPath()); 15050 } catch (IOException e) { 15051 Slog.e(TAG, "Failed to get path: " + afterCodeFile, e); 15052 return false; 15053 } 15054 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 15055 afterCodeFile, pkg.baseCodePath)); 15056 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 15057 afterCodeFile, pkg.splitCodePaths)); 15058 15059 // Reflect the rename in app info 15060 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15061 pkg.setApplicationInfoCodePath(pkg.codePath); 15062 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15063 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15064 pkg.setApplicationInfoResourcePath(pkg.codePath); 15065 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15066 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15067 15068 return true; 15069 } 15070 15071 int doPostInstall(int status, int uid) { 15072 if (status != PackageManager.INSTALL_SUCCEEDED) { 15073 cleanUp(); 15074 } 15075 return status; 15076 } 15077 15078 @Override 15079 String getCodePath() { 15080 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 15081 } 15082 15083 @Override 15084 String getResourcePath() { 15085 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 15086 } 15087 15088 private boolean cleanUp() { 15089 if (codeFile == null || !codeFile.exists()) { 15090 return false; 15091 } 15092 15093 removeCodePathLI(codeFile); 15094 15095 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 15096 resourceFile.delete(); 15097 } 15098 15099 return true; 15100 } 15101 15102 void cleanUpResourcesLI() { 15103 // Try enumerating all code paths before deleting 15104 List<String> allCodePaths = Collections.EMPTY_LIST; 15105 if (codeFile != null && codeFile.exists()) { 15106 try { 15107 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 15108 allCodePaths = pkg.getAllCodePaths(); 15109 } catch (PackageParserException e) { 15110 // Ignored; we tried our best 15111 } 15112 } 15113 15114 cleanUp(); 15115 removeDexFiles(allCodePaths, instructionSets); 15116 } 15117 15118 boolean doPostDeleteLI(boolean delete) { 15119 // XXX err, shouldn't we respect the delete flag? 15120 cleanUpResourcesLI(); 15121 return true; 15122 } 15123 } 15124 15125 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 15126 PackageManagerException { 15127 if (copyRet < 0) { 15128 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 15129 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 15130 throw new PackageManagerException(copyRet, message); 15131 } 15132 } 15133 } 15134 15135 /** 15136 * Extract the StorageManagerService "container ID" from the full code path of an 15137 * .apk. 15138 */ 15139 static String cidFromCodePath(String fullCodePath) { 15140 int eidx = fullCodePath.lastIndexOf("/"); 15141 String subStr1 = fullCodePath.substring(0, eidx); 15142 int sidx = subStr1.lastIndexOf("/"); 15143 return subStr1.substring(sidx+1, eidx); 15144 } 15145 15146 /** 15147 * Logic to handle movement of existing installed applications. 15148 */ 15149 class MoveInstallArgs extends InstallArgs { 15150 private File codeFile; 15151 private File resourceFile; 15152 15153 /** New install */ 15154 MoveInstallArgs(InstallParams params) { 15155 super(params.origin, params.move, params.observer, params.installFlags, 15156 params.installerPackageName, params.volumeUuid, 15157 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 15158 params.grantedRuntimePermissions, 15159 params.traceMethod, params.traceCookie, params.certificates, 15160 params.installReason); 15161 } 15162 15163 int copyApk(IMediaContainerService imcs, boolean temp) { 15164 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 15165 + move.fromUuid + " to " + move.toUuid); 15166 synchronized (mInstaller) { 15167 try { 15168 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 15169 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 15170 } catch (InstallerException e) { 15171 Slog.w(TAG, "Failed to move app", e); 15172 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15173 } 15174 } 15175 15176 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 15177 resourceFile = codeFile; 15178 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 15179 15180 return PackageManager.INSTALL_SUCCEEDED; 15181 } 15182 15183 int doPreInstall(int status) { 15184 if (status != PackageManager.INSTALL_SUCCEEDED) { 15185 cleanUp(move.toUuid); 15186 } 15187 return status; 15188 } 15189 15190 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15191 if (status != PackageManager.INSTALL_SUCCEEDED) { 15192 cleanUp(move.toUuid); 15193 return false; 15194 } 15195 15196 // Reflect the move in app info 15197 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15198 pkg.setApplicationInfoCodePath(pkg.codePath); 15199 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15200 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15201 pkg.setApplicationInfoResourcePath(pkg.codePath); 15202 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15203 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15204 15205 return true; 15206 } 15207 15208 int doPostInstall(int status, int uid) { 15209 if (status == PackageManager.INSTALL_SUCCEEDED) { 15210 cleanUp(move.fromUuid); 15211 } else { 15212 cleanUp(move.toUuid); 15213 } 15214 return status; 15215 } 15216 15217 @Override 15218 String getCodePath() { 15219 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 15220 } 15221 15222 @Override 15223 String getResourcePath() { 15224 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 15225 } 15226 15227 private boolean cleanUp(String volumeUuid) { 15228 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 15229 move.dataAppName); 15230 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 15231 final int[] userIds = sUserManager.getUserIds(); 15232 synchronized (mInstallLock) { 15233 // Clean up both app data and code 15234 // All package moves are frozen until finished 15235 for (int userId : userIds) { 15236 try { 15237 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 15238 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 15239 } catch (InstallerException e) { 15240 Slog.w(TAG, String.valueOf(e)); 15241 } 15242 } 15243 removeCodePathLI(codeFile); 15244 } 15245 return true; 15246 } 15247 15248 void cleanUpResourcesLI() { 15249 throw new UnsupportedOperationException(); 15250 } 15251 15252 boolean doPostDeleteLI(boolean delete) { 15253 throw new UnsupportedOperationException(); 15254 } 15255 } 15256 15257 static String getAsecPackageName(String packageCid) { 15258 int idx = packageCid.lastIndexOf("-"); 15259 if (idx == -1) { 15260 return packageCid; 15261 } 15262 return packageCid.substring(0, idx); 15263 } 15264 15265 // Utility method used to create code paths based on package name and available index. 15266 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 15267 String idxStr = ""; 15268 int idx = 1; 15269 // Fall back to default value of idx=1 if prefix is not 15270 // part of oldCodePath 15271 if (oldCodePath != null) { 15272 String subStr = oldCodePath; 15273 // Drop the suffix right away 15274 if (suffix != null && subStr.endsWith(suffix)) { 15275 subStr = subStr.substring(0, subStr.length() - suffix.length()); 15276 } 15277 // If oldCodePath already contains prefix find out the 15278 // ending index to either increment or decrement. 15279 int sidx = subStr.lastIndexOf(prefix); 15280 if (sidx != -1) { 15281 subStr = subStr.substring(sidx + prefix.length()); 15282 if (subStr != null) { 15283 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 15284 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 15285 } 15286 try { 15287 idx = Integer.parseInt(subStr); 15288 if (idx <= 1) { 15289 idx++; 15290 } else { 15291 idx--; 15292 } 15293 } catch(NumberFormatException e) { 15294 } 15295 } 15296 } 15297 } 15298 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 15299 return prefix + idxStr; 15300 } 15301 15302 private File getNextCodePath(File targetDir, String packageName) { 15303 File result; 15304 SecureRandom random = new SecureRandom(); 15305 byte[] bytes = new byte[16]; 15306 do { 15307 random.nextBytes(bytes); 15308 String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP); 15309 result = new File(targetDir, packageName + "-" + suffix); 15310 } while (result.exists()); 15311 return result; 15312 } 15313 15314 // Utility method that returns the relative package path with respect 15315 // to the installation directory. Like say for /data/data/com.test-1.apk 15316 // string com.test-1 is returned. 15317 static String deriveCodePathName(String codePath) { 15318 if (codePath == null) { 15319 return null; 15320 } 15321 final File codeFile = new File(codePath); 15322 final String name = codeFile.getName(); 15323 if (codeFile.isDirectory()) { 15324 return name; 15325 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 15326 final int lastDot = name.lastIndexOf('.'); 15327 return name.substring(0, lastDot); 15328 } else { 15329 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 15330 return null; 15331 } 15332 } 15333 15334 static class PackageInstalledInfo { 15335 String name; 15336 int uid; 15337 // The set of users that originally had this package installed. 15338 int[] origUsers; 15339 // The set of users that now have this package installed. 15340 int[] newUsers; 15341 PackageParser.Package pkg; 15342 int returnCode; 15343 String returnMsg; 15344 String installerPackageName; 15345 PackageRemovedInfo removedInfo; 15346 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 15347 15348 public void setError(int code, String msg) { 15349 setReturnCode(code); 15350 setReturnMessage(msg); 15351 Slog.w(TAG, msg); 15352 } 15353 15354 public void setError(String msg, PackageParserException e) { 15355 setReturnCode(e.error); 15356 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 15357 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15358 for (int i = 0; i < childCount; i++) { 15359 addedChildPackages.valueAt(i).setError(msg, e); 15360 } 15361 Slog.w(TAG, msg, e); 15362 } 15363 15364 public void setError(String msg, PackageManagerException e) { 15365 returnCode = e.error; 15366 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 15367 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15368 for (int i = 0; i < childCount; i++) { 15369 addedChildPackages.valueAt(i).setError(msg, e); 15370 } 15371 Slog.w(TAG, msg, e); 15372 } 15373 15374 public void setReturnCode(int returnCode) { 15375 this.returnCode = returnCode; 15376 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15377 for (int i = 0; i < childCount; i++) { 15378 addedChildPackages.valueAt(i).returnCode = returnCode; 15379 } 15380 } 15381 15382 private void setReturnMessage(String returnMsg) { 15383 this.returnMsg = returnMsg; 15384 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15385 for (int i = 0; i < childCount; i++) { 15386 addedChildPackages.valueAt(i).returnMsg = returnMsg; 15387 } 15388 } 15389 15390 // In some error cases we want to convey more info back to the observer 15391 String origPackage; 15392 String origPermission; 15393 } 15394 15395 /* 15396 * Install a non-existing package. 15397 */ 15398 private void installNewPackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags, 15399 final @ScanFlags int scanFlags, UserHandle user, String installerPackageName, 15400 String volumeUuid, PackageInstalledInfo res, int installReason) { 15401 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 15402 15403 // Remember this for later, in case we need to rollback this install 15404 String pkgName = pkg.packageName; 15405 15406 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 15407 15408 synchronized(mPackages) { 15409 final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName); 15410 if (renamedPackage != null) { 15411 // A package with the same name is already installed, though 15412 // it has been renamed to an older name. The package we 15413 // are trying to install should be installed as an update to 15414 // the existing one, but that has not been requested, so bail. 15415 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 15416 + " without first uninstalling package running as " 15417 + renamedPackage); 15418 return; 15419 } 15420 if (mPackages.containsKey(pkgName)) { 15421 // Don't allow installation over an existing package with the same name. 15422 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 15423 + " without first uninstalling."); 15424 return; 15425 } 15426 } 15427 15428 try { 15429 PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 15430 System.currentTimeMillis(), user); 15431 15432 updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason); 15433 15434 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 15435 prepareAppDataAfterInstallLIF(newPackage); 15436 15437 } else { 15438 // Remove package from internal structures, but keep around any 15439 // data that might have already existed 15440 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 15441 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 15442 } 15443 } catch (PackageManagerException e) { 15444 res.setError("Package couldn't be installed in " + pkg.codePath, e); 15445 } 15446 15447 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15448 } 15449 15450 private static void updateDigest(MessageDigest digest, File file) throws IOException { 15451 try (DigestInputStream digestStream = 15452 new DigestInputStream(new FileInputStream(file), digest)) { 15453 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 15454 } 15455 } 15456 15457 private void replacePackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags, 15458 final @ScanFlags int scanFlags, UserHandle user, String installerPackageName, 15459 PackageInstalledInfo res, int installReason) { 15460 final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 15461 15462 final PackageParser.Package oldPackage; 15463 final PackageSetting ps; 15464 final String pkgName = pkg.packageName; 15465 final int[] allUsers; 15466 final int[] installedUsers; 15467 15468 synchronized(mPackages) { 15469 oldPackage = mPackages.get(pkgName); 15470 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 15471 15472 // don't allow upgrade to target a release SDK from a pre-release SDK 15473 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 15474 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 15475 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 15476 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 15477 if (oldTargetsPreRelease 15478 && !newTargetsPreRelease 15479 && ((parseFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 15480 Slog.w(TAG, "Can't install package targeting released sdk"); 15481 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 15482 return; 15483 } 15484 15485 ps = mSettings.mPackages.get(pkgName); 15486 15487 // verify signatures are valid 15488 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 15489 if (ksms.shouldCheckUpgradeKeySetLocked(ps, scanFlags)) { 15490 if (!ksms.checkUpgradeKeySetLocked(ps, pkg)) { 15491 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 15492 "New package not signed by keys specified by upgrade-keysets: " 15493 + pkgName); 15494 return; 15495 } 15496 } else { 15497 // default to original signature matching 15498 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 15499 != PackageManager.SIGNATURE_MATCH) { 15500 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 15501 "New package has a different signature: " + pkgName); 15502 return; 15503 } 15504 } 15505 15506 // don't allow a system upgrade unless the upgrade hash matches 15507 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystem()) { 15508 byte[] digestBytes = null; 15509 try { 15510 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 15511 updateDigest(digest, new File(pkg.baseCodePath)); 15512 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 15513 for (String path : pkg.splitCodePaths) { 15514 updateDigest(digest, new File(path)); 15515 } 15516 } 15517 digestBytes = digest.digest(); 15518 } catch (NoSuchAlgorithmException | IOException e) { 15519 res.setError(INSTALL_FAILED_INVALID_APK, 15520 "Could not compute hash: " + pkgName); 15521 return; 15522 } 15523 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 15524 res.setError(INSTALL_FAILED_INVALID_APK, 15525 "New package fails restrict-update check: " + pkgName); 15526 return; 15527 } 15528 // retain upgrade restriction 15529 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 15530 } 15531 15532 // Check for shared user id changes 15533 String invalidPackageName = 15534 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 15535 if (invalidPackageName != null) { 15536 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 15537 "Package " + invalidPackageName + " tried to change user " 15538 + oldPackage.mSharedUserId); 15539 return; 15540 } 15541 15542 // In case of rollback, remember per-user/profile install state 15543 allUsers = sUserManager.getUserIds(); 15544 installedUsers = ps.queryInstalledUsers(allUsers, true); 15545 15546 // don't allow an upgrade from full to ephemeral 15547 if (isInstantApp) { 15548 if (user == null || user.getIdentifier() == UserHandle.USER_ALL) { 15549 for (int currentUser : allUsers) { 15550 if (!ps.getInstantApp(currentUser)) { 15551 // can't downgrade from full to instant 15552 Slog.w(TAG, "Can't replace full app with instant app: " + pkgName 15553 + " for user: " + currentUser); 15554 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 15555 return; 15556 } 15557 } 15558 } else if (!ps.getInstantApp(user.getIdentifier())) { 15559 // can't downgrade from full to instant 15560 Slog.w(TAG, "Can't replace full app with instant app: " + pkgName 15561 + " for user: " + user.getIdentifier()); 15562 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 15563 return; 15564 } 15565 } 15566 } 15567 15568 // Update what is removed 15569 res.removedInfo = new PackageRemovedInfo(this); 15570 res.removedInfo.uid = oldPackage.applicationInfo.uid; 15571 res.removedInfo.removedPackage = oldPackage.packageName; 15572 res.removedInfo.installerPackageName = ps.installerPackageName; 15573 res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null; 15574 res.removedInfo.isUpdate = true; 15575 res.removedInfo.origUsers = installedUsers; 15576 res.removedInfo.installReasons = new SparseArray<>(installedUsers.length); 15577 for (int i = 0; i < installedUsers.length; i++) { 15578 final int userId = installedUsers[i]; 15579 res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId)); 15580 } 15581 15582 final int childCount = (oldPackage.childPackages != null) 15583 ? oldPackage.childPackages.size() : 0; 15584 for (int i = 0; i < childCount; i++) { 15585 boolean childPackageUpdated = false; 15586 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 15587 final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 15588 if (res.addedChildPackages != null) { 15589 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 15590 if (childRes != null) { 15591 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 15592 childRes.removedInfo.removedPackage = childPkg.packageName; 15593 if (childPs != null) { 15594 childRes.removedInfo.installerPackageName = childPs.installerPackageName; 15595 } 15596 childRes.removedInfo.isUpdate = true; 15597 childRes.removedInfo.installReasons = res.removedInfo.installReasons; 15598 childPackageUpdated = true; 15599 } 15600 } 15601 if (!childPackageUpdated) { 15602 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this); 15603 childRemovedRes.removedPackage = childPkg.packageName; 15604 if (childPs != null) { 15605 childRemovedRes.installerPackageName = childPs.installerPackageName; 15606 } 15607 childRemovedRes.isUpdate = false; 15608 childRemovedRes.dataRemoved = true; 15609 synchronized (mPackages) { 15610 if (childPs != null) { 15611 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 15612 } 15613 } 15614 if (res.removedInfo.removedChildPackages == null) { 15615 res.removedInfo.removedChildPackages = new ArrayMap<>(); 15616 } 15617 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 15618 } 15619 } 15620 15621 boolean sysPkg = (isSystemApp(oldPackage)); 15622 if (sysPkg) { 15623 // Set the system/privileged/oem/vendor flags as needed 15624 final boolean privileged = 15625 (oldPackage.applicationInfo.privateFlags 15626 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 15627 final boolean oem = 15628 (oldPackage.applicationInfo.privateFlags 15629 & ApplicationInfo.PRIVATE_FLAG_OEM) != 0; 15630 final boolean vendor = 15631 (oldPackage.applicationInfo.privateFlags 15632 & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0; 15633 final @ParseFlags int systemParseFlags = parseFlags; 15634 final @ScanFlags int systemScanFlags = scanFlags 15635 | SCAN_AS_SYSTEM 15636 | (privileged ? SCAN_AS_PRIVILEGED : 0) 15637 | (oem ? SCAN_AS_OEM : 0) 15638 | (vendor ? SCAN_AS_VENDOR : 0); 15639 15640 replaceSystemPackageLIF(oldPackage, pkg, systemParseFlags, systemScanFlags, 15641 user, allUsers, installerPackageName, res, installReason); 15642 } else { 15643 replaceNonSystemPackageLIF(oldPackage, pkg, parseFlags, scanFlags, 15644 user, allUsers, installerPackageName, res, installReason); 15645 } 15646 } 15647 15648 @Override 15649 public List<String> getPreviousCodePaths(String packageName) { 15650 final int callingUid = Binder.getCallingUid(); 15651 final List<String> result = new ArrayList<>(); 15652 if (getInstantAppPackageName(callingUid) != null) { 15653 return result; 15654 } 15655 final PackageSetting ps = mSettings.mPackages.get(packageName); 15656 if (ps != null 15657 && ps.oldCodePaths != null 15658 && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 15659 result.addAll(ps.oldCodePaths); 15660 } 15661 return result; 15662 } 15663 15664 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 15665 PackageParser.Package pkg, final @ParseFlags int parseFlags, 15666 final @ScanFlags int scanFlags, UserHandle user, int[] allUsers, 15667 String installerPackageName, PackageInstalledInfo res, int installReason) { 15668 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 15669 + deletedPackage); 15670 15671 String pkgName = deletedPackage.packageName; 15672 boolean deletedPkg = true; 15673 boolean addedPkg = false; 15674 boolean updatedSettings = false; 15675 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 15676 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 15677 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 15678 15679 final long origUpdateTime = (pkg.mExtras != null) 15680 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 15681 15682 // First delete the existing package while retaining the data directory 15683 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 15684 res.removedInfo, true, pkg)) { 15685 // If the existing package wasn't successfully deleted 15686 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 15687 deletedPkg = false; 15688 } else { 15689 // Successfully deleted the old package; proceed with replace. 15690 15691 // If deleted package lived in a container, give users a chance to 15692 // relinquish resources before killing. 15693 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 15694 if (DEBUG_INSTALL) { 15695 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 15696 } 15697 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 15698 final ArrayList<String> pkgList = new ArrayList<String>(1); 15699 pkgList.add(deletedPackage.applicationInfo.packageName); 15700 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 15701 } 15702 15703 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 15704 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 15705 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 15706 15707 try { 15708 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, 15709 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 15710 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 15711 installReason); 15712 15713 // Update the in-memory copy of the previous code paths. 15714 PackageSetting ps = mSettings.mPackages.get(pkgName); 15715 if (!killApp) { 15716 if (ps.oldCodePaths == null) { 15717 ps.oldCodePaths = new ArraySet<>(); 15718 } 15719 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 15720 if (deletedPackage.splitCodePaths != null) { 15721 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 15722 } 15723 } else { 15724 ps.oldCodePaths = null; 15725 } 15726 if (ps.childPackageNames != null) { 15727 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 15728 final String childPkgName = ps.childPackageNames.get(i); 15729 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 15730 childPs.oldCodePaths = ps.oldCodePaths; 15731 } 15732 } 15733 // set instant app status, but, only if it's explicitly specified 15734 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 15735 final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0; 15736 setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp); 15737 prepareAppDataAfterInstallLIF(newPackage); 15738 addedPkg = true; 15739 mDexManager.notifyPackageUpdated(newPackage.packageName, 15740 newPackage.baseCodePath, newPackage.splitCodePaths); 15741 } catch (PackageManagerException e) { 15742 res.setError("Package couldn't be installed in " + pkg.codePath, e); 15743 } 15744 } 15745 15746 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 15747 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 15748 15749 // Revert all internal state mutations and added folders for the failed install 15750 if (addedPkg) { 15751 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 15752 res.removedInfo, true, null); 15753 } 15754 15755 // Restore the old package 15756 if (deletedPkg) { 15757 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 15758 File restoreFile = new File(deletedPackage.codePath); 15759 // Parse old package 15760 boolean oldExternal = isExternal(deletedPackage); 15761 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 15762 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 15763 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 15764 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 15765 try { 15766 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 15767 null); 15768 } catch (PackageManagerException e) { 15769 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 15770 + e.getMessage()); 15771 return; 15772 } 15773 15774 synchronized (mPackages) { 15775 // Ensure the installer package name up to date 15776 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 15777 15778 // Update permissions for restored package 15779 mPermissionManager.updatePermissions( 15780 deletedPackage.packageName, deletedPackage, false, mPackages.values(), 15781 mPermissionCallback); 15782 15783 mSettings.writeLPr(); 15784 } 15785 15786 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 15787 } 15788 } else { 15789 synchronized (mPackages) { 15790 PackageSetting ps = mSettings.getPackageLPr(pkg.packageName); 15791 if (ps != null) { 15792 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 15793 if (res.removedInfo.removedChildPackages != null) { 15794 final int childCount = res.removedInfo.removedChildPackages.size(); 15795 // Iterate in reverse as we may modify the collection 15796 for (int i = childCount - 1; i >= 0; i--) { 15797 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 15798 if (res.addedChildPackages.containsKey(childPackageName)) { 15799 res.removedInfo.removedChildPackages.removeAt(i); 15800 } else { 15801 PackageRemovedInfo childInfo = res.removedInfo 15802 .removedChildPackages.valueAt(i); 15803 childInfo.removedForAllUsers = mPackages.get( 15804 childInfo.removedPackage) == null; 15805 } 15806 } 15807 } 15808 } 15809 } 15810 } 15811 } 15812 15813 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 15814 PackageParser.Package pkg, final @ParseFlags int parseFlags, 15815 final @ScanFlags int scanFlags, UserHandle user, 15816 int[] allUsers, String installerPackageName, PackageInstalledInfo res, 15817 int installReason) { 15818 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 15819 + ", old=" + deletedPackage); 15820 15821 final boolean disabledSystem; 15822 15823 // Remove existing system package 15824 removePackageLI(deletedPackage, true); 15825 15826 synchronized (mPackages) { 15827 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 15828 } 15829 if (!disabledSystem) { 15830 // We didn't need to disable the .apk as a current system package, 15831 // which means we are replacing another update that is already 15832 // installed. We need to make sure to delete the older one's .apk. 15833 res.removedInfo.args = createInstallArgsForExisting(0, 15834 deletedPackage.applicationInfo.getCodePath(), 15835 deletedPackage.applicationInfo.getResourcePath(), 15836 getAppDexInstructionSets(deletedPackage.applicationInfo)); 15837 } else { 15838 res.removedInfo.args = null; 15839 } 15840 15841 // Successfully disabled the old package. Now proceed with re-installation 15842 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 15843 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 15844 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 15845 15846 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 15847 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 15848 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 15849 15850 PackageParser.Package newPackage = null; 15851 try { 15852 // Add the package to the internal data structures 15853 newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user); 15854 15855 // Set the update and install times 15856 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 15857 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 15858 System.currentTimeMillis()); 15859 15860 // Update the package dynamic state if succeeded 15861 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 15862 // Now that the install succeeded make sure we remove data 15863 // directories for any child package the update removed. 15864 final int deletedChildCount = (deletedPackage.childPackages != null) 15865 ? deletedPackage.childPackages.size() : 0; 15866 final int newChildCount = (newPackage.childPackages != null) 15867 ? newPackage.childPackages.size() : 0; 15868 for (int i = 0; i < deletedChildCount; i++) { 15869 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 15870 boolean childPackageDeleted = true; 15871 for (int j = 0; j < newChildCount; j++) { 15872 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 15873 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 15874 childPackageDeleted = false; 15875 break; 15876 } 15877 } 15878 if (childPackageDeleted) { 15879 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 15880 deletedChildPkg.packageName); 15881 if (ps != null && res.removedInfo.removedChildPackages != null) { 15882 PackageRemovedInfo removedChildRes = res.removedInfo 15883 .removedChildPackages.get(deletedChildPkg.packageName); 15884 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 15885 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 15886 } 15887 } 15888 } 15889 15890 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 15891 installReason); 15892 prepareAppDataAfterInstallLIF(newPackage); 15893 15894 mDexManager.notifyPackageUpdated(newPackage.packageName, 15895 newPackage.baseCodePath, newPackage.splitCodePaths); 15896 } 15897 } catch (PackageManagerException e) { 15898 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 15899 res.setError("Package couldn't be installed in " + pkg.codePath, e); 15900 } 15901 15902 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 15903 // Re installation failed. Restore old information 15904 // Remove new pkg information 15905 if (newPackage != null) { 15906 removeInstalledPackageLI(newPackage, true); 15907 } 15908 // Add back the old system package 15909 try { 15910 scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 15911 } catch (PackageManagerException e) { 15912 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 15913 } 15914 15915 synchronized (mPackages) { 15916 if (disabledSystem) { 15917 enableSystemPackageLPw(deletedPackage); 15918 } 15919 15920 // Ensure the installer package name up to date 15921 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 15922 15923 // Update permissions for restored package 15924 mPermissionManager.updatePermissions( 15925 deletedPackage.packageName, deletedPackage, false, mPackages.values(), 15926 mPermissionCallback); 15927 15928 mSettings.writeLPr(); 15929 } 15930 15931 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 15932 + " after failed upgrade"); 15933 } 15934 } 15935 15936 /** 15937 * Checks whether the parent or any of the child packages have a change shared 15938 * user. For a package to be a valid update the shred users of the parent and 15939 * the children should match. We may later support changing child shared users. 15940 * @param oldPkg The updated package. 15941 * @param newPkg The update package. 15942 * @return The shared user that change between the versions. 15943 */ 15944 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 15945 PackageParser.Package newPkg) { 15946 // Check parent shared user 15947 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 15948 return newPkg.packageName; 15949 } 15950 // Check child shared users 15951 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 15952 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 15953 for (int i = 0; i < newChildCount; i++) { 15954 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 15955 // If this child was present, did it have the same shared user? 15956 for (int j = 0; j < oldChildCount; j++) { 15957 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 15958 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 15959 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 15960 return newChildPkg.packageName; 15961 } 15962 } 15963 } 15964 return null; 15965 } 15966 15967 private void removeNativeBinariesLI(PackageSetting ps) { 15968 // Remove the lib path for the parent package 15969 if (ps != null) { 15970 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 15971 // Remove the lib path for the child packages 15972 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 15973 for (int i = 0; i < childCount; i++) { 15974 PackageSetting childPs = null; 15975 synchronized (mPackages) { 15976 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 15977 } 15978 if (childPs != null) { 15979 NativeLibraryHelper.removeNativeBinariesLI(childPs 15980 .legacyNativeLibraryPathString); 15981 } 15982 } 15983 } 15984 } 15985 15986 private void enableSystemPackageLPw(PackageParser.Package pkg) { 15987 // Enable the parent package 15988 mSettings.enableSystemPackageLPw(pkg.packageName); 15989 // Enable the child packages 15990 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15991 for (int i = 0; i < childCount; i++) { 15992 PackageParser.Package childPkg = pkg.childPackages.get(i); 15993 mSettings.enableSystemPackageLPw(childPkg.packageName); 15994 } 15995 } 15996 15997 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 15998 PackageParser.Package newPkg) { 15999 // Disable the parent package (parent always replaced) 16000 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 16001 // Disable the child packages 16002 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 16003 for (int i = 0; i < childCount; i++) { 16004 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 16005 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 16006 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 16007 } 16008 return disabled; 16009 } 16010 16011 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 16012 String installerPackageName) { 16013 // Enable the parent package 16014 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 16015 // Enable the child packages 16016 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16017 for (int i = 0; i < childCount; i++) { 16018 PackageParser.Package childPkg = pkg.childPackages.get(i); 16019 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 16020 } 16021 } 16022 16023 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 16024 int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) { 16025 // Update the parent package setting 16026 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 16027 res, user, installReason); 16028 // Update the child packages setting 16029 final int childCount = (newPackage.childPackages != null) 16030 ? newPackage.childPackages.size() : 0; 16031 for (int i = 0; i < childCount; i++) { 16032 PackageParser.Package childPackage = newPackage.childPackages.get(i); 16033 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 16034 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 16035 childRes.origUsers, childRes, user, installReason); 16036 } 16037 } 16038 16039 private void updateSettingsInternalLI(PackageParser.Package pkg, 16040 String installerPackageName, int[] allUsers, int[] installedForUsers, 16041 PackageInstalledInfo res, UserHandle user, int installReason) { 16042 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 16043 16044 String pkgName = pkg.packageName; 16045 synchronized (mPackages) { 16046 //write settings. the installStatus will be incomplete at this stage. 16047 //note that the new package setting would have already been 16048 //added to mPackages. It hasn't been persisted yet. 16049 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 16050 // TODO: Remove this write? It's also written at the end of this method 16051 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 16052 mSettings.writeLPr(); 16053 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16054 } 16055 16056 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + pkg.codePath); 16057 synchronized (mPackages) { 16058// NOTE: This changes slightly to include UPDATE_PERMISSIONS_ALL regardless of the size of pkg.permissions 16059 mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(), 16060 mPermissionCallback); 16061 // For system-bundled packages, we assume that installing an upgraded version 16062 // of the package implies that the user actually wants to run that new code, 16063 // so we enable the package. 16064 PackageSetting ps = mSettings.mPackages.get(pkgName); 16065 final int userId = user.getIdentifier(); 16066 if (ps != null) { 16067 if (isSystemApp(pkg)) { 16068 if (DEBUG_INSTALL) { 16069 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 16070 } 16071 // Enable system package for requested users 16072 if (res.origUsers != null) { 16073 for (int origUserId : res.origUsers) { 16074 if (userId == UserHandle.USER_ALL || userId == origUserId) { 16075 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 16076 origUserId, installerPackageName); 16077 } 16078 } 16079 } 16080 // Also convey the prior install/uninstall state 16081 if (allUsers != null && installedForUsers != null) { 16082 for (int currentUserId : allUsers) { 16083 final boolean installed = ArrayUtils.contains( 16084 installedForUsers, currentUserId); 16085 if (DEBUG_INSTALL) { 16086 Slog.d(TAG, " user " + currentUserId + " => " + installed); 16087 } 16088 ps.setInstalled(installed, currentUserId); 16089 } 16090 // these install state changes will be persisted in the 16091 // upcoming call to mSettings.writeLPr(). 16092 } 16093 } 16094 // It's implied that when a user requests installation, they want the app to be 16095 // installed and enabled. 16096 if (userId != UserHandle.USER_ALL) { 16097 ps.setInstalled(true, userId); 16098 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 16099 } 16100 16101 // When replacing an existing package, preserve the original install reason for all 16102 // users that had the package installed before. 16103 final Set<Integer> previousUserIds = new ArraySet<>(); 16104 if (res.removedInfo != null && res.removedInfo.installReasons != null) { 16105 final int installReasonCount = res.removedInfo.installReasons.size(); 16106 for (int i = 0; i < installReasonCount; i++) { 16107 final int previousUserId = res.removedInfo.installReasons.keyAt(i); 16108 final int previousInstallReason = res.removedInfo.installReasons.valueAt(i); 16109 ps.setInstallReason(previousInstallReason, previousUserId); 16110 previousUserIds.add(previousUserId); 16111 } 16112 } 16113 16114 // Set install reason for users that are having the package newly installed. 16115 if (userId == UserHandle.USER_ALL) { 16116 for (int currentUserId : sUserManager.getUserIds()) { 16117 if (!previousUserIds.contains(currentUserId)) { 16118 ps.setInstallReason(installReason, currentUserId); 16119 } 16120 } 16121 } else if (!previousUserIds.contains(userId)) { 16122 ps.setInstallReason(installReason, userId); 16123 } 16124 mSettings.writeKernelMappingLPr(ps); 16125 } 16126 res.name = pkgName; 16127 res.uid = pkg.applicationInfo.uid; 16128 res.pkg = pkg; 16129 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 16130 mSettings.setInstallerPackageName(pkgName, installerPackageName); 16131 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16132 //to update install status 16133 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 16134 mSettings.writeLPr(); 16135 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16136 } 16137 16138 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16139 } 16140 16141 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 16142 try { 16143 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 16144 installPackageLI(args, res); 16145 } finally { 16146 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16147 } 16148 } 16149 16150 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 16151 final int installFlags = args.installFlags; 16152 final String installerPackageName = args.installerPackageName; 16153 final String volumeUuid = args.volumeUuid; 16154 final File tmpPackageFile = new File(args.getCodePath()); 16155 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 16156 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 16157 || (args.volumeUuid != null)); 16158 final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0); 16159 final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0); 16160 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 16161 final boolean virtualPreload = 16162 ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0); 16163 boolean replace = false; 16164 @ScanFlags int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 16165 if (args.move != null) { 16166 // moving a complete application; perform an initial scan on the new install location 16167 scanFlags |= SCAN_INITIAL; 16168 } 16169 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 16170 scanFlags |= SCAN_DONT_KILL_APP; 16171 } 16172 if (instantApp) { 16173 scanFlags |= SCAN_AS_INSTANT_APP; 16174 } 16175 if (fullApp) { 16176 scanFlags |= SCAN_AS_FULL_APP; 16177 } 16178 if (virtualPreload) { 16179 scanFlags |= SCAN_AS_VIRTUAL_PRELOAD; 16180 } 16181 16182 // Result object to be returned 16183 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16184 res.installerPackageName = installerPackageName; 16185 16186 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 16187 16188 // Sanity check 16189 if (instantApp && (forwardLocked || onExternal)) { 16190 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 16191 + " external=" + onExternal); 16192 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 16193 return; 16194 } 16195 16196 // Retrieve PackageSettings and parse package 16197 @ParseFlags final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 16198 | PackageParser.PARSE_ENFORCE_CODE 16199 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 16200 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 16201 | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0) 16202 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 16203 PackageParser pp = new PackageParser(); 16204 pp.setSeparateProcesses(mSeparateProcesses); 16205 pp.setDisplayMetrics(mMetrics); 16206 pp.setCallback(mPackageParserCallback); 16207 16208 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 16209 final PackageParser.Package pkg; 16210 try { 16211 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 16212 } catch (PackageParserException e) { 16213 res.setError("Failed parse during installPackageLI", e); 16214 return; 16215 } finally { 16216 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16217 } 16218 16219 // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2 16220 if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) { 16221 Slog.w(TAG, "Instant app package " + pkg.packageName + " does not target O"); 16222 res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE, 16223 "Instant app package must target O"); 16224 return; 16225 } 16226 if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) { 16227 Slog.w(TAG, "Instant app package " + pkg.packageName 16228 + " does not target targetSandboxVersion 2"); 16229 res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE, 16230 "Instant app package must use targetSanboxVersion 2"); 16231 return; 16232 } 16233 16234 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16235 // Static shared libraries have synthetic package names 16236 renameStaticSharedLibraryPackage(pkg); 16237 16238 // No static shared libs on external storage 16239 if (onExternal) { 16240 Slog.i(TAG, "Static shared libs can only be installed on internal storage."); 16241 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 16242 "Packages declaring static-shared libs cannot be updated"); 16243 return; 16244 } 16245 } 16246 16247 // If we are installing a clustered package add results for the children 16248 if (pkg.childPackages != null) { 16249 synchronized (mPackages) { 16250 final int childCount = pkg.childPackages.size(); 16251 for (int i = 0; i < childCount; i++) { 16252 PackageParser.Package childPkg = pkg.childPackages.get(i); 16253 PackageInstalledInfo childRes = new PackageInstalledInfo(); 16254 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16255 childRes.pkg = childPkg; 16256 childRes.name = childPkg.packageName; 16257 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 16258 if (childPs != null) { 16259 childRes.origUsers = childPs.queryInstalledUsers( 16260 sUserManager.getUserIds(), true); 16261 } 16262 if ((mPackages.containsKey(childPkg.packageName))) { 16263 childRes.removedInfo = new PackageRemovedInfo(this); 16264 childRes.removedInfo.removedPackage = childPkg.packageName; 16265 childRes.removedInfo.installerPackageName = childPs.installerPackageName; 16266 } 16267 if (res.addedChildPackages == null) { 16268 res.addedChildPackages = new ArrayMap<>(); 16269 } 16270 res.addedChildPackages.put(childPkg.packageName, childRes); 16271 } 16272 } 16273 } 16274 16275 // If package doesn't declare API override, mark that we have an install 16276 // time CPU ABI override. 16277 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 16278 pkg.cpuAbiOverride = args.abiOverride; 16279 } 16280 16281 String pkgName = res.name = pkg.packageName; 16282 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 16283 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 16284 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 16285 return; 16286 } 16287 } 16288 16289 try { 16290 // either use what we've been given or parse directly from the APK 16291 if (args.certificates != null) { 16292 try { 16293 PackageParser.populateCertificates(pkg, args.certificates); 16294 } catch (PackageParserException e) { 16295 // there was something wrong with the certificates we were given; 16296 // try to pull them from the APK 16297 PackageParser.collectCertificates(pkg, parseFlags); 16298 } 16299 } else { 16300 PackageParser.collectCertificates(pkg, parseFlags); 16301 } 16302 } catch (PackageParserException e) { 16303 res.setError("Failed collect during installPackageLI", e); 16304 return; 16305 } 16306 16307 // Get rid of all references to package scan path via parser. 16308 pp = null; 16309 String oldCodePath = null; 16310 boolean systemApp = false; 16311 synchronized (mPackages) { 16312 // Check if installing already existing package 16313 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 16314 String oldName = mSettings.getRenamedPackageLPr(pkgName); 16315 if (pkg.mOriginalPackages != null 16316 && pkg.mOriginalPackages.contains(oldName) 16317 && mPackages.containsKey(oldName)) { 16318 // This package is derived from an original package, 16319 // and this device has been updating from that original 16320 // name. We must continue using the original name, so 16321 // rename the new package here. 16322 pkg.setPackageName(oldName); 16323 pkgName = pkg.packageName; 16324 replace = true; 16325 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 16326 + oldName + " pkgName=" + pkgName); 16327 } else if (mPackages.containsKey(pkgName)) { 16328 // This package, under its official name, already exists 16329 // on the device; we should replace it. 16330 replace = true; 16331 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 16332 } 16333 16334 // Child packages are installed through the parent package 16335 if (pkg.parentPackage != null) { 16336 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 16337 "Package " + pkg.packageName + " is child of package " 16338 + pkg.parentPackage.parentPackage + ". Child packages " 16339 + "can be updated only through the parent package."); 16340 return; 16341 } 16342 16343 if (replace) { 16344 // Prevent apps opting out from runtime permissions 16345 PackageParser.Package oldPackage = mPackages.get(pkgName); 16346 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 16347 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 16348 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 16349 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 16350 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 16351 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 16352 + " doesn't support runtime permissions but the old" 16353 + " target SDK " + oldTargetSdk + " does."); 16354 return; 16355 } 16356 // Prevent apps from downgrading their targetSandbox. 16357 final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion; 16358 final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion; 16359 if (oldTargetSandbox == 2 && newTargetSandbox != 2) { 16360 res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE, 16361 "Package " + pkg.packageName + " new target sandbox " 16362 + newTargetSandbox + " is incompatible with the previous value of" 16363 + oldTargetSandbox + "."); 16364 return; 16365 } 16366 16367 // Prevent installing of child packages 16368 if (oldPackage.parentPackage != null) { 16369 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 16370 "Package " + pkg.packageName + " is child of package " 16371 + oldPackage.parentPackage + ". Child packages " 16372 + "can be updated only through the parent package."); 16373 return; 16374 } 16375 } 16376 } 16377 16378 PackageSetting ps = mSettings.mPackages.get(pkgName); 16379 if (ps != null) { 16380 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 16381 16382 // Static shared libs have same package with different versions where 16383 // we internally use a synthetic package name to allow multiple versions 16384 // of the same package, therefore we need to compare signatures against 16385 // the package setting for the latest library version. 16386 PackageSetting signatureCheckPs = ps; 16387 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16388 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg); 16389 if (libraryEntry != null) { 16390 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk); 16391 } 16392 } 16393 16394 // Quick sanity check that we're signed correctly if updating; 16395 // we'll check this again later when scanning, but we want to 16396 // bail early here before tripping over redefined permissions. 16397 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 16398 if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) { 16399 if (!ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) { 16400 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 16401 + pkg.packageName + " upgrade keys do not match the " 16402 + "previously installed version"); 16403 return; 16404 } 16405 } else { 16406 try { 16407 final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg); 16408 final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg); 16409 final boolean compatMatch = verifySignatures( 16410 signatureCheckPs, pkg.mSignatures, compareCompat, compareRecover); 16411 // The new KeySets will be re-added later in the scanning process. 16412 if (compatMatch) { 16413 synchronized (mPackages) { 16414 ksms.removeAppKeySetDataLPw(pkg.packageName); 16415 } 16416 } 16417 } catch (PackageManagerException e) { 16418 res.setError(e.error, e.getMessage()); 16419 return; 16420 } 16421 } 16422 16423 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 16424 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 16425 systemApp = (ps.pkg.applicationInfo.flags & 16426 ApplicationInfo.FLAG_SYSTEM) != 0; 16427 } 16428 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 16429 } 16430 16431 int N = pkg.permissions.size(); 16432 for (int i = N-1; i >= 0; i--) { 16433 final PackageParser.Permission perm = pkg.permissions.get(i); 16434 final BasePermission bp = 16435 (BasePermission) mPermissionManager.getPermissionTEMP(perm.info.name); 16436 16437 // Don't allow anyone but the system to define ephemeral permissions. 16438 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0 16439 && !systemApp) { 16440 Slog.w(TAG, "Non-System package " + pkg.packageName 16441 + " attempting to delcare ephemeral permission " 16442 + perm.info.name + "; Removing ephemeral."); 16443 perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTANT; 16444 } 16445 16446 // Check whether the newly-scanned package wants to define an already-defined perm 16447 if (bp != null) { 16448 // If the defining package is signed with our cert, it's okay. This 16449 // also includes the "updating the same package" case, of course. 16450 // "updating same package" could also involve key-rotation. 16451 final boolean sigsOk; 16452 final String sourcePackageName = bp.getSourcePackageName(); 16453 final PackageSettingBase sourcePackageSetting = bp.getSourcePackageSetting(); 16454 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 16455 if (sourcePackageName.equals(pkg.packageName) 16456 && (ksms.shouldCheckUpgradeKeySetLocked( 16457 sourcePackageSetting, scanFlags))) { 16458 sigsOk = ksms.checkUpgradeKeySetLocked(sourcePackageSetting, pkg); 16459 } else { 16460 sigsOk = compareSignatures(sourcePackageSetting.signatures.mSignatures, 16461 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 16462 } 16463 if (!sigsOk) { 16464 // If the owning package is the system itself, we log but allow 16465 // install to proceed; we fail the install on all other permission 16466 // redefinitions. 16467 if (!sourcePackageName.equals("android")) { 16468 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 16469 + pkg.packageName + " attempting to redeclare permission " 16470 + perm.info.name + " already owned by " + sourcePackageName); 16471 res.origPermission = perm.info.name; 16472 res.origPackage = sourcePackageName; 16473 return; 16474 } else { 16475 Slog.w(TAG, "Package " + pkg.packageName 16476 + " attempting to redeclare system permission " 16477 + perm.info.name + "; ignoring new declaration"); 16478 pkg.permissions.remove(i); 16479 } 16480 } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) { 16481 // Prevent apps to change protection level to dangerous from any other 16482 // type as this would allow a privilege escalation where an app adds a 16483 // normal/signature permission in other app's group and later redefines 16484 // it as dangerous leading to the group auto-grant. 16485 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE) 16486 == PermissionInfo.PROTECTION_DANGEROUS) { 16487 if (bp != null && !bp.isRuntime()) { 16488 Slog.w(TAG, "Package " + pkg.packageName + " trying to change a " 16489 + "non-runtime permission " + perm.info.name 16490 + " to runtime; keeping old protection level"); 16491 perm.info.protectionLevel = bp.getProtectionLevel(); 16492 } 16493 } 16494 } 16495 } 16496 } 16497 } 16498 16499 if (systemApp) { 16500 if (onExternal) { 16501 // Abort update; system app can't be replaced with app on sdcard 16502 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 16503 "Cannot install updates to system apps on sdcard"); 16504 return; 16505 } else if (instantApp) { 16506 // Abort update; system app can't be replaced with an instant app 16507 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID, 16508 "Cannot update a system app with an instant app"); 16509 return; 16510 } 16511 } 16512 16513 if (args.move != null) { 16514 // We did an in-place move, so dex is ready to roll 16515 scanFlags |= SCAN_NO_DEX; 16516 scanFlags |= SCAN_MOVE; 16517 16518 synchronized (mPackages) { 16519 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16520 if (ps == null) { 16521 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 16522 "Missing settings for moved package " + pkgName); 16523 } 16524 16525 // We moved the entire application as-is, so bring over the 16526 // previously derived ABI information. 16527 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 16528 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 16529 } 16530 16531 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 16532 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 16533 scanFlags |= SCAN_NO_DEX; 16534 16535 try { 16536 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 16537 args.abiOverride : pkg.cpuAbiOverride); 16538 final boolean extractNativeLibs = !pkg.isLibrary(); 16539 derivePackageAbi(pkg, abiOverride, extractNativeLibs, mAppLib32InstallDir); 16540 } catch (PackageManagerException pme) { 16541 Slog.e(TAG, "Error deriving application ABI", pme); 16542 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 16543 return; 16544 } 16545 16546 // Shared libraries for the package need to be updated. 16547 synchronized (mPackages) { 16548 try { 16549 updateSharedLibrariesLPr(pkg, null); 16550 } catch (PackageManagerException e) { 16551 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 16552 } 16553 } 16554 } 16555 16556 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 16557 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 16558 return; 16559 } 16560 16561 // Verify if we need to dexopt the app. 16562 // 16563 // NOTE: it is *important* to call dexopt after doRename which will sync the 16564 // package data from PackageParser.Package and its corresponding ApplicationInfo. 16565 // 16566 // We only need to dexopt if the package meets ALL of the following conditions: 16567 // 1) it is not forward locked. 16568 // 2) it is not on on an external ASEC container. 16569 // 3) it is not an instant app or if it is then dexopt is enabled via gservices. 16570 // 16571 // Note that we do not dexopt instant apps by default. dexopt can take some time to 16572 // complete, so we skip this step during installation. Instead, we'll take extra time 16573 // the first time the instant app starts. It's preferred to do it this way to provide 16574 // continuous progress to the useur instead of mysteriously blocking somewhere in the 16575 // middle of running an instant app. The default behaviour can be overridden 16576 // via gservices. 16577 final boolean performDexopt = !forwardLocked 16578 && !pkg.applicationInfo.isExternalAsec() 16579 && (!instantApp || Global.getInt(mContext.getContentResolver(), 16580 Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0); 16581 16582 if (performDexopt) { 16583 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 16584 // Do not run PackageDexOptimizer through the local performDexOpt 16585 // method because `pkg` may not be in `mPackages` yet. 16586 // 16587 // Also, don't fail application installs if the dexopt step fails. 16588 DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName, 16589 REASON_INSTALL, 16590 DexoptOptions.DEXOPT_BOOT_COMPLETE); 16591 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 16592 null /* instructionSets */, 16593 getOrCreateCompilerPackageStats(pkg), 16594 mDexManager.getPackageUseInfoOrDefault(pkg.packageName), 16595 dexoptOptions); 16596 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16597 } 16598 16599 // Notify BackgroundDexOptService that the package has been changed. 16600 // If this is an update of a package which used to fail to compile, 16601 // BackgroundDexOptService will remove it from its blacklist. 16602 // TODO: Layering violation 16603 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 16604 16605 if (!instantApp) { 16606 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 16607 } else { 16608 if (DEBUG_DOMAIN_VERIFICATION) { 16609 Slog.d(TAG, "Not verifying instant app install for app links: " + pkgName); 16610 } 16611 } 16612 16613 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 16614 "installPackageLI")) { 16615 if (replace) { 16616 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16617 // Static libs have a synthetic package name containing the version 16618 // and cannot be updated as an update would get a new package name, 16619 // unless this is the exact same version code which is useful for 16620 // development. 16621 PackageParser.Package existingPkg = mPackages.get(pkg.packageName); 16622 if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) { 16623 res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring " 16624 + "static-shared libs cannot be updated"); 16625 return; 16626 } 16627 } 16628 replacePackageLIF(pkg, parseFlags, scanFlags, args.user, 16629 installerPackageName, res, args.installReason); 16630 } else { 16631 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 16632 args.user, installerPackageName, volumeUuid, res, args.installReason); 16633 } 16634 } 16635 16636 synchronized (mPackages) { 16637 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16638 if (ps != null) { 16639 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 16640 ps.setUpdateAvailable(false /*updateAvailable*/); 16641 } 16642 16643 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16644 for (int i = 0; i < childCount; i++) { 16645 PackageParser.Package childPkg = pkg.childPackages.get(i); 16646 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 16647 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 16648 if (childPs != null) { 16649 childRes.newUsers = childPs.queryInstalledUsers( 16650 sUserManager.getUserIds(), true); 16651 } 16652 } 16653 16654 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 16655 updateSequenceNumberLP(ps, res.newUsers); 16656 updateInstantAppInstallerLocked(pkgName); 16657 } 16658 } 16659 } 16660 16661 private void startIntentFilterVerifications(int userId, boolean replacing, 16662 PackageParser.Package pkg) { 16663 if (mIntentFilterVerifierComponent == null) { 16664 Slog.w(TAG, "No IntentFilter verification will not be done as " 16665 + "there is no IntentFilterVerifier available!"); 16666 return; 16667 } 16668 16669 final int verifierUid = getPackageUid( 16670 mIntentFilterVerifierComponent.getPackageName(), 16671 MATCH_DEBUG_TRIAGED_MISSING, 16672 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 16673 16674 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 16675 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 16676 mHandler.sendMessage(msg); 16677 16678 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16679 for (int i = 0; i < childCount; i++) { 16680 PackageParser.Package childPkg = pkg.childPackages.get(i); 16681 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 16682 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 16683 mHandler.sendMessage(msg); 16684 } 16685 } 16686 16687 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 16688 PackageParser.Package pkg) { 16689 int size = pkg.activities.size(); 16690 if (size == 0) { 16691 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 16692 "No activity, so no need to verify any IntentFilter!"); 16693 return; 16694 } 16695 16696 final boolean hasDomainURLs = hasDomainURLs(pkg); 16697 if (!hasDomainURLs) { 16698 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 16699 "No domain URLs, so no need to verify any IntentFilter!"); 16700 return; 16701 } 16702 16703 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 16704 + " if any IntentFilter from the " + size 16705 + " Activities needs verification ..."); 16706 16707 int count = 0; 16708 final String packageName = pkg.packageName; 16709 16710 synchronized (mPackages) { 16711 // If this is a new install and we see that we've already run verification for this 16712 // package, we have nothing to do: it means the state was restored from backup. 16713 if (!replacing) { 16714 IntentFilterVerificationInfo ivi = 16715 mSettings.getIntentFilterVerificationLPr(packageName); 16716 if (ivi != null) { 16717 if (DEBUG_DOMAIN_VERIFICATION) { 16718 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 16719 + ivi.getStatusString()); 16720 } 16721 return; 16722 } 16723 } 16724 16725 // If any filters need to be verified, then all need to be. 16726 boolean needToVerify = false; 16727 for (PackageParser.Activity a : pkg.activities) { 16728 for (ActivityIntentInfo filter : a.intents) { 16729 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 16730 if (DEBUG_DOMAIN_VERIFICATION) { 16731 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 16732 } 16733 needToVerify = true; 16734 break; 16735 } 16736 } 16737 } 16738 16739 if (needToVerify) { 16740 final int verificationId = mIntentFilterVerificationToken++; 16741 for (PackageParser.Activity a : pkg.activities) { 16742 for (ActivityIntentInfo filter : a.intents) { 16743 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 16744 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 16745 "Verification needed for IntentFilter:" + filter.toString()); 16746 mIntentFilterVerifier.addOneIntentFilterVerification( 16747 verifierUid, userId, verificationId, filter, packageName); 16748 count++; 16749 } 16750 } 16751 } 16752 } 16753 } 16754 16755 if (count > 0) { 16756 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 16757 + " IntentFilter verification" + (count > 1 ? "s" : "") 16758 + " for userId:" + userId); 16759 mIntentFilterVerifier.startVerifications(userId); 16760 } else { 16761 if (DEBUG_DOMAIN_VERIFICATION) { 16762 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 16763 } 16764 } 16765 } 16766 16767 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 16768 final ComponentName cn = filter.activity.getComponentName(); 16769 final String packageName = cn.getPackageName(); 16770 16771 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 16772 packageName); 16773 if (ivi == null) { 16774 return true; 16775 } 16776 int status = ivi.getStatus(); 16777 switch (status) { 16778 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 16779 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 16780 return true; 16781 16782 default: 16783 // Nothing to do 16784 return false; 16785 } 16786 } 16787 16788 private static boolean isMultiArch(ApplicationInfo info) { 16789 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 16790 } 16791 16792 private static boolean isExternal(PackageParser.Package pkg) { 16793 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 16794 } 16795 16796 private static boolean isExternal(PackageSetting ps) { 16797 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 16798 } 16799 16800 private static boolean isSystemApp(PackageParser.Package pkg) { 16801 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 16802 } 16803 16804 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 16805 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 16806 } 16807 16808 private static boolean isOemApp(PackageParser.Package pkg) { 16809 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0; 16810 } 16811 16812 private static boolean isVendorApp(PackageParser.Package pkg) { 16813 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0; 16814 } 16815 16816 private static boolean hasDomainURLs(PackageParser.Package pkg) { 16817 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 16818 } 16819 16820 private static boolean isSystemApp(PackageSetting ps) { 16821 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 16822 } 16823 16824 private static boolean isUpdatedSystemApp(PackageSetting ps) { 16825 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 16826 } 16827 16828 private int packageFlagsToInstallFlags(PackageSetting ps) { 16829 int installFlags = 0; 16830 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 16831 // This existing package was an external ASEC install when we have 16832 // the external flag without a UUID 16833 installFlags |= PackageManager.INSTALL_EXTERNAL; 16834 } 16835 if (ps.isForwardLocked()) { 16836 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 16837 } 16838 return installFlags; 16839 } 16840 16841 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 16842 if (isExternal(pkg)) { 16843 if (TextUtils.isEmpty(pkg.volumeUuid)) { 16844 return mSettings.getExternalVersion(); 16845 } else { 16846 return mSettings.findOrCreateVersion(pkg.volumeUuid); 16847 } 16848 } else { 16849 return mSettings.getInternalVersion(); 16850 } 16851 } 16852 16853 private void deleteTempPackageFiles() { 16854 final FilenameFilter filter = new FilenameFilter() { 16855 public boolean accept(File dir, String name) { 16856 return name.startsWith("vmdl") && name.endsWith(".tmp"); 16857 } 16858 }; 16859 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 16860 file.delete(); 16861 } 16862 } 16863 16864 @Override 16865 public void deletePackageAsUser(String packageName, int versionCode, 16866 IPackageDeleteObserver observer, int userId, int flags) { 16867 deletePackageVersioned(new VersionedPackage(packageName, versionCode), 16868 new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags); 16869 } 16870 16871 @Override 16872 public void deletePackageVersioned(VersionedPackage versionedPackage, 16873 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 16874 final int callingUid = Binder.getCallingUid(); 16875 mContext.enforceCallingOrSelfPermission( 16876 android.Manifest.permission.DELETE_PACKAGES, null); 16877 final boolean canViewInstantApps = canViewInstantApps(callingUid, userId); 16878 Preconditions.checkNotNull(versionedPackage); 16879 Preconditions.checkNotNull(observer); 16880 Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(), 16881 PackageManager.VERSION_CODE_HIGHEST, 16882 Integer.MAX_VALUE, "versionCode must be >= -1"); 16883 16884 final String packageName = versionedPackage.getPackageName(); 16885 final int versionCode = versionedPackage.getVersionCode(); 16886 final String internalPackageName; 16887 synchronized (mPackages) { 16888 // Normalize package name to handle renamed packages and static libs 16889 internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(), 16890 versionedPackage.getVersionCode()); 16891 } 16892 16893 final int uid = Binder.getCallingUid(); 16894 if (!isOrphaned(internalPackageName) 16895 && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) { 16896 try { 16897 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 16898 intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null)); 16899 intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder()); 16900 observer.onUserActionRequired(intent); 16901 } catch (RemoteException re) { 16902 } 16903 return; 16904 } 16905 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 16906 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 16907 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 16908 mContext.enforceCallingOrSelfPermission( 16909 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 16910 "deletePackage for user " + userId); 16911 } 16912 16913 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 16914 try { 16915 observer.onPackageDeleted(packageName, 16916 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 16917 } catch (RemoteException re) { 16918 } 16919 return; 16920 } 16921 16922 if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) { 16923 try { 16924 observer.onPackageDeleted(packageName, 16925 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 16926 } catch (RemoteException re) { 16927 } 16928 return; 16929 } 16930 16931 if (DEBUG_REMOVE) { 16932 Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId 16933 + " deleteAllUsers: " + deleteAllUsers + " version=" 16934 + (versionCode == PackageManager.VERSION_CODE_HIGHEST 16935 ? "VERSION_CODE_HIGHEST" : versionCode)); 16936 } 16937 // Queue up an async operation since the package deletion may take a little while. 16938 mHandler.post(new Runnable() { 16939 public void run() { 16940 mHandler.removeCallbacks(this); 16941 int returnCode; 16942 final PackageSetting ps = mSettings.mPackages.get(internalPackageName); 16943 boolean doDeletePackage = true; 16944 if (ps != null) { 16945 final boolean targetIsInstantApp = 16946 ps.getInstantApp(UserHandle.getUserId(callingUid)); 16947 doDeletePackage = !targetIsInstantApp 16948 || canViewInstantApps; 16949 } 16950 if (doDeletePackage) { 16951 if (!deleteAllUsers) { 16952 returnCode = deletePackageX(internalPackageName, versionCode, 16953 userId, deleteFlags); 16954 } else { 16955 int[] blockUninstallUserIds = getBlockUninstallForUsers( 16956 internalPackageName, users); 16957 // If nobody is blocking uninstall, proceed with delete for all users 16958 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 16959 returnCode = deletePackageX(internalPackageName, versionCode, 16960 userId, deleteFlags); 16961 } else { 16962 // Otherwise uninstall individually for users with blockUninstalls=false 16963 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 16964 for (int userId : users) { 16965 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 16966 returnCode = deletePackageX(internalPackageName, versionCode, 16967 userId, userFlags); 16968 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 16969 Slog.w(TAG, "Package delete failed for user " + userId 16970 + ", returnCode " + returnCode); 16971 } 16972 } 16973 } 16974 // The app has only been marked uninstalled for certain users. 16975 // We still need to report that delete was blocked 16976 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 16977 } 16978 } 16979 } else { 16980 returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR; 16981 } 16982 try { 16983 observer.onPackageDeleted(packageName, returnCode, null); 16984 } catch (RemoteException e) { 16985 Log.i(TAG, "Observer no longer exists."); 16986 } //end catch 16987 } //end run 16988 }); 16989 } 16990 16991 private String resolveExternalPackageNameLPr(PackageParser.Package pkg) { 16992 if (pkg.staticSharedLibName != null) { 16993 return pkg.manifestPackageName; 16994 } 16995 return pkg.packageName; 16996 } 16997 16998 private String resolveInternalPackageNameLPr(String packageName, int versionCode) { 16999 // Handle renamed packages 17000 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 17001 packageName = normalizedPackageName != null ? normalizedPackageName : packageName; 17002 17003 // Is this a static library? 17004 SparseArray<SharedLibraryEntry> versionedLib = 17005 mStaticLibsByDeclaringPackage.get(packageName); 17006 if (versionedLib == null || versionedLib.size() <= 0) { 17007 return packageName; 17008 } 17009 17010 // Figure out which lib versions the caller can see 17011 SparseIntArray versionsCallerCanSee = null; 17012 final int callingAppId = UserHandle.getAppId(Binder.getCallingUid()); 17013 if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID 17014 && callingAppId != Process.ROOT_UID) { 17015 versionsCallerCanSee = new SparseIntArray(); 17016 String libName = versionedLib.valueAt(0).info.getName(); 17017 String[] uidPackages = getPackagesForUid(Binder.getCallingUid()); 17018 if (uidPackages != null) { 17019 for (String uidPackage : uidPackages) { 17020 PackageSetting ps = mSettings.getPackageLPr(uidPackage); 17021 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 17022 if (libIdx >= 0) { 17023 final int libVersion = ps.usesStaticLibrariesVersions[libIdx]; 17024 versionsCallerCanSee.append(libVersion, libVersion); 17025 } 17026 } 17027 } 17028 } 17029 17030 // Caller can see nothing - done 17031 if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) { 17032 return packageName; 17033 } 17034 17035 // Find the version the caller can see and the app version code 17036 SharedLibraryEntry highestVersion = null; 17037 final int versionCount = versionedLib.size(); 17038 for (int i = 0; i < versionCount; i++) { 17039 SharedLibraryEntry libEntry = versionedLib.valueAt(i); 17040 if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey( 17041 libEntry.info.getVersion()) < 0) { 17042 continue; 17043 } 17044 final int libVersionCode = libEntry.info.getDeclaringPackage().getVersionCode(); 17045 if (versionCode != PackageManager.VERSION_CODE_HIGHEST) { 17046 if (libVersionCode == versionCode) { 17047 return libEntry.apk; 17048 } 17049 } else if (highestVersion == null) { 17050 highestVersion = libEntry; 17051 } else if (libVersionCode > highestVersion.info 17052 .getDeclaringPackage().getVersionCode()) { 17053 highestVersion = libEntry; 17054 } 17055 } 17056 17057 if (highestVersion != null) { 17058 return highestVersion.apk; 17059 } 17060 17061 return packageName; 17062 } 17063 17064 boolean isCallerVerifier(int callingUid) { 17065 final int callingUserId = UserHandle.getUserId(callingUid); 17066 return mRequiredVerifierPackage != null && 17067 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId); 17068 } 17069 17070 private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) { 17071 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID 17072 || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 17073 return true; 17074 } 17075 final int callingUserId = UserHandle.getUserId(callingUid); 17076 // If the caller installed the pkgName, then allow it to silently uninstall. 17077 if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) { 17078 return true; 17079 } 17080 17081 // Allow package verifier to silently uninstall. 17082 if (mRequiredVerifierPackage != null && 17083 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) { 17084 return true; 17085 } 17086 17087 // Allow package uninstaller to silently uninstall. 17088 if (mRequiredUninstallerPackage != null && 17089 callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) { 17090 return true; 17091 } 17092 17093 // Allow storage manager to silently uninstall. 17094 if (mStorageManagerPackage != null && 17095 callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) { 17096 return true; 17097 } 17098 17099 // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently 17100 // uninstall for device owner provisioning. 17101 if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid) 17102 == PERMISSION_GRANTED) { 17103 return true; 17104 } 17105 17106 return false; 17107 } 17108 17109 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 17110 int[] result = EMPTY_INT_ARRAY; 17111 for (int userId : userIds) { 17112 if (getBlockUninstallForUser(packageName, userId)) { 17113 result = ArrayUtils.appendInt(result, userId); 17114 } 17115 } 17116 return result; 17117 } 17118 17119 @Override 17120 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 17121 final int callingUid = Binder.getCallingUid(); 17122 if (getInstantAppPackageName(callingUid) != null 17123 && !isCallerSameApp(packageName, callingUid)) { 17124 return false; 17125 } 17126 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 17127 } 17128 17129 private boolean isPackageDeviceAdmin(String packageName, int userId) { 17130 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 17131 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 17132 try { 17133 if (dpm != null) { 17134 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 17135 /* callingUserOnly =*/ false); 17136 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 17137 : deviceOwnerComponentName.getPackageName(); 17138 // Does the package contains the device owner? 17139 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 17140 // this check is probably not needed, since DO should be registered as a device 17141 // admin on some user too. (Original bug for this: b/17657954) 17142 if (packageName.equals(deviceOwnerPackageName)) { 17143 return true; 17144 } 17145 // Does it contain a device admin for any user? 17146 int[] users; 17147 if (userId == UserHandle.USER_ALL) { 17148 users = sUserManager.getUserIds(); 17149 } else { 17150 users = new int[]{userId}; 17151 } 17152 for (int i = 0; i < users.length; ++i) { 17153 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 17154 return true; 17155 } 17156 } 17157 } 17158 } catch (RemoteException e) { 17159 } 17160 return false; 17161 } 17162 17163 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 17164 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 17165 } 17166 17167 /** 17168 * This method is an internal method that could be get invoked either 17169 * to delete an installed package or to clean up a failed installation. 17170 * After deleting an installed package, a broadcast is sent to notify any 17171 * listeners that the package has been removed. For cleaning up a failed 17172 * installation, the broadcast is not necessary since the package's 17173 * installation wouldn't have sent the initial broadcast either 17174 * The key steps in deleting a package are 17175 * deleting the package information in internal structures like mPackages, 17176 * deleting the packages base directories through installd 17177 * updating mSettings to reflect current status 17178 * persisting settings for later use 17179 * sending a broadcast if necessary 17180 */ 17181 int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) { 17182 final PackageRemovedInfo info = new PackageRemovedInfo(this); 17183 final boolean res; 17184 17185 final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 17186 ? UserHandle.USER_ALL : userId; 17187 17188 if (isPackageDeviceAdmin(packageName, removeUser)) { 17189 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 17190 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 17191 } 17192 17193 PackageSetting uninstalledPs = null; 17194 PackageParser.Package pkg = null; 17195 17196 // for the uninstall-updates case and restricted profiles, remember the per- 17197 // user handle installed state 17198 int[] allUsers; 17199 synchronized (mPackages) { 17200 uninstalledPs = mSettings.mPackages.get(packageName); 17201 if (uninstalledPs == null) { 17202 Slog.w(TAG, "Not removing non-existent package " + packageName); 17203 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17204 } 17205 17206 if (versionCode != PackageManager.VERSION_CODE_HIGHEST 17207 && uninstalledPs.versionCode != versionCode) { 17208 Slog.w(TAG, "Not removing package " + packageName + " with versionCode " 17209 + uninstalledPs.versionCode + " != " + versionCode); 17210 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17211 } 17212 17213 // Static shared libs can be declared by any package, so let us not 17214 // allow removing a package if it provides a lib others depend on. 17215 pkg = mPackages.get(packageName); 17216 17217 allUsers = sUserManager.getUserIds(); 17218 17219 if (pkg != null && pkg.staticSharedLibName != null) { 17220 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName, 17221 pkg.staticSharedLibVersion); 17222 if (libEntry != null) { 17223 for (int currUserId : allUsers) { 17224 if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) { 17225 continue; 17226 } 17227 List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr( 17228 libEntry.info, 0, currUserId); 17229 if (!ArrayUtils.isEmpty(libClientPackages)) { 17230 Slog.w(TAG, "Not removing package " + pkg.manifestPackageName 17231 + " hosting lib " + libEntry.info.getName() + " version " 17232 + libEntry.info.getVersion() + " used by " + libClientPackages 17233 + " for user " + currUserId); 17234 return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY; 17235 } 17236 } 17237 } 17238 } 17239 17240 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 17241 } 17242 17243 final int freezeUser; 17244 if (isUpdatedSystemApp(uninstalledPs) 17245 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) { 17246 // We're downgrading a system app, which will apply to all users, so 17247 // freeze them all during the downgrade 17248 freezeUser = UserHandle.USER_ALL; 17249 } else { 17250 freezeUser = removeUser; 17251 } 17252 17253 synchronized (mInstallLock) { 17254 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 17255 try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser, 17256 deleteFlags, "deletePackageX")) { 17257 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers, 17258 deleteFlags | PackageManager.DELETE_CHATTY, info, true, null); 17259 } 17260 synchronized (mPackages) { 17261 if (res) { 17262 if (pkg != null) { 17263 mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers); 17264 } 17265 updateSequenceNumberLP(uninstalledPs, info.removedUsers); 17266 updateInstantAppInstallerLocked(packageName); 17267 } 17268 } 17269 } 17270 17271 if (res) { 17272 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 17273 info.sendPackageRemovedBroadcasts(killApp); 17274 info.sendSystemPackageUpdatedBroadcasts(); 17275 info.sendSystemPackageAppearedBroadcasts(); 17276 } 17277 // Force a gc here. 17278 Runtime.getRuntime().gc(); 17279 // Delete the resources here after sending the broadcast to let 17280 // other processes clean up before deleting resources. 17281 if (info.args != null) { 17282 synchronized (mInstallLock) { 17283 info.args.doPostDeleteLI(true); 17284 } 17285 } 17286 17287 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17288 } 17289 17290 static class PackageRemovedInfo { 17291 final PackageSender packageSender; 17292 String removedPackage; 17293 String installerPackageName; 17294 int uid = -1; 17295 int removedAppId = -1; 17296 int[] origUsers; 17297 int[] removedUsers = null; 17298 int[] broadcastUsers = null; 17299 SparseArray<Integer> installReasons; 17300 boolean isRemovedPackageSystemUpdate = false; 17301 boolean isUpdate; 17302 boolean dataRemoved; 17303 boolean removedForAllUsers; 17304 boolean isStaticSharedLib; 17305 // Clean up resources deleted packages. 17306 InstallArgs args = null; 17307 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 17308 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 17309 17310 PackageRemovedInfo(PackageSender packageSender) { 17311 this.packageSender = packageSender; 17312 } 17313 17314 void sendPackageRemovedBroadcasts(boolean killApp) { 17315 sendPackageRemovedBroadcastInternal(killApp); 17316 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 17317 for (int i = 0; i < childCount; i++) { 17318 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 17319 childInfo.sendPackageRemovedBroadcastInternal(killApp); 17320 } 17321 } 17322 17323 void sendSystemPackageUpdatedBroadcasts() { 17324 if (isRemovedPackageSystemUpdate) { 17325 sendSystemPackageUpdatedBroadcastsInternal(); 17326 final int childCount = (removedChildPackages != null) 17327 ? removedChildPackages.size() : 0; 17328 for (int i = 0; i < childCount; i++) { 17329 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 17330 if (childInfo.isRemovedPackageSystemUpdate) { 17331 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 17332 } 17333 } 17334 } 17335 } 17336 17337 void sendSystemPackageAppearedBroadcasts() { 17338 final int packageCount = (appearedChildPackages != null) 17339 ? appearedChildPackages.size() : 0; 17340 for (int i = 0; i < packageCount; i++) { 17341 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 17342 packageSender.sendPackageAddedForNewUsers(installedInfo.name, 17343 true /*sendBootCompleted*/, false /*startReceiver*/, 17344 UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers); 17345 } 17346 } 17347 17348 private void sendSystemPackageUpdatedBroadcastsInternal() { 17349 Bundle extras = new Bundle(2); 17350 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 17351 extras.putBoolean(Intent.EXTRA_REPLACING, true); 17352 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 17353 removedPackage, extras, 0, null /*targetPackage*/, null, null); 17354 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 17355 removedPackage, extras, 0, null /*targetPackage*/, null, null); 17356 packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 17357 null, null, 0, removedPackage, null, null); 17358 if (installerPackageName != null) { 17359 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 17360 removedPackage, extras, 0 /*flags*/, 17361 installerPackageName, null, null); 17362 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 17363 removedPackage, extras, 0 /*flags*/, 17364 installerPackageName, null, null); 17365 } 17366 } 17367 17368 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 17369 // Don't send static shared library removal broadcasts as these 17370 // libs are visible only the the apps that depend on them an one 17371 // cannot remove the library if it has a dependency. 17372 if (isStaticSharedLib) { 17373 return; 17374 } 17375 Bundle extras = new Bundle(2); 17376 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 17377 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 17378 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 17379 if (isUpdate || isRemovedPackageSystemUpdate) { 17380 extras.putBoolean(Intent.EXTRA_REPLACING, true); 17381 } 17382 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 17383 if (removedPackage != null) { 17384 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, 17385 removedPackage, extras, 0, null /*targetPackage*/, null, broadcastUsers); 17386 if (installerPackageName != null) { 17387 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, 17388 removedPackage, extras, 0 /*flags*/, 17389 installerPackageName, null, broadcastUsers); 17390 } 17391 if (dataRemoved && !isRemovedPackageSystemUpdate) { 17392 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 17393 removedPackage, extras, 17394 Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, 17395 null, null, broadcastUsers); 17396 } 17397 } 17398 if (removedAppId >= 0) { 17399 packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED, 17400 null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, 17401 null, null, broadcastUsers); 17402 } 17403 } 17404 17405 void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) { 17406 removedUsers = userIds; 17407 if (removedUsers == null) { 17408 broadcastUsers = null; 17409 return; 17410 } 17411 17412 broadcastUsers = EMPTY_INT_ARRAY; 17413 for (int i = userIds.length - 1; i >= 0; --i) { 17414 final int userId = userIds[i]; 17415 if (deletedPackageSetting.getInstantApp(userId)) { 17416 continue; 17417 } 17418 broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId); 17419 } 17420 } 17421 } 17422 17423 /* 17424 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 17425 * flag is not set, the data directory is removed as well. 17426 * make sure this flag is set for partially installed apps. If not its meaningless to 17427 * delete a partially installed application. 17428 */ 17429 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 17430 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 17431 String packageName = ps.name; 17432 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 17433 // Retrieve object to delete permissions for shared user later on 17434 final PackageParser.Package deletedPkg; 17435 final PackageSetting deletedPs; 17436 // reader 17437 synchronized (mPackages) { 17438 deletedPkg = mPackages.get(packageName); 17439 deletedPs = mSettings.mPackages.get(packageName); 17440 if (outInfo != null) { 17441 outInfo.removedPackage = packageName; 17442 outInfo.installerPackageName = ps.installerPackageName; 17443 outInfo.isStaticSharedLib = deletedPkg != null 17444 && deletedPkg.staticSharedLibName != null; 17445 outInfo.populateUsers(deletedPs == null ? null 17446 : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs); 17447 } 17448 } 17449 17450 removePackageLI(ps, (flags & PackageManager.DELETE_CHATTY) != 0); 17451 17452 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 17453 final PackageParser.Package resolvedPkg; 17454 if (deletedPkg != null) { 17455 resolvedPkg = deletedPkg; 17456 } else { 17457 // We don't have a parsed package when it lives on an ejected 17458 // adopted storage device, so fake something together 17459 resolvedPkg = new PackageParser.Package(ps.name); 17460 resolvedPkg.setVolumeUuid(ps.volumeUuid); 17461 } 17462 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 17463 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 17464 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 17465 if (outInfo != null) { 17466 outInfo.dataRemoved = true; 17467 } 17468 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 17469 } 17470 17471 int removedAppId = -1; 17472 17473 // writer 17474 synchronized (mPackages) { 17475 boolean installedStateChanged = false; 17476 if (deletedPs != null) { 17477 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 17478 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 17479 clearDefaultBrowserIfNeeded(packageName); 17480 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 17481 removedAppId = mSettings.removePackageLPw(packageName); 17482 if (outInfo != null) { 17483 outInfo.removedAppId = removedAppId; 17484 } 17485 mPermissionManager.updatePermissions( 17486 deletedPs.name, null, false, mPackages.values(), mPermissionCallback); 17487 if (deletedPs.sharedUser != null) { 17488 // Remove permissions associated with package. Since runtime 17489 // permissions are per user we have to kill the removed package 17490 // or packages running under the shared user of the removed 17491 // package if revoking the permissions requested only by the removed 17492 // package is successful and this causes a change in gids. 17493 for (int userId : UserManagerService.getInstance().getUserIds()) { 17494 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 17495 userId); 17496 if (userIdToKill == UserHandle.USER_ALL 17497 || userIdToKill >= UserHandle.USER_SYSTEM) { 17498 // If gids changed for this user, kill all affected packages. 17499 mHandler.post(new Runnable() { 17500 @Override 17501 public void run() { 17502 // This has to happen with no lock held. 17503 killApplication(deletedPs.name, deletedPs.appId, 17504 KILL_APP_REASON_GIDS_CHANGED); 17505 } 17506 }); 17507 break; 17508 } 17509 } 17510 } 17511 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 17512 } 17513 // make sure to preserve per-user disabled state if this removal was just 17514 // a downgrade of a system app to the factory package 17515 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 17516 if (DEBUG_REMOVE) { 17517 Slog.d(TAG, "Propagating install state across downgrade"); 17518 } 17519 for (int userId : allUserHandles) { 17520 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 17521 if (DEBUG_REMOVE) { 17522 Slog.d(TAG, " user " + userId + " => " + installed); 17523 } 17524 if (installed != ps.getInstalled(userId)) { 17525 installedStateChanged = true; 17526 } 17527 ps.setInstalled(installed, userId); 17528 } 17529 } 17530 } 17531 // can downgrade to reader 17532 if (writeSettings) { 17533 // Save settings now 17534 mSettings.writeLPr(); 17535 } 17536 if (installedStateChanged) { 17537 mSettings.writeKernelMappingLPr(ps); 17538 } 17539 } 17540 if (removedAppId != -1) { 17541 // A user ID was deleted here. Go through all users and remove it 17542 // from KeyStore. 17543 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId); 17544 } 17545 } 17546 17547 static boolean locationIsPrivileged(String path) { 17548 try { 17549 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 17550 final File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app"); 17551 return path.startsWith(privilegedAppDir.getCanonicalPath()) 17552 || path.startsWith(privilegedVendorAppDir.getCanonicalPath()); 17553 } catch (IOException e) { 17554 Slog.e(TAG, "Unable to access code path " + path); 17555 } 17556 return false; 17557 } 17558 17559 static boolean locationIsOem(String path) { 17560 try { 17561 return path.startsWith(Environment.getOemDirectory().getCanonicalPath()); 17562 } catch (IOException e) { 17563 Slog.e(TAG, "Unable to access code path " + path); 17564 } 17565 return false; 17566 } 17567 17568 static boolean locationIsVendor(String path) { 17569 try { 17570 return path.startsWith(Environment.getVendorDirectory().getCanonicalPath()); 17571 } catch (IOException e) { 17572 Slog.e(TAG, "Unable to access code path " + path); 17573 } 17574 return false; 17575 } 17576 17577 /* 17578 * Tries to delete system package. 17579 */ 17580 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 17581 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 17582 boolean writeSettings) { 17583 if (deletedPs.parentPackageName != null) { 17584 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 17585 return false; 17586 } 17587 17588 final boolean applyUserRestrictions 17589 = (allUserHandles != null) && (outInfo.origUsers != null); 17590 final PackageSetting disabledPs; 17591 // Confirm if the system package has been updated 17592 // An updated system app can be deleted. This will also have to restore 17593 // the system pkg from system partition 17594 // reader 17595 synchronized (mPackages) { 17596 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 17597 } 17598 17599 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 17600 + " disabledPs=" + disabledPs); 17601 17602 if (disabledPs == null) { 17603 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 17604 return false; 17605 } else if (DEBUG_REMOVE) { 17606 Slog.d(TAG, "Deleting system pkg from data partition"); 17607 } 17608 17609 if (DEBUG_REMOVE) { 17610 if (applyUserRestrictions) { 17611 Slog.d(TAG, "Remembering install states:"); 17612 for (int userId : allUserHandles) { 17613 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 17614 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 17615 } 17616 } 17617 } 17618 17619 // Delete the updated package 17620 outInfo.isRemovedPackageSystemUpdate = true; 17621 if (outInfo.removedChildPackages != null) { 17622 final int childCount = (deletedPs.childPackageNames != null) 17623 ? deletedPs.childPackageNames.size() : 0; 17624 for (int i = 0; i < childCount; i++) { 17625 String childPackageName = deletedPs.childPackageNames.get(i); 17626 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 17627 .contains(childPackageName)) { 17628 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 17629 childPackageName); 17630 if (childInfo != null) { 17631 childInfo.isRemovedPackageSystemUpdate = true; 17632 } 17633 } 17634 } 17635 } 17636 17637 if (disabledPs.versionCode < deletedPs.versionCode) { 17638 // Delete data for downgrades 17639 flags &= ~PackageManager.DELETE_KEEP_DATA; 17640 } else { 17641 // Preserve data by setting flag 17642 flags |= PackageManager.DELETE_KEEP_DATA; 17643 } 17644 17645 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 17646 outInfo, writeSettings, disabledPs.pkg); 17647 if (!ret) { 17648 return false; 17649 } 17650 17651 // writer 17652 synchronized (mPackages) { 17653 // NOTE: The system package always needs to be enabled; even if it's for 17654 // a compressed stub. If we don't, installing the system package fails 17655 // during scan [scanning checks the disabled packages]. We will reverse 17656 // this later, after we've "installed" the stub. 17657 // Reinstate the old system package 17658 enableSystemPackageLPw(disabledPs.pkg); 17659 // Remove any native libraries from the upgraded package. 17660 removeNativeBinariesLI(deletedPs); 17661 } 17662 17663 // Install the system package 17664 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 17665 try { 17666 installPackageFromSystemLIF(disabledPs.codePathString, false, allUserHandles, 17667 outInfo.origUsers, deletedPs.getPermissionsState(), writeSettings); 17668 } catch (PackageManagerException e) { 17669 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 17670 + e.getMessage()); 17671 return false; 17672 } finally { 17673 if (disabledPs.pkg.isStub) { 17674 mSettings.disableSystemPackageLPw(disabledPs.name, true /*replaced*/); 17675 } 17676 } 17677 return true; 17678 } 17679 17680 /** 17681 * Installs a package that's already on the system partition. 17682 */ 17683 private PackageParser.Package installPackageFromSystemLIF(@NonNull String codePathString, 17684 boolean isPrivileged, @Nullable int[] allUserHandles, @Nullable int[] origUserHandles, 17685 @Nullable PermissionsState origPermissionState, boolean writeSettings) 17686 throws PackageManagerException { 17687 @ParseFlags int parseFlags = 17688 mDefParseFlags 17689 | PackageParser.PARSE_MUST_BE_APK 17690 | PackageParser.PARSE_IS_SYSTEM_DIR; 17691 @ScanFlags int scanFlags = SCAN_AS_SYSTEM; 17692 if (isPrivileged || locationIsPrivileged(codePathString)) { 17693 scanFlags |= SCAN_AS_PRIVILEGED; 17694 } 17695 if (locationIsOem(codePathString)) { 17696 scanFlags |= SCAN_AS_OEM; 17697 } 17698 if (locationIsVendor(codePathString)) { 17699 scanFlags |= SCAN_AS_VENDOR; 17700 } 17701 17702 final File codePath = new File(codePathString); 17703 final PackageParser.Package pkg = 17704 scanPackageTracedLI(codePath, parseFlags, scanFlags, 0 /*currentTime*/, null); 17705 17706 try { 17707 // update shared libraries for the newly re-installed system package 17708 updateSharedLibrariesLPr(pkg, null); 17709 } catch (PackageManagerException e) { 17710 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 17711 } 17712 17713 prepareAppDataAfterInstallLIF(pkg); 17714 17715 // writer 17716 synchronized (mPackages) { 17717 PackageSetting ps = mSettings.mPackages.get(pkg.packageName); 17718 17719 // Propagate the permissions state as we do not want to drop on the floor 17720 // runtime permissions. The update permissions method below will take 17721 // care of removing obsolete permissions and grant install permissions. 17722 if (origPermissionState != null) { 17723 ps.getPermissionsState().copyFrom(origPermissionState); 17724 } 17725 mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(), 17726 mPermissionCallback); 17727 17728 final boolean applyUserRestrictions 17729 = (allUserHandles != null) && (origUserHandles != null); 17730 if (applyUserRestrictions) { 17731 boolean installedStateChanged = false; 17732 if (DEBUG_REMOVE) { 17733 Slog.d(TAG, "Propagating install state across reinstall"); 17734 } 17735 for (int userId : allUserHandles) { 17736 final boolean installed = ArrayUtils.contains(origUserHandles, userId); 17737 if (DEBUG_REMOVE) { 17738 Slog.d(TAG, " user " + userId + " => " + installed); 17739 } 17740 if (installed != ps.getInstalled(userId)) { 17741 installedStateChanged = true; 17742 } 17743 ps.setInstalled(installed, userId); 17744 17745 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 17746 } 17747 // Regardless of writeSettings we need to ensure that this restriction 17748 // state propagation is persisted 17749 mSettings.writeAllUsersPackageRestrictionsLPr(); 17750 if (installedStateChanged) { 17751 mSettings.writeKernelMappingLPr(ps); 17752 } 17753 } 17754 // can downgrade to reader here 17755 if (writeSettings) { 17756 mSettings.writeLPr(); 17757 } 17758 } 17759 return pkg; 17760 } 17761 17762 private boolean deleteInstalledPackageLIF(PackageSetting ps, 17763 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 17764 PackageRemovedInfo outInfo, boolean writeSettings, 17765 PackageParser.Package replacingPackage) { 17766 synchronized (mPackages) { 17767 if (outInfo != null) { 17768 outInfo.uid = ps.appId; 17769 } 17770 17771 if (outInfo != null && outInfo.removedChildPackages != null) { 17772 final int childCount = (ps.childPackageNames != null) 17773 ? ps.childPackageNames.size() : 0; 17774 for (int i = 0; i < childCount; i++) { 17775 String childPackageName = ps.childPackageNames.get(i); 17776 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 17777 if (childPs == null) { 17778 return false; 17779 } 17780 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 17781 childPackageName); 17782 if (childInfo != null) { 17783 childInfo.uid = childPs.appId; 17784 } 17785 } 17786 } 17787 } 17788 17789 // Delete package data from internal structures and also remove data if flag is set 17790 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 17791 17792 // Delete the child packages data 17793 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 17794 for (int i = 0; i < childCount; i++) { 17795 PackageSetting childPs; 17796 synchronized (mPackages) { 17797 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 17798 } 17799 if (childPs != null) { 17800 PackageRemovedInfo childOutInfo = (outInfo != null 17801 && outInfo.removedChildPackages != null) 17802 ? outInfo.removedChildPackages.get(childPs.name) : null; 17803 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 17804 && (replacingPackage != null 17805 && !replacingPackage.hasChildPackage(childPs.name)) 17806 ? flags & ~DELETE_KEEP_DATA : flags; 17807 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 17808 deleteFlags, writeSettings); 17809 } 17810 } 17811 17812 // Delete application code and resources only for parent packages 17813 if (ps.parentPackageName == null) { 17814 if (deleteCodeAndResources && (outInfo != null)) { 17815 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 17816 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 17817 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 17818 } 17819 } 17820 17821 return true; 17822 } 17823 17824 @Override 17825 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 17826 int userId) { 17827 mContext.enforceCallingOrSelfPermission( 17828 android.Manifest.permission.DELETE_PACKAGES, null); 17829 synchronized (mPackages) { 17830 // Cannot block uninstall of static shared libs as they are 17831 // considered a part of the using app (emulating static linking). 17832 // Also static libs are installed always on internal storage. 17833 PackageParser.Package pkg = mPackages.get(packageName); 17834 if (pkg != null && pkg.staticSharedLibName != null) { 17835 Slog.w(TAG, "Cannot block uninstall of package: " + packageName 17836 + " providing static shared library: " + pkg.staticSharedLibName); 17837 return false; 17838 } 17839 mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall); 17840 mSettings.writePackageRestrictionsLPr(userId); 17841 } 17842 return true; 17843 } 17844 17845 @Override 17846 public boolean getBlockUninstallForUser(String packageName, int userId) { 17847 synchronized (mPackages) { 17848 final PackageSetting ps = mSettings.mPackages.get(packageName); 17849 if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) { 17850 return false; 17851 } 17852 return mSettings.getBlockUninstallLPr(userId, packageName); 17853 } 17854 } 17855 17856 @Override 17857 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 17858 enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root"); 17859 synchronized (mPackages) { 17860 PackageSetting ps = mSettings.mPackages.get(packageName); 17861 if (ps == null) { 17862 Log.w(TAG, "Package doesn't exist: " + packageName); 17863 return false; 17864 } 17865 if (systemUserApp) { 17866 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 17867 } else { 17868 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 17869 } 17870 mSettings.writeLPr(); 17871 } 17872 return true; 17873 } 17874 17875 /* 17876 * This method handles package deletion in general 17877 */ 17878 private boolean deletePackageLIF(String packageName, UserHandle user, 17879 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 17880 PackageRemovedInfo outInfo, boolean writeSettings, 17881 PackageParser.Package replacingPackage) { 17882 if (packageName == null) { 17883 Slog.w(TAG, "Attempt to delete null packageName."); 17884 return false; 17885 } 17886 17887 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 17888 17889 PackageSetting ps; 17890 synchronized (mPackages) { 17891 ps = mSettings.mPackages.get(packageName); 17892 if (ps == null) { 17893 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 17894 return false; 17895 } 17896 17897 if (ps.parentPackageName != null && (!isSystemApp(ps) 17898 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 17899 if (DEBUG_REMOVE) { 17900 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 17901 + ((user == null) ? UserHandle.USER_ALL : user)); 17902 } 17903 final int removedUserId = (user != null) ? user.getIdentifier() 17904 : UserHandle.USER_ALL; 17905 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 17906 return false; 17907 } 17908 markPackageUninstalledForUserLPw(ps, user); 17909 scheduleWritePackageRestrictionsLocked(user); 17910 return true; 17911 } 17912 } 17913 17914 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 17915 && user.getIdentifier() != UserHandle.USER_ALL)) { 17916 // The caller is asking that the package only be deleted for a single 17917 // user. To do this, we just mark its uninstalled state and delete 17918 // its data. If this is a system app, we only allow this to happen if 17919 // they have set the special DELETE_SYSTEM_APP which requests different 17920 // semantics than normal for uninstalling system apps. 17921 markPackageUninstalledForUserLPw(ps, user); 17922 17923 if (!isSystemApp(ps)) { 17924 // Do not uninstall the APK if an app should be cached 17925 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 17926 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 17927 // Other user still have this package installed, so all 17928 // we need to do is clear this user's data and save that 17929 // it is uninstalled. 17930 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 17931 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 17932 return false; 17933 } 17934 scheduleWritePackageRestrictionsLocked(user); 17935 return true; 17936 } else { 17937 // We need to set it back to 'installed' so the uninstall 17938 // broadcasts will be sent correctly. 17939 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 17940 ps.setInstalled(true, user.getIdentifier()); 17941 mSettings.writeKernelMappingLPr(ps); 17942 } 17943 } else { 17944 // This is a system app, so we assume that the 17945 // other users still have this package installed, so all 17946 // we need to do is clear this user's data and save that 17947 // it is uninstalled. 17948 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 17949 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 17950 return false; 17951 } 17952 scheduleWritePackageRestrictionsLocked(user); 17953 return true; 17954 } 17955 } 17956 17957 // If we are deleting a composite package for all users, keep track 17958 // of result for each child. 17959 if (ps.childPackageNames != null && outInfo != null) { 17960 synchronized (mPackages) { 17961 final int childCount = ps.childPackageNames.size(); 17962 outInfo.removedChildPackages = new ArrayMap<>(childCount); 17963 for (int i = 0; i < childCount; i++) { 17964 String childPackageName = ps.childPackageNames.get(i); 17965 PackageRemovedInfo childInfo = new PackageRemovedInfo(this); 17966 childInfo.removedPackage = childPackageName; 17967 childInfo.installerPackageName = ps.installerPackageName; 17968 outInfo.removedChildPackages.put(childPackageName, childInfo); 17969 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 17970 if (childPs != null) { 17971 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 17972 } 17973 } 17974 } 17975 } 17976 17977 boolean ret = false; 17978 if (isSystemApp(ps)) { 17979 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 17980 // When an updated system application is deleted we delete the existing resources 17981 // as well and fall back to existing code in system partition 17982 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 17983 } else { 17984 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 17985 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 17986 outInfo, writeSettings, replacingPackage); 17987 } 17988 17989 // Take a note whether we deleted the package for all users 17990 if (outInfo != null) { 17991 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 17992 if (outInfo.removedChildPackages != null) { 17993 synchronized (mPackages) { 17994 final int childCount = outInfo.removedChildPackages.size(); 17995 for (int i = 0; i < childCount; i++) { 17996 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 17997 if (childInfo != null) { 17998 childInfo.removedForAllUsers = mPackages.get( 17999 childInfo.removedPackage) == null; 18000 } 18001 } 18002 } 18003 } 18004 // If we uninstalled an update to a system app there may be some 18005 // child packages that appeared as they are declared in the system 18006 // app but were not declared in the update. 18007 if (isSystemApp(ps)) { 18008 synchronized (mPackages) { 18009 PackageSetting updatedPs = mSettings.getPackageLPr(ps.name); 18010 final int childCount = (updatedPs.childPackageNames != null) 18011 ? updatedPs.childPackageNames.size() : 0; 18012 for (int i = 0; i < childCount; i++) { 18013 String childPackageName = updatedPs.childPackageNames.get(i); 18014 if (outInfo.removedChildPackages == null 18015 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 18016 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 18017 if (childPs == null) { 18018 continue; 18019 } 18020 PackageInstalledInfo installRes = new PackageInstalledInfo(); 18021 installRes.name = childPackageName; 18022 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 18023 installRes.pkg = mPackages.get(childPackageName); 18024 installRes.uid = childPs.pkg.applicationInfo.uid; 18025 if (outInfo.appearedChildPackages == null) { 18026 outInfo.appearedChildPackages = new ArrayMap<>(); 18027 } 18028 outInfo.appearedChildPackages.put(childPackageName, installRes); 18029 } 18030 } 18031 } 18032 } 18033 } 18034 18035 return ret; 18036 } 18037 18038 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 18039 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 18040 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 18041 for (int nextUserId : userIds) { 18042 if (DEBUG_REMOVE) { 18043 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 18044 } 18045 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 18046 false /*installed*/, 18047 true /*stopped*/, 18048 true /*notLaunched*/, 18049 false /*hidden*/, 18050 false /*suspended*/, 18051 false /*instantApp*/, 18052 false /*virtualPreload*/, 18053 null /*lastDisableAppCaller*/, 18054 null /*enabledComponents*/, 18055 null /*disabledComponents*/, 18056 ps.readUserState(nextUserId).domainVerificationStatus, 18057 0, PackageManager.INSTALL_REASON_UNKNOWN); 18058 } 18059 mSettings.writeKernelMappingLPr(ps); 18060 } 18061 18062 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 18063 PackageRemovedInfo outInfo) { 18064 final PackageParser.Package pkg; 18065 synchronized (mPackages) { 18066 pkg = mPackages.get(ps.name); 18067 } 18068 18069 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 18070 : new int[] {userId}; 18071 for (int nextUserId : userIds) { 18072 if (DEBUG_REMOVE) { 18073 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 18074 + nextUserId); 18075 } 18076 18077 destroyAppDataLIF(pkg, userId, 18078 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18079 destroyAppProfilesLIF(pkg, userId); 18080 clearDefaultBrowserIfNeededForUser(ps.name, userId); 18081 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 18082 schedulePackageCleaning(ps.name, nextUserId, false); 18083 synchronized (mPackages) { 18084 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 18085 scheduleWritePackageRestrictionsLocked(nextUserId); 18086 } 18087 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 18088 } 18089 } 18090 18091 if (outInfo != null) { 18092 outInfo.removedPackage = ps.name; 18093 outInfo.installerPackageName = ps.installerPackageName; 18094 outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null; 18095 outInfo.removedAppId = ps.appId; 18096 outInfo.removedUsers = userIds; 18097 outInfo.broadcastUsers = userIds; 18098 } 18099 18100 return true; 18101 } 18102 18103 private final class ClearStorageConnection implements ServiceConnection { 18104 IMediaContainerService mContainerService; 18105 18106 @Override 18107 public void onServiceConnected(ComponentName name, IBinder service) { 18108 synchronized (this) { 18109 mContainerService = IMediaContainerService.Stub 18110 .asInterface(Binder.allowBlocking(service)); 18111 notifyAll(); 18112 } 18113 } 18114 18115 @Override 18116 public void onServiceDisconnected(ComponentName name) { 18117 } 18118 } 18119 18120 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 18121 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 18122 18123 final boolean mounted; 18124 if (Environment.isExternalStorageEmulated()) { 18125 mounted = true; 18126 } else { 18127 final String status = Environment.getExternalStorageState(); 18128 18129 mounted = status.equals(Environment.MEDIA_MOUNTED) 18130 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 18131 } 18132 18133 if (!mounted) { 18134 return; 18135 } 18136 18137 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 18138 int[] users; 18139 if (userId == UserHandle.USER_ALL) { 18140 users = sUserManager.getUserIds(); 18141 } else { 18142 users = new int[] { userId }; 18143 } 18144 final ClearStorageConnection conn = new ClearStorageConnection(); 18145 if (mContext.bindServiceAsUser( 18146 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 18147 try { 18148 for (int curUser : users) { 18149 long timeout = SystemClock.uptimeMillis() + 5000; 18150 synchronized (conn) { 18151 long now; 18152 while (conn.mContainerService == null && 18153 (now = SystemClock.uptimeMillis()) < timeout) { 18154 try { 18155 conn.wait(timeout - now); 18156 } catch (InterruptedException e) { 18157 } 18158 } 18159 } 18160 if (conn.mContainerService == null) { 18161 return; 18162 } 18163 18164 final UserEnvironment userEnv = new UserEnvironment(curUser); 18165 clearDirectory(conn.mContainerService, 18166 userEnv.buildExternalStorageAppCacheDirs(packageName)); 18167 if (allData) { 18168 clearDirectory(conn.mContainerService, 18169 userEnv.buildExternalStorageAppDataDirs(packageName)); 18170 clearDirectory(conn.mContainerService, 18171 userEnv.buildExternalStorageAppMediaDirs(packageName)); 18172 } 18173 } 18174 } finally { 18175 mContext.unbindService(conn); 18176 } 18177 } 18178 } 18179 18180 @Override 18181 public void clearApplicationProfileData(String packageName) { 18182 enforceSystemOrRoot("Only the system can clear all profile data"); 18183 18184 final PackageParser.Package pkg; 18185 synchronized (mPackages) { 18186 pkg = mPackages.get(packageName); 18187 } 18188 18189 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 18190 synchronized (mInstallLock) { 18191 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 18192 } 18193 } 18194 } 18195 18196 @Override 18197 public void clearApplicationUserData(final String packageName, 18198 final IPackageDataObserver observer, final int userId) { 18199 mContext.enforceCallingOrSelfPermission( 18200 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 18201 18202 final int callingUid = Binder.getCallingUid(); 18203 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 18204 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 18205 18206 final PackageSetting ps = mSettings.getPackageLPr(packageName); 18207 final boolean filterApp = (ps != null && filterAppAccessLPr(ps, callingUid, userId)); 18208 if (!filterApp && mProtectedPackages.isPackageDataProtected(userId, packageName)) { 18209 throw new SecurityException("Cannot clear data for a protected package: " 18210 + packageName); 18211 } 18212 // Queue up an async operation since the package deletion may take a little while. 18213 mHandler.post(new Runnable() { 18214 public void run() { 18215 mHandler.removeCallbacks(this); 18216 final boolean succeeded; 18217 if (!filterApp) { 18218 try (PackageFreezer freezer = freezePackage(packageName, 18219 "clearApplicationUserData")) { 18220 synchronized (mInstallLock) { 18221 succeeded = clearApplicationUserDataLIF(packageName, userId); 18222 } 18223 clearExternalStorageDataSync(packageName, userId, true); 18224 synchronized (mPackages) { 18225 mInstantAppRegistry.deleteInstantApplicationMetadataLPw( 18226 packageName, userId); 18227 } 18228 } 18229 if (succeeded) { 18230 // invoke DeviceStorageMonitor's update method to clear any notifications 18231 DeviceStorageMonitorInternal dsm = LocalServices 18232 .getService(DeviceStorageMonitorInternal.class); 18233 if (dsm != null) { 18234 dsm.checkMemory(); 18235 } 18236 } 18237 } else { 18238 succeeded = false; 18239 } 18240 if (observer != null) { 18241 try { 18242 observer.onRemoveCompleted(packageName, succeeded); 18243 } catch (RemoteException e) { 18244 Log.i(TAG, "Observer no longer exists."); 18245 } 18246 } //end if observer 18247 } //end run 18248 }); 18249 } 18250 18251 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 18252 if (packageName == null) { 18253 Slog.w(TAG, "Attempt to delete null packageName."); 18254 return false; 18255 } 18256 18257 // Try finding details about the requested package 18258 PackageParser.Package pkg; 18259 synchronized (mPackages) { 18260 pkg = mPackages.get(packageName); 18261 if (pkg == null) { 18262 final PackageSetting ps = mSettings.mPackages.get(packageName); 18263 if (ps != null) { 18264 pkg = ps.pkg; 18265 } 18266 } 18267 18268 if (pkg == null) { 18269 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 18270 return false; 18271 } 18272 18273 PackageSetting ps = (PackageSetting) pkg.mExtras; 18274 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 18275 } 18276 18277 clearAppDataLIF(pkg, userId, 18278 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18279 18280 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 18281 removeKeystoreDataIfNeeded(userId, appId); 18282 18283 UserManagerInternal umInternal = getUserManagerInternal(); 18284 final int flags; 18285 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 18286 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18287 } else if (umInternal.isUserRunning(userId)) { 18288 flags = StorageManager.FLAG_STORAGE_DE; 18289 } else { 18290 flags = 0; 18291 } 18292 prepareAppDataContentsLIF(pkg, userId, flags); 18293 18294 return true; 18295 } 18296 18297 /** 18298 * Reverts user permission state changes (permissions and flags) in 18299 * all packages for a given user. 18300 * 18301 * @param userId The device user for which to do a reset. 18302 */ 18303 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 18304 final int packageCount = mPackages.size(); 18305 for (int i = 0; i < packageCount; i++) { 18306 PackageParser.Package pkg = mPackages.valueAt(i); 18307 PackageSetting ps = (PackageSetting) pkg.mExtras; 18308 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 18309 } 18310 } 18311 18312 private void resetNetworkPolicies(int userId) { 18313 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 18314 } 18315 18316 /** 18317 * Reverts user permission state changes (permissions and flags). 18318 * 18319 * @param ps The package for which to reset. 18320 * @param userId The device user for which to do a reset. 18321 */ 18322 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 18323 final PackageSetting ps, final int userId) { 18324 if (ps.pkg == null) { 18325 return; 18326 } 18327 18328 // These are flags that can change base on user actions. 18329 final int userSettableMask = FLAG_PERMISSION_USER_SET 18330 | FLAG_PERMISSION_USER_FIXED 18331 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 18332 | FLAG_PERMISSION_REVIEW_REQUIRED; 18333 18334 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 18335 | FLAG_PERMISSION_POLICY_FIXED; 18336 18337 boolean writeInstallPermissions = false; 18338 boolean writeRuntimePermissions = false; 18339 18340 final int permissionCount = ps.pkg.requestedPermissions.size(); 18341 for (int i = 0; i < permissionCount; i++) { 18342 final String permName = ps.pkg.requestedPermissions.get(i); 18343 final BasePermission bp = 18344 (BasePermission) mPermissionManager.getPermissionTEMP(permName); 18345 if (bp == null) { 18346 continue; 18347 } 18348 18349 // If shared user we just reset the state to which only this app contributed. 18350 if (ps.sharedUser != null) { 18351 boolean used = false; 18352 final int packageCount = ps.sharedUser.packages.size(); 18353 for (int j = 0; j < packageCount; j++) { 18354 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 18355 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 18356 && pkg.pkg.requestedPermissions.contains(permName)) { 18357 used = true; 18358 break; 18359 } 18360 } 18361 if (used) { 18362 continue; 18363 } 18364 } 18365 18366 final PermissionsState permissionsState = ps.getPermissionsState(); 18367 18368 final int oldFlags = permissionsState.getPermissionFlags(permName, userId); 18369 18370 // Always clear the user settable flags. 18371 final boolean hasInstallState = 18372 permissionsState.getInstallPermissionState(permName) != null; 18373 // If permission review is enabled and this is a legacy app, mark the 18374 // permission as requiring a review as this is the initial state. 18375 int flags = 0; 18376 if (mSettings.mPermissions.mPermissionReviewRequired 18377 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 18378 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 18379 } 18380 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 18381 if (hasInstallState) { 18382 writeInstallPermissions = true; 18383 } else { 18384 writeRuntimePermissions = true; 18385 } 18386 } 18387 18388 // Below is only runtime permission handling. 18389 if (!bp.isRuntime()) { 18390 continue; 18391 } 18392 18393 // Never clobber system or policy. 18394 if ((oldFlags & policyOrSystemFlags) != 0) { 18395 continue; 18396 } 18397 18398 // If this permission was granted by default, make sure it is. 18399 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 18400 if (permissionsState.grantRuntimePermission(bp, userId) 18401 != PERMISSION_OPERATION_FAILURE) { 18402 writeRuntimePermissions = true; 18403 } 18404 // If permission review is enabled the permissions for a legacy apps 18405 // are represented as constantly granted runtime ones, so don't revoke. 18406 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 18407 // Otherwise, reset the permission. 18408 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 18409 switch (revokeResult) { 18410 case PERMISSION_OPERATION_SUCCESS: 18411 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 18412 writeRuntimePermissions = true; 18413 final int appId = ps.appId; 18414 mHandler.post(new Runnable() { 18415 @Override 18416 public void run() { 18417 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 18418 } 18419 }); 18420 } break; 18421 } 18422 } 18423 } 18424 18425 // Synchronously write as we are taking permissions away. 18426 if (writeRuntimePermissions) { 18427 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 18428 } 18429 18430 // Synchronously write as we are taking permissions away. 18431 if (writeInstallPermissions) { 18432 mSettings.writeLPr(); 18433 } 18434 } 18435 18436 /** 18437 * Remove entries from the keystore daemon. Will only remove it if the 18438 * {@code appId} is valid. 18439 */ 18440 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 18441 if (appId < 0) { 18442 return; 18443 } 18444 18445 final KeyStore keyStore = KeyStore.getInstance(); 18446 if (keyStore != null) { 18447 if (userId == UserHandle.USER_ALL) { 18448 for (final int individual : sUserManager.getUserIds()) { 18449 keyStore.clearUid(UserHandle.getUid(individual, appId)); 18450 } 18451 } else { 18452 keyStore.clearUid(UserHandle.getUid(userId, appId)); 18453 } 18454 } else { 18455 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 18456 } 18457 } 18458 18459 @Override 18460 public void deleteApplicationCacheFiles(final String packageName, 18461 final IPackageDataObserver observer) { 18462 final int userId = UserHandle.getCallingUserId(); 18463 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 18464 } 18465 18466 @Override 18467 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 18468 final IPackageDataObserver observer) { 18469 final int callingUid = Binder.getCallingUid(); 18470 mContext.enforceCallingOrSelfPermission( 18471 android.Manifest.permission.DELETE_CACHE_FILES, null); 18472 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 18473 /* requireFullPermission= */ true, /* checkShell= */ false, 18474 "delete application cache files"); 18475 final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission( 18476 android.Manifest.permission.ACCESS_INSTANT_APPS); 18477 18478 final PackageParser.Package pkg; 18479 synchronized (mPackages) { 18480 pkg = mPackages.get(packageName); 18481 } 18482 18483 // Queue up an async operation since the package deletion may take a little while. 18484 mHandler.post(new Runnable() { 18485 public void run() { 18486 final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras; 18487 boolean doClearData = true; 18488 if (ps != null) { 18489 final boolean targetIsInstantApp = 18490 ps.getInstantApp(UserHandle.getUserId(callingUid)); 18491 doClearData = !targetIsInstantApp 18492 || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED; 18493 } 18494 if (doClearData) { 18495 synchronized (mInstallLock) { 18496 final int flags = StorageManager.FLAG_STORAGE_DE 18497 | StorageManager.FLAG_STORAGE_CE; 18498 // We're only clearing cache files, so we don't care if the 18499 // app is unfrozen and still able to run 18500 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 18501 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 18502 } 18503 clearExternalStorageDataSync(packageName, userId, false); 18504 } 18505 if (observer != null) { 18506 try { 18507 observer.onRemoveCompleted(packageName, true); 18508 } catch (RemoteException e) { 18509 Log.i(TAG, "Observer no longer exists."); 18510 } 18511 } 18512 } 18513 }); 18514 } 18515 18516 @Override 18517 public void getPackageSizeInfo(final String packageName, int userHandle, 18518 final IPackageStatsObserver observer) { 18519 throw new UnsupportedOperationException( 18520 "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!"); 18521 } 18522 18523 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 18524 final PackageSetting ps; 18525 synchronized (mPackages) { 18526 ps = mSettings.mPackages.get(packageName); 18527 if (ps == null) { 18528 Slog.w(TAG, "Failed to find settings for " + packageName); 18529 return false; 18530 } 18531 } 18532 18533 final String[] packageNames = { packageName }; 18534 final long[] ceDataInodes = { ps.getCeDataInode(userId) }; 18535 final String[] codePaths = { ps.codePathString }; 18536 18537 try { 18538 mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0, 18539 ps.appId, ceDataInodes, codePaths, stats); 18540 18541 // For now, ignore code size of packages on system partition 18542 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 18543 stats.codeSize = 0; 18544 } 18545 18546 // External clients expect these to be tracked separately 18547 stats.dataSize -= stats.cacheSize; 18548 18549 } catch (InstallerException e) { 18550 Slog.w(TAG, String.valueOf(e)); 18551 return false; 18552 } 18553 18554 return true; 18555 } 18556 18557 private int getUidTargetSdkVersionLockedLPr(int uid) { 18558 Object obj = mSettings.getUserIdLPr(uid); 18559 if (obj instanceof SharedUserSetting) { 18560 final SharedUserSetting sus = (SharedUserSetting) obj; 18561 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 18562 final Iterator<PackageSetting> it = sus.packages.iterator(); 18563 while (it.hasNext()) { 18564 final PackageSetting ps = it.next(); 18565 if (ps.pkg != null) { 18566 int v = ps.pkg.applicationInfo.targetSdkVersion; 18567 if (v < vers) vers = v; 18568 } 18569 } 18570 return vers; 18571 } else if (obj instanceof PackageSetting) { 18572 final PackageSetting ps = (PackageSetting) obj; 18573 if (ps.pkg != null) { 18574 return ps.pkg.applicationInfo.targetSdkVersion; 18575 } 18576 } 18577 return Build.VERSION_CODES.CUR_DEVELOPMENT; 18578 } 18579 18580 @Override 18581 public void addPreferredActivity(IntentFilter filter, int match, 18582 ComponentName[] set, ComponentName activity, int userId) { 18583 addPreferredActivityInternal(filter, match, set, activity, true, userId, 18584 "Adding preferred"); 18585 } 18586 18587 private void addPreferredActivityInternal(IntentFilter filter, int match, 18588 ComponentName[] set, ComponentName activity, boolean always, int userId, 18589 String opname) { 18590 // writer 18591 int callingUid = Binder.getCallingUid(); 18592 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 18593 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 18594 if (filter.countActions() == 0) { 18595 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 18596 return; 18597 } 18598 synchronized (mPackages) { 18599 if (mContext.checkCallingOrSelfPermission( 18600 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 18601 != PackageManager.PERMISSION_GRANTED) { 18602 if (getUidTargetSdkVersionLockedLPr(callingUid) 18603 < Build.VERSION_CODES.FROYO) { 18604 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 18605 + callingUid); 18606 return; 18607 } 18608 mContext.enforceCallingOrSelfPermission( 18609 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 18610 } 18611 18612 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 18613 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 18614 + userId + ":"); 18615 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18616 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 18617 scheduleWritePackageRestrictionsLocked(userId); 18618 postPreferredActivityChangedBroadcast(userId); 18619 } 18620 } 18621 18622 private void postPreferredActivityChangedBroadcast(int userId) { 18623 mHandler.post(() -> { 18624 final IActivityManager am = ActivityManager.getService(); 18625 if (am == null) { 18626 return; 18627 } 18628 18629 final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED); 18630 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 18631 try { 18632 am.broadcastIntent(null, intent, null, null, 18633 0, null, null, null, android.app.AppOpsManager.OP_NONE, 18634 null, false, false, userId); 18635 } catch (RemoteException e) { 18636 } 18637 }); 18638 } 18639 18640 @Override 18641 public void replacePreferredActivity(IntentFilter filter, int match, 18642 ComponentName[] set, ComponentName activity, int userId) { 18643 if (filter.countActions() != 1) { 18644 throw new IllegalArgumentException( 18645 "replacePreferredActivity expects filter to have only 1 action."); 18646 } 18647 if (filter.countDataAuthorities() != 0 18648 || filter.countDataPaths() != 0 18649 || filter.countDataSchemes() > 1 18650 || filter.countDataTypes() != 0) { 18651 throw new IllegalArgumentException( 18652 "replacePreferredActivity expects filter to have no data authorities, " + 18653 "paths, or types; and at most one scheme."); 18654 } 18655 18656 final int callingUid = Binder.getCallingUid(); 18657 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 18658 true /* requireFullPermission */, false /* checkShell */, 18659 "replace preferred activity"); 18660 synchronized (mPackages) { 18661 if (mContext.checkCallingOrSelfPermission( 18662 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 18663 != PackageManager.PERMISSION_GRANTED) { 18664 if (getUidTargetSdkVersionLockedLPr(callingUid) 18665 < Build.VERSION_CODES.FROYO) { 18666 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 18667 + Binder.getCallingUid()); 18668 return; 18669 } 18670 mContext.enforceCallingOrSelfPermission( 18671 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 18672 } 18673 18674 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 18675 if (pir != null) { 18676 // Get all of the existing entries that exactly match this filter. 18677 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 18678 if (existing != null && existing.size() == 1) { 18679 PreferredActivity cur = existing.get(0); 18680 if (DEBUG_PREFERRED) { 18681 Slog.i(TAG, "Checking replace of preferred:"); 18682 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18683 if (!cur.mPref.mAlways) { 18684 Slog.i(TAG, " -- CUR; not mAlways!"); 18685 } else { 18686 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 18687 Slog.i(TAG, " -- CUR: mSet=" 18688 + Arrays.toString(cur.mPref.mSetComponents)); 18689 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 18690 Slog.i(TAG, " -- NEW: mMatch=" 18691 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 18692 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 18693 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 18694 } 18695 } 18696 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 18697 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 18698 && cur.mPref.sameSet(set)) { 18699 // Setting the preferred activity to what it happens to be already 18700 if (DEBUG_PREFERRED) { 18701 Slog.i(TAG, "Replacing with same preferred activity " 18702 + cur.mPref.mShortComponent + " for user " 18703 + userId + ":"); 18704 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18705 } 18706 return; 18707 } 18708 } 18709 18710 if (existing != null) { 18711 if (DEBUG_PREFERRED) { 18712 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 18713 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18714 } 18715 for (int i = 0; i < existing.size(); i++) { 18716 PreferredActivity pa = existing.get(i); 18717 if (DEBUG_PREFERRED) { 18718 Slog.i(TAG, "Removing existing preferred activity " 18719 + pa.mPref.mComponent + ":"); 18720 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 18721 } 18722 pir.removeFilter(pa); 18723 } 18724 } 18725 } 18726 addPreferredActivityInternal(filter, match, set, activity, true, userId, 18727 "Replacing preferred"); 18728 } 18729 } 18730 18731 @Override 18732 public void clearPackagePreferredActivities(String packageName) { 18733 final int callingUid = Binder.getCallingUid(); 18734 if (getInstantAppPackageName(callingUid) != null) { 18735 return; 18736 } 18737 // writer 18738 synchronized (mPackages) { 18739 PackageParser.Package pkg = mPackages.get(packageName); 18740 if (pkg == null || pkg.applicationInfo.uid != callingUid) { 18741 if (mContext.checkCallingOrSelfPermission( 18742 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 18743 != PackageManager.PERMISSION_GRANTED) { 18744 if (getUidTargetSdkVersionLockedLPr(callingUid) 18745 < Build.VERSION_CODES.FROYO) { 18746 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 18747 + callingUid); 18748 return; 18749 } 18750 mContext.enforceCallingOrSelfPermission( 18751 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 18752 } 18753 } 18754 final PackageSetting ps = mSettings.getPackageLPr(packageName); 18755 if (ps != null 18756 && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 18757 return; 18758 } 18759 int user = UserHandle.getCallingUserId(); 18760 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 18761 scheduleWritePackageRestrictionsLocked(user); 18762 } 18763 } 18764 } 18765 18766 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 18767 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 18768 ArrayList<PreferredActivity> removed = null; 18769 boolean changed = false; 18770 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18771 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 18772 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18773 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 18774 continue; 18775 } 18776 Iterator<PreferredActivity> it = pir.filterIterator(); 18777 while (it.hasNext()) { 18778 PreferredActivity pa = it.next(); 18779 // Mark entry for removal only if it matches the package name 18780 // and the entry is of type "always". 18781 if (packageName == null || 18782 (pa.mPref.mComponent.getPackageName().equals(packageName) 18783 && pa.mPref.mAlways)) { 18784 if (removed == null) { 18785 removed = new ArrayList<PreferredActivity>(); 18786 } 18787 removed.add(pa); 18788 } 18789 } 18790 if (removed != null) { 18791 for (int j=0; j<removed.size(); j++) { 18792 PreferredActivity pa = removed.get(j); 18793 pir.removeFilter(pa); 18794 } 18795 changed = true; 18796 } 18797 } 18798 if (changed) { 18799 postPreferredActivityChangedBroadcast(userId); 18800 } 18801 return changed; 18802 } 18803 18804 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 18805 private void clearIntentFilterVerificationsLPw(int userId) { 18806 final int packageCount = mPackages.size(); 18807 for (int i = 0; i < packageCount; i++) { 18808 PackageParser.Package pkg = mPackages.valueAt(i); 18809 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 18810 } 18811 } 18812 18813 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 18814 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 18815 if (userId == UserHandle.USER_ALL) { 18816 if (mSettings.removeIntentFilterVerificationLPw(packageName, 18817 sUserManager.getUserIds())) { 18818 for (int oneUserId : sUserManager.getUserIds()) { 18819 scheduleWritePackageRestrictionsLocked(oneUserId); 18820 } 18821 } 18822 } else { 18823 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 18824 scheduleWritePackageRestrictionsLocked(userId); 18825 } 18826 } 18827 } 18828 18829 /** Clears state for all users, and touches intent filter verification policy */ 18830 void clearDefaultBrowserIfNeeded(String packageName) { 18831 for (int oneUserId : sUserManager.getUserIds()) { 18832 clearDefaultBrowserIfNeededForUser(packageName, oneUserId); 18833 } 18834 } 18835 18836 private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) { 18837 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 18838 if (!TextUtils.isEmpty(defaultBrowserPackageName)) { 18839 if (packageName.equals(defaultBrowserPackageName)) { 18840 setDefaultBrowserPackageName(null, userId); 18841 } 18842 } 18843 } 18844 18845 @Override 18846 public void resetApplicationPreferences(int userId) { 18847 mContext.enforceCallingOrSelfPermission( 18848 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 18849 final long identity = Binder.clearCallingIdentity(); 18850 // writer 18851 try { 18852 synchronized (mPackages) { 18853 clearPackagePreferredActivitiesLPw(null, userId); 18854 mSettings.applyDefaultPreferredAppsLPw(this, userId); 18855 // TODO: We have to reset the default SMS and Phone. This requires 18856 // significant refactoring to keep all default apps in the package 18857 // manager (cleaner but more work) or have the services provide 18858 // callbacks to the package manager to request a default app reset. 18859 applyFactoryDefaultBrowserLPw(userId); 18860 clearIntentFilterVerificationsLPw(userId); 18861 primeDomainVerificationsLPw(userId); 18862 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 18863 scheduleWritePackageRestrictionsLocked(userId); 18864 } 18865 resetNetworkPolicies(userId); 18866 } finally { 18867 Binder.restoreCallingIdentity(identity); 18868 } 18869 } 18870 18871 @Override 18872 public int getPreferredActivities(List<IntentFilter> outFilters, 18873 List<ComponentName> outActivities, String packageName) { 18874 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 18875 return 0; 18876 } 18877 int num = 0; 18878 final int userId = UserHandle.getCallingUserId(); 18879 // reader 18880 synchronized (mPackages) { 18881 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 18882 if (pir != null) { 18883 final Iterator<PreferredActivity> it = pir.filterIterator(); 18884 while (it.hasNext()) { 18885 final PreferredActivity pa = it.next(); 18886 if (packageName == null 18887 || (pa.mPref.mComponent.getPackageName().equals(packageName) 18888 && pa.mPref.mAlways)) { 18889 if (outFilters != null) { 18890 outFilters.add(new IntentFilter(pa)); 18891 } 18892 if (outActivities != null) { 18893 outActivities.add(pa.mPref.mComponent); 18894 } 18895 } 18896 } 18897 } 18898 } 18899 18900 return num; 18901 } 18902 18903 @Override 18904 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 18905 int userId) { 18906 int callingUid = Binder.getCallingUid(); 18907 if (callingUid != Process.SYSTEM_UID) { 18908 throw new SecurityException( 18909 "addPersistentPreferredActivity can only be run by the system"); 18910 } 18911 if (filter.countActions() == 0) { 18912 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 18913 return; 18914 } 18915 synchronized (mPackages) { 18916 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 18917 ":"); 18918 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18919 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 18920 new PersistentPreferredActivity(filter, activity)); 18921 scheduleWritePackageRestrictionsLocked(userId); 18922 postPreferredActivityChangedBroadcast(userId); 18923 } 18924 } 18925 18926 @Override 18927 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 18928 int callingUid = Binder.getCallingUid(); 18929 if (callingUid != Process.SYSTEM_UID) { 18930 throw new SecurityException( 18931 "clearPackagePersistentPreferredActivities can only be run by the system"); 18932 } 18933 ArrayList<PersistentPreferredActivity> removed = null; 18934 boolean changed = false; 18935 synchronized (mPackages) { 18936 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 18937 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 18938 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 18939 .valueAt(i); 18940 if (userId != thisUserId) { 18941 continue; 18942 } 18943 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 18944 while (it.hasNext()) { 18945 PersistentPreferredActivity ppa = it.next(); 18946 // Mark entry for removal only if it matches the package name. 18947 if (ppa.mComponent.getPackageName().equals(packageName)) { 18948 if (removed == null) { 18949 removed = new ArrayList<PersistentPreferredActivity>(); 18950 } 18951 removed.add(ppa); 18952 } 18953 } 18954 if (removed != null) { 18955 for (int j=0; j<removed.size(); j++) { 18956 PersistentPreferredActivity ppa = removed.get(j); 18957 ppir.removeFilter(ppa); 18958 } 18959 changed = true; 18960 } 18961 } 18962 18963 if (changed) { 18964 scheduleWritePackageRestrictionsLocked(userId); 18965 postPreferredActivityChangedBroadcast(userId); 18966 } 18967 } 18968 } 18969 18970 /** 18971 * Common machinery for picking apart a restored XML blob and passing 18972 * it to a caller-supplied functor to be applied to the running system. 18973 */ 18974 private void restoreFromXml(XmlPullParser parser, int userId, 18975 String expectedStartTag, BlobXmlRestorer functor) 18976 throws IOException, XmlPullParserException { 18977 int type; 18978 while ((type = parser.next()) != XmlPullParser.START_TAG 18979 && type != XmlPullParser.END_DOCUMENT) { 18980 } 18981 if (type != XmlPullParser.START_TAG) { 18982 // oops didn't find a start tag?! 18983 if (DEBUG_BACKUP) { 18984 Slog.e(TAG, "Didn't find start tag during restore"); 18985 } 18986 return; 18987 } 18988Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 18989 // this is supposed to be TAG_PREFERRED_BACKUP 18990 if (!expectedStartTag.equals(parser.getName())) { 18991 if (DEBUG_BACKUP) { 18992 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 18993 } 18994 return; 18995 } 18996 18997 // skip interfering stuff, then we're aligned with the backing implementation 18998 while ((type = parser.next()) == XmlPullParser.TEXT) { } 18999Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 19000 functor.apply(parser, userId); 19001 } 19002 19003 private interface BlobXmlRestorer { 19004 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 19005 } 19006 19007 /** 19008 * Non-Binder method, support for the backup/restore mechanism: write the 19009 * full set of preferred activities in its canonical XML format. Returns the 19010 * XML output as a byte array, or null if there is none. 19011 */ 19012 @Override 19013 public byte[] getPreferredActivityBackup(int userId) { 19014 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19015 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 19016 } 19017 19018 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19019 try { 19020 final XmlSerializer serializer = new FastXmlSerializer(); 19021 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19022 serializer.startDocument(null, true); 19023 serializer.startTag(null, TAG_PREFERRED_BACKUP); 19024 19025 synchronized (mPackages) { 19026 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 19027 } 19028 19029 serializer.endTag(null, TAG_PREFERRED_BACKUP); 19030 serializer.endDocument(); 19031 serializer.flush(); 19032 } catch (Exception e) { 19033 if (DEBUG_BACKUP) { 19034 Slog.e(TAG, "Unable to write preferred activities for backup", e); 19035 } 19036 return null; 19037 } 19038 19039 return dataStream.toByteArray(); 19040 } 19041 19042 @Override 19043 public void restorePreferredActivities(byte[] backup, int userId) { 19044 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19045 throw new SecurityException("Only the system may call restorePreferredActivities()"); 19046 } 19047 19048 try { 19049 final XmlPullParser parser = Xml.newPullParser(); 19050 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19051 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 19052 new BlobXmlRestorer() { 19053 @Override 19054 public void apply(XmlPullParser parser, int userId) 19055 throws XmlPullParserException, IOException { 19056 synchronized (mPackages) { 19057 mSettings.readPreferredActivitiesLPw(parser, userId); 19058 } 19059 } 19060 } ); 19061 } catch (Exception e) { 19062 if (DEBUG_BACKUP) { 19063 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19064 } 19065 } 19066 } 19067 19068 /** 19069 * Non-Binder method, support for the backup/restore mechanism: write the 19070 * default browser (etc) settings in its canonical XML format. Returns the default 19071 * browser XML representation as a byte array, or null if there is none. 19072 */ 19073 @Override 19074 public byte[] getDefaultAppsBackup(int userId) { 19075 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19076 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 19077 } 19078 19079 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19080 try { 19081 final XmlSerializer serializer = new FastXmlSerializer(); 19082 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19083 serializer.startDocument(null, true); 19084 serializer.startTag(null, TAG_DEFAULT_APPS); 19085 19086 synchronized (mPackages) { 19087 mSettings.writeDefaultAppsLPr(serializer, userId); 19088 } 19089 19090 serializer.endTag(null, TAG_DEFAULT_APPS); 19091 serializer.endDocument(); 19092 serializer.flush(); 19093 } catch (Exception e) { 19094 if (DEBUG_BACKUP) { 19095 Slog.e(TAG, "Unable to write default apps for backup", e); 19096 } 19097 return null; 19098 } 19099 19100 return dataStream.toByteArray(); 19101 } 19102 19103 @Override 19104 public void restoreDefaultApps(byte[] backup, int userId) { 19105 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19106 throw new SecurityException("Only the system may call restoreDefaultApps()"); 19107 } 19108 19109 try { 19110 final XmlPullParser parser = Xml.newPullParser(); 19111 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19112 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 19113 new BlobXmlRestorer() { 19114 @Override 19115 public void apply(XmlPullParser parser, int userId) 19116 throws XmlPullParserException, IOException { 19117 synchronized (mPackages) { 19118 mSettings.readDefaultAppsLPw(parser, userId); 19119 } 19120 } 19121 } ); 19122 } catch (Exception e) { 19123 if (DEBUG_BACKUP) { 19124 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 19125 } 19126 } 19127 } 19128 19129 @Override 19130 public byte[] getIntentFilterVerificationBackup(int userId) { 19131 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19132 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 19133 } 19134 19135 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19136 try { 19137 final XmlSerializer serializer = new FastXmlSerializer(); 19138 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19139 serializer.startDocument(null, true); 19140 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 19141 19142 synchronized (mPackages) { 19143 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 19144 } 19145 19146 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 19147 serializer.endDocument(); 19148 serializer.flush(); 19149 } catch (Exception e) { 19150 if (DEBUG_BACKUP) { 19151 Slog.e(TAG, "Unable to write default apps for backup", e); 19152 } 19153 return null; 19154 } 19155 19156 return dataStream.toByteArray(); 19157 } 19158 19159 @Override 19160 public void restoreIntentFilterVerification(byte[] backup, int userId) { 19161 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19162 throw new SecurityException("Only the system may call restorePreferredActivities()"); 19163 } 19164 19165 try { 19166 final XmlPullParser parser = Xml.newPullParser(); 19167 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19168 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 19169 new BlobXmlRestorer() { 19170 @Override 19171 public void apply(XmlPullParser parser, int userId) 19172 throws XmlPullParserException, IOException { 19173 synchronized (mPackages) { 19174 mSettings.readAllDomainVerificationsLPr(parser, userId); 19175 mSettings.writeLPr(); 19176 } 19177 } 19178 } ); 19179 } catch (Exception e) { 19180 if (DEBUG_BACKUP) { 19181 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19182 } 19183 } 19184 } 19185 19186 @Override 19187 public byte[] getPermissionGrantBackup(int userId) { 19188 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19189 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 19190 } 19191 19192 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19193 try { 19194 final XmlSerializer serializer = new FastXmlSerializer(); 19195 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19196 serializer.startDocument(null, true); 19197 serializer.startTag(null, TAG_PERMISSION_BACKUP); 19198 19199 synchronized (mPackages) { 19200 serializeRuntimePermissionGrantsLPr(serializer, userId); 19201 } 19202 19203 serializer.endTag(null, TAG_PERMISSION_BACKUP); 19204 serializer.endDocument(); 19205 serializer.flush(); 19206 } catch (Exception e) { 19207 if (DEBUG_BACKUP) { 19208 Slog.e(TAG, "Unable to write default apps for backup", e); 19209 } 19210 return null; 19211 } 19212 19213 return dataStream.toByteArray(); 19214 } 19215 19216 @Override 19217 public void restorePermissionGrants(byte[] backup, int userId) { 19218 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19219 throw new SecurityException("Only the system may call restorePermissionGrants()"); 19220 } 19221 19222 try { 19223 final XmlPullParser parser = Xml.newPullParser(); 19224 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19225 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 19226 new BlobXmlRestorer() { 19227 @Override 19228 public void apply(XmlPullParser parser, int userId) 19229 throws XmlPullParserException, IOException { 19230 synchronized (mPackages) { 19231 processRestoredPermissionGrantsLPr(parser, userId); 19232 } 19233 } 19234 } ); 19235 } catch (Exception e) { 19236 if (DEBUG_BACKUP) { 19237 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19238 } 19239 } 19240 } 19241 19242 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 19243 throws IOException { 19244 serializer.startTag(null, TAG_ALL_GRANTS); 19245 19246 final int N = mSettings.mPackages.size(); 19247 for (int i = 0; i < N; i++) { 19248 final PackageSetting ps = mSettings.mPackages.valueAt(i); 19249 boolean pkgGrantsKnown = false; 19250 19251 PermissionsState packagePerms = ps.getPermissionsState(); 19252 19253 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 19254 final int grantFlags = state.getFlags(); 19255 // only look at grants that are not system/policy fixed 19256 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 19257 final boolean isGranted = state.isGranted(); 19258 // And only back up the user-twiddled state bits 19259 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 19260 final String packageName = mSettings.mPackages.keyAt(i); 19261 if (!pkgGrantsKnown) { 19262 serializer.startTag(null, TAG_GRANT); 19263 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 19264 pkgGrantsKnown = true; 19265 } 19266 19267 final boolean userSet = 19268 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 19269 final boolean userFixed = 19270 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 19271 final boolean revoke = 19272 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 19273 19274 serializer.startTag(null, TAG_PERMISSION); 19275 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 19276 if (isGranted) { 19277 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 19278 } 19279 if (userSet) { 19280 serializer.attribute(null, ATTR_USER_SET, "true"); 19281 } 19282 if (userFixed) { 19283 serializer.attribute(null, ATTR_USER_FIXED, "true"); 19284 } 19285 if (revoke) { 19286 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 19287 } 19288 serializer.endTag(null, TAG_PERMISSION); 19289 } 19290 } 19291 } 19292 19293 if (pkgGrantsKnown) { 19294 serializer.endTag(null, TAG_GRANT); 19295 } 19296 } 19297 19298 serializer.endTag(null, TAG_ALL_GRANTS); 19299 } 19300 19301 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 19302 throws XmlPullParserException, IOException { 19303 String pkgName = null; 19304 int outerDepth = parser.getDepth(); 19305 int type; 19306 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 19307 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 19308 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 19309 continue; 19310 } 19311 19312 final String tagName = parser.getName(); 19313 if (tagName.equals(TAG_GRANT)) { 19314 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 19315 if (DEBUG_BACKUP) { 19316 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 19317 } 19318 } else if (tagName.equals(TAG_PERMISSION)) { 19319 19320 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 19321 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 19322 19323 int newFlagSet = 0; 19324 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 19325 newFlagSet |= FLAG_PERMISSION_USER_SET; 19326 } 19327 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 19328 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 19329 } 19330 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 19331 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 19332 } 19333 if (DEBUG_BACKUP) { 19334 Slog.v(TAG, " + Restoring grant:" 19335 + " pkg=" + pkgName 19336 + " perm=" + permName 19337 + " granted=" + isGranted 19338 + " bits=0x" + Integer.toHexString(newFlagSet)); 19339 } 19340 final PackageSetting ps = mSettings.mPackages.get(pkgName); 19341 if (ps != null) { 19342 // Already installed so we apply the grant immediately 19343 if (DEBUG_BACKUP) { 19344 Slog.v(TAG, " + already installed; applying"); 19345 } 19346 PermissionsState perms = ps.getPermissionsState(); 19347 BasePermission bp = 19348 (BasePermission) mPermissionManager.getPermissionTEMP(permName); 19349 if (bp != null) { 19350 if (isGranted) { 19351 perms.grantRuntimePermission(bp, userId); 19352 } 19353 if (newFlagSet != 0) { 19354 perms.updatePermissionFlags( 19355 bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 19356 } 19357 } 19358 } else { 19359 // Need to wait for post-restore install to apply the grant 19360 if (DEBUG_BACKUP) { 19361 Slog.v(TAG, " - not yet installed; saving for later"); 19362 } 19363 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 19364 isGranted, newFlagSet, userId); 19365 } 19366 } else { 19367 PackageManagerService.reportSettingsProblem(Log.WARN, 19368 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 19369 XmlUtils.skipCurrentTag(parser); 19370 } 19371 } 19372 19373 scheduleWriteSettingsLocked(); 19374 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 19375 } 19376 19377 @Override 19378 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 19379 int sourceUserId, int targetUserId, int flags) { 19380 mContext.enforceCallingOrSelfPermission( 19381 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 19382 int callingUid = Binder.getCallingUid(); 19383 enforceOwnerRights(ownerPackage, callingUid); 19384 PackageManagerServiceUtils.enforceShellRestriction( 19385 UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 19386 if (intentFilter.countActions() == 0) { 19387 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 19388 return; 19389 } 19390 synchronized (mPackages) { 19391 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 19392 ownerPackage, targetUserId, flags); 19393 CrossProfileIntentResolver resolver = 19394 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 19395 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 19396 // We have all those whose filter is equal. Now checking if the rest is equal as well. 19397 if (existing != null) { 19398 int size = existing.size(); 19399 for (int i = 0; i < size; i++) { 19400 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 19401 return; 19402 } 19403 } 19404 } 19405 resolver.addFilter(newFilter); 19406 scheduleWritePackageRestrictionsLocked(sourceUserId); 19407 } 19408 } 19409 19410 @Override 19411 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 19412 mContext.enforceCallingOrSelfPermission( 19413 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 19414 final int callingUid = Binder.getCallingUid(); 19415 enforceOwnerRights(ownerPackage, callingUid); 19416 PackageManagerServiceUtils.enforceShellRestriction( 19417 UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 19418 synchronized (mPackages) { 19419 CrossProfileIntentResolver resolver = 19420 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 19421 ArraySet<CrossProfileIntentFilter> set = 19422 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 19423 for (CrossProfileIntentFilter filter : set) { 19424 if (filter.getOwnerPackage().equals(ownerPackage)) { 19425 resolver.removeFilter(filter); 19426 } 19427 } 19428 scheduleWritePackageRestrictionsLocked(sourceUserId); 19429 } 19430 } 19431 19432 // Enforcing that callingUid is owning pkg on userId 19433 private void enforceOwnerRights(String pkg, int callingUid) { 19434 // The system owns everything. 19435 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 19436 return; 19437 } 19438 final int callingUserId = UserHandle.getUserId(callingUid); 19439 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 19440 if (pi == null) { 19441 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 19442 + callingUserId); 19443 } 19444 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 19445 throw new SecurityException("Calling uid " + callingUid 19446 + " does not own package " + pkg); 19447 } 19448 } 19449 19450 @Override 19451 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 19452 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 19453 return null; 19454 } 19455 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 19456 } 19457 19458 public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) { 19459 UserManagerService ums = UserManagerService.getInstance(); 19460 if (ums != null) { 19461 final UserInfo parent = ums.getProfileParent(userId); 19462 final int launcherUid = (parent != null) ? parent.id : userId; 19463 final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid); 19464 if (launcherComponent != null) { 19465 Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED) 19466 .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo) 19467 .putExtra(Intent.EXTRA_USER, UserHandle.of(userId)) 19468 .setPackage(launcherComponent.getPackageName()); 19469 mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid)); 19470 } 19471 } 19472 } 19473 19474 /** 19475 * Report the 'Home' activity which is currently set as "always use this one". If non is set 19476 * then reports the most likely home activity or null if there are more than one. 19477 */ 19478 private ComponentName getDefaultHomeActivity(int userId) { 19479 List<ResolveInfo> allHomeCandidates = new ArrayList<>(); 19480 ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId); 19481 if (cn != null) { 19482 return cn; 19483 } 19484 19485 // Find the launcher with the highest priority and return that component if there are no 19486 // other home activity with the same priority. 19487 int lastPriority = Integer.MIN_VALUE; 19488 ComponentName lastComponent = null; 19489 final int size = allHomeCandidates.size(); 19490 for (int i = 0; i < size; i++) { 19491 final ResolveInfo ri = allHomeCandidates.get(i); 19492 if (ri.priority > lastPriority) { 19493 lastComponent = ri.activityInfo.getComponentName(); 19494 lastPriority = ri.priority; 19495 } else if (ri.priority == lastPriority) { 19496 // Two components found with same priority. 19497 lastComponent = null; 19498 } 19499 } 19500 return lastComponent; 19501 } 19502 19503 private Intent getHomeIntent() { 19504 Intent intent = new Intent(Intent.ACTION_MAIN); 19505 intent.addCategory(Intent.CATEGORY_HOME); 19506 intent.addCategory(Intent.CATEGORY_DEFAULT); 19507 return intent; 19508 } 19509 19510 private IntentFilter getHomeFilter() { 19511 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 19512 filter.addCategory(Intent.CATEGORY_HOME); 19513 filter.addCategory(Intent.CATEGORY_DEFAULT); 19514 return filter; 19515 } 19516 19517 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 19518 int userId) { 19519 Intent intent = getHomeIntent(); 19520 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 19521 PackageManager.GET_META_DATA, userId); 19522 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 19523 true, false, false, userId); 19524 19525 allHomeCandidates.clear(); 19526 if (list != null) { 19527 for (ResolveInfo ri : list) { 19528 allHomeCandidates.add(ri); 19529 } 19530 } 19531 return (preferred == null || preferred.activityInfo == null) 19532 ? null 19533 : new ComponentName(preferred.activityInfo.packageName, 19534 preferred.activityInfo.name); 19535 } 19536 19537 @Override 19538 public void setHomeActivity(ComponentName comp, int userId) { 19539 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 19540 return; 19541 } 19542 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 19543 getHomeActivitiesAsUser(homeActivities, userId); 19544 19545 boolean found = false; 19546 19547 final int size = homeActivities.size(); 19548 final ComponentName[] set = new ComponentName[size]; 19549 for (int i = 0; i < size; i++) { 19550 final ResolveInfo candidate = homeActivities.get(i); 19551 final ActivityInfo info = candidate.activityInfo; 19552 final ComponentName activityName = new ComponentName(info.packageName, info.name); 19553 set[i] = activityName; 19554 if (!found && activityName.equals(comp)) { 19555 found = true; 19556 } 19557 } 19558 if (!found) { 19559 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 19560 + userId); 19561 } 19562 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 19563 set, comp, userId); 19564 } 19565 19566 private @Nullable String getSetupWizardPackageName() { 19567 final Intent intent = new Intent(Intent.ACTION_MAIN); 19568 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 19569 19570 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 19571 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 19572 | MATCH_DISABLED_COMPONENTS, 19573 UserHandle.myUserId()); 19574 if (matches.size() == 1) { 19575 return matches.get(0).getComponentInfo().packageName; 19576 } else { 19577 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 19578 + ": matches=" + matches); 19579 return null; 19580 } 19581 } 19582 19583 private @Nullable String getStorageManagerPackageName() { 19584 final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE); 19585 19586 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 19587 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 19588 | MATCH_DISABLED_COMPONENTS, 19589 UserHandle.myUserId()); 19590 if (matches.size() == 1) { 19591 return matches.get(0).getComponentInfo().packageName; 19592 } else { 19593 Slog.e(TAG, "There should probably be exactly one storage manager; found " 19594 + matches.size() + ": matches=" + matches); 19595 return null; 19596 } 19597 } 19598 19599 @Override 19600 public void setApplicationEnabledSetting(String appPackageName, 19601 int newState, int flags, int userId, String callingPackage) { 19602 if (!sUserManager.exists(userId)) return; 19603 if (callingPackage == null) { 19604 callingPackage = Integer.toString(Binder.getCallingUid()); 19605 } 19606 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 19607 } 19608 19609 @Override 19610 public void setUpdateAvailable(String packageName, boolean updateAvailable) { 19611 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 19612 synchronized (mPackages) { 19613 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 19614 if (pkgSetting != null) { 19615 pkgSetting.setUpdateAvailable(updateAvailable); 19616 } 19617 } 19618 } 19619 19620 @Override 19621 public void setComponentEnabledSetting(ComponentName componentName, 19622 int newState, int flags, int userId) { 19623 if (!sUserManager.exists(userId)) return; 19624 setEnabledSetting(componentName.getPackageName(), 19625 componentName.getClassName(), newState, flags, userId, null); 19626 } 19627 19628 private void setEnabledSetting(final String packageName, String className, int newState, 19629 final int flags, int userId, String callingPackage) { 19630 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 19631 || newState == COMPONENT_ENABLED_STATE_ENABLED 19632 || newState == COMPONENT_ENABLED_STATE_DISABLED 19633 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 19634 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 19635 throw new IllegalArgumentException("Invalid new component state: " 19636 + newState); 19637 } 19638 PackageSetting pkgSetting; 19639 final int callingUid = Binder.getCallingUid(); 19640 final int permission; 19641 if (callingUid == Process.SYSTEM_UID) { 19642 permission = PackageManager.PERMISSION_GRANTED; 19643 } else { 19644 permission = mContext.checkCallingOrSelfPermission( 19645 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 19646 } 19647 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 19648 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 19649 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 19650 boolean sendNow = false; 19651 boolean isApp = (className == null); 19652 final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null); 19653 String componentName = isApp ? packageName : className; 19654 int packageUid = -1; 19655 ArrayList<String> components; 19656 19657 // reader 19658 synchronized (mPackages) { 19659 pkgSetting = mSettings.mPackages.get(packageName); 19660 if (pkgSetting == null) { 19661 if (!isCallerInstantApp) { 19662 if (className == null) { 19663 throw new IllegalArgumentException("Unknown package: " + packageName); 19664 } 19665 throw new IllegalArgumentException( 19666 "Unknown component: " + packageName + "/" + className); 19667 } else { 19668 // throw SecurityException to prevent leaking package information 19669 throw new SecurityException( 19670 "Attempt to change component state; " 19671 + "pid=" + Binder.getCallingPid() 19672 + ", uid=" + callingUid 19673 + (className == null 19674 ? ", package=" + packageName 19675 : ", component=" + packageName + "/" + className)); 19676 } 19677 } 19678 } 19679 19680 // Limit who can change which apps 19681 if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) { 19682 // Don't allow apps that don't have permission to modify other apps 19683 if (!allowedByPermission 19684 || filterAppAccessLPr(pkgSetting, callingUid, userId)) { 19685 throw new SecurityException( 19686 "Attempt to change component state; " 19687 + "pid=" + Binder.getCallingPid() 19688 + ", uid=" + callingUid 19689 + (className == null 19690 ? ", package=" + packageName 19691 : ", component=" + packageName + "/" + className)); 19692 } 19693 // Don't allow changing protected packages. 19694 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 19695 throw new SecurityException("Cannot disable a protected package: " + packageName); 19696 } 19697 } 19698 19699 synchronized (mPackages) { 19700 if (callingUid == Process.SHELL_UID 19701 && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) { 19702 // Shell can only change whole packages between ENABLED and DISABLED_USER states 19703 // unless it is a test package. 19704 int oldState = pkgSetting.getEnabled(userId); 19705 if (className == null 19706 && 19707 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 19708 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 19709 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 19710 && 19711 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 19712 || newState == COMPONENT_ENABLED_STATE_DEFAULT 19713 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 19714 // ok 19715 } else { 19716 throw new SecurityException( 19717 "Shell cannot change component state for " + packageName + "/" 19718 + className + " to " + newState); 19719 } 19720 } 19721 } 19722 if (className == null) { 19723 // We're dealing with an application/package level state change 19724 synchronized (mPackages) { 19725 if (pkgSetting.getEnabled(userId) == newState) { 19726 // Nothing to do 19727 return; 19728 } 19729 } 19730 // If we're enabling a system stub, there's a little more work to do. 19731 // Prior to enabling the package, we need to decompress the APK(s) to the 19732 // data partition and then replace the version on the system partition. 19733 final PackageParser.Package deletedPkg = pkgSetting.pkg; 19734 final boolean isSystemStub = deletedPkg.isStub 19735 && deletedPkg.isSystem(); 19736 if (isSystemStub 19737 && (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 19738 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)) { 19739 final File codePath = decompressPackage(deletedPkg); 19740 if (codePath == null) { 19741 Slog.e(TAG, "couldn't decompress pkg: " + pkgSetting.name); 19742 return; 19743 } 19744 // TODO remove direct parsing of the package object during internal cleanup 19745 // of scan package 19746 // We need to call parse directly here for no other reason than we need 19747 // the new package in order to disable the old one [we use the information 19748 // for some internal optimization to optionally create a new package setting 19749 // object on replace]. However, we can't get the package from the scan 19750 // because the scan modifies live structures and we need to remove the 19751 // old [system] package from the system before a scan can be attempted. 19752 // Once scan is indempotent we can remove this parse and use the package 19753 // object we scanned, prior to adding it to package settings. 19754 final PackageParser pp = new PackageParser(); 19755 pp.setSeparateProcesses(mSeparateProcesses); 19756 pp.setDisplayMetrics(mMetrics); 19757 pp.setCallback(mPackageParserCallback); 19758 final PackageParser.Package tmpPkg; 19759 try { 19760 final @ParseFlags int parseFlags = mDefParseFlags 19761 | PackageParser.PARSE_MUST_BE_APK 19762 | PackageParser.PARSE_IS_SYSTEM_DIR; 19763 tmpPkg = pp.parsePackage(codePath, parseFlags); 19764 } catch (PackageParserException e) { 19765 Slog.w(TAG, "Failed to parse compressed system package:" + pkgSetting.name, e); 19766 return; 19767 } 19768 synchronized (mInstallLock) { 19769 // Disable the stub and remove any package entries 19770 removePackageLI(deletedPkg, true); 19771 synchronized (mPackages) { 19772 disableSystemPackageLPw(deletedPkg, tmpPkg); 19773 } 19774 final PackageParser.Package pkg; 19775 try (PackageFreezer freezer = 19776 freezePackage(deletedPkg.packageName, "setEnabledSetting")) { 19777 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 19778 | PackageParser.PARSE_ENFORCE_CODE; 19779 pkg = scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/, 19780 0 /*currentTime*/, null /*user*/); 19781 prepareAppDataAfterInstallLIF(pkg); 19782 synchronized (mPackages) { 19783 try { 19784 updateSharedLibrariesLPr(pkg, null); 19785 } catch (PackageManagerException e) { 19786 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: ", e); 19787 } 19788 mPermissionManager.updatePermissions( 19789 pkg.packageName, pkg, true, mPackages.values(), 19790 mPermissionCallback); 19791 mSettings.writeLPr(); 19792 } 19793 } catch (PackageManagerException e) { 19794 // Whoops! Something went wrong; try to roll back to the stub 19795 Slog.w(TAG, "Failed to install compressed system package:" 19796 + pkgSetting.name, e); 19797 // Remove the failed install 19798 removeCodePathLI(codePath); 19799 19800 // Install the system package 19801 try (PackageFreezer freezer = 19802 freezePackage(deletedPkg.packageName, "setEnabledSetting")) { 19803 synchronized (mPackages) { 19804 // NOTE: The system package always needs to be enabled; even 19805 // if it's for a compressed stub. If we don't, installing the 19806 // system package fails during scan [scanning checks the disabled 19807 // packages]. We will reverse this later, after we've "installed" 19808 // the stub. 19809 // This leaves us in a fragile state; the stub should never be 19810 // enabled, so, cross your fingers and hope nothing goes wrong 19811 // until we can disable the package later. 19812 enableSystemPackageLPw(deletedPkg); 19813 } 19814 installPackageFromSystemLIF(deletedPkg.codePath, 19815 false /*isPrivileged*/, null /*allUserHandles*/, 19816 null /*origUserHandles*/, null /*origPermissionsState*/, 19817 true /*writeSettings*/); 19818 } catch (PackageManagerException pme) { 19819 Slog.w(TAG, "Failed to restore system package:" 19820 + deletedPkg.packageName, pme); 19821 } finally { 19822 synchronized (mPackages) { 19823 mSettings.disableSystemPackageLPw( 19824 deletedPkg.packageName, true /*replaced*/); 19825 mSettings.writeLPr(); 19826 } 19827 } 19828 return; 19829 } 19830 clearAppDataLIF(pkg, UserHandle.USER_ALL, FLAG_STORAGE_DE 19831 | FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 19832 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 19833 mDexManager.notifyPackageUpdated(pkg.packageName, 19834 pkg.baseCodePath, pkg.splitCodePaths); 19835 } 19836 } 19837 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 19838 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 19839 // Don't care about who enables an app. 19840 callingPackage = null; 19841 } 19842 synchronized (mPackages) { 19843 pkgSetting.setEnabled(newState, userId, callingPackage); 19844 } 19845 } else { 19846 synchronized (mPackages) { 19847 // We're dealing with a component level state change 19848 // First, verify that this is a valid class name. 19849 PackageParser.Package pkg = pkgSetting.pkg; 19850 if (pkg == null || !pkg.hasComponentClassName(className)) { 19851 if (pkg != null && 19852 pkg.applicationInfo.targetSdkVersion >= 19853 Build.VERSION_CODES.JELLY_BEAN) { 19854 throw new IllegalArgumentException("Component class " + className 19855 + " does not exist in " + packageName); 19856 } else { 19857 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 19858 + className + " does not exist in " + packageName); 19859 } 19860 } 19861 switch (newState) { 19862 case COMPONENT_ENABLED_STATE_ENABLED: 19863 if (!pkgSetting.enableComponentLPw(className, userId)) { 19864 return; 19865 } 19866 break; 19867 case COMPONENT_ENABLED_STATE_DISABLED: 19868 if (!pkgSetting.disableComponentLPw(className, userId)) { 19869 return; 19870 } 19871 break; 19872 case COMPONENT_ENABLED_STATE_DEFAULT: 19873 if (!pkgSetting.restoreComponentLPw(className, userId)) { 19874 return; 19875 } 19876 break; 19877 default: 19878 Slog.e(TAG, "Invalid new component state: " + newState); 19879 return; 19880 } 19881 } 19882 } 19883 synchronized (mPackages) { 19884 scheduleWritePackageRestrictionsLocked(userId); 19885 updateSequenceNumberLP(pkgSetting, new int[] { userId }); 19886 final long callingId = Binder.clearCallingIdentity(); 19887 try { 19888 updateInstantAppInstallerLocked(packageName); 19889 } finally { 19890 Binder.restoreCallingIdentity(callingId); 19891 } 19892 components = mPendingBroadcasts.get(userId, packageName); 19893 final boolean newPackage = components == null; 19894 if (newPackage) { 19895 components = new ArrayList<String>(); 19896 } 19897 if (!components.contains(componentName)) { 19898 components.add(componentName); 19899 } 19900 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 19901 sendNow = true; 19902 // Purge entry from pending broadcast list if another one exists already 19903 // since we are sending one right away. 19904 mPendingBroadcasts.remove(userId, packageName); 19905 } else { 19906 if (newPackage) { 19907 mPendingBroadcasts.put(userId, packageName, components); 19908 } 19909 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 19910 // Schedule a message 19911 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 19912 } 19913 } 19914 } 19915 19916 long callingId = Binder.clearCallingIdentity(); 19917 try { 19918 if (sendNow) { 19919 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 19920 sendPackageChangedBroadcast(packageName, 19921 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 19922 } 19923 } finally { 19924 Binder.restoreCallingIdentity(callingId); 19925 } 19926 } 19927 19928 @Override 19929 public void flushPackageRestrictionsAsUser(int userId) { 19930 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 19931 return; 19932 } 19933 if (!sUserManager.exists(userId)) { 19934 return; 19935 } 19936 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 19937 false /* checkShell */, "flushPackageRestrictions"); 19938 synchronized (mPackages) { 19939 mSettings.writePackageRestrictionsLPr(userId); 19940 mDirtyUsers.remove(userId); 19941 if (mDirtyUsers.isEmpty()) { 19942 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 19943 } 19944 } 19945 } 19946 19947 private void sendPackageChangedBroadcast(String packageName, 19948 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 19949 if (DEBUG_INSTALL) 19950 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 19951 + componentNames); 19952 Bundle extras = new Bundle(4); 19953 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 19954 String nameList[] = new String[componentNames.size()]; 19955 componentNames.toArray(nameList); 19956 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 19957 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 19958 extras.putInt(Intent.EXTRA_UID, packageUid); 19959 // If this is not reporting a change of the overall package, then only send it 19960 // to registered receivers. We don't want to launch a swath of apps for every 19961 // little component state change. 19962 final int flags = !componentNames.contains(packageName) 19963 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 19964 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 19965 new int[] {UserHandle.getUserId(packageUid)}); 19966 } 19967 19968 @Override 19969 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 19970 if (!sUserManager.exists(userId)) return; 19971 final int callingUid = Binder.getCallingUid(); 19972 if (getInstantAppPackageName(callingUid) != null) { 19973 return; 19974 } 19975 final int permission = mContext.checkCallingOrSelfPermission( 19976 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 19977 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 19978 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 19979 true /* requireFullPermission */, true /* checkShell */, "stop package"); 19980 // writer 19981 synchronized (mPackages) { 19982 final PackageSetting ps = mSettings.mPackages.get(packageName); 19983 if (!filterAppAccessLPr(ps, callingUid, userId) 19984 && mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 19985 allowedByPermission, callingUid, userId)) { 19986 scheduleWritePackageRestrictionsLocked(userId); 19987 } 19988 } 19989 } 19990 19991 @Override 19992 public String getInstallerPackageName(String packageName) { 19993 final int callingUid = Binder.getCallingUid(); 19994 if (getInstantAppPackageName(callingUid) != null) { 19995 return null; 19996 } 19997 // reader 19998 synchronized (mPackages) { 19999 final PackageSetting ps = mSettings.mPackages.get(packageName); 20000 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 20001 return null; 20002 } 20003 return mSettings.getInstallerPackageNameLPr(packageName); 20004 } 20005 } 20006 20007 public boolean isOrphaned(String packageName) { 20008 // reader 20009 synchronized (mPackages) { 20010 return mSettings.isOrphaned(packageName); 20011 } 20012 } 20013 20014 @Override 20015 public int getApplicationEnabledSetting(String packageName, int userId) { 20016 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 20017 int callingUid = Binder.getCallingUid(); 20018 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 20019 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 20020 // reader 20021 synchronized (mPackages) { 20022 if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) { 20023 return COMPONENT_ENABLED_STATE_DISABLED; 20024 } 20025 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 20026 } 20027 } 20028 20029 @Override 20030 public int getComponentEnabledSetting(ComponentName component, int userId) { 20031 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 20032 int callingUid = Binder.getCallingUid(); 20033 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 20034 false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled"); 20035 synchronized (mPackages) { 20036 if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid, 20037 component, TYPE_UNKNOWN, userId)) { 20038 return COMPONENT_ENABLED_STATE_DISABLED; 20039 } 20040 return mSettings.getComponentEnabledSettingLPr(component, userId); 20041 } 20042 } 20043 20044 @Override 20045 public void enterSafeMode() { 20046 enforceSystemOrRoot("Only the system can request entering safe mode"); 20047 20048 if (!mSystemReady) { 20049 mSafeMode = true; 20050 } 20051 } 20052 20053 @Override 20054 public void systemReady() { 20055 enforceSystemOrRoot("Only the system can claim the system is ready"); 20056 20057 mSystemReady = true; 20058 final ContentResolver resolver = mContext.getContentResolver(); 20059 ContentObserver co = new ContentObserver(mHandler) { 20060 @Override 20061 public void onChange(boolean selfChange) { 20062 mEphemeralAppsDisabled = 20063 (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) || 20064 (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0); 20065 } 20066 }; 20067 mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global 20068 .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE), 20069 false, co, UserHandle.USER_SYSTEM); 20070 mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global 20071 .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM); 20072 co.onChange(true); 20073 20074 // This observer provides an one directional mapping from Global.PRIV_APP_OOB_ENABLED to 20075 // pm.dexopt.priv-apps-oob property. This is only for experiment and should be removed once 20076 // it is done. 20077 ContentObserver privAppOobObserver = new ContentObserver(mHandler) { 20078 @Override 20079 public void onChange(boolean selfChange) { 20080 int oobEnabled = Global.getInt(resolver, Global.PRIV_APP_OOB_ENABLED, 0); 20081 SystemProperties.set(PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB, 20082 oobEnabled == 1 ? "true" : "false"); 20083 } 20084 }; 20085 mContext.getContentResolver().registerContentObserver( 20086 Global.getUriFor(Global.PRIV_APP_OOB_ENABLED), false, privAppOobObserver, 20087 UserHandle.USER_SYSTEM); 20088 // At boot, restore the value from the setting, which persists across reboot. 20089 privAppOobObserver.onChange(true); 20090 20091 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 20092 // disabled after already being started. 20093 CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this, 20094 mContext.getContentResolver(), UserHandle.USER_SYSTEM); 20095 20096 // Read the compatibilty setting when the system is ready. 20097 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 20098 mContext.getContentResolver(), 20099 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 20100 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 20101 if (DEBUG_SETTINGS) { 20102 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 20103 } 20104 20105 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 20106 20107 synchronized (mPackages) { 20108 // Verify that all of the preferred activity components actually 20109 // exist. It is possible for applications to be updated and at 20110 // that point remove a previously declared activity component that 20111 // had been set as a preferred activity. We try to clean this up 20112 // the next time we encounter that preferred activity, but it is 20113 // possible for the user flow to never be able to return to that 20114 // situation so here we do a sanity check to make sure we haven't 20115 // left any junk around. 20116 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 20117 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 20118 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 20119 removed.clear(); 20120 for (PreferredActivity pa : pir.filterSet()) { 20121 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 20122 removed.add(pa); 20123 } 20124 } 20125 if (removed.size() > 0) { 20126 for (int r=0; r<removed.size(); r++) { 20127 PreferredActivity pa = removed.get(r); 20128 Slog.w(TAG, "Removing dangling preferred activity: " 20129 + pa.mPref.mComponent); 20130 pir.removeFilter(pa); 20131 } 20132 mSettings.writePackageRestrictionsLPr( 20133 mSettings.mPreferredActivities.keyAt(i)); 20134 } 20135 } 20136 20137 for (int userId : UserManagerService.getInstance().getUserIds()) { 20138 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 20139 grantPermissionsUserIds = ArrayUtils.appendInt( 20140 grantPermissionsUserIds, userId); 20141 } 20142 } 20143 } 20144 sUserManager.systemReady(); 20145 20146 // If we upgraded grant all default permissions before kicking off. 20147 for (int userId : grantPermissionsUserIds) { 20148 mDefaultPermissionPolicy.grantDefaultPermissions(mPackages.values(), userId); 20149 } 20150 20151 if (grantPermissionsUserIds == EMPTY_INT_ARRAY) { 20152 // If we did not grant default permissions, we preload from this the 20153 // default permission exceptions lazily to ensure we don't hit the 20154 // disk on a new user creation. 20155 mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions(); 20156 } 20157 20158 // Now that we've scanned all packages, and granted any default 20159 // permissions, ensure permissions are updated. Beware of dragons if you 20160 // try optimizing this. 20161 synchronized (mPackages) { 20162 mPermissionManager.updateAllPermissions( 20163 StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(), 20164 mPermissionCallback); 20165 } 20166 20167 // Kick off any messages waiting for system ready 20168 if (mPostSystemReadyMessages != null) { 20169 for (Message msg : mPostSystemReadyMessages) { 20170 msg.sendToTarget(); 20171 } 20172 mPostSystemReadyMessages = null; 20173 } 20174 20175 // Watch for external volumes that come and go over time 20176 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20177 storage.registerListener(mStorageListener); 20178 20179 mInstallerService.systemReady(); 20180 mPackageDexOptimizer.systemReady(); 20181 20182 StorageManagerInternal StorageManagerInternal = LocalServices.getService( 20183 StorageManagerInternal.class); 20184 StorageManagerInternal.addExternalStoragePolicy( 20185 new StorageManagerInternal.ExternalStorageMountPolicy() { 20186 @Override 20187 public int getMountMode(int uid, String packageName) { 20188 if (Process.isIsolated(uid)) { 20189 return Zygote.MOUNT_EXTERNAL_NONE; 20190 } 20191 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 20192 return Zygote.MOUNT_EXTERNAL_DEFAULT; 20193 } 20194 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 20195 return Zygote.MOUNT_EXTERNAL_DEFAULT; 20196 } 20197 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 20198 return Zygote.MOUNT_EXTERNAL_READ; 20199 } 20200 return Zygote.MOUNT_EXTERNAL_WRITE; 20201 } 20202 20203 @Override 20204 public boolean hasExternalStorage(int uid, String packageName) { 20205 return true; 20206 } 20207 }); 20208 20209 // Now that we're mostly running, clean up stale users and apps 20210 sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 20211 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 20212 20213 mPermissionManager.systemReady(); 20214 } 20215 20216 public void waitForAppDataPrepared() { 20217 if (mPrepareAppDataFuture == null) { 20218 return; 20219 } 20220 ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData"); 20221 mPrepareAppDataFuture = null; 20222 } 20223 20224 @Override 20225 public boolean isSafeMode() { 20226 // allow instant applications 20227 return mSafeMode; 20228 } 20229 20230 @Override 20231 public boolean hasSystemUidErrors() { 20232 // allow instant applications 20233 return mHasSystemUidErrors; 20234 } 20235 20236 static String arrayToString(int[] array) { 20237 StringBuffer buf = new StringBuffer(128); 20238 buf.append('['); 20239 if (array != null) { 20240 for (int i=0; i<array.length; i++) { 20241 if (i > 0) buf.append(", "); 20242 buf.append(array[i]); 20243 } 20244 } 20245 buf.append(']'); 20246 return buf.toString(); 20247 } 20248 20249 @Override 20250 public void onShellCommand(FileDescriptor in, FileDescriptor out, 20251 FileDescriptor err, String[] args, ShellCallback callback, 20252 ResultReceiver resultReceiver) { 20253 (new PackageManagerShellCommand(this)).exec( 20254 this, in, out, err, args, callback, resultReceiver); 20255 } 20256 20257 @Override 20258 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 20259 if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return; 20260 20261 DumpState dumpState = new DumpState(); 20262 boolean fullPreferred = false; 20263 boolean checkin = false; 20264 20265 String packageName = null; 20266 ArraySet<String> permissionNames = null; 20267 20268 int opti = 0; 20269 while (opti < args.length) { 20270 String opt = args[opti]; 20271 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 20272 break; 20273 } 20274 opti++; 20275 20276 if ("-a".equals(opt)) { 20277 // Right now we only know how to print all. 20278 } else if ("-h".equals(opt)) { 20279 pw.println("Package manager dump options:"); 20280 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 20281 pw.println(" --checkin: dump for a checkin"); 20282 pw.println(" -f: print details of intent filters"); 20283 pw.println(" -h: print this help"); 20284 pw.println(" cmd may be one of:"); 20285 pw.println(" l[ibraries]: list known shared libraries"); 20286 pw.println(" f[eatures]: list device features"); 20287 pw.println(" k[eysets]: print known keysets"); 20288 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 20289 pw.println(" perm[issions]: dump permissions"); 20290 pw.println(" permission [name ...]: dump declaration and use of given permission"); 20291 pw.println(" pref[erred]: print preferred package settings"); 20292 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 20293 pw.println(" prov[iders]: dump content providers"); 20294 pw.println(" p[ackages]: dump installed packages"); 20295 pw.println(" s[hared-users]: dump shared user IDs"); 20296 pw.println(" m[essages]: print collected runtime messages"); 20297 pw.println(" v[erifiers]: print package verifier info"); 20298 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 20299 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 20300 pw.println(" version: print database version info"); 20301 pw.println(" write: write current settings now"); 20302 pw.println(" installs: details about install sessions"); 20303 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 20304 pw.println(" dexopt: dump dexopt state"); 20305 pw.println(" compiler-stats: dump compiler statistics"); 20306 pw.println(" enabled-overlays: dump list of enabled overlay packages"); 20307 pw.println(" <package.name>: info about given package"); 20308 return; 20309 } else if ("--checkin".equals(opt)) { 20310 checkin = true; 20311 } else if ("-f".equals(opt)) { 20312 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 20313 } else if ("--proto".equals(opt)) { 20314 dumpProto(fd); 20315 return; 20316 } else { 20317 pw.println("Unknown argument: " + opt + "; use -h for help"); 20318 } 20319 } 20320 20321 // Is the caller requesting to dump a particular piece of data? 20322 if (opti < args.length) { 20323 String cmd = args[opti]; 20324 opti++; 20325 // Is this a package name? 20326 if ("android".equals(cmd) || cmd.contains(".")) { 20327 packageName = cmd; 20328 // When dumping a single package, we always dump all of its 20329 // filter information since the amount of data will be reasonable. 20330 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 20331 } else if ("check-permission".equals(cmd)) { 20332 if (opti >= args.length) { 20333 pw.println("Error: check-permission missing permission argument"); 20334 return; 20335 } 20336 String perm = args[opti]; 20337 opti++; 20338 if (opti >= args.length) { 20339 pw.println("Error: check-permission missing package argument"); 20340 return; 20341 } 20342 20343 String pkg = args[opti]; 20344 opti++; 20345 int user = UserHandle.getUserId(Binder.getCallingUid()); 20346 if (opti < args.length) { 20347 try { 20348 user = Integer.parseInt(args[opti]); 20349 } catch (NumberFormatException e) { 20350 pw.println("Error: check-permission user argument is not a number: " 20351 + args[opti]); 20352 return; 20353 } 20354 } 20355 20356 // Normalize package name to handle renamed packages and static libs 20357 pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST); 20358 20359 pw.println(checkPermission(perm, pkg, user)); 20360 return; 20361 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 20362 dumpState.setDump(DumpState.DUMP_LIBS); 20363 } else if ("f".equals(cmd) || "features".equals(cmd)) { 20364 dumpState.setDump(DumpState.DUMP_FEATURES); 20365 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 20366 if (opti >= args.length) { 20367 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 20368 | DumpState.DUMP_SERVICE_RESOLVERS 20369 | DumpState.DUMP_RECEIVER_RESOLVERS 20370 | DumpState.DUMP_CONTENT_RESOLVERS); 20371 } else { 20372 while (opti < args.length) { 20373 String name = args[opti]; 20374 if ("a".equals(name) || "activity".equals(name)) { 20375 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 20376 } else if ("s".equals(name) || "service".equals(name)) { 20377 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 20378 } else if ("r".equals(name) || "receiver".equals(name)) { 20379 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 20380 } else if ("c".equals(name) || "content".equals(name)) { 20381 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 20382 } else { 20383 pw.println("Error: unknown resolver table type: " + name); 20384 return; 20385 } 20386 opti++; 20387 } 20388 } 20389 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 20390 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 20391 } else if ("permission".equals(cmd)) { 20392 if (opti >= args.length) { 20393 pw.println("Error: permission requires permission name"); 20394 return; 20395 } 20396 permissionNames = new ArraySet<>(); 20397 while (opti < args.length) { 20398 permissionNames.add(args[opti]); 20399 opti++; 20400 } 20401 dumpState.setDump(DumpState.DUMP_PERMISSIONS 20402 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 20403 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 20404 dumpState.setDump(DumpState.DUMP_PREFERRED); 20405 } else if ("preferred-xml".equals(cmd)) { 20406 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 20407 if (opti < args.length && "--full".equals(args[opti])) { 20408 fullPreferred = true; 20409 opti++; 20410 } 20411 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 20412 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 20413 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 20414 dumpState.setDump(DumpState.DUMP_PACKAGES); 20415 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 20416 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 20417 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 20418 dumpState.setDump(DumpState.DUMP_PROVIDERS); 20419 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 20420 dumpState.setDump(DumpState.DUMP_MESSAGES); 20421 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 20422 dumpState.setDump(DumpState.DUMP_VERIFIERS); 20423 } else if ("i".equals(cmd) || "ifv".equals(cmd) 20424 || "intent-filter-verifiers".equals(cmd)) { 20425 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 20426 } else if ("version".equals(cmd)) { 20427 dumpState.setDump(DumpState.DUMP_VERSION); 20428 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 20429 dumpState.setDump(DumpState.DUMP_KEYSETS); 20430 } else if ("installs".equals(cmd)) { 20431 dumpState.setDump(DumpState.DUMP_INSTALLS); 20432 } else if ("frozen".equals(cmd)) { 20433 dumpState.setDump(DumpState.DUMP_FROZEN); 20434 } else if ("volumes".equals(cmd)) { 20435 dumpState.setDump(DumpState.DUMP_VOLUMES); 20436 } else if ("dexopt".equals(cmd)) { 20437 dumpState.setDump(DumpState.DUMP_DEXOPT); 20438 } else if ("compiler-stats".equals(cmd)) { 20439 dumpState.setDump(DumpState.DUMP_COMPILER_STATS); 20440 } else if ("changes".equals(cmd)) { 20441 dumpState.setDump(DumpState.DUMP_CHANGES); 20442 } else if ("write".equals(cmd)) { 20443 synchronized (mPackages) { 20444 mSettings.writeLPr(); 20445 pw.println("Settings written."); 20446 return; 20447 } 20448 } 20449 } 20450 20451 if (checkin) { 20452 pw.println("vers,1"); 20453 } 20454 20455 // reader 20456 synchronized (mPackages) { 20457 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 20458 if (!checkin) { 20459 if (dumpState.onTitlePrinted()) 20460 pw.println(); 20461 pw.println("Database versions:"); 20462 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 20463 } 20464 } 20465 20466 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 20467 if (!checkin) { 20468 if (dumpState.onTitlePrinted()) 20469 pw.println(); 20470 pw.println("Verifiers:"); 20471 pw.print(" Required: "); 20472 pw.print(mRequiredVerifierPackage); 20473 pw.print(" (uid="); 20474 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 20475 UserHandle.USER_SYSTEM)); 20476 pw.println(")"); 20477 } else if (mRequiredVerifierPackage != null) { 20478 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 20479 pw.print(","); 20480 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 20481 UserHandle.USER_SYSTEM)); 20482 } 20483 } 20484 20485 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 20486 packageName == null) { 20487 if (mIntentFilterVerifierComponent != null) { 20488 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 20489 if (!checkin) { 20490 if (dumpState.onTitlePrinted()) 20491 pw.println(); 20492 pw.println("Intent Filter Verifier:"); 20493 pw.print(" Using: "); 20494 pw.print(verifierPackageName); 20495 pw.print(" (uid="); 20496 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 20497 UserHandle.USER_SYSTEM)); 20498 pw.println(")"); 20499 } else if (verifierPackageName != null) { 20500 pw.print("ifv,"); pw.print(verifierPackageName); 20501 pw.print(","); 20502 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 20503 UserHandle.USER_SYSTEM)); 20504 } 20505 } else { 20506 pw.println(); 20507 pw.println("No Intent Filter Verifier available!"); 20508 } 20509 } 20510 20511 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 20512 boolean printedHeader = false; 20513 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 20514 while (it.hasNext()) { 20515 String libName = it.next(); 20516 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName); 20517 if (versionedLib == null) { 20518 continue; 20519 } 20520 final int versionCount = versionedLib.size(); 20521 for (int i = 0; i < versionCount; i++) { 20522 SharedLibraryEntry libEntry = versionedLib.valueAt(i); 20523 if (!checkin) { 20524 if (!printedHeader) { 20525 if (dumpState.onTitlePrinted()) 20526 pw.println(); 20527 pw.println("Libraries:"); 20528 printedHeader = true; 20529 } 20530 pw.print(" "); 20531 } else { 20532 pw.print("lib,"); 20533 } 20534 pw.print(libEntry.info.getName()); 20535 if (libEntry.info.isStatic()) { 20536 pw.print(" version=" + libEntry.info.getVersion()); 20537 } 20538 if (!checkin) { 20539 pw.print(" -> "); 20540 } 20541 if (libEntry.path != null) { 20542 pw.print(" (jar) "); 20543 pw.print(libEntry.path); 20544 } else { 20545 pw.print(" (apk) "); 20546 pw.print(libEntry.apk); 20547 } 20548 pw.println(); 20549 } 20550 } 20551 } 20552 20553 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 20554 if (dumpState.onTitlePrinted()) 20555 pw.println(); 20556 if (!checkin) { 20557 pw.println("Features:"); 20558 } 20559 20560 synchronized (mAvailableFeatures) { 20561 for (FeatureInfo feat : mAvailableFeatures.values()) { 20562 if (checkin) { 20563 pw.print("feat,"); 20564 pw.print(feat.name); 20565 pw.print(","); 20566 pw.println(feat.version); 20567 } else { 20568 pw.print(" "); 20569 pw.print(feat.name); 20570 if (feat.version > 0) { 20571 pw.print(" version="); 20572 pw.print(feat.version); 20573 } 20574 pw.println(); 20575 } 20576 } 20577 } 20578 } 20579 20580 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 20581 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 20582 : "Activity Resolver Table:", " ", packageName, 20583 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20584 dumpState.setTitlePrinted(true); 20585 } 20586 } 20587 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 20588 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 20589 : "Receiver Resolver Table:", " ", packageName, 20590 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20591 dumpState.setTitlePrinted(true); 20592 } 20593 } 20594 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 20595 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 20596 : "Service Resolver Table:", " ", packageName, 20597 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20598 dumpState.setTitlePrinted(true); 20599 } 20600 } 20601 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 20602 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 20603 : "Provider Resolver Table:", " ", packageName, 20604 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20605 dumpState.setTitlePrinted(true); 20606 } 20607 } 20608 20609 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 20610 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 20611 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 20612 int user = mSettings.mPreferredActivities.keyAt(i); 20613 if (pir.dump(pw, 20614 dumpState.getTitlePrinted() 20615 ? "\nPreferred Activities User " + user + ":" 20616 : "Preferred Activities User " + user + ":", " ", 20617 packageName, true, false)) { 20618 dumpState.setTitlePrinted(true); 20619 } 20620 } 20621 } 20622 20623 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 20624 pw.flush(); 20625 FileOutputStream fout = new FileOutputStream(fd); 20626 BufferedOutputStream str = new BufferedOutputStream(fout); 20627 XmlSerializer serializer = new FastXmlSerializer(); 20628 try { 20629 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 20630 serializer.startDocument(null, true); 20631 serializer.setFeature( 20632 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 20633 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 20634 serializer.endDocument(); 20635 serializer.flush(); 20636 } catch (IllegalArgumentException e) { 20637 pw.println("Failed writing: " + e); 20638 } catch (IllegalStateException e) { 20639 pw.println("Failed writing: " + e); 20640 } catch (IOException e) { 20641 pw.println("Failed writing: " + e); 20642 } 20643 } 20644 20645 if (!checkin 20646 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 20647 && packageName == null) { 20648 pw.println(); 20649 int count = mSettings.mPackages.size(); 20650 if (count == 0) { 20651 pw.println("No applications!"); 20652 pw.println(); 20653 } else { 20654 final String prefix = " "; 20655 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 20656 if (allPackageSettings.size() == 0) { 20657 pw.println("No domain preferred apps!"); 20658 pw.println(); 20659 } else { 20660 pw.println("App verification status:"); 20661 pw.println(); 20662 count = 0; 20663 for (PackageSetting ps : allPackageSettings) { 20664 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 20665 if (ivi == null || ivi.getPackageName() == null) continue; 20666 pw.println(prefix + "Package: " + ivi.getPackageName()); 20667 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 20668 pw.println(prefix + "Status: " + ivi.getStatusString()); 20669 pw.println(); 20670 count++; 20671 } 20672 if (count == 0) { 20673 pw.println(prefix + "No app verification established."); 20674 pw.println(); 20675 } 20676 for (int userId : sUserManager.getUserIds()) { 20677 pw.println("App linkages for user " + userId + ":"); 20678 pw.println(); 20679 count = 0; 20680 for (PackageSetting ps : allPackageSettings) { 20681 final long status = ps.getDomainVerificationStatusForUser(userId); 20682 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 20683 && !DEBUG_DOMAIN_VERIFICATION) { 20684 continue; 20685 } 20686 pw.println(prefix + "Package: " + ps.name); 20687 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 20688 String statusStr = IntentFilterVerificationInfo. 20689 getStatusStringFromValue(status); 20690 pw.println(prefix + "Status: " + statusStr); 20691 pw.println(); 20692 count++; 20693 } 20694 if (count == 0) { 20695 pw.println(prefix + "No configured app linkages."); 20696 pw.println(); 20697 } 20698 } 20699 } 20700 } 20701 } 20702 20703 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 20704 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 20705 } 20706 20707 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 20708 boolean printedSomething = false; 20709 for (PackageParser.Provider p : mProviders.mProviders.values()) { 20710 if (packageName != null && !packageName.equals(p.info.packageName)) { 20711 continue; 20712 } 20713 if (!printedSomething) { 20714 if (dumpState.onTitlePrinted()) 20715 pw.println(); 20716 pw.println("Registered ContentProviders:"); 20717 printedSomething = true; 20718 } 20719 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 20720 pw.print(" "); pw.println(p.toString()); 20721 } 20722 printedSomething = false; 20723 for (Map.Entry<String, PackageParser.Provider> entry : 20724 mProvidersByAuthority.entrySet()) { 20725 PackageParser.Provider p = entry.getValue(); 20726 if (packageName != null && !packageName.equals(p.info.packageName)) { 20727 continue; 20728 } 20729 if (!printedSomething) { 20730 if (dumpState.onTitlePrinted()) 20731 pw.println(); 20732 pw.println("ContentProvider Authorities:"); 20733 printedSomething = true; 20734 } 20735 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 20736 pw.print(" "); pw.println(p.toString()); 20737 if (p.info != null && p.info.applicationInfo != null) { 20738 final String appInfo = p.info.applicationInfo.toString(); 20739 pw.print(" applicationInfo="); pw.println(appInfo); 20740 } 20741 } 20742 } 20743 20744 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 20745 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 20746 } 20747 20748 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 20749 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 20750 } 20751 20752 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 20753 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 20754 } 20755 20756 if (dumpState.isDumping(DumpState.DUMP_CHANGES)) { 20757 if (dumpState.onTitlePrinted()) pw.println(); 20758 pw.println("Package Changes:"); 20759 pw.print(" Sequence number="); pw.println(mChangedPackagesSequenceNumber); 20760 final int K = mChangedPackages.size(); 20761 for (int i = 0; i < K; i++) { 20762 final SparseArray<String> changes = mChangedPackages.valueAt(i); 20763 pw.print(" User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":"); 20764 final int N = changes.size(); 20765 if (N == 0) { 20766 pw.print(" "); pw.println("No packages changed"); 20767 } else { 20768 for (int j = 0; j < N; j++) { 20769 final String pkgName = changes.valueAt(j); 20770 final int sequenceNumber = changes.keyAt(j); 20771 pw.print(" "); 20772 pw.print("seq="); 20773 pw.print(sequenceNumber); 20774 pw.print(", package="); 20775 pw.println(pkgName); 20776 } 20777 } 20778 } 20779 } 20780 20781 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 20782 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 20783 } 20784 20785 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 20786 // XXX should handle packageName != null by dumping only install data that 20787 // the given package is involved with. 20788 if (dumpState.onTitlePrinted()) pw.println(); 20789 20790 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 20791 ipw.println(); 20792 ipw.println("Frozen packages:"); 20793 ipw.increaseIndent(); 20794 if (mFrozenPackages.size() == 0) { 20795 ipw.println("(none)"); 20796 } else { 20797 for (int i = 0; i < mFrozenPackages.size(); i++) { 20798 ipw.println(mFrozenPackages.valueAt(i)); 20799 } 20800 } 20801 ipw.decreaseIndent(); 20802 } 20803 20804 if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) { 20805 if (dumpState.onTitlePrinted()) pw.println(); 20806 20807 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 20808 ipw.println(); 20809 ipw.println("Loaded volumes:"); 20810 ipw.increaseIndent(); 20811 if (mLoadedVolumes.size() == 0) { 20812 ipw.println("(none)"); 20813 } else { 20814 for (int i = 0; i < mLoadedVolumes.size(); i++) { 20815 ipw.println(mLoadedVolumes.valueAt(i)); 20816 } 20817 } 20818 ipw.decreaseIndent(); 20819 } 20820 20821 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 20822 if (dumpState.onTitlePrinted()) pw.println(); 20823 dumpDexoptStateLPr(pw, packageName); 20824 } 20825 20826 if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) { 20827 if (dumpState.onTitlePrinted()) pw.println(); 20828 dumpCompilerStatsLPr(pw, packageName); 20829 } 20830 20831 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 20832 if (dumpState.onTitlePrinted()) pw.println(); 20833 mSettings.dumpReadMessagesLPr(pw, dumpState); 20834 20835 pw.println(); 20836 pw.println("Package warning messages:"); 20837 dumpCriticalInfo(pw, null); 20838 } 20839 20840 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 20841 dumpCriticalInfo(pw, "msg,"); 20842 } 20843 } 20844 20845 // PackageInstaller should be called outside of mPackages lock 20846 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 20847 // XXX should handle packageName != null by dumping only install data that 20848 // the given package is involved with. 20849 if (dumpState.onTitlePrinted()) pw.println(); 20850 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 20851 } 20852 } 20853 20854 private void dumpProto(FileDescriptor fd) { 20855 final ProtoOutputStream proto = new ProtoOutputStream(fd); 20856 20857 synchronized (mPackages) { 20858 final long requiredVerifierPackageToken = 20859 proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE); 20860 proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage); 20861 proto.write( 20862 PackageServiceDumpProto.PackageShortProto.UID, 20863 getPackageUid( 20864 mRequiredVerifierPackage, 20865 MATCH_DEBUG_TRIAGED_MISSING, 20866 UserHandle.USER_SYSTEM)); 20867 proto.end(requiredVerifierPackageToken); 20868 20869 if (mIntentFilterVerifierComponent != null) { 20870 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 20871 final long verifierPackageToken = 20872 proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE); 20873 proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName); 20874 proto.write( 20875 PackageServiceDumpProto.PackageShortProto.UID, 20876 getPackageUid( 20877 verifierPackageName, 20878 MATCH_DEBUG_TRIAGED_MISSING, 20879 UserHandle.USER_SYSTEM)); 20880 proto.end(verifierPackageToken); 20881 } 20882 20883 dumpSharedLibrariesProto(proto); 20884 dumpFeaturesProto(proto); 20885 mSettings.dumpPackagesProto(proto); 20886 mSettings.dumpSharedUsersProto(proto); 20887 dumpCriticalInfo(proto); 20888 } 20889 proto.flush(); 20890 } 20891 20892 private void dumpFeaturesProto(ProtoOutputStream proto) { 20893 synchronized (mAvailableFeatures) { 20894 final int count = mAvailableFeatures.size(); 20895 for (int i = 0; i < count; i++) { 20896 mAvailableFeatures.valueAt(i).writeToProto(proto, PackageServiceDumpProto.FEATURES); 20897 } 20898 } 20899 } 20900 20901 private void dumpSharedLibrariesProto(ProtoOutputStream proto) { 20902 final int count = mSharedLibraries.size(); 20903 for (int i = 0; i < count; i++) { 20904 final String libName = mSharedLibraries.keyAt(i); 20905 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName); 20906 if (versionedLib == null) { 20907 continue; 20908 } 20909 final int versionCount = versionedLib.size(); 20910 for (int j = 0; j < versionCount; j++) { 20911 final SharedLibraryEntry libEntry = versionedLib.valueAt(j); 20912 final long sharedLibraryToken = 20913 proto.start(PackageServiceDumpProto.SHARED_LIBRARIES); 20914 proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName()); 20915 final boolean isJar = (libEntry.path != null); 20916 proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar); 20917 if (isJar) { 20918 proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path); 20919 } else { 20920 proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk); 20921 } 20922 proto.end(sharedLibraryToken); 20923 } 20924 } 20925 } 20926 20927 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 20928 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " "); 20929 ipw.println(); 20930 ipw.println("Dexopt state:"); 20931 ipw.increaseIndent(); 20932 Collection<PackageParser.Package> packages = null; 20933 if (packageName != null) { 20934 PackageParser.Package targetPackage = mPackages.get(packageName); 20935 if (targetPackage != null) { 20936 packages = Collections.singletonList(targetPackage); 20937 } else { 20938 ipw.println("Unable to find package: " + packageName); 20939 return; 20940 } 20941 } else { 20942 packages = mPackages.values(); 20943 } 20944 20945 for (PackageParser.Package pkg : packages) { 20946 ipw.println("[" + pkg.packageName + "]"); 20947 ipw.increaseIndent(); 20948 mPackageDexOptimizer.dumpDexoptState(ipw, pkg, 20949 mDexManager.getPackageUseInfoOrDefault(pkg.packageName)); 20950 ipw.decreaseIndent(); 20951 } 20952 } 20953 20954 private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) { 20955 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " "); 20956 ipw.println(); 20957 ipw.println("Compiler stats:"); 20958 ipw.increaseIndent(); 20959 Collection<PackageParser.Package> packages = null; 20960 if (packageName != null) { 20961 PackageParser.Package targetPackage = mPackages.get(packageName); 20962 if (targetPackage != null) { 20963 packages = Collections.singletonList(targetPackage); 20964 } else { 20965 ipw.println("Unable to find package: " + packageName); 20966 return; 20967 } 20968 } else { 20969 packages = mPackages.values(); 20970 } 20971 20972 for (PackageParser.Package pkg : packages) { 20973 ipw.println("[" + pkg.packageName + "]"); 20974 ipw.increaseIndent(); 20975 20976 CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName); 20977 if (stats == null) { 20978 ipw.println("(No recorded stats)"); 20979 } else { 20980 stats.dump(ipw); 20981 } 20982 ipw.decreaseIndent(); 20983 } 20984 } 20985 20986 private String dumpDomainString(String packageName) { 20987 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 20988 .getList(); 20989 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 20990 20991 ArraySet<String> result = new ArraySet<>(); 20992 if (iviList.size() > 0) { 20993 for (IntentFilterVerificationInfo ivi : iviList) { 20994 for (String host : ivi.getDomains()) { 20995 result.add(host); 20996 } 20997 } 20998 } 20999 if (filters != null && filters.size() > 0) { 21000 for (IntentFilter filter : filters) { 21001 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 21002 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 21003 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 21004 result.addAll(filter.getHostsList()); 21005 } 21006 } 21007 } 21008 21009 StringBuilder sb = new StringBuilder(result.size() * 16); 21010 for (String domain : result) { 21011 if (sb.length() > 0) sb.append(" "); 21012 sb.append(domain); 21013 } 21014 return sb.toString(); 21015 } 21016 21017 // ------- apps on sdcard specific code ------- 21018 static final boolean DEBUG_SD_INSTALL = false; 21019 21020 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 21021 21022 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 21023 21024 private boolean mMediaMounted = false; 21025 21026 static String getEncryptKey() { 21027 try { 21028 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 21029 SD_ENCRYPTION_KEYSTORE_NAME); 21030 if (sdEncKey == null) { 21031 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 21032 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 21033 if (sdEncKey == null) { 21034 Slog.e(TAG, "Failed to create encryption keys"); 21035 return null; 21036 } 21037 } 21038 return sdEncKey; 21039 } catch (NoSuchAlgorithmException nsae) { 21040 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 21041 return null; 21042 } catch (IOException ioe) { 21043 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 21044 return null; 21045 } 21046 } 21047 21048 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21049 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 21050 final int size = infos.size(); 21051 final String[] packageNames = new String[size]; 21052 final int[] packageUids = new int[size]; 21053 for (int i = 0; i < size; i++) { 21054 final ApplicationInfo info = infos.get(i); 21055 packageNames[i] = info.packageName; 21056 packageUids[i] = info.uid; 21057 } 21058 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 21059 finishedReceiver); 21060 } 21061 21062 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21063 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 21064 sendResourcesChangedBroadcast(mediaStatus, replacing, 21065 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 21066 } 21067 21068 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21069 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 21070 int size = pkgList.length; 21071 if (size > 0) { 21072 // Send broadcasts here 21073 Bundle extras = new Bundle(); 21074 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 21075 if (uidArr != null) { 21076 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 21077 } 21078 if (replacing) { 21079 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 21080 } 21081 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 21082 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 21083 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 21084 } 21085 } 21086 21087 private void loadPrivatePackages(final VolumeInfo vol) { 21088 mHandler.post(new Runnable() { 21089 @Override 21090 public void run() { 21091 loadPrivatePackagesInner(vol); 21092 } 21093 }); 21094 } 21095 21096 private void loadPrivatePackagesInner(VolumeInfo vol) { 21097 final String volumeUuid = vol.fsUuid; 21098 if (TextUtils.isEmpty(volumeUuid)) { 21099 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 21100 return; 21101 } 21102 21103 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 21104 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 21105 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 21106 21107 final VersionInfo ver; 21108 final List<PackageSetting> packages; 21109 synchronized (mPackages) { 21110 ver = mSettings.findOrCreateVersion(volumeUuid); 21111 packages = mSettings.getVolumePackagesLPr(volumeUuid); 21112 } 21113 21114 for (PackageSetting ps : packages) { 21115 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 21116 synchronized (mInstallLock) { 21117 final PackageParser.Package pkg; 21118 try { 21119 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 21120 loaded.add(pkg.applicationInfo); 21121 21122 } catch (PackageManagerException e) { 21123 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 21124 } 21125 21126 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 21127 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 21128 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 21129 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 21130 } 21131 } 21132 } 21133 21134 // Reconcile app data for all started/unlocked users 21135 final StorageManager sm = mContext.getSystemService(StorageManager.class); 21136 final UserManager um = mContext.getSystemService(UserManager.class); 21137 UserManagerInternal umInternal = getUserManagerInternal(); 21138 for (UserInfo user : um.getUsers()) { 21139 final int flags; 21140 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 21141 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 21142 } else if (umInternal.isUserRunning(user.id)) { 21143 flags = StorageManager.FLAG_STORAGE_DE; 21144 } else { 21145 continue; 21146 } 21147 21148 try { 21149 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 21150 synchronized (mInstallLock) { 21151 reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */); 21152 } 21153 } catch (IllegalStateException e) { 21154 // Device was probably ejected, and we'll process that event momentarily 21155 Slog.w(TAG, "Failed to prepare storage: " + e); 21156 } 21157 } 21158 21159 synchronized (mPackages) { 21160 final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion); 21161 if (sdkUpdated) { 21162 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 21163 + mSdkVersion + "; regranting permissions for " + volumeUuid); 21164 } 21165 mPermissionManager.updateAllPermissions(volumeUuid, sdkUpdated, mPackages.values(), 21166 mPermissionCallback); 21167 21168 // Yay, everything is now upgraded 21169 ver.forceCurrent(); 21170 21171 mSettings.writeLPr(); 21172 } 21173 21174 for (PackageFreezer freezer : freezers) { 21175 freezer.close(); 21176 } 21177 21178 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 21179 sendResourcesChangedBroadcast(true, false, loaded, null); 21180 mLoadedVolumes.add(vol.getId()); 21181 } 21182 21183 private void unloadPrivatePackages(final VolumeInfo vol) { 21184 mHandler.post(new Runnable() { 21185 @Override 21186 public void run() { 21187 unloadPrivatePackagesInner(vol); 21188 } 21189 }); 21190 } 21191 21192 private void unloadPrivatePackagesInner(VolumeInfo vol) { 21193 final String volumeUuid = vol.fsUuid; 21194 if (TextUtils.isEmpty(volumeUuid)) { 21195 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 21196 return; 21197 } 21198 21199 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 21200 synchronized (mInstallLock) { 21201 synchronized (mPackages) { 21202 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 21203 for (PackageSetting ps : packages) { 21204 if (ps.pkg == null) continue; 21205 21206 final ApplicationInfo info = ps.pkg.applicationInfo; 21207 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 21208 final PackageRemovedInfo outInfo = new PackageRemovedInfo(this); 21209 21210 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 21211 "unloadPrivatePackagesInner")) { 21212 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 21213 false, null)) { 21214 unloaded.add(info); 21215 } else { 21216 Slog.w(TAG, "Failed to unload " + ps.codePath); 21217 } 21218 } 21219 21220 // Try very hard to release any references to this package 21221 // so we don't risk the system server being killed due to 21222 // open FDs 21223 AttributeCache.instance().removePackage(ps.name); 21224 } 21225 21226 mSettings.writeLPr(); 21227 } 21228 } 21229 21230 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 21231 sendResourcesChangedBroadcast(false, false, unloaded, null); 21232 mLoadedVolumes.remove(vol.getId()); 21233 21234 // Try very hard to release any references to this path so we don't risk 21235 // the system server being killed due to open FDs 21236 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 21237 21238 for (int i = 0; i < 3; i++) { 21239 System.gc(); 21240 System.runFinalization(); 21241 } 21242 } 21243 21244 private void assertPackageKnown(String volumeUuid, String packageName) 21245 throws PackageManagerException { 21246 synchronized (mPackages) { 21247 // Normalize package name to handle renamed packages 21248 packageName = normalizePackageNameLPr(packageName); 21249 21250 final PackageSetting ps = mSettings.mPackages.get(packageName); 21251 if (ps == null) { 21252 throw new PackageManagerException("Package " + packageName + " is unknown"); 21253 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 21254 throw new PackageManagerException( 21255 "Package " + packageName + " found on unknown volume " + volumeUuid 21256 + "; expected volume " + ps.volumeUuid); 21257 } 21258 } 21259 } 21260 21261 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 21262 throws PackageManagerException { 21263 synchronized (mPackages) { 21264 // Normalize package name to handle renamed packages 21265 packageName = normalizePackageNameLPr(packageName); 21266 21267 final PackageSetting ps = mSettings.mPackages.get(packageName); 21268 if (ps == null) { 21269 throw new PackageManagerException("Package " + packageName + " is unknown"); 21270 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 21271 throw new PackageManagerException( 21272 "Package " + packageName + " found on unknown volume " + volumeUuid 21273 + "; expected volume " + ps.volumeUuid); 21274 } else if (!ps.getInstalled(userId)) { 21275 throw new PackageManagerException( 21276 "Package " + packageName + " not installed for user " + userId); 21277 } 21278 } 21279 } 21280 21281 private List<String> collectAbsoluteCodePaths() { 21282 synchronized (mPackages) { 21283 List<String> codePaths = new ArrayList<>(); 21284 final int packageCount = mSettings.mPackages.size(); 21285 for (int i = 0; i < packageCount; i++) { 21286 final PackageSetting ps = mSettings.mPackages.valueAt(i); 21287 codePaths.add(ps.codePath.getAbsolutePath()); 21288 } 21289 return codePaths; 21290 } 21291 } 21292 21293 /** 21294 * Examine all apps present on given mounted volume, and destroy apps that 21295 * aren't expected, either due to uninstallation or reinstallation on 21296 * another volume. 21297 */ 21298 private void reconcileApps(String volumeUuid) { 21299 List<String> absoluteCodePaths = collectAbsoluteCodePaths(); 21300 List<File> filesToDelete = null; 21301 21302 final File[] files = FileUtils.listFilesOrEmpty( 21303 Environment.getDataAppDirectory(volumeUuid)); 21304 for (File file : files) { 21305 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 21306 && !PackageInstallerService.isStageName(file.getName()); 21307 if (!isPackage) { 21308 // Ignore entries which are not packages 21309 continue; 21310 } 21311 21312 String absolutePath = file.getAbsolutePath(); 21313 21314 boolean pathValid = false; 21315 final int absoluteCodePathCount = absoluteCodePaths.size(); 21316 for (int i = 0; i < absoluteCodePathCount; i++) { 21317 String absoluteCodePath = absoluteCodePaths.get(i); 21318 if (absolutePath.startsWith(absoluteCodePath)) { 21319 pathValid = true; 21320 break; 21321 } 21322 } 21323 21324 if (!pathValid) { 21325 if (filesToDelete == null) { 21326 filesToDelete = new ArrayList<>(); 21327 } 21328 filesToDelete.add(file); 21329 } 21330 } 21331 21332 if (filesToDelete != null) { 21333 final int fileToDeleteCount = filesToDelete.size(); 21334 for (int i = 0; i < fileToDeleteCount; i++) { 21335 File fileToDelete = filesToDelete.get(i); 21336 logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete); 21337 synchronized (mInstallLock) { 21338 removeCodePathLI(fileToDelete); 21339 } 21340 } 21341 } 21342 } 21343 21344 /** 21345 * Reconcile all app data for the given user. 21346 * <p> 21347 * Verifies that directories exist and that ownership and labeling is 21348 * correct for all installed apps on all mounted volumes. 21349 */ 21350 void reconcileAppsData(int userId, int flags, boolean migrateAppsData) { 21351 final StorageManager storage = mContext.getSystemService(StorageManager.class); 21352 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 21353 final String volumeUuid = vol.getFsUuid(); 21354 synchronized (mInstallLock) { 21355 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData); 21356 } 21357 } 21358 } 21359 21360 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags, 21361 boolean migrateAppData) { 21362 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */); 21363 } 21364 21365 /** 21366 * Reconcile all app data on given mounted volume. 21367 * <p> 21368 * Destroys app data that isn't expected, either due to uninstallation or 21369 * reinstallation on another volume. 21370 * <p> 21371 * Verifies that directories exist and that ownership and labeling is 21372 * correct for all installed apps. 21373 * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true) 21374 */ 21375 private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags, 21376 boolean migrateAppData, boolean onlyCoreApps) { 21377 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 21378 + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData); 21379 List<String> result = onlyCoreApps ? new ArrayList<>() : null; 21380 21381 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 21382 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 21383 21384 // First look for stale data that doesn't belong, and check if things 21385 // have changed since we did our last restorecon 21386 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 21387 if (StorageManager.isFileEncryptedNativeOrEmulated() 21388 && !StorageManager.isUserKeyUnlocked(userId)) { 21389 throw new RuntimeException( 21390 "Yikes, someone asked us to reconcile CE storage while " + userId 21391 + " was still locked; this would have caused massive data loss!"); 21392 } 21393 21394 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 21395 for (File file : files) { 21396 final String packageName = file.getName(); 21397 try { 21398 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 21399 } catch (PackageManagerException e) { 21400 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 21401 try { 21402 mInstaller.destroyAppData(volumeUuid, packageName, userId, 21403 StorageManager.FLAG_STORAGE_CE, 0); 21404 } catch (InstallerException e2) { 21405 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 21406 } 21407 } 21408 } 21409 } 21410 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 21411 final File[] files = FileUtils.listFilesOrEmpty(deDir); 21412 for (File file : files) { 21413 final String packageName = file.getName(); 21414 try { 21415 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 21416 } catch (PackageManagerException e) { 21417 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 21418 try { 21419 mInstaller.destroyAppData(volumeUuid, packageName, userId, 21420 StorageManager.FLAG_STORAGE_DE, 0); 21421 } catch (InstallerException e2) { 21422 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 21423 } 21424 } 21425 } 21426 } 21427 21428 // Ensure that data directories are ready to roll for all packages 21429 // installed for this volume and user 21430 final List<PackageSetting> packages; 21431 synchronized (mPackages) { 21432 packages = mSettings.getVolumePackagesLPr(volumeUuid); 21433 } 21434 int preparedCount = 0; 21435 for (PackageSetting ps : packages) { 21436 final String packageName = ps.name; 21437 if (ps.pkg == null) { 21438 Slog.w(TAG, "Odd, missing scanned package " + packageName); 21439 // TODO: might be due to legacy ASEC apps; we should circle back 21440 // and reconcile again once they're scanned 21441 continue; 21442 } 21443 // Skip non-core apps if requested 21444 if (onlyCoreApps && !ps.pkg.coreApp) { 21445 result.add(packageName); 21446 continue; 21447 } 21448 21449 if (ps.getInstalled(userId)) { 21450 prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData); 21451 preparedCount++; 21452 } 21453 } 21454 21455 Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages"); 21456 return result; 21457 } 21458 21459 /** 21460 * Prepare app data for the given app just after it was installed or 21461 * upgraded. This method carefully only touches users that it's installed 21462 * for, and it forces a restorecon to handle any seinfo changes. 21463 * <p> 21464 * Verifies that directories exist and that ownership and labeling is 21465 * correct for all installed apps. If there is an ownership mismatch, it 21466 * will try recovering system apps by wiping data; third-party app data is 21467 * left intact. 21468 * <p> 21469 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 21470 */ 21471 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 21472 final PackageSetting ps; 21473 synchronized (mPackages) { 21474 ps = mSettings.mPackages.get(pkg.packageName); 21475 mSettings.writeKernelMappingLPr(ps); 21476 } 21477 21478 final UserManager um = mContext.getSystemService(UserManager.class); 21479 UserManagerInternal umInternal = getUserManagerInternal(); 21480 for (UserInfo user : um.getUsers()) { 21481 final int flags; 21482 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 21483 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 21484 } else if (umInternal.isUserRunning(user.id)) { 21485 flags = StorageManager.FLAG_STORAGE_DE; 21486 } else { 21487 continue; 21488 } 21489 21490 if (ps.getInstalled(user.id)) { 21491 // TODO: when user data is locked, mark that we're still dirty 21492 prepareAppDataLIF(pkg, user.id, flags); 21493 } 21494 } 21495 } 21496 21497 /** 21498 * Prepare app data for the given app. 21499 * <p> 21500 * Verifies that directories exist and that ownership and labeling is 21501 * correct for all installed apps. If there is an ownership mismatch, this 21502 * will try recovering system apps by wiping data; third-party app data is 21503 * left intact. 21504 */ 21505 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 21506 if (pkg == null) { 21507 Slog.wtf(TAG, "Package was null!", new Throwable()); 21508 return; 21509 } 21510 prepareAppDataLeafLIF(pkg, userId, flags); 21511 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 21512 for (int i = 0; i < childCount; i++) { 21513 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 21514 } 21515 } 21516 21517 private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags, 21518 boolean maybeMigrateAppData) { 21519 prepareAppDataLIF(pkg, userId, flags); 21520 21521 if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) { 21522 // We may have just shuffled around app data directories, so 21523 // prepare them one more time 21524 prepareAppDataLIF(pkg, userId, flags); 21525 } 21526 } 21527 21528 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 21529 if (DEBUG_APP_DATA) { 21530 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 21531 + Integer.toHexString(flags)); 21532 } 21533 21534 final String volumeUuid = pkg.volumeUuid; 21535 final String packageName = pkg.packageName; 21536 final ApplicationInfo app = pkg.applicationInfo; 21537 final int appId = UserHandle.getAppId(app.uid); 21538 21539 Preconditions.checkNotNull(app.seInfo); 21540 21541 long ceDataInode = -1; 21542 try { 21543 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 21544 appId, app.seInfo, app.targetSdkVersion); 21545 } catch (InstallerException e) { 21546 if (app.isSystemApp()) { 21547 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 21548 + ", but trying to recover: " + e); 21549 destroyAppDataLeafLIF(pkg, userId, flags); 21550 try { 21551 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 21552 appId, app.seInfo, app.targetSdkVersion); 21553 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 21554 } catch (InstallerException e2) { 21555 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 21556 } 21557 } else { 21558 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 21559 } 21560 } 21561 21562 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) { 21563 // TODO: mark this structure as dirty so we persist it! 21564 synchronized (mPackages) { 21565 final PackageSetting ps = mSettings.mPackages.get(packageName); 21566 if (ps != null) { 21567 ps.setCeDataInode(ceDataInode, userId); 21568 } 21569 } 21570 } 21571 21572 prepareAppDataContentsLeafLIF(pkg, userId, flags); 21573 } 21574 21575 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 21576 if (pkg == null) { 21577 Slog.wtf(TAG, "Package was null!", new Throwable()); 21578 return; 21579 } 21580 prepareAppDataContentsLeafLIF(pkg, userId, flags); 21581 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 21582 for (int i = 0; i < childCount; i++) { 21583 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 21584 } 21585 } 21586 21587 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 21588 final String volumeUuid = pkg.volumeUuid; 21589 final String packageName = pkg.packageName; 21590 final ApplicationInfo app = pkg.applicationInfo; 21591 21592 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 21593 // Create a native library symlink only if we have native libraries 21594 // and if the native libraries are 32 bit libraries. We do not provide 21595 // this symlink for 64 bit libraries. 21596 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 21597 final String nativeLibPath = app.nativeLibraryDir; 21598 try { 21599 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 21600 nativeLibPath, userId); 21601 } catch (InstallerException e) { 21602 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 21603 } 21604 } 21605 } 21606 } 21607 21608 /** 21609 * For system apps on non-FBE devices, this method migrates any existing 21610 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 21611 * requested by the app. 21612 */ 21613 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 21614 if (pkg.isSystem() && !StorageManager.isFileEncryptedNativeOrEmulated() 21615 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 21616 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 21617 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 21618 try { 21619 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 21620 storageTarget); 21621 } catch (InstallerException e) { 21622 logCriticalInfo(Log.WARN, 21623 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 21624 } 21625 return true; 21626 } else { 21627 return false; 21628 } 21629 } 21630 21631 public PackageFreezer freezePackage(String packageName, String killReason) { 21632 return freezePackage(packageName, UserHandle.USER_ALL, killReason); 21633 } 21634 21635 public PackageFreezer freezePackage(String packageName, int userId, String killReason) { 21636 return new PackageFreezer(packageName, userId, killReason); 21637 } 21638 21639 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 21640 String killReason) { 21641 return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason); 21642 } 21643 21644 public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags, 21645 String killReason) { 21646 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 21647 return new PackageFreezer(); 21648 } else { 21649 return freezePackage(packageName, userId, killReason); 21650 } 21651 } 21652 21653 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 21654 String killReason) { 21655 return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason); 21656 } 21657 21658 public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags, 21659 String killReason) { 21660 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 21661 return new PackageFreezer(); 21662 } else { 21663 return freezePackage(packageName, userId, killReason); 21664 } 21665 } 21666 21667 /** 21668 * Class that freezes and kills the given package upon creation, and 21669 * unfreezes it upon closing. This is typically used when doing surgery on 21670 * app code/data to prevent the app from running while you're working. 21671 */ 21672 private class PackageFreezer implements AutoCloseable { 21673 private final String mPackageName; 21674 private final PackageFreezer[] mChildren; 21675 21676 private final boolean mWeFroze; 21677 21678 private final AtomicBoolean mClosed = new AtomicBoolean(); 21679 private final CloseGuard mCloseGuard = CloseGuard.get(); 21680 21681 /** 21682 * Create and return a stub freezer that doesn't actually do anything, 21683 * typically used when someone requested 21684 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 21685 * {@link PackageManager#DELETE_DONT_KILL_APP}. 21686 */ 21687 public PackageFreezer() { 21688 mPackageName = null; 21689 mChildren = null; 21690 mWeFroze = false; 21691 mCloseGuard.open("close"); 21692 } 21693 21694 public PackageFreezer(String packageName, int userId, String killReason) { 21695 synchronized (mPackages) { 21696 mPackageName = packageName; 21697 mWeFroze = mFrozenPackages.add(mPackageName); 21698 21699 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 21700 if (ps != null) { 21701 killApplication(ps.name, ps.appId, userId, killReason); 21702 } 21703 21704 final PackageParser.Package p = mPackages.get(packageName); 21705 if (p != null && p.childPackages != null) { 21706 final int N = p.childPackages.size(); 21707 mChildren = new PackageFreezer[N]; 21708 for (int i = 0; i < N; i++) { 21709 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 21710 userId, killReason); 21711 } 21712 } else { 21713 mChildren = null; 21714 } 21715 } 21716 mCloseGuard.open("close"); 21717 } 21718 21719 @Override 21720 protected void finalize() throws Throwable { 21721 try { 21722 if (mCloseGuard != null) { 21723 mCloseGuard.warnIfOpen(); 21724 } 21725 21726 close(); 21727 } finally { 21728 super.finalize(); 21729 } 21730 } 21731 21732 @Override 21733 public void close() { 21734 mCloseGuard.close(); 21735 if (mClosed.compareAndSet(false, true)) { 21736 synchronized (mPackages) { 21737 if (mWeFroze) { 21738 mFrozenPackages.remove(mPackageName); 21739 } 21740 21741 if (mChildren != null) { 21742 for (PackageFreezer freezer : mChildren) { 21743 freezer.close(); 21744 } 21745 } 21746 } 21747 } 21748 } 21749 } 21750 21751 /** 21752 * Verify that given package is currently frozen. 21753 */ 21754 private void checkPackageFrozen(String packageName) { 21755 synchronized (mPackages) { 21756 if (!mFrozenPackages.contains(packageName)) { 21757 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 21758 } 21759 } 21760 } 21761 21762 @Override 21763 public int movePackage(final String packageName, final String volumeUuid) { 21764 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 21765 21766 final int callingUid = Binder.getCallingUid(); 21767 final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid)); 21768 final int moveId = mNextMoveId.getAndIncrement(); 21769 mHandler.post(new Runnable() { 21770 @Override 21771 public void run() { 21772 try { 21773 movePackageInternal(packageName, volumeUuid, moveId, callingUid, user); 21774 } catch (PackageManagerException e) { 21775 Slog.w(TAG, "Failed to move " + packageName, e); 21776 mMoveCallbacks.notifyStatusChanged(moveId, e.error); 21777 } 21778 } 21779 }); 21780 return moveId; 21781 } 21782 21783 private void movePackageInternal(final String packageName, final String volumeUuid, 21784 final int moveId, final int callingUid, UserHandle user) 21785 throws PackageManagerException { 21786 final StorageManager storage = mContext.getSystemService(StorageManager.class); 21787 final PackageManager pm = mContext.getPackageManager(); 21788 21789 final boolean currentAsec; 21790 final String currentVolumeUuid; 21791 final File codeFile; 21792 final String installerPackageName; 21793 final String packageAbiOverride; 21794 final int appId; 21795 final String seinfo; 21796 final String label; 21797 final int targetSdkVersion; 21798 final PackageFreezer freezer; 21799 final int[] installedUserIds; 21800 21801 // reader 21802 synchronized (mPackages) { 21803 final PackageParser.Package pkg = mPackages.get(packageName); 21804 final PackageSetting ps = mSettings.mPackages.get(packageName); 21805 if (pkg == null 21806 || ps == null 21807 || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) { 21808 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 21809 } 21810 if (pkg.applicationInfo.isSystemApp()) { 21811 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 21812 "Cannot move system application"); 21813 } 21814 21815 final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid); 21816 final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean( 21817 com.android.internal.R.bool.config_allow3rdPartyAppOnInternal); 21818 if (isInternalStorage && !allow3rdPartyOnInternal) { 21819 throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL, 21820 "3rd party apps are not allowed on internal storage"); 21821 } 21822 21823 if (pkg.applicationInfo.isExternalAsec()) { 21824 currentAsec = true; 21825 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 21826 } else if (pkg.applicationInfo.isForwardLocked()) { 21827 currentAsec = true; 21828 currentVolumeUuid = "forward_locked"; 21829 } else { 21830 currentAsec = false; 21831 currentVolumeUuid = ps.volumeUuid; 21832 21833 final File probe = new File(pkg.codePath); 21834 final File probeOat = new File(probe, "oat"); 21835 if (!probe.isDirectory() || !probeOat.isDirectory()) { 21836 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 21837 "Move only supported for modern cluster style installs"); 21838 } 21839 } 21840 21841 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 21842 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 21843 "Package already moved to " + volumeUuid); 21844 } 21845 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 21846 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 21847 "Device admin cannot be moved"); 21848 } 21849 21850 if (mFrozenPackages.contains(packageName)) { 21851 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 21852 "Failed to move already frozen package"); 21853 } 21854 21855 codeFile = new File(pkg.codePath); 21856 installerPackageName = ps.installerPackageName; 21857 packageAbiOverride = ps.cpuAbiOverrideString; 21858 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 21859 seinfo = pkg.applicationInfo.seInfo; 21860 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 21861 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 21862 freezer = freezePackage(packageName, "movePackageInternal"); 21863 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 21864 } 21865 21866 final Bundle extras = new Bundle(); 21867 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 21868 extras.putString(Intent.EXTRA_TITLE, label); 21869 mMoveCallbacks.notifyCreated(moveId, extras); 21870 21871 int installFlags; 21872 final boolean moveCompleteApp; 21873 final File measurePath; 21874 21875 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 21876 installFlags = INSTALL_INTERNAL; 21877 moveCompleteApp = !currentAsec; 21878 measurePath = Environment.getDataAppDirectory(volumeUuid); 21879 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 21880 installFlags = INSTALL_EXTERNAL; 21881 moveCompleteApp = false; 21882 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 21883 } else { 21884 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 21885 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 21886 || !volume.isMountedWritable()) { 21887 freezer.close(); 21888 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 21889 "Move location not mounted private volume"); 21890 } 21891 21892 Preconditions.checkState(!currentAsec); 21893 21894 installFlags = INSTALL_INTERNAL; 21895 moveCompleteApp = true; 21896 measurePath = Environment.getDataAppDirectory(volumeUuid); 21897 } 21898 21899 // If we're moving app data around, we need all the users unlocked 21900 if (moveCompleteApp) { 21901 for (int userId : installedUserIds) { 21902 if (StorageManager.isFileEncryptedNativeOrEmulated() 21903 && !StorageManager.isUserKeyUnlocked(userId)) { 21904 throw new PackageManagerException(MOVE_FAILED_LOCKED_USER, 21905 "User " + userId + " must be unlocked"); 21906 } 21907 } 21908 } 21909 21910 final PackageStats stats = new PackageStats(null, -1); 21911 synchronized (mInstaller) { 21912 for (int userId : installedUserIds) { 21913 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 21914 freezer.close(); 21915 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 21916 "Failed to measure package size"); 21917 } 21918 } 21919 } 21920 21921 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 21922 + stats.dataSize); 21923 21924 final long startFreeBytes = measurePath.getUsableSpace(); 21925 final long sizeBytes; 21926 if (moveCompleteApp) { 21927 sizeBytes = stats.codeSize + stats.dataSize; 21928 } else { 21929 sizeBytes = stats.codeSize; 21930 } 21931 21932 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 21933 freezer.close(); 21934 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 21935 "Not enough free space to move"); 21936 } 21937 21938 mMoveCallbacks.notifyStatusChanged(moveId, 10); 21939 21940 final CountDownLatch installedLatch = new CountDownLatch(1); 21941 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 21942 @Override 21943 public void onUserActionRequired(Intent intent) throws RemoteException { 21944 throw new IllegalStateException(); 21945 } 21946 21947 @Override 21948 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 21949 Bundle extras) throws RemoteException { 21950 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 21951 + PackageManager.installStatusToString(returnCode, msg)); 21952 21953 installedLatch.countDown(); 21954 freezer.close(); 21955 21956 final int status = PackageManager.installStatusToPublicStatus(returnCode); 21957 switch (status) { 21958 case PackageInstaller.STATUS_SUCCESS: 21959 mMoveCallbacks.notifyStatusChanged(moveId, 21960 PackageManager.MOVE_SUCCEEDED); 21961 break; 21962 case PackageInstaller.STATUS_FAILURE_STORAGE: 21963 mMoveCallbacks.notifyStatusChanged(moveId, 21964 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 21965 break; 21966 default: 21967 mMoveCallbacks.notifyStatusChanged(moveId, 21968 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 21969 break; 21970 } 21971 } 21972 }; 21973 21974 final MoveInfo move; 21975 if (moveCompleteApp) { 21976 // Kick off a thread to report progress estimates 21977 new Thread() { 21978 @Override 21979 public void run() { 21980 while (true) { 21981 try { 21982 if (installedLatch.await(1, TimeUnit.SECONDS)) { 21983 break; 21984 } 21985 } catch (InterruptedException ignored) { 21986 } 21987 21988 final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace(); 21989 final int progress = 10 + (int) MathUtils.constrain( 21990 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 21991 mMoveCallbacks.notifyStatusChanged(moveId, progress); 21992 } 21993 } 21994 }.start(); 21995 21996 final String dataAppName = codeFile.getName(); 21997 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 21998 dataAppName, appId, seinfo, targetSdkVersion); 21999 } else { 22000 move = null; 22001 } 22002 22003 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 22004 22005 final Message msg = mHandler.obtainMessage(INIT_COPY); 22006 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 22007 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 22008 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 22009 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/, 22010 PackageManager.INSTALL_REASON_UNKNOWN); 22011 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 22012 msg.obj = params; 22013 22014 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 22015 System.identityHashCode(msg.obj)); 22016 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 22017 System.identityHashCode(msg.obj)); 22018 22019 mHandler.sendMessage(msg); 22020 } 22021 22022 @Override 22023 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 22024 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 22025 22026 final int realMoveId = mNextMoveId.getAndIncrement(); 22027 final Bundle extras = new Bundle(); 22028 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 22029 mMoveCallbacks.notifyCreated(realMoveId, extras); 22030 22031 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 22032 @Override 22033 public void onCreated(int moveId, Bundle extras) { 22034 // Ignored 22035 } 22036 22037 @Override 22038 public void onStatusChanged(int moveId, int status, long estMillis) { 22039 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 22040 } 22041 }; 22042 22043 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22044 storage.setPrimaryStorageUuid(volumeUuid, callback); 22045 return realMoveId; 22046 } 22047 22048 @Override 22049 public int getMoveStatus(int moveId) { 22050 mContext.enforceCallingOrSelfPermission( 22051 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22052 return mMoveCallbacks.mLastStatus.get(moveId); 22053 } 22054 22055 @Override 22056 public void registerMoveCallback(IPackageMoveObserver callback) { 22057 mContext.enforceCallingOrSelfPermission( 22058 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22059 mMoveCallbacks.register(callback); 22060 } 22061 22062 @Override 22063 public void unregisterMoveCallback(IPackageMoveObserver callback) { 22064 mContext.enforceCallingOrSelfPermission( 22065 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22066 mMoveCallbacks.unregister(callback); 22067 } 22068 22069 @Override 22070 public boolean setInstallLocation(int loc) { 22071 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 22072 null); 22073 if (getInstallLocation() == loc) { 22074 return true; 22075 } 22076 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 22077 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 22078 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 22079 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 22080 return true; 22081 } 22082 return false; 22083 } 22084 22085 @Override 22086 public int getInstallLocation() { 22087 // allow instant app access 22088 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 22089 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 22090 PackageHelper.APP_INSTALL_AUTO); 22091 } 22092 22093 /** Called by UserManagerService */ 22094 void cleanUpUser(UserManagerService userManager, int userHandle) { 22095 synchronized (mPackages) { 22096 mDirtyUsers.remove(userHandle); 22097 mUserNeedsBadging.delete(userHandle); 22098 mSettings.removeUserLPw(userHandle); 22099 mPendingBroadcasts.remove(userHandle); 22100 mInstantAppRegistry.onUserRemovedLPw(userHandle); 22101 removeUnusedPackagesLPw(userManager, userHandle); 22102 } 22103 } 22104 22105 /** 22106 * We're removing userHandle and would like to remove any downloaded packages 22107 * that are no longer in use by any other user. 22108 * @param userHandle the user being removed 22109 */ 22110 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 22111 final boolean DEBUG_CLEAN_APKS = false; 22112 int [] users = userManager.getUserIds(); 22113 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 22114 while (psit.hasNext()) { 22115 PackageSetting ps = psit.next(); 22116 if (ps.pkg == null) { 22117 continue; 22118 } 22119 final String packageName = ps.pkg.packageName; 22120 // Skip over if system app 22121 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 22122 continue; 22123 } 22124 if (DEBUG_CLEAN_APKS) { 22125 Slog.i(TAG, "Checking package " + packageName); 22126 } 22127 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 22128 if (keep) { 22129 if (DEBUG_CLEAN_APKS) { 22130 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 22131 } 22132 } else { 22133 for (int i = 0; i < users.length; i++) { 22134 if (users[i] != userHandle && ps.getInstalled(users[i])) { 22135 keep = true; 22136 if (DEBUG_CLEAN_APKS) { 22137 Slog.i(TAG, " Keeping package " + packageName + " for user " 22138 + users[i]); 22139 } 22140 break; 22141 } 22142 } 22143 } 22144 if (!keep) { 22145 if (DEBUG_CLEAN_APKS) { 22146 Slog.i(TAG, " Removing package " + packageName); 22147 } 22148 mHandler.post(new Runnable() { 22149 public void run() { 22150 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 22151 userHandle, 0); 22152 } //end run 22153 }); 22154 } 22155 } 22156 } 22157 22158 /** Called by UserManagerService */ 22159 void createNewUser(int userId, String[] disallowedPackages) { 22160 synchronized (mInstallLock) { 22161 mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages); 22162 } 22163 synchronized (mPackages) { 22164 scheduleWritePackageRestrictionsLocked(userId); 22165 scheduleWritePackageListLocked(userId); 22166 applyFactoryDefaultBrowserLPw(userId); 22167 primeDomainVerificationsLPw(userId); 22168 } 22169 } 22170 22171 void onNewUserCreated(final int userId) { 22172 synchronized(mPackages) { 22173 mDefaultPermissionPolicy.grantDefaultPermissions(mPackages.values(), userId); 22174 // If permission review for legacy apps is required, we represent 22175 // dagerous permissions for such apps as always granted runtime 22176 // permissions to keep per user flag state whether review is needed. 22177 // Hence, if a new user is added we have to propagate dangerous 22178 // permission grants for these legacy apps. 22179 if (mSettings.mPermissions.mPermissionReviewRequired) { 22180// NOTE: This adds UPDATE_PERMISSIONS_REPLACE_PKG 22181 mPermissionManager.updateAllPermissions( 22182 StorageManager.UUID_PRIVATE_INTERNAL, true, mPackages.values(), 22183 mPermissionCallback); 22184 } 22185 } 22186 } 22187 22188 @Override 22189 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 22190 mContext.enforceCallingOrSelfPermission( 22191 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 22192 "Only package verification agents can read the verifier device identity"); 22193 22194 synchronized (mPackages) { 22195 return mSettings.getVerifierDeviceIdentityLPw(); 22196 } 22197 } 22198 22199 @Override 22200 public void setPermissionEnforced(String permission, boolean enforced) { 22201 // TODO: Now that we no longer change GID for storage, this should to away. 22202 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 22203 "setPermissionEnforced"); 22204 if (READ_EXTERNAL_STORAGE.equals(permission)) { 22205 synchronized (mPackages) { 22206 if (mSettings.mReadExternalStorageEnforced == null 22207 || mSettings.mReadExternalStorageEnforced != enforced) { 22208 mSettings.mReadExternalStorageEnforced = 22209 enforced ? Boolean.TRUE : Boolean.FALSE; 22210 mSettings.writeLPr(); 22211 } 22212 } 22213 // kill any non-foreground processes so we restart them and 22214 // grant/revoke the GID. 22215 final IActivityManager am = ActivityManager.getService(); 22216 if (am != null) { 22217 final long token = Binder.clearCallingIdentity(); 22218 try { 22219 am.killProcessesBelowForeground("setPermissionEnforcement"); 22220 } catch (RemoteException e) { 22221 } finally { 22222 Binder.restoreCallingIdentity(token); 22223 } 22224 } 22225 } else { 22226 throw new IllegalArgumentException("No selective enforcement for " + permission); 22227 } 22228 } 22229 22230 @Override 22231 @Deprecated 22232 public boolean isPermissionEnforced(String permission) { 22233 // allow instant applications 22234 return true; 22235 } 22236 22237 @Override 22238 public boolean isStorageLow() { 22239 // allow instant applications 22240 final long token = Binder.clearCallingIdentity(); 22241 try { 22242 final DeviceStorageMonitorInternal 22243 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 22244 if (dsm != null) { 22245 return dsm.isMemoryLow(); 22246 } else { 22247 return false; 22248 } 22249 } finally { 22250 Binder.restoreCallingIdentity(token); 22251 } 22252 } 22253 22254 @Override 22255 public IPackageInstaller getPackageInstaller() { 22256 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 22257 return null; 22258 } 22259 return mInstallerService; 22260 } 22261 22262 private boolean userNeedsBadging(int userId) { 22263 int index = mUserNeedsBadging.indexOfKey(userId); 22264 if (index < 0) { 22265 final UserInfo userInfo; 22266 final long token = Binder.clearCallingIdentity(); 22267 try { 22268 userInfo = sUserManager.getUserInfo(userId); 22269 } finally { 22270 Binder.restoreCallingIdentity(token); 22271 } 22272 final boolean b; 22273 if (userInfo != null && userInfo.isManagedProfile()) { 22274 b = true; 22275 } else { 22276 b = false; 22277 } 22278 mUserNeedsBadging.put(userId, b); 22279 return b; 22280 } 22281 return mUserNeedsBadging.valueAt(index); 22282 } 22283 22284 @Override 22285 public KeySet getKeySetByAlias(String packageName, String alias) { 22286 if (packageName == null || alias == null) { 22287 return null; 22288 } 22289 synchronized(mPackages) { 22290 final PackageParser.Package pkg = mPackages.get(packageName); 22291 if (pkg == null) { 22292 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22293 throw new IllegalArgumentException("Unknown package: " + packageName); 22294 } 22295 final PackageSetting ps = (PackageSetting) pkg.mExtras; 22296 if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) { 22297 Slog.w(TAG, "KeySet requested for filtered package: " + packageName); 22298 throw new IllegalArgumentException("Unknown package: " + packageName); 22299 } 22300 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 22301 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 22302 } 22303 } 22304 22305 @Override 22306 public KeySet getSigningKeySet(String packageName) { 22307 if (packageName == null) { 22308 return null; 22309 } 22310 synchronized(mPackages) { 22311 final int callingUid = Binder.getCallingUid(); 22312 final int callingUserId = UserHandle.getUserId(callingUid); 22313 final PackageParser.Package pkg = mPackages.get(packageName); 22314 if (pkg == null) { 22315 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22316 throw new IllegalArgumentException("Unknown package: " + packageName); 22317 } 22318 final PackageSetting ps = (PackageSetting) pkg.mExtras; 22319 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 22320 // filter and pretend the package doesn't exist 22321 Slog.w(TAG, "KeySet requested for filtered package: " + packageName 22322 + ", uid:" + callingUid); 22323 throw new IllegalArgumentException("Unknown package: " + packageName); 22324 } 22325 if (pkg.applicationInfo.uid != callingUid 22326 && Process.SYSTEM_UID != callingUid) { 22327 throw new SecurityException("May not access signing KeySet of other apps."); 22328 } 22329 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 22330 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 22331 } 22332 } 22333 22334 @Override 22335 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 22336 final int callingUid = Binder.getCallingUid(); 22337 if (getInstantAppPackageName(callingUid) != null) { 22338 return false; 22339 } 22340 if (packageName == null || ks == null) { 22341 return false; 22342 } 22343 synchronized(mPackages) { 22344 final PackageParser.Package pkg = mPackages.get(packageName); 22345 if (pkg == null 22346 || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid, 22347 UserHandle.getUserId(callingUid))) { 22348 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22349 throw new IllegalArgumentException("Unknown package: " + packageName); 22350 } 22351 IBinder ksh = ks.getToken(); 22352 if (ksh instanceof KeySetHandle) { 22353 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 22354 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 22355 } 22356 return false; 22357 } 22358 } 22359 22360 @Override 22361 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 22362 final int callingUid = Binder.getCallingUid(); 22363 if (getInstantAppPackageName(callingUid) != null) { 22364 return false; 22365 } 22366 if (packageName == null || ks == null) { 22367 return false; 22368 } 22369 synchronized(mPackages) { 22370 final PackageParser.Package pkg = mPackages.get(packageName); 22371 if (pkg == null 22372 || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid, 22373 UserHandle.getUserId(callingUid))) { 22374 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22375 throw new IllegalArgumentException("Unknown package: " + packageName); 22376 } 22377 IBinder ksh = ks.getToken(); 22378 if (ksh instanceof KeySetHandle) { 22379 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 22380 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 22381 } 22382 return false; 22383 } 22384 } 22385 22386 private void deletePackageIfUnusedLPr(final String packageName) { 22387 PackageSetting ps = mSettings.mPackages.get(packageName); 22388 if (ps == null) { 22389 return; 22390 } 22391 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 22392 // TODO Implement atomic delete if package is unused 22393 // It is currently possible that the package will be deleted even if it is installed 22394 // after this method returns. 22395 mHandler.post(new Runnable() { 22396 public void run() { 22397 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 22398 0, PackageManager.DELETE_ALL_USERS); 22399 } 22400 }); 22401 } 22402 } 22403 22404 /** 22405 * Check and throw if the given before/after packages would be considered a 22406 * downgrade. 22407 */ 22408 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 22409 throws PackageManagerException { 22410 if (after.versionCode < before.mVersionCode) { 22411 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 22412 "Update version code " + after.versionCode + " is older than current " 22413 + before.mVersionCode); 22414 } else if (after.versionCode == before.mVersionCode) { 22415 if (after.baseRevisionCode < before.baseRevisionCode) { 22416 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 22417 "Update base revision code " + after.baseRevisionCode 22418 + " is older than current " + before.baseRevisionCode); 22419 } 22420 22421 if (!ArrayUtils.isEmpty(after.splitNames)) { 22422 for (int i = 0; i < after.splitNames.length; i++) { 22423 final String splitName = after.splitNames[i]; 22424 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 22425 if (j != -1) { 22426 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 22427 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 22428 "Update split " + splitName + " revision code " 22429 + after.splitRevisionCodes[i] + " is older than current " 22430 + before.splitRevisionCodes[j]); 22431 } 22432 } 22433 } 22434 } 22435 } 22436 } 22437 22438 private static class MoveCallbacks extends Handler { 22439 private static final int MSG_CREATED = 1; 22440 private static final int MSG_STATUS_CHANGED = 2; 22441 22442 private final RemoteCallbackList<IPackageMoveObserver> 22443 mCallbacks = new RemoteCallbackList<>(); 22444 22445 private final SparseIntArray mLastStatus = new SparseIntArray(); 22446 22447 public MoveCallbacks(Looper looper) { 22448 super(looper); 22449 } 22450 22451 public void register(IPackageMoveObserver callback) { 22452 mCallbacks.register(callback); 22453 } 22454 22455 public void unregister(IPackageMoveObserver callback) { 22456 mCallbacks.unregister(callback); 22457 } 22458 22459 @Override 22460 public void handleMessage(Message msg) { 22461 final SomeArgs args = (SomeArgs) msg.obj; 22462 final int n = mCallbacks.beginBroadcast(); 22463 for (int i = 0; i < n; i++) { 22464 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 22465 try { 22466 invokeCallback(callback, msg.what, args); 22467 } catch (RemoteException ignored) { 22468 } 22469 } 22470 mCallbacks.finishBroadcast(); 22471 args.recycle(); 22472 } 22473 22474 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 22475 throws RemoteException { 22476 switch (what) { 22477 case MSG_CREATED: { 22478 callback.onCreated(args.argi1, (Bundle) args.arg2); 22479 break; 22480 } 22481 case MSG_STATUS_CHANGED: { 22482 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 22483 break; 22484 } 22485 } 22486 } 22487 22488 private void notifyCreated(int moveId, Bundle extras) { 22489 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 22490 22491 final SomeArgs args = SomeArgs.obtain(); 22492 args.argi1 = moveId; 22493 args.arg2 = extras; 22494 obtainMessage(MSG_CREATED, args).sendToTarget(); 22495 } 22496 22497 private void notifyStatusChanged(int moveId, int status) { 22498 notifyStatusChanged(moveId, status, -1); 22499 } 22500 22501 private void notifyStatusChanged(int moveId, int status, long estMillis) { 22502 Slog.v(TAG, "Move " + moveId + " status " + status); 22503 22504 final SomeArgs args = SomeArgs.obtain(); 22505 args.argi1 = moveId; 22506 args.argi2 = status; 22507 args.arg3 = estMillis; 22508 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 22509 22510 synchronized (mLastStatus) { 22511 mLastStatus.put(moveId, status); 22512 } 22513 } 22514 } 22515 22516 private final static class OnPermissionChangeListeners extends Handler { 22517 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 22518 22519 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 22520 new RemoteCallbackList<>(); 22521 22522 public OnPermissionChangeListeners(Looper looper) { 22523 super(looper); 22524 } 22525 22526 @Override 22527 public void handleMessage(Message msg) { 22528 switch (msg.what) { 22529 case MSG_ON_PERMISSIONS_CHANGED: { 22530 final int uid = msg.arg1; 22531 handleOnPermissionsChanged(uid); 22532 } break; 22533 } 22534 } 22535 22536 public void addListenerLocked(IOnPermissionsChangeListener listener) { 22537 mPermissionListeners.register(listener); 22538 22539 } 22540 22541 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 22542 mPermissionListeners.unregister(listener); 22543 } 22544 22545 public void onPermissionsChanged(int uid) { 22546 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 22547 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 22548 } 22549 } 22550 22551 private void handleOnPermissionsChanged(int uid) { 22552 final int count = mPermissionListeners.beginBroadcast(); 22553 try { 22554 for (int i = 0; i < count; i++) { 22555 IOnPermissionsChangeListener callback = mPermissionListeners 22556 .getBroadcastItem(i); 22557 try { 22558 callback.onPermissionsChanged(uid); 22559 } catch (RemoteException e) { 22560 Log.e(TAG, "Permission listener is dead", e); 22561 } 22562 } 22563 } finally { 22564 mPermissionListeners.finishBroadcast(); 22565 } 22566 } 22567 } 22568 22569 private class PackageManagerNative extends IPackageManagerNative.Stub { 22570 @Override 22571 public String[] getNamesForUids(int[] uids) throws RemoteException { 22572 final String[] results = PackageManagerService.this.getNamesForUids(uids); 22573 // massage results so they can be parsed by the native binder 22574 for (int i = results.length - 1; i >= 0; --i) { 22575 if (results[i] == null) { 22576 results[i] = ""; 22577 } 22578 } 22579 return results; 22580 } 22581 22582 // NB: this differentiates between preloads and sideloads 22583 @Override 22584 public String getInstallerForPackage(String packageName) throws RemoteException { 22585 final String installerName = getInstallerPackageName(packageName); 22586 if (!TextUtils.isEmpty(installerName)) { 22587 return installerName; 22588 } 22589 // differentiate between preload and sideload 22590 int callingUser = UserHandle.getUserId(Binder.getCallingUid()); 22591 ApplicationInfo appInfo = getApplicationInfo(packageName, 22592 /*flags*/ 0, 22593 /*userId*/ callingUser); 22594 if (appInfo != null && (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 22595 return "preload"; 22596 } 22597 return ""; 22598 } 22599 22600 @Override 22601 public int getVersionCodeForPackage(String packageName) throws RemoteException { 22602 try { 22603 int callingUser = UserHandle.getUserId(Binder.getCallingUid()); 22604 PackageInfo pInfo = getPackageInfo(packageName, 0, callingUser); 22605 if (pInfo != null) { 22606 return pInfo.versionCode; 22607 } 22608 } catch (Exception e) { 22609 } 22610 return 0; 22611 } 22612 } 22613 22614 private class PackageManagerInternalImpl extends PackageManagerInternal { 22615 @Override 22616 public void updatePermissionFlagsTEMP(String permName, String packageName, int flagMask, 22617 int flagValues, int userId) { 22618 PackageManagerService.this.updatePermissionFlags( 22619 permName, packageName, flagMask, flagValues, userId); 22620 } 22621 22622 @Override 22623 public int getPermissionFlagsTEMP(String permName, String packageName, int userId) { 22624 return PackageManagerService.this.getPermissionFlags(permName, packageName, userId); 22625 } 22626 22627 @Override 22628 public boolean isInstantApp(String packageName, int userId) { 22629 return PackageManagerService.this.isInstantApp(packageName, userId); 22630 } 22631 22632 @Override 22633 public String getInstantAppPackageName(int uid) { 22634 return PackageManagerService.this.getInstantAppPackageName(uid); 22635 } 22636 22637 @Override 22638 public boolean filterAppAccess(PackageParser.Package pkg, int callingUid, int userId) { 22639 synchronized (mPackages) { 22640 return PackageManagerService.this.filterAppAccessLPr( 22641 (PackageSetting) pkg.mExtras, callingUid, userId); 22642 } 22643 } 22644 22645 @Override 22646 public PackageParser.Package getPackage(String packageName) { 22647 synchronized (mPackages) { 22648 packageName = resolveInternalPackageNameLPr( 22649 packageName, PackageManager.VERSION_CODE_HIGHEST); 22650 return mPackages.get(packageName); 22651 } 22652 } 22653 22654 @Override 22655 public PackageParser.Package getDisabledPackage(String packageName) { 22656 synchronized (mPackages) { 22657 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 22658 return (ps != null) ? ps.pkg : null; 22659 } 22660 } 22661 22662 @Override 22663 public String getKnownPackageName(int knownPackage, int userId) { 22664 switch(knownPackage) { 22665 case PackageManagerInternal.PACKAGE_BROWSER: 22666 return getDefaultBrowserPackageName(userId); 22667 case PackageManagerInternal.PACKAGE_INSTALLER: 22668 return mRequiredInstallerPackage; 22669 case PackageManagerInternal.PACKAGE_SETUP_WIZARD: 22670 return mSetupWizardPackage; 22671 case PackageManagerInternal.PACKAGE_SYSTEM: 22672 return "android"; 22673 case PackageManagerInternal.PACKAGE_VERIFIER: 22674 return mRequiredVerifierPackage; 22675 } 22676 return null; 22677 } 22678 22679 @Override 22680 public boolean isResolveActivityComponent(ComponentInfo component) { 22681 return mResolveActivity.packageName.equals(component.packageName) 22682 && mResolveActivity.name.equals(component.name); 22683 } 22684 22685 @Override 22686 public void setLocationPackagesProvider(PackagesProvider provider) { 22687 mDefaultPermissionPolicy.setLocationPackagesProvider(provider); 22688 } 22689 22690 @Override 22691 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 22692 mDefaultPermissionPolicy.setVoiceInteractionPackagesProvider(provider); 22693 } 22694 22695 @Override 22696 public void setSmsAppPackagesProvider(PackagesProvider provider) { 22697 mDefaultPermissionPolicy.setSmsAppPackagesProvider(provider); 22698 } 22699 22700 @Override 22701 public void setDialerAppPackagesProvider(PackagesProvider provider) { 22702 mDefaultPermissionPolicy.setDialerAppPackagesProvider(provider); 22703 } 22704 22705 @Override 22706 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 22707 mDefaultPermissionPolicy.setSimCallManagerPackagesProvider(provider); 22708 } 22709 22710 @Override 22711 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 22712 mDefaultPermissionPolicy.setSyncAdapterPackagesProvider(provider); 22713 } 22714 22715 @Override 22716 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 22717 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsApp(packageName, userId); 22718 } 22719 22720 @Override 22721 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 22722 synchronized (mPackages) { 22723 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 22724 } 22725 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerApp(packageName, userId); 22726 } 22727 22728 @Override 22729 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 22730 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManager( 22731 packageName, userId); 22732 } 22733 22734 @Override 22735 public void setKeepUninstalledPackages(final List<String> packageList) { 22736 Preconditions.checkNotNull(packageList); 22737 List<String> removedFromList = null; 22738 synchronized (mPackages) { 22739 if (mKeepUninstalledPackages != null) { 22740 final int packagesCount = mKeepUninstalledPackages.size(); 22741 for (int i = 0; i < packagesCount; i++) { 22742 String oldPackage = mKeepUninstalledPackages.get(i); 22743 if (packageList != null && packageList.contains(oldPackage)) { 22744 continue; 22745 } 22746 if (removedFromList == null) { 22747 removedFromList = new ArrayList<>(); 22748 } 22749 removedFromList.add(oldPackage); 22750 } 22751 } 22752 mKeepUninstalledPackages = new ArrayList<>(packageList); 22753 if (removedFromList != null) { 22754 final int removedCount = removedFromList.size(); 22755 for (int i = 0; i < removedCount; i++) { 22756 deletePackageIfUnusedLPr(removedFromList.get(i)); 22757 } 22758 } 22759 } 22760 } 22761 22762 @Override 22763 public boolean isPermissionsReviewRequired(String packageName, int userId) { 22764 synchronized (mPackages) { 22765 return mPermissionManager.isPermissionsReviewRequired( 22766 mPackages.get(packageName), userId); 22767 } 22768 } 22769 22770 @Override 22771 public PackageInfo getPackageInfo( 22772 String packageName, int flags, int filterCallingUid, int userId) { 22773 return PackageManagerService.this 22774 .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST, 22775 flags, filterCallingUid, userId); 22776 } 22777 22778 @Override 22779 public int getPackageUid(String packageName, int flags, int userId) { 22780 return PackageManagerService.this 22781 .getPackageUid(packageName, flags, userId); 22782 } 22783 22784 @Override 22785 public ApplicationInfo getApplicationInfo( 22786 String packageName, int flags, int filterCallingUid, int userId) { 22787 return PackageManagerService.this 22788 .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId); 22789 } 22790 22791 @Override 22792 public ActivityInfo getActivityInfo( 22793 ComponentName component, int flags, int filterCallingUid, int userId) { 22794 return PackageManagerService.this 22795 .getActivityInfoInternal(component, flags, filterCallingUid, userId); 22796 } 22797 22798 @Override 22799 public List<ResolveInfo> queryIntentActivities( 22800 Intent intent, int flags, int filterCallingUid, int userId) { 22801 final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver()); 22802 return PackageManagerService.this 22803 .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid, 22804 userId, false /*resolveForStart*/, true /*allowDynamicSplits*/); 22805 } 22806 22807 @Override 22808 public List<ResolveInfo> queryIntentServices( 22809 Intent intent, int flags, int callingUid, int userId) { 22810 final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver()); 22811 return PackageManagerService.this 22812 .queryIntentServicesInternal(intent, resolvedType, flags, userId, callingUid, 22813 false); 22814 } 22815 22816 @Override 22817 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 22818 int userId) { 22819 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 22820 } 22821 22822 @Override 22823 public void setDeviceAndProfileOwnerPackages( 22824 int deviceOwnerUserId, String deviceOwnerPackage, 22825 SparseArray<String> profileOwnerPackages) { 22826 mProtectedPackages.setDeviceAndProfileOwnerPackages( 22827 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages); 22828 } 22829 22830 @Override 22831 public boolean isPackageDataProtected(int userId, String packageName) { 22832 return mProtectedPackages.isPackageDataProtected(userId, packageName); 22833 } 22834 22835 @Override 22836 public boolean isPackageEphemeral(int userId, String packageName) { 22837 synchronized (mPackages) { 22838 final PackageSetting ps = mSettings.mPackages.get(packageName); 22839 return ps != null ? ps.getInstantApp(userId) : false; 22840 } 22841 } 22842 22843 @Override 22844 public boolean wasPackageEverLaunched(String packageName, int userId) { 22845 synchronized (mPackages) { 22846 return mSettings.wasPackageEverLaunchedLPr(packageName, userId); 22847 } 22848 } 22849 22850 @Override 22851 public void grantRuntimePermission(String packageName, String permName, int userId, 22852 boolean overridePolicy) { 22853 PackageManagerService.this.mPermissionManager.grantRuntimePermission( 22854 permName, packageName, overridePolicy, getCallingUid(), userId, 22855 mPermissionCallback); 22856 } 22857 22858 @Override 22859 public void revokeRuntimePermission(String packageName, String permName, int userId, 22860 boolean overridePolicy) { 22861 mPermissionManager.revokeRuntimePermission( 22862 permName, packageName, overridePolicy, getCallingUid(), userId, 22863 mPermissionCallback); 22864 } 22865 22866 @Override 22867 public String getNameForUid(int uid) { 22868 return PackageManagerService.this.getNameForUid(uid); 22869 } 22870 22871 @Override 22872 public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj, 22873 Intent origIntent, String resolvedType, String callingPackage, 22874 Bundle verificationBundle, int userId) { 22875 PackageManagerService.this.requestInstantAppResolutionPhaseTwo( 22876 responseObj, origIntent, resolvedType, callingPackage, verificationBundle, 22877 userId); 22878 } 22879 22880 @Override 22881 public void grantEphemeralAccess(int userId, Intent intent, 22882 int targetAppId, int ephemeralAppId) { 22883 synchronized (mPackages) { 22884 mInstantAppRegistry.grantInstantAccessLPw(userId, intent, 22885 targetAppId, ephemeralAppId); 22886 } 22887 } 22888 22889 @Override 22890 public boolean isInstantAppInstallerComponent(ComponentName component) { 22891 synchronized (mPackages) { 22892 return mInstantAppInstallerActivity != null 22893 && mInstantAppInstallerActivity.getComponentName().equals(component); 22894 } 22895 } 22896 22897 @Override 22898 public void pruneInstantApps() { 22899 mInstantAppRegistry.pruneInstantApps(); 22900 } 22901 22902 @Override 22903 public String getSetupWizardPackageName() { 22904 return mSetupWizardPackage; 22905 } 22906 22907 public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) { 22908 if (policy != null) { 22909 mExternalSourcesPolicy = policy; 22910 } 22911 } 22912 22913 @Override 22914 public boolean isPackagePersistent(String packageName) { 22915 synchronized (mPackages) { 22916 PackageParser.Package pkg = mPackages.get(packageName); 22917 return pkg != null 22918 ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM 22919 | ApplicationInfo.FLAG_PERSISTENT)) == 22920 (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT)) 22921 : false; 22922 } 22923 } 22924 22925 @Override 22926 public boolean isLegacySystemApp(Package pkg) { 22927 synchronized (mPackages) { 22928 final PackageSetting ps = (PackageSetting) pkg.mExtras; 22929 return mPromoteSystemApps 22930 && ps.isSystem() 22931 && mExistingSystemPackages.contains(ps.name); 22932 } 22933 } 22934 22935 @Override 22936 public List<PackageInfo> getOverlayPackages(int userId) { 22937 final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>(); 22938 synchronized (mPackages) { 22939 for (PackageParser.Package p : mPackages.values()) { 22940 if (p.mOverlayTarget != null) { 22941 PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId); 22942 if (pkg != null) { 22943 overlayPackages.add(pkg); 22944 } 22945 } 22946 } 22947 } 22948 return overlayPackages; 22949 } 22950 22951 @Override 22952 public List<String> getTargetPackageNames(int userId) { 22953 List<String> targetPackages = new ArrayList<>(); 22954 synchronized (mPackages) { 22955 for (PackageParser.Package p : mPackages.values()) { 22956 if (p.mOverlayTarget == null) { 22957 targetPackages.add(p.packageName); 22958 } 22959 } 22960 } 22961 return targetPackages; 22962 } 22963 22964 @Override 22965 public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName, 22966 @Nullable List<String> overlayPackageNames) { 22967 synchronized (mPackages) { 22968 if (targetPackageName == null || mPackages.get(targetPackageName) == null) { 22969 Slog.e(TAG, "failed to find package " + targetPackageName); 22970 return false; 22971 } 22972 ArrayList<String> overlayPaths = null; 22973 if (overlayPackageNames != null && overlayPackageNames.size() > 0) { 22974 final int N = overlayPackageNames.size(); 22975 overlayPaths = new ArrayList<>(N); 22976 for (int i = 0; i < N; i++) { 22977 final String packageName = overlayPackageNames.get(i); 22978 final PackageParser.Package pkg = mPackages.get(packageName); 22979 if (pkg == null) { 22980 Slog.e(TAG, "failed to find package " + packageName); 22981 return false; 22982 } 22983 overlayPaths.add(pkg.baseCodePath); 22984 } 22985 } 22986 22987 final PackageSetting ps = mSettings.mPackages.get(targetPackageName); 22988 ps.setOverlayPaths(overlayPaths, userId); 22989 return true; 22990 } 22991 } 22992 22993 @Override 22994 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 22995 int flags, int userId, boolean resolveForStart) { 22996 return resolveIntentInternal( 22997 intent, resolvedType, flags, userId, resolveForStart); 22998 } 22999 23000 @Override 23001 public ResolveInfo resolveService(Intent intent, String resolvedType, 23002 int flags, int userId, int callingUid) { 23003 return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid); 23004 } 23005 23006 @Override 23007 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 23008 return PackageManagerService.this.resolveContentProviderInternal( 23009 name, flags, userId); 23010 } 23011 23012 @Override 23013 public void addIsolatedUid(int isolatedUid, int ownerUid) { 23014 synchronized (mPackages) { 23015 mIsolatedOwners.put(isolatedUid, ownerUid); 23016 } 23017 } 23018 23019 @Override 23020 public void removeIsolatedUid(int isolatedUid) { 23021 synchronized (mPackages) { 23022 mIsolatedOwners.delete(isolatedUid); 23023 } 23024 } 23025 23026 @Override 23027 public int getUidTargetSdkVersion(int uid) { 23028 synchronized (mPackages) { 23029 return getUidTargetSdkVersionLockedLPr(uid); 23030 } 23031 } 23032 23033 @Override 23034 public boolean canAccessInstantApps(int callingUid, int userId) { 23035 return PackageManagerService.this.canViewInstantApps(callingUid, userId); 23036 } 23037 23038 @Override 23039 public boolean hasInstantApplicationMetadata(String packageName, int userId) { 23040 synchronized (mPackages) { 23041 return mInstantAppRegistry.hasInstantApplicationMetadataLPr(packageName, userId); 23042 } 23043 } 23044 23045 @Override 23046 public void notifyPackageUse(String packageName, int reason) { 23047 synchronized (mPackages) { 23048 PackageManagerService.this.notifyPackageUseLocked(packageName, reason); 23049 } 23050 } 23051 } 23052 23053 @Override 23054 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 23055 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 23056 synchronized (mPackages) { 23057 final long identity = Binder.clearCallingIdentity(); 23058 try { 23059 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierApps( 23060 packageNames, userId); 23061 } finally { 23062 Binder.restoreCallingIdentity(identity); 23063 } 23064 } 23065 } 23066 23067 @Override 23068 public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) { 23069 enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices"); 23070 synchronized (mPackages) { 23071 final long identity = Binder.clearCallingIdentity(); 23072 try { 23073 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServices( 23074 packageNames, userId); 23075 } finally { 23076 Binder.restoreCallingIdentity(identity); 23077 } 23078 } 23079 } 23080 23081 private static void enforceSystemOrPhoneCaller(String tag) { 23082 int callingUid = Binder.getCallingUid(); 23083 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 23084 throw new SecurityException( 23085 "Cannot call " + tag + " from UID " + callingUid); 23086 } 23087 } 23088 23089 boolean isHistoricalPackageUsageAvailable() { 23090 return mPackageUsage.isHistoricalPackageUsageAvailable(); 23091 } 23092 23093 /** 23094 * Return a <b>copy</b> of the collection of packages known to the package manager. 23095 * @return A copy of the values of mPackages. 23096 */ 23097 Collection<PackageParser.Package> getPackages() { 23098 synchronized (mPackages) { 23099 return new ArrayList<>(mPackages.values()); 23100 } 23101 } 23102 23103 /** 23104 * Logs process start information (including base APK hash) to the security log. 23105 * @hide 23106 */ 23107 @Override 23108 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 23109 String apkFile, int pid) { 23110 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 23111 return; 23112 } 23113 if (!SecurityLog.isLoggingEnabled()) { 23114 return; 23115 } 23116 Bundle data = new Bundle(); 23117 data.putLong("startTimestamp", System.currentTimeMillis()); 23118 data.putString("processName", processName); 23119 data.putInt("uid", uid); 23120 data.putString("seinfo", seinfo); 23121 data.putString("apkFile", apkFile); 23122 data.putInt("pid", pid); 23123 Message msg = mProcessLoggingHandler.obtainMessage( 23124 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 23125 msg.setData(data); 23126 mProcessLoggingHandler.sendMessage(msg); 23127 } 23128 23129 public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) { 23130 return mCompilerStats.getPackageStats(pkgName); 23131 } 23132 23133 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) { 23134 return getOrCreateCompilerPackageStats(pkg.packageName); 23135 } 23136 23137 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) { 23138 return mCompilerStats.getOrCreatePackageStats(pkgName); 23139 } 23140 23141 public void deleteCompilerPackageStats(String pkgName) { 23142 mCompilerStats.deletePackageStats(pkgName); 23143 } 23144 23145 @Override 23146 public int getInstallReason(String packageName, int userId) { 23147 final int callingUid = Binder.getCallingUid(); 23148 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 23149 true /* requireFullPermission */, false /* checkShell */, 23150 "get install reason"); 23151 synchronized (mPackages) { 23152 final PackageSetting ps = mSettings.mPackages.get(packageName); 23153 if (filterAppAccessLPr(ps, callingUid, userId)) { 23154 return PackageManager.INSTALL_REASON_UNKNOWN; 23155 } 23156 if (ps != null) { 23157 return ps.getInstallReason(userId); 23158 } 23159 } 23160 return PackageManager.INSTALL_REASON_UNKNOWN; 23161 } 23162 23163 @Override 23164 public boolean canRequestPackageInstalls(String packageName, int userId) { 23165 return canRequestPackageInstallsInternal(packageName, 0, userId, 23166 true /* throwIfPermNotDeclared*/); 23167 } 23168 23169 private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId, 23170 boolean throwIfPermNotDeclared) { 23171 int callingUid = Binder.getCallingUid(); 23172 int uid = getPackageUid(packageName, 0, userId); 23173 if (callingUid != uid && callingUid != Process.ROOT_UID 23174 && callingUid != Process.SYSTEM_UID) { 23175 throw new SecurityException( 23176 "Caller uid " + callingUid + " does not own package " + packageName); 23177 } 23178 ApplicationInfo info = getApplicationInfo(packageName, flags, userId); 23179 if (info == null) { 23180 return false; 23181 } 23182 if (info.targetSdkVersion < Build.VERSION_CODES.O) { 23183 return false; 23184 } 23185 String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES; 23186 String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission); 23187 if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) { 23188 if (throwIfPermNotDeclared) { 23189 throw new SecurityException("Need to declare " + appOpPermission 23190 + " to call this api"); 23191 } else { 23192 Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api"); 23193 return false; 23194 } 23195 } 23196 if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) { 23197 return false; 23198 } 23199 if (mExternalSourcesPolicy != null) { 23200 int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid); 23201 if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) { 23202 return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED; 23203 } 23204 } 23205 return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED; 23206 } 23207 23208 @Override 23209 public ComponentName getInstantAppResolverSettingsComponent() { 23210 return mInstantAppResolverSettingsComponent; 23211 } 23212 23213 @Override 23214 public ComponentName getInstantAppInstallerComponent() { 23215 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 23216 return null; 23217 } 23218 return mInstantAppInstallerActivity == null 23219 ? null : mInstantAppInstallerActivity.getComponentName(); 23220 } 23221 23222 @Override 23223 public String getInstantAppAndroidId(String packageName, int userId) { 23224 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS, 23225 "getInstantAppAndroidId"); 23226 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 23227 true /* requireFullPermission */, false /* checkShell */, 23228 "getInstantAppAndroidId"); 23229 // Make sure the target is an Instant App. 23230 if (!isInstantApp(packageName, userId)) { 23231 return null; 23232 } 23233 synchronized (mPackages) { 23234 return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId); 23235 } 23236 } 23237 23238 boolean canHaveOatDir(String packageName) { 23239 synchronized (mPackages) { 23240 PackageParser.Package p = mPackages.get(packageName); 23241 if (p == null) { 23242 return false; 23243 } 23244 return p.canHaveOatDir(); 23245 } 23246 } 23247 23248 private String getOatDir(PackageParser.Package pkg) { 23249 if (!pkg.canHaveOatDir()) { 23250 return null; 23251 } 23252 File codePath = new File(pkg.codePath); 23253 if (codePath.isDirectory()) { 23254 return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath(); 23255 } 23256 return null; 23257 } 23258 23259 void deleteOatArtifactsOfPackage(String packageName) { 23260 final String[] instructionSets; 23261 final List<String> codePaths; 23262 final String oatDir; 23263 final PackageParser.Package pkg; 23264 synchronized (mPackages) { 23265 pkg = mPackages.get(packageName); 23266 } 23267 instructionSets = getAppDexInstructionSets(pkg.applicationInfo); 23268 codePaths = pkg.getAllCodePaths(); 23269 oatDir = getOatDir(pkg); 23270 23271 for (String codePath : codePaths) { 23272 for (String isa : instructionSets) { 23273 try { 23274 mInstaller.deleteOdex(codePath, isa, oatDir); 23275 } catch (InstallerException e) { 23276 Log.e(TAG, "Failed deleting oat files for " + codePath, e); 23277 } 23278 } 23279 } 23280 } 23281 23282 Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) { 23283 Set<String> unusedPackages = new HashSet<>(); 23284 long currentTimeInMillis = System.currentTimeMillis(); 23285 synchronized (mPackages) { 23286 for (PackageParser.Package pkg : mPackages.values()) { 23287 PackageSetting ps = mSettings.mPackages.get(pkg.packageName); 23288 if (ps == null) { 23289 continue; 23290 } 23291 PackageDexUsage.PackageUseInfo packageUseInfo = 23292 getDexManager().getPackageUseInfoOrDefault(pkg.packageName); 23293 if (PackageManagerServiceUtils 23294 .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis, 23295 downgradeTimeThresholdMillis, packageUseInfo, 23296 pkg.getLatestPackageUseTimeInMills(), 23297 pkg.getLatestForegroundPackageUseTimeInMills())) { 23298 unusedPackages.add(pkg.packageName); 23299 } 23300 } 23301 } 23302 return unusedPackages; 23303 } 23304} 23305 23306interface PackageSender { 23307 void sendPackageBroadcast(final String action, final String pkg, 23308 final Bundle extras, final int flags, final String targetPkg, 23309 final IIntentReceiver finishedReceiver, final int[] userIds); 23310 void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted, 23311 boolean includeStopped, int appId, int... userIds); 23312} 23313