PackageManagerService.java revision 5f2faaa7ed71a3d1aa862c37e27ebf817f094dc5
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.PARSE_IS_OEM; 85import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED; 86import static android.content.pm.PackageParser.isApkFile; 87import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 88import static android.os.storage.StorageManager.FLAG_STORAGE_CE; 89import static android.os.storage.StorageManager.FLAG_STORAGE_DE; 90import static android.system.OsConstants.O_CREAT; 91import static android.system.OsConstants.O_RDWR; 92 93import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 94import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 95import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 96import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 97import static com.android.internal.util.ArrayUtils.appendInt; 98import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 99import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 100import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 101import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 102import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 103import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason; 104import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter; 105import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_FAILURE; 106import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS; 107import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 108import static dalvik.system.DexFile.getNonProfileGuidedCompilerFilter; 109 110import android.Manifest; 111import android.annotation.IntDef; 112import android.annotation.NonNull; 113import android.annotation.Nullable; 114import android.app.ActivityManager; 115import android.app.AppOpsManager; 116import android.app.IActivityManager; 117import android.app.ResourcesManager; 118import android.app.admin.IDevicePolicyManager; 119import android.app.admin.SecurityLog; 120import android.app.backup.IBackupManager; 121import android.content.BroadcastReceiver; 122import android.content.ComponentName; 123import android.content.ContentResolver; 124import android.content.Context; 125import android.content.IIntentReceiver; 126import android.content.Intent; 127import android.content.IntentFilter; 128import android.content.IntentSender; 129import android.content.IntentSender.SendIntentException; 130import android.content.ServiceConnection; 131import android.content.pm.ActivityInfo; 132import android.content.pm.ApplicationInfo; 133import android.content.pm.AppsQueryHelper; 134import android.content.pm.AuxiliaryResolveInfo; 135import android.content.pm.ChangedPackages; 136import android.content.pm.ComponentInfo; 137import android.content.pm.FallbackCategoryProvider; 138import android.content.pm.FeatureInfo; 139import android.content.pm.IDexModuleRegisterCallback; 140import android.content.pm.IOnPermissionsChangeListener; 141import android.content.pm.IPackageDataObserver; 142import android.content.pm.IPackageDeleteObserver; 143import android.content.pm.IPackageDeleteObserver2; 144import android.content.pm.IPackageInstallObserver2; 145import android.content.pm.IPackageInstaller; 146import android.content.pm.IPackageManager; 147import android.content.pm.IPackageManagerNative; 148import android.content.pm.IPackageMoveObserver; 149import android.content.pm.IPackageStatsObserver; 150import android.content.pm.InstantAppInfo; 151import android.content.pm.InstantAppRequest; 152import android.content.pm.InstantAppResolveInfo; 153import android.content.pm.InstrumentationInfo; 154import android.content.pm.IntentFilterVerificationInfo; 155import android.content.pm.KeySet; 156import android.content.pm.PackageCleanItem; 157import android.content.pm.PackageInfo; 158import android.content.pm.PackageInfoLite; 159import android.content.pm.PackageInstaller; 160import android.content.pm.PackageManager; 161import android.content.pm.PackageManagerInternal; 162import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 163import android.content.pm.PackageParser; 164import android.content.pm.PackageParser.ActivityIntentInfo; 165import android.content.pm.PackageParser.Package; 166import android.content.pm.PackageParser.PackageLite; 167import android.content.pm.PackageParser.PackageParserException; 168import android.content.pm.PackageStats; 169import android.content.pm.PackageUserState; 170import android.content.pm.ParceledListSlice; 171import android.content.pm.PermissionGroupInfo; 172import android.content.pm.PermissionInfo; 173import android.content.pm.ProviderInfo; 174import android.content.pm.ResolveInfo; 175import android.content.pm.ServiceInfo; 176import android.content.pm.SharedLibraryInfo; 177import android.content.pm.Signature; 178import android.content.pm.UserInfo; 179import android.content.pm.VerifierDeviceIdentity; 180import android.content.pm.VerifierInfo; 181import android.content.pm.VersionedPackage; 182import android.content.res.Resources; 183import android.database.ContentObserver; 184import android.graphics.Bitmap; 185import android.hardware.display.DisplayManager; 186import android.net.Uri; 187import android.os.Binder; 188import android.os.Build; 189import android.os.Bundle; 190import android.os.Debug; 191import android.os.Environment; 192import android.os.Environment.UserEnvironment; 193import android.os.FileUtils; 194import android.os.Handler; 195import android.os.IBinder; 196import android.os.Looper; 197import android.os.Message; 198import android.os.Parcel; 199import android.os.ParcelFileDescriptor; 200import android.os.PatternMatcher; 201import android.os.Process; 202import android.os.RemoteCallbackList; 203import android.os.RemoteException; 204import android.os.ResultReceiver; 205import android.os.SELinux; 206import android.os.ServiceManager; 207import android.os.ShellCallback; 208import android.os.SystemClock; 209import android.os.SystemProperties; 210import android.os.Trace; 211import android.os.UserHandle; 212import android.os.UserManager; 213import android.os.UserManagerInternal; 214import android.os.storage.IStorageManager; 215import android.os.storage.StorageEventListener; 216import android.os.storage.StorageManager; 217import android.os.storage.StorageManagerInternal; 218import android.os.storage.VolumeInfo; 219import android.os.storage.VolumeRecord; 220import android.provider.Settings.Global; 221import android.provider.Settings.Secure; 222import android.security.KeyStore; 223import android.security.SystemKeyStore; 224import android.service.pm.PackageServiceDumpProto; 225import android.system.ErrnoException; 226import android.system.Os; 227import android.text.TextUtils; 228import android.text.format.DateUtils; 229import android.util.ArrayMap; 230import android.util.ArraySet; 231import android.util.Base64; 232import android.util.DisplayMetrics; 233import android.util.EventLog; 234import android.util.ExceptionUtils; 235import android.util.Log; 236import android.util.LogPrinter; 237import android.util.MathUtils; 238import android.util.PackageUtils; 239import android.util.Pair; 240import android.util.PrintStreamPrinter; 241import android.util.Slog; 242import android.util.SparseArray; 243import android.util.SparseBooleanArray; 244import android.util.SparseIntArray; 245import android.util.TimingsTraceLog; 246import android.util.Xml; 247import android.util.jar.StrictJarFile; 248import android.util.proto.ProtoOutputStream; 249import android.view.Display; 250 251import com.android.internal.R; 252import com.android.internal.annotations.GuardedBy; 253import com.android.internal.app.IMediaContainerService; 254import com.android.internal.app.ResolverActivity; 255import com.android.internal.content.NativeLibraryHelper; 256import com.android.internal.content.PackageHelper; 257import com.android.internal.logging.MetricsLogger; 258import com.android.internal.logging.nano.MetricsProto.MetricsEvent; 259import com.android.internal.os.IParcelFileDescriptorFactory; 260import com.android.internal.os.RoSystemProperties; 261import com.android.internal.os.SomeArgs; 262import com.android.internal.os.Zygote; 263import com.android.internal.telephony.CarrierAppUtils; 264import com.android.internal.util.ArrayUtils; 265import com.android.internal.util.ConcurrentUtils; 266import com.android.internal.util.DumpUtils; 267import com.android.internal.util.FastPrintWriter; 268import com.android.internal.util.FastXmlSerializer; 269import com.android.internal.util.IndentingPrintWriter; 270import com.android.internal.util.Preconditions; 271import com.android.internal.util.XmlUtils; 272import com.android.server.AttributeCache; 273import com.android.server.DeviceIdleController; 274import com.android.server.EventLogTags; 275import com.android.server.FgThread; 276import com.android.server.IntentResolver; 277import com.android.server.LocalServices; 278import com.android.server.LockGuard; 279import com.android.server.ServiceThread; 280import com.android.server.SystemConfig; 281import com.android.server.SystemServerInitThreadPool; 282import com.android.server.Watchdog; 283import com.android.server.net.NetworkPolicyManagerInternal; 284import com.android.server.pm.Installer.InstallerException; 285import com.android.server.pm.Settings.DatabaseVersion; 286import com.android.server.pm.Settings.VersionInfo; 287import com.android.server.pm.dex.DexManager; 288import com.android.server.pm.dex.DexoptOptions; 289import com.android.server.pm.dex.PackageDexUsage; 290import com.android.server.pm.permission.BasePermission; 291import com.android.server.pm.permission.DefaultPermissionGrantPolicy; 292import com.android.server.pm.permission.PermissionManagerService; 293import com.android.server.pm.permission.PermissionManagerInternal; 294import com.android.server.pm.permission.DefaultPermissionGrantPolicy.DefaultPermissionGrantedCallback; 295import com.android.server.pm.permission.PermissionManagerInternal.PermissionCallback; 296import com.android.server.pm.permission.PermissionsState; 297import com.android.server.pm.permission.PermissionsState.PermissionState; 298import com.android.server.storage.DeviceStorageMonitorInternal; 299 300import dalvik.system.CloseGuard; 301import dalvik.system.DexFile; 302import dalvik.system.VMRuntime; 303 304import libcore.io.IoUtils; 305import libcore.io.Streams; 306import libcore.util.EmptyArray; 307 308import org.xmlpull.v1.XmlPullParser; 309import org.xmlpull.v1.XmlPullParserException; 310import org.xmlpull.v1.XmlSerializer; 311 312import java.io.BufferedOutputStream; 313import java.io.BufferedReader; 314import java.io.ByteArrayInputStream; 315import java.io.ByteArrayOutputStream; 316import java.io.File; 317import java.io.FileDescriptor; 318import java.io.FileInputStream; 319import java.io.FileOutputStream; 320import java.io.FileReader; 321import java.io.FilenameFilter; 322import java.io.IOException; 323import java.io.InputStream; 324import java.io.OutputStream; 325import java.io.PrintWriter; 326import java.lang.annotation.Retention; 327import java.lang.annotation.RetentionPolicy; 328import java.nio.charset.StandardCharsets; 329import java.security.DigestInputStream; 330import java.security.MessageDigest; 331import java.security.NoSuchAlgorithmException; 332import java.security.PublicKey; 333import java.security.SecureRandom; 334import java.security.cert.Certificate; 335import java.security.cert.CertificateEncodingException; 336import java.security.cert.CertificateException; 337import java.text.SimpleDateFormat; 338import java.util.ArrayList; 339import java.util.Arrays; 340import java.util.Collection; 341import java.util.Collections; 342import java.util.Comparator; 343import java.util.Date; 344import java.util.HashMap; 345import java.util.HashSet; 346import java.util.Iterator; 347import java.util.LinkedHashSet; 348import java.util.List; 349import java.util.Map; 350import java.util.Objects; 351import java.util.Set; 352import java.util.concurrent.CountDownLatch; 353import java.util.concurrent.Future; 354import java.util.concurrent.TimeUnit; 355import java.util.concurrent.atomic.AtomicBoolean; 356import java.util.concurrent.atomic.AtomicInteger; 357import java.util.zip.GZIPInputStream; 358 359/** 360 * Keep track of all those APKs everywhere. 361 * <p> 362 * Internally there are two important locks: 363 * <ul> 364 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 365 * and other related state. It is a fine-grained lock that should only be held 366 * momentarily, as it's one of the most contended locks in the system. 367 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 368 * operations typically involve heavy lifting of application data on disk. Since 369 * {@code installd} is single-threaded, and it's operations can often be slow, 370 * this lock should never be acquired while already holding {@link #mPackages}. 371 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 372 * holding {@link #mInstallLock}. 373 * </ul> 374 * Many internal methods rely on the caller to hold the appropriate locks, and 375 * this contract is expressed through method name suffixes: 376 * <ul> 377 * <li>fooLI(): the caller must hold {@link #mInstallLock} 378 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 379 * being modified must be frozen 380 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 381 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 382 * </ul> 383 * <p> 384 * Because this class is very central to the platform's security; please run all 385 * CTS and unit tests whenever making modifications: 386 * 387 * <pre> 388 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 389 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases 390 * </pre> 391 */ 392public class PackageManagerService extends IPackageManager.Stub 393 implements PackageSender { 394 static final String TAG = "PackageManager"; 395 public static final boolean DEBUG_SETTINGS = false; 396 static final boolean DEBUG_PREFERRED = false; 397 static final boolean DEBUG_UPGRADE = false; 398 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 399 private static final boolean DEBUG_BACKUP = false; 400 public static final boolean DEBUG_INSTALL = false; 401 public static final boolean DEBUG_REMOVE = false; 402 private static final boolean DEBUG_BROADCASTS = false; 403 private static final boolean DEBUG_SHOW_INFO = false; 404 private static final boolean DEBUG_PACKAGE_INFO = false; 405 private static final boolean DEBUG_INTENT_MATCHING = false; 406 public static final boolean DEBUG_PACKAGE_SCANNING = false; 407 private static final boolean DEBUG_VERIFY = false; 408 private static final boolean DEBUG_FILTERS = false; 409 public static final boolean DEBUG_PERMISSIONS = false; 410 private static final boolean DEBUG_SHARED_LIBRARIES = false; 411 private static final boolean DEBUG_COMPRESSION = Build.IS_DEBUGGABLE; 412 413 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 414 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 415 // user, but by default initialize to this. 416 public static final boolean DEBUG_DEXOPT = false; 417 418 private static final boolean DEBUG_ABI_SELECTION = false; 419 private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE; 420 private static final boolean DEBUG_TRIAGED_MISSING = false; 421 private static final boolean DEBUG_APP_DATA = false; 422 423 /** REMOVE. According to Svet, this was only used to reset permissions during development. */ 424 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 425 426 private static final boolean HIDE_EPHEMERAL_APIS = false; 427 428 private static final boolean ENABLE_FREE_CACHE_V2 = 429 SystemProperties.getBoolean("fw.free_cache_v2", true); 430 431 private static final int RADIO_UID = Process.PHONE_UID; 432 private static final int LOG_UID = Process.LOG_UID; 433 private static final int NFC_UID = Process.NFC_UID; 434 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 435 private static final int SHELL_UID = Process.SHELL_UID; 436 437 // Suffix used during package installation when copying/moving 438 // package apks to install directory. 439 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 440 441 static final int SCAN_NO_DEX = 1<<1; 442 static final int SCAN_FORCE_DEX = 1<<2; 443 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 444 static final int SCAN_NEW_INSTALL = 1<<4; 445 static final int SCAN_UPDATE_TIME = 1<<5; 446 static final int SCAN_BOOTING = 1<<6; 447 static final int SCAN_TRUSTED_OVERLAY = 1<<7; 448 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8; 449 static final int SCAN_REPLACING = 1<<9; 450 static final int SCAN_REQUIRE_KNOWN = 1<<10; 451 static final int SCAN_MOVE = 1<<11; 452 static final int SCAN_INITIAL = 1<<12; 453 static final int SCAN_CHECK_ONLY = 1<<13; 454 static final int SCAN_DONT_KILL_APP = 1<<14; 455 static final int SCAN_IGNORE_FROZEN = 1<<15; 456 static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16; 457 static final int SCAN_AS_INSTANT_APP = 1<<17; 458 static final int SCAN_AS_FULL_APP = 1<<18; 459 static final int SCAN_AS_VIRTUAL_PRELOAD = 1<<19; 460 /** Should not be with the scan flags */ 461 static final int FLAGS_REMOVE_CHATTY = 1<<31; 462 463 private static final String STATIC_SHARED_LIB_DELIMITER = "_"; 464 /** Extension of the compressed packages */ 465 private final static String COMPRESSED_EXTENSION = ".gz"; 466 /** Suffix of stub packages on the system partition */ 467 private final static String STUB_SUFFIX = "-Stub"; 468 469 private static final int[] EMPTY_INT_ARRAY = new int[0]; 470 471 private static final int TYPE_UNKNOWN = 0; 472 private static final int TYPE_ACTIVITY = 1; 473 private static final int TYPE_RECEIVER = 2; 474 private static final int TYPE_SERVICE = 3; 475 private static final int TYPE_PROVIDER = 4; 476 @IntDef(prefix = { "TYPE_" }, value = { 477 TYPE_UNKNOWN, 478 TYPE_ACTIVITY, 479 TYPE_RECEIVER, 480 TYPE_SERVICE, 481 TYPE_PROVIDER, 482 }) 483 @Retention(RetentionPolicy.SOURCE) 484 public @interface ComponentType {} 485 486 /** 487 * Timeout (in milliseconds) after which the watchdog should declare that 488 * our handler thread is wedged. The usual default for such things is one 489 * minute but we sometimes do very lengthy I/O operations on this thread, 490 * such as installing multi-gigabyte applications, so ours needs to be longer. 491 */ 492 static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 493 494 /** 495 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 496 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 497 * settings entry if available, otherwise we use the hardcoded default. If it's been 498 * more than this long since the last fstrim, we force one during the boot sequence. 499 * 500 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 501 * one gets run at the next available charging+idle time. This final mandatory 502 * no-fstrim check kicks in only of the other scheduling criteria is never met. 503 */ 504 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 505 506 /** 507 * Whether verification is enabled by default. 508 */ 509 private static final boolean DEFAULT_VERIFY_ENABLE = true; 510 511 /** 512 * The default maximum time to wait for the verification agent to return in 513 * milliseconds. 514 */ 515 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 516 517 /** 518 * The default response for package verification timeout. 519 * 520 * This can be either PackageManager.VERIFICATION_ALLOW or 521 * PackageManager.VERIFICATION_REJECT. 522 */ 523 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 524 525 public static final String PLATFORM_PACKAGE_NAME = "android"; 526 527 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 528 529 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 530 DEFAULT_CONTAINER_PACKAGE, 531 "com.android.defcontainer.DefaultContainerService"); 532 533 private static final String KILL_APP_REASON_GIDS_CHANGED = 534 "permission grant or revoke changed gids"; 535 536 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 537 "permissions revoked"; 538 539 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 540 541 private static final String PACKAGE_SCHEME = "package"; 542 543 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 544 545 /** Canonical intent used to identify what counts as a "web browser" app */ 546 private static final Intent sBrowserIntent; 547 static { 548 sBrowserIntent = new Intent(); 549 sBrowserIntent.setAction(Intent.ACTION_VIEW); 550 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 551 sBrowserIntent.setData(Uri.parse("http:")); 552 } 553 554 /** 555 * The set of all protected actions [i.e. those actions for which a high priority 556 * intent filter is disallowed]. 557 */ 558 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 559 static { 560 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 561 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 562 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 563 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 564 } 565 566 // Compilation reasons. 567 public static final int REASON_FIRST_BOOT = 0; 568 public static final int REASON_BOOT = 1; 569 public static final int REASON_INSTALL = 2; 570 public static final int REASON_BACKGROUND_DEXOPT = 3; 571 public static final int REASON_AB_OTA = 4; 572 public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5; 573 public static final int REASON_SHARED = 6; 574 575 public static final int REASON_LAST = REASON_SHARED; 576 577 /** All dangerous permission names in the same order as the events in MetricsEvent */ 578 private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList( 579 Manifest.permission.READ_CALENDAR, 580 Manifest.permission.WRITE_CALENDAR, 581 Manifest.permission.CAMERA, 582 Manifest.permission.READ_CONTACTS, 583 Manifest.permission.WRITE_CONTACTS, 584 Manifest.permission.GET_ACCOUNTS, 585 Manifest.permission.ACCESS_FINE_LOCATION, 586 Manifest.permission.ACCESS_COARSE_LOCATION, 587 Manifest.permission.RECORD_AUDIO, 588 Manifest.permission.READ_PHONE_STATE, 589 Manifest.permission.CALL_PHONE, 590 Manifest.permission.READ_CALL_LOG, 591 Manifest.permission.WRITE_CALL_LOG, 592 Manifest.permission.ADD_VOICEMAIL, 593 Manifest.permission.USE_SIP, 594 Manifest.permission.PROCESS_OUTGOING_CALLS, 595 Manifest.permission.READ_CELL_BROADCASTS, 596 Manifest.permission.BODY_SENSORS, 597 Manifest.permission.SEND_SMS, 598 Manifest.permission.RECEIVE_SMS, 599 Manifest.permission.READ_SMS, 600 Manifest.permission.RECEIVE_WAP_PUSH, 601 Manifest.permission.RECEIVE_MMS, 602 Manifest.permission.READ_EXTERNAL_STORAGE, 603 Manifest.permission.WRITE_EXTERNAL_STORAGE, 604 Manifest.permission.READ_PHONE_NUMBERS, 605 Manifest.permission.ANSWER_PHONE_CALLS); 606 607 608 /** 609 * Version number for the package parser cache. Increment this whenever the format or 610 * extent of cached data changes. See {@code PackageParser#setCacheDir}. 611 */ 612 private static final String PACKAGE_PARSER_CACHE_VERSION = "1"; 613 614 /** 615 * Whether the package parser cache is enabled. 616 */ 617 private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true; 618 619 final ServiceThread mHandlerThread; 620 621 final PackageHandler mHandler; 622 623 private final ProcessLoggingHandler mProcessLoggingHandler; 624 625 /** 626 * Messages for {@link #mHandler} that need to wait for system ready before 627 * being dispatched. 628 */ 629 private ArrayList<Message> mPostSystemReadyMessages; 630 631 final int mSdkVersion = Build.VERSION.SDK_INT; 632 633 final Context mContext; 634 final boolean mFactoryTest; 635 final boolean mOnlyCore; 636 final DisplayMetrics mMetrics; 637 final int mDefParseFlags; 638 final String[] mSeparateProcesses; 639 final boolean mIsUpgrade; 640 final boolean mIsPreNUpgrade; 641 final boolean mIsPreNMR1Upgrade; 642 643 // Have we told the Activity Manager to whitelist the default container service by uid yet? 644 @GuardedBy("mPackages") 645 boolean mDefaultContainerWhitelisted = false; 646 647 @GuardedBy("mPackages") 648 private boolean mDexOptDialogShown; 649 650 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 651 // LOCK HELD. Can be called with mInstallLock held. 652 @GuardedBy("mInstallLock") 653 final Installer mInstaller; 654 655 /** Directory where installed third-party apps stored */ 656 final File mAppInstallDir; 657 658 /** 659 * Directory to which applications installed internally have their 660 * 32 bit native libraries copied. 661 */ 662 private File mAppLib32InstallDir; 663 664 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 665 // apps. 666 final File mDrmAppPrivateInstallDir; 667 668 // ---------------------------------------------------------------- 669 670 // Lock for state used when installing and doing other long running 671 // operations. Methods that must be called with this lock held have 672 // the suffix "LI". 673 final Object mInstallLock = new Object(); 674 675 // ---------------------------------------------------------------- 676 677 // Keys are String (package name), values are Package. This also serves 678 // as the lock for the global state. Methods that must be called with 679 // this lock held have the prefix "LP". 680 @GuardedBy("mPackages") 681 final ArrayMap<String, PackageParser.Package> mPackages = 682 new ArrayMap<String, PackageParser.Package>(); 683 684 final ArrayMap<String, Set<String>> mKnownCodebase = 685 new ArrayMap<String, Set<String>>(); 686 687 // Keys are isolated uids and values are the uid of the application 688 // that created the isolated proccess. 689 @GuardedBy("mPackages") 690 final SparseIntArray mIsolatedOwners = new SparseIntArray(); 691 692 /** 693 * Tracks new system packages [received in an OTA] that we expect to 694 * find updated user-installed versions. Keys are package name, values 695 * are package location. 696 */ 697 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 698 /** 699 * Tracks high priority intent filters for protected actions. During boot, certain 700 * filter actions are protected and should never be allowed to have a high priority 701 * intent filter for them. However, there is one, and only one exception -- the 702 * setup wizard. It must be able to define a high priority intent filter for these 703 * actions to ensure there are no escapes from the wizard. We need to delay processing 704 * of these during boot as we need to look at all of the system packages in order 705 * to know which component is the setup wizard. 706 */ 707 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 708 /** 709 * Whether or not processing protected filters should be deferred. 710 */ 711 private boolean mDeferProtectedFilters = true; 712 713 /** 714 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 715 */ 716 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 717 /** 718 * Whether or not system app permissions should be promoted from install to runtime. 719 */ 720 boolean mPromoteSystemApps; 721 722 @GuardedBy("mPackages") 723 final Settings mSettings; 724 725 /** 726 * Set of package names that are currently "frozen", which means active 727 * surgery is being done on the code/data for that package. The platform 728 * will refuse to launch frozen packages to avoid race conditions. 729 * 730 * @see PackageFreezer 731 */ 732 @GuardedBy("mPackages") 733 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 734 735 final ProtectedPackages mProtectedPackages; 736 737 @GuardedBy("mLoadedVolumes") 738 final ArraySet<String> mLoadedVolumes = new ArraySet<>(); 739 740 boolean mFirstBoot; 741 742 PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy; 743 744 @GuardedBy("mAvailableFeatures") 745 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 746 747 // If mac_permissions.xml was found for seinfo labeling. 748 boolean mFoundPolicyFile; 749 750 private final InstantAppRegistry mInstantAppRegistry; 751 752 @GuardedBy("mPackages") 753 int mChangedPackagesSequenceNumber; 754 /** 755 * List of changed [installed, removed or updated] packages. 756 * mapping from user id -> sequence number -> package name 757 */ 758 @GuardedBy("mPackages") 759 final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>(); 760 /** 761 * The sequence number of the last change to a package. 762 * mapping from user id -> package name -> sequence number 763 */ 764 @GuardedBy("mPackages") 765 final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>(); 766 767 class PackageParserCallback implements PackageParser.Callback { 768 @Override public final boolean hasFeature(String feature) { 769 return PackageManagerService.this.hasSystemFeature(feature, 0); 770 } 771 772 final List<PackageParser.Package> getStaticOverlayPackagesLocked( 773 Collection<PackageParser.Package> allPackages, String targetPackageName) { 774 List<PackageParser.Package> overlayPackages = null; 775 for (PackageParser.Package p : allPackages) { 776 if (targetPackageName.equals(p.mOverlayTarget) && p.mIsStaticOverlay) { 777 if (overlayPackages == null) { 778 overlayPackages = new ArrayList<PackageParser.Package>(); 779 } 780 overlayPackages.add(p); 781 } 782 } 783 if (overlayPackages != null) { 784 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 785 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 786 return p1.mOverlayPriority - p2.mOverlayPriority; 787 } 788 }; 789 Collections.sort(overlayPackages, cmp); 790 } 791 return overlayPackages; 792 } 793 794 final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages, 795 String targetPackageName, String targetPath) { 796 if ("android".equals(targetPackageName)) { 797 // Static RROs targeting to "android", ie framework-res.apk, are already applied by 798 // native AssetManager. 799 return null; 800 } 801 List<PackageParser.Package> overlayPackages = 802 getStaticOverlayPackagesLocked(allPackages, targetPackageName); 803 if (overlayPackages == null || overlayPackages.isEmpty()) { 804 return null; 805 } 806 List<String> overlayPathList = null; 807 for (PackageParser.Package overlayPackage : overlayPackages) { 808 if (targetPath == null) { 809 if (overlayPathList == null) { 810 overlayPathList = new ArrayList<String>(); 811 } 812 overlayPathList.add(overlayPackage.baseCodePath); 813 continue; 814 } 815 816 try { 817 // Creates idmaps for system to parse correctly the Android manifest of the 818 // target package. 819 // 820 // OverlayManagerService will update each of them with a correct gid from its 821 // target package app id. 822 mInstaller.idmap(targetPath, overlayPackage.baseCodePath, 823 UserHandle.getSharedAppGid( 824 UserHandle.getUserGid(UserHandle.USER_SYSTEM))); 825 if (overlayPathList == null) { 826 overlayPathList = new ArrayList<String>(); 827 } 828 overlayPathList.add(overlayPackage.baseCodePath); 829 } catch (InstallerException e) { 830 Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " + 831 overlayPackage.baseCodePath); 832 } 833 } 834 return overlayPathList == null ? null : overlayPathList.toArray(new String[0]); 835 } 836 837 String[] getStaticOverlayPaths(String targetPackageName, String targetPath) { 838 synchronized (mPackages) { 839 return getStaticOverlayPathsLocked( 840 mPackages.values(), targetPackageName, targetPath); 841 } 842 } 843 844 @Override public final String[] getOverlayApks(String targetPackageName) { 845 return getStaticOverlayPaths(targetPackageName, null); 846 } 847 848 @Override public final String[] getOverlayPaths(String targetPackageName, 849 String targetPath) { 850 return getStaticOverlayPaths(targetPackageName, targetPath); 851 } 852 } 853 854 class ParallelPackageParserCallback extends PackageParserCallback { 855 List<PackageParser.Package> mOverlayPackages = null; 856 857 void findStaticOverlayPackages() { 858 synchronized (mPackages) { 859 for (PackageParser.Package p : mPackages.values()) { 860 if (p.mIsStaticOverlay) { 861 if (mOverlayPackages == null) { 862 mOverlayPackages = new ArrayList<PackageParser.Package>(); 863 } 864 mOverlayPackages.add(p); 865 } 866 } 867 } 868 } 869 870 @Override 871 synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) { 872 // We can trust mOverlayPackages without holding mPackages because package uninstall 873 // can't happen while running parallel parsing. 874 // Moreover holding mPackages on each parsing thread causes dead-lock. 875 return mOverlayPackages == null ? null : 876 getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath); 877 } 878 } 879 880 final PackageParser.Callback mPackageParserCallback = new PackageParserCallback(); 881 final ParallelPackageParserCallback mParallelPackageParserCallback = 882 new ParallelPackageParserCallback(); 883 884 public static final class SharedLibraryEntry { 885 public final @Nullable String path; 886 public final @Nullable String apk; 887 public final @NonNull SharedLibraryInfo info; 888 889 SharedLibraryEntry(String _path, String _apk, String name, int version, int type, 890 String declaringPackageName, int declaringPackageVersionCode) { 891 path = _path; 892 apk = _apk; 893 info = new SharedLibraryInfo(name, version, type, new VersionedPackage( 894 declaringPackageName, declaringPackageVersionCode), null); 895 } 896 } 897 898 // Currently known shared libraries. 899 final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>(); 900 final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage = 901 new ArrayMap<>(); 902 903 // All available activities, for your resolving pleasure. 904 final ActivityIntentResolver mActivities = 905 new ActivityIntentResolver(); 906 907 // All available receivers, for your resolving pleasure. 908 final ActivityIntentResolver mReceivers = 909 new ActivityIntentResolver(); 910 911 // All available services, for your resolving pleasure. 912 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 913 914 // All available providers, for your resolving pleasure. 915 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 916 917 // Mapping from provider base names (first directory in content URI codePath) 918 // to the provider information. 919 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 920 new ArrayMap<String, PackageParser.Provider>(); 921 922 // Mapping from instrumentation class names to info about them. 923 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 924 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 925 926 // Packages whose data we have transfered into another package, thus 927 // should no longer exist. 928 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 929 930 // Broadcast actions that are only available to the system. 931 @GuardedBy("mProtectedBroadcasts") 932 final ArraySet<String> mProtectedBroadcasts = new ArraySet<>(); 933 934 /** List of packages waiting for verification. */ 935 final SparseArray<PackageVerificationState> mPendingVerification 936 = new SparseArray<PackageVerificationState>(); 937 938 final PackageInstallerService mInstallerService; 939 940 private final PackageDexOptimizer mPackageDexOptimizer; 941 // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package 942 // is used by other apps). 943 private final DexManager mDexManager; 944 945 private AtomicInteger mNextMoveId = new AtomicInteger(); 946 private final MoveCallbacks mMoveCallbacks; 947 948 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 949 950 // Cache of users who need badging. 951 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 952 953 /** Token for keys in mPendingVerification. */ 954 private int mPendingVerificationToken = 0; 955 956 volatile boolean mSystemReady; 957 volatile boolean mSafeMode; 958 volatile boolean mHasSystemUidErrors; 959 private volatile boolean mEphemeralAppsDisabled; 960 961 ApplicationInfo mAndroidApplication; 962 final ActivityInfo mResolveActivity = new ActivityInfo(); 963 final ResolveInfo mResolveInfo = new ResolveInfo(); 964 ComponentName mResolveComponentName; 965 PackageParser.Package mPlatformPackage; 966 ComponentName mCustomResolverComponentName; 967 968 boolean mResolverReplaced = false; 969 970 private final @Nullable ComponentName mIntentFilterVerifierComponent; 971 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 972 973 private int mIntentFilterVerificationToken = 0; 974 975 /** The service connection to the ephemeral resolver */ 976 final EphemeralResolverConnection mInstantAppResolverConnection; 977 /** Component used to show resolver settings for Instant Apps */ 978 final ComponentName mInstantAppResolverSettingsComponent; 979 980 /** Activity used to install instant applications */ 981 ActivityInfo mInstantAppInstallerActivity; 982 final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo(); 983 984 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 985 = new SparseArray<IntentFilterVerificationState>(); 986 987 // TODO remove this and go through mPermissonManager directly 988 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy; 989 private final PermissionManagerInternal mPermissionManager; 990 991 // List of packages names to keep cached, even if they are uninstalled for all users 992 private List<String> mKeepUninstalledPackages; 993 994 private UserManagerInternal mUserManagerInternal; 995 996 private DeviceIdleController.LocalService mDeviceIdleController; 997 998 private File mCacheDir; 999 1000 private Future<?> mPrepareAppDataFuture; 1001 1002 private static class IFVerificationParams { 1003 PackageParser.Package pkg; 1004 boolean replacing; 1005 int userId; 1006 int verifierUid; 1007 1008 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 1009 int _userId, int _verifierUid) { 1010 pkg = _pkg; 1011 replacing = _replacing; 1012 userId = _userId; 1013 replacing = _replacing; 1014 verifierUid = _verifierUid; 1015 } 1016 } 1017 1018 private interface IntentFilterVerifier<T extends IntentFilter> { 1019 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 1020 T filter, String packageName); 1021 void startVerifications(int userId); 1022 void receiveVerificationResponse(int verificationId); 1023 } 1024 1025 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 1026 private Context mContext; 1027 private ComponentName mIntentFilterVerifierComponent; 1028 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 1029 1030 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 1031 mContext = context; 1032 mIntentFilterVerifierComponent = verifierComponent; 1033 } 1034 1035 private String getDefaultScheme() { 1036 return IntentFilter.SCHEME_HTTPS; 1037 } 1038 1039 @Override 1040 public void startVerifications(int userId) { 1041 // Launch verifications requests 1042 int count = mCurrentIntentFilterVerifications.size(); 1043 for (int n=0; n<count; n++) { 1044 int verificationId = mCurrentIntentFilterVerifications.get(n); 1045 final IntentFilterVerificationState ivs = 1046 mIntentFilterVerificationStates.get(verificationId); 1047 1048 String packageName = ivs.getPackageName(); 1049 1050 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 1051 final int filterCount = filters.size(); 1052 ArraySet<String> domainsSet = new ArraySet<>(); 1053 for (int m=0; m<filterCount; m++) { 1054 PackageParser.ActivityIntentInfo filter = filters.get(m); 1055 domainsSet.addAll(filter.getHostsList()); 1056 } 1057 synchronized (mPackages) { 1058 if (mSettings.createIntentFilterVerificationIfNeededLPw( 1059 packageName, domainsSet) != null) { 1060 scheduleWriteSettingsLocked(); 1061 } 1062 } 1063 sendVerificationRequest(verificationId, ivs); 1064 } 1065 mCurrentIntentFilterVerifications.clear(); 1066 } 1067 1068 private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) { 1069 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 1070 verificationIntent.putExtra( 1071 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 1072 verificationId); 1073 verificationIntent.putExtra( 1074 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 1075 getDefaultScheme()); 1076 verificationIntent.putExtra( 1077 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 1078 ivs.getHostsString()); 1079 verificationIntent.putExtra( 1080 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 1081 ivs.getPackageName()); 1082 verificationIntent.setComponent(mIntentFilterVerifierComponent); 1083 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 1084 1085 DeviceIdleController.LocalService idleController = getDeviceIdleController(); 1086 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 1087 mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(), 1088 UserHandle.USER_SYSTEM, true, "intent filter verifier"); 1089 1090 mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM); 1091 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1092 "Sending IntentFilter verification broadcast"); 1093 } 1094 1095 public void receiveVerificationResponse(int verificationId) { 1096 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 1097 1098 final boolean verified = ivs.isVerified(); 1099 1100 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 1101 final int count = filters.size(); 1102 if (DEBUG_DOMAIN_VERIFICATION) { 1103 Slog.i(TAG, "Received verification response " + verificationId 1104 + " for " + count + " filters, verified=" + verified); 1105 } 1106 for (int n=0; n<count; n++) { 1107 PackageParser.ActivityIntentInfo filter = filters.get(n); 1108 filter.setVerified(verified); 1109 1110 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 1111 + " verified with result:" + verified + " and hosts:" 1112 + ivs.getHostsString()); 1113 } 1114 1115 mIntentFilterVerificationStates.remove(verificationId); 1116 1117 final String packageName = ivs.getPackageName(); 1118 IntentFilterVerificationInfo ivi = null; 1119 1120 synchronized (mPackages) { 1121 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 1122 } 1123 if (ivi == null) { 1124 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 1125 + verificationId + " packageName:" + packageName); 1126 return; 1127 } 1128 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1129 "Updating IntentFilterVerificationInfo for package " + packageName 1130 +" verificationId:" + verificationId); 1131 1132 synchronized (mPackages) { 1133 if (verified) { 1134 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 1135 } else { 1136 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 1137 } 1138 scheduleWriteSettingsLocked(); 1139 1140 final int userId = ivs.getUserId(); 1141 if (userId != UserHandle.USER_ALL) { 1142 final int userStatus = 1143 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 1144 1145 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 1146 boolean needUpdate = false; 1147 1148 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 1149 // already been set by the User thru the Disambiguation dialog 1150 switch (userStatus) { 1151 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 1152 if (verified) { 1153 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 1154 } else { 1155 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 1156 } 1157 needUpdate = true; 1158 break; 1159 1160 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 1161 if (verified) { 1162 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 1163 needUpdate = true; 1164 } 1165 break; 1166 1167 default: 1168 // Nothing to do 1169 } 1170 1171 if (needUpdate) { 1172 mSettings.updateIntentFilterVerificationStatusLPw( 1173 packageName, updatedStatus, userId); 1174 scheduleWritePackageRestrictionsLocked(userId); 1175 } 1176 } 1177 } 1178 } 1179 1180 @Override 1181 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 1182 ActivityIntentInfo filter, String packageName) { 1183 if (!hasValidDomains(filter)) { 1184 return false; 1185 } 1186 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 1187 if (ivs == null) { 1188 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 1189 packageName); 1190 } 1191 if (DEBUG_DOMAIN_VERIFICATION) { 1192 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 1193 } 1194 ivs.addFilter(filter); 1195 return true; 1196 } 1197 1198 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 1199 int userId, int verificationId, String packageName) { 1200 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 1201 verifierUid, userId, packageName); 1202 ivs.setPendingState(); 1203 synchronized (mPackages) { 1204 mIntentFilterVerificationStates.append(verificationId, ivs); 1205 mCurrentIntentFilterVerifications.add(verificationId); 1206 } 1207 return ivs; 1208 } 1209 } 1210 1211 private static boolean hasValidDomains(ActivityIntentInfo filter) { 1212 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 1213 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 1214 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 1215 } 1216 1217 // Set of pending broadcasts for aggregating enable/disable of components. 1218 static class PendingPackageBroadcasts { 1219 // for each user id, a map of <package name -> components within that package> 1220 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 1221 1222 public PendingPackageBroadcasts() { 1223 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 1224 } 1225 1226 public ArrayList<String> get(int userId, String packageName) { 1227 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1228 return packages.get(packageName); 1229 } 1230 1231 public void put(int userId, String packageName, ArrayList<String> components) { 1232 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1233 packages.put(packageName, components); 1234 } 1235 1236 public void remove(int userId, String packageName) { 1237 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 1238 if (packages != null) { 1239 packages.remove(packageName); 1240 } 1241 } 1242 1243 public void remove(int userId) { 1244 mUidMap.remove(userId); 1245 } 1246 1247 public int userIdCount() { 1248 return mUidMap.size(); 1249 } 1250 1251 public int userIdAt(int n) { 1252 return mUidMap.keyAt(n); 1253 } 1254 1255 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 1256 return mUidMap.get(userId); 1257 } 1258 1259 public int size() { 1260 // total number of pending broadcast entries across all userIds 1261 int num = 0; 1262 for (int i = 0; i< mUidMap.size(); i++) { 1263 num += mUidMap.valueAt(i).size(); 1264 } 1265 return num; 1266 } 1267 1268 public void clear() { 1269 mUidMap.clear(); 1270 } 1271 1272 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1273 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1274 if (map == null) { 1275 map = new ArrayMap<String, ArrayList<String>>(); 1276 mUidMap.put(userId, map); 1277 } 1278 return map; 1279 } 1280 } 1281 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1282 1283 // Service Connection to remote media container service to copy 1284 // package uri's from external media onto secure containers 1285 // or internal storage. 1286 private IMediaContainerService mContainerService = null; 1287 1288 static final int SEND_PENDING_BROADCAST = 1; 1289 static final int MCS_BOUND = 3; 1290 static final int END_COPY = 4; 1291 static final int INIT_COPY = 5; 1292 static final int MCS_UNBIND = 6; 1293 static final int START_CLEANING_PACKAGE = 7; 1294 static final int FIND_INSTALL_LOC = 8; 1295 static final int POST_INSTALL = 9; 1296 static final int MCS_RECONNECT = 10; 1297 static final int MCS_GIVE_UP = 11; 1298 static final int WRITE_SETTINGS = 13; 1299 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1300 static final int PACKAGE_VERIFIED = 15; 1301 static final int CHECK_PENDING_VERIFICATION = 16; 1302 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1303 static final int INTENT_FILTER_VERIFIED = 18; 1304 static final int WRITE_PACKAGE_LIST = 19; 1305 static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20; 1306 1307 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1308 1309 // Delay time in millisecs 1310 static final int BROADCAST_DELAY = 10 * 1000; 1311 1312 private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD = 1313 2 * 60 * 60 * 1000L; /* two hours */ 1314 1315 static UserManagerService sUserManager; 1316 1317 // Stores a list of users whose package restrictions file needs to be updated 1318 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1319 1320 final private DefaultContainerConnection mDefContainerConn = 1321 new DefaultContainerConnection(); 1322 class DefaultContainerConnection implements ServiceConnection { 1323 public void onServiceConnected(ComponentName name, IBinder service) { 1324 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1325 final IMediaContainerService imcs = IMediaContainerService.Stub 1326 .asInterface(Binder.allowBlocking(service)); 1327 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1328 } 1329 1330 public void onServiceDisconnected(ComponentName name) { 1331 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1332 } 1333 } 1334 1335 // Recordkeeping of restore-after-install operations that are currently in flight 1336 // between the Package Manager and the Backup Manager 1337 static class PostInstallData { 1338 public InstallArgs args; 1339 public PackageInstalledInfo res; 1340 1341 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1342 args = _a; 1343 res = _r; 1344 } 1345 } 1346 1347 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1348 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1349 1350 // XML tags for backup/restore of various bits of state 1351 private static final String TAG_PREFERRED_BACKUP = "pa"; 1352 private static final String TAG_DEFAULT_APPS = "da"; 1353 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1354 1355 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1356 private static final String TAG_ALL_GRANTS = "rt-grants"; 1357 private static final String TAG_GRANT = "grant"; 1358 private static final String ATTR_PACKAGE_NAME = "pkg"; 1359 1360 private static final String TAG_PERMISSION = "perm"; 1361 private static final String ATTR_PERMISSION_NAME = "name"; 1362 private static final String ATTR_IS_GRANTED = "g"; 1363 private static final String ATTR_USER_SET = "set"; 1364 private static final String ATTR_USER_FIXED = "fixed"; 1365 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1366 1367 // System/policy permission grants are not backed up 1368 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1369 FLAG_PERMISSION_POLICY_FIXED 1370 | FLAG_PERMISSION_SYSTEM_FIXED 1371 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1372 1373 // And we back up these user-adjusted states 1374 private static final int USER_RUNTIME_GRANT_MASK = 1375 FLAG_PERMISSION_USER_SET 1376 | FLAG_PERMISSION_USER_FIXED 1377 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1378 1379 final @Nullable String mRequiredVerifierPackage; 1380 final @NonNull String mRequiredInstallerPackage; 1381 final @NonNull String mRequiredUninstallerPackage; 1382 final @Nullable String mSetupWizardPackage; 1383 final @Nullable String mStorageManagerPackage; 1384 final @NonNull String mServicesSystemSharedLibraryPackageName; 1385 final @NonNull String mSharedSystemSharedLibraryPackageName; 1386 1387 private final PackageUsage mPackageUsage = new PackageUsage(); 1388 private final CompilerStats mCompilerStats = new CompilerStats(); 1389 1390 class PackageHandler extends Handler { 1391 private boolean mBound = false; 1392 final ArrayList<HandlerParams> mPendingInstalls = 1393 new ArrayList<HandlerParams>(); 1394 1395 private boolean connectToService() { 1396 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1397 " DefaultContainerService"); 1398 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1399 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1400 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1401 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1402 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1403 mBound = true; 1404 return true; 1405 } 1406 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1407 return false; 1408 } 1409 1410 private void disconnectService() { 1411 mContainerService = null; 1412 mBound = false; 1413 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1414 mContext.unbindService(mDefContainerConn); 1415 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1416 } 1417 1418 PackageHandler(Looper looper) { 1419 super(looper); 1420 } 1421 1422 public void handleMessage(Message msg) { 1423 try { 1424 doHandleMessage(msg); 1425 } finally { 1426 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1427 } 1428 } 1429 1430 void doHandleMessage(Message msg) { 1431 switch (msg.what) { 1432 case INIT_COPY: { 1433 HandlerParams params = (HandlerParams) msg.obj; 1434 int idx = mPendingInstalls.size(); 1435 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1436 // If a bind was already initiated we dont really 1437 // need to do anything. The pending install 1438 // will be processed later on. 1439 if (!mBound) { 1440 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1441 System.identityHashCode(mHandler)); 1442 // If this is the only one pending we might 1443 // have to bind to the service again. 1444 if (!connectToService()) { 1445 Slog.e(TAG, "Failed to bind to media container service"); 1446 params.serviceError(); 1447 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1448 System.identityHashCode(mHandler)); 1449 if (params.traceMethod != null) { 1450 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1451 params.traceCookie); 1452 } 1453 return; 1454 } else { 1455 // Once we bind to the service, the first 1456 // pending request will be processed. 1457 mPendingInstalls.add(idx, params); 1458 } 1459 } else { 1460 mPendingInstalls.add(idx, params); 1461 // Already bound to the service. Just make 1462 // sure we trigger off processing the first request. 1463 if (idx == 0) { 1464 mHandler.sendEmptyMessage(MCS_BOUND); 1465 } 1466 } 1467 break; 1468 } 1469 case MCS_BOUND: { 1470 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1471 if (msg.obj != null) { 1472 mContainerService = (IMediaContainerService) msg.obj; 1473 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1474 System.identityHashCode(mHandler)); 1475 } 1476 if (mContainerService == null) { 1477 if (!mBound) { 1478 // Something seriously wrong since we are not bound and we are not 1479 // waiting for connection. Bail out. 1480 Slog.e(TAG, "Cannot bind to media container service"); 1481 for (HandlerParams params : mPendingInstalls) { 1482 // Indicate service bind error 1483 params.serviceError(); 1484 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1485 System.identityHashCode(params)); 1486 if (params.traceMethod != null) { 1487 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1488 params.traceMethod, params.traceCookie); 1489 } 1490 return; 1491 } 1492 mPendingInstalls.clear(); 1493 } else { 1494 Slog.w(TAG, "Waiting to connect to media container service"); 1495 } 1496 } else if (mPendingInstalls.size() > 0) { 1497 HandlerParams params = mPendingInstalls.get(0); 1498 if (params != null) { 1499 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1500 System.identityHashCode(params)); 1501 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1502 if (params.startCopy()) { 1503 // We are done... look for more work or to 1504 // go idle. 1505 if (DEBUG_SD_INSTALL) Log.i(TAG, 1506 "Checking for more work or unbind..."); 1507 // Delete pending install 1508 if (mPendingInstalls.size() > 0) { 1509 mPendingInstalls.remove(0); 1510 } 1511 if (mPendingInstalls.size() == 0) { 1512 if (mBound) { 1513 if (DEBUG_SD_INSTALL) Log.i(TAG, 1514 "Posting delayed MCS_UNBIND"); 1515 removeMessages(MCS_UNBIND); 1516 Message ubmsg = obtainMessage(MCS_UNBIND); 1517 // Unbind after a little delay, to avoid 1518 // continual thrashing. 1519 sendMessageDelayed(ubmsg, 10000); 1520 } 1521 } else { 1522 // There are more pending requests in queue. 1523 // Just post MCS_BOUND message to trigger processing 1524 // of next pending install. 1525 if (DEBUG_SD_INSTALL) Log.i(TAG, 1526 "Posting MCS_BOUND for next work"); 1527 mHandler.sendEmptyMessage(MCS_BOUND); 1528 } 1529 } 1530 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1531 } 1532 } else { 1533 // Should never happen ideally. 1534 Slog.w(TAG, "Empty queue"); 1535 } 1536 break; 1537 } 1538 case MCS_RECONNECT: { 1539 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1540 if (mPendingInstalls.size() > 0) { 1541 if (mBound) { 1542 disconnectService(); 1543 } 1544 if (!connectToService()) { 1545 Slog.e(TAG, "Failed to bind to media container service"); 1546 for (HandlerParams params : mPendingInstalls) { 1547 // Indicate service bind error 1548 params.serviceError(); 1549 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1550 System.identityHashCode(params)); 1551 } 1552 mPendingInstalls.clear(); 1553 } 1554 } 1555 break; 1556 } 1557 case MCS_UNBIND: { 1558 // If there is no actual work left, then time to unbind. 1559 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1560 1561 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1562 if (mBound) { 1563 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1564 1565 disconnectService(); 1566 } 1567 } else if (mPendingInstalls.size() > 0) { 1568 // There are more pending requests in queue. 1569 // Just post MCS_BOUND message to trigger processing 1570 // of next pending install. 1571 mHandler.sendEmptyMessage(MCS_BOUND); 1572 } 1573 1574 break; 1575 } 1576 case MCS_GIVE_UP: { 1577 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1578 HandlerParams params = mPendingInstalls.remove(0); 1579 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1580 System.identityHashCode(params)); 1581 break; 1582 } 1583 case SEND_PENDING_BROADCAST: { 1584 String packages[]; 1585 ArrayList<String> components[]; 1586 int size = 0; 1587 int uids[]; 1588 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1589 synchronized (mPackages) { 1590 if (mPendingBroadcasts == null) { 1591 return; 1592 } 1593 size = mPendingBroadcasts.size(); 1594 if (size <= 0) { 1595 // Nothing to be done. Just return 1596 return; 1597 } 1598 packages = new String[size]; 1599 components = new ArrayList[size]; 1600 uids = new int[size]; 1601 int i = 0; // filling out the above arrays 1602 1603 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1604 int packageUserId = mPendingBroadcasts.userIdAt(n); 1605 Iterator<Map.Entry<String, ArrayList<String>>> it 1606 = mPendingBroadcasts.packagesForUserId(packageUserId) 1607 .entrySet().iterator(); 1608 while (it.hasNext() && i < size) { 1609 Map.Entry<String, ArrayList<String>> ent = it.next(); 1610 packages[i] = ent.getKey(); 1611 components[i] = ent.getValue(); 1612 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1613 uids[i] = (ps != null) 1614 ? UserHandle.getUid(packageUserId, ps.appId) 1615 : -1; 1616 i++; 1617 } 1618 } 1619 size = i; 1620 mPendingBroadcasts.clear(); 1621 } 1622 // Send broadcasts 1623 for (int i = 0; i < size; i++) { 1624 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1625 } 1626 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1627 break; 1628 } 1629 case START_CLEANING_PACKAGE: { 1630 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1631 final String packageName = (String)msg.obj; 1632 final int userId = msg.arg1; 1633 final boolean andCode = msg.arg2 != 0; 1634 synchronized (mPackages) { 1635 if (userId == UserHandle.USER_ALL) { 1636 int[] users = sUserManager.getUserIds(); 1637 for (int user : users) { 1638 mSettings.addPackageToCleanLPw( 1639 new PackageCleanItem(user, packageName, andCode)); 1640 } 1641 } else { 1642 mSettings.addPackageToCleanLPw( 1643 new PackageCleanItem(userId, packageName, andCode)); 1644 } 1645 } 1646 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1647 startCleaningPackages(); 1648 } break; 1649 case POST_INSTALL: { 1650 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1651 1652 PostInstallData data = mRunningInstalls.get(msg.arg1); 1653 final boolean didRestore = (msg.arg2 != 0); 1654 mRunningInstalls.delete(msg.arg1); 1655 1656 if (data != null) { 1657 InstallArgs args = data.args; 1658 PackageInstalledInfo parentRes = data.res; 1659 1660 final boolean grantPermissions = (args.installFlags 1661 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1662 final boolean killApp = (args.installFlags 1663 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1664 final boolean virtualPreload = ((args.installFlags 1665 & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0); 1666 final String[] grantedPermissions = args.installGrantPermissions; 1667 1668 // Handle the parent package 1669 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1670 virtualPreload, grantedPermissions, didRestore, 1671 args.installerPackageName, args.observer); 1672 1673 // Handle the child packages 1674 final int childCount = (parentRes.addedChildPackages != null) 1675 ? parentRes.addedChildPackages.size() : 0; 1676 for (int i = 0; i < childCount; i++) { 1677 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1678 handlePackagePostInstall(childRes, grantPermissions, killApp, 1679 virtualPreload, grantedPermissions, false /*didRestore*/, 1680 args.installerPackageName, args.observer); 1681 } 1682 1683 // Log tracing if needed 1684 if (args.traceMethod != null) { 1685 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1686 args.traceCookie); 1687 } 1688 } else { 1689 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1690 } 1691 1692 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1693 } break; 1694 case WRITE_SETTINGS: { 1695 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1696 synchronized (mPackages) { 1697 removeMessages(WRITE_SETTINGS); 1698 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1699 mSettings.writeLPr(); 1700 mDirtyUsers.clear(); 1701 } 1702 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1703 } break; 1704 case WRITE_PACKAGE_RESTRICTIONS: { 1705 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1706 synchronized (mPackages) { 1707 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1708 for (int userId : mDirtyUsers) { 1709 mSettings.writePackageRestrictionsLPr(userId); 1710 } 1711 mDirtyUsers.clear(); 1712 } 1713 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1714 } break; 1715 case WRITE_PACKAGE_LIST: { 1716 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1717 synchronized (mPackages) { 1718 removeMessages(WRITE_PACKAGE_LIST); 1719 mSettings.writePackageListLPr(msg.arg1); 1720 } 1721 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1722 } break; 1723 case CHECK_PENDING_VERIFICATION: { 1724 final int verificationId = msg.arg1; 1725 final PackageVerificationState state = mPendingVerification.get(verificationId); 1726 1727 if ((state != null) && !state.timeoutExtended()) { 1728 final InstallArgs args = state.getInstallArgs(); 1729 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1730 1731 Slog.i(TAG, "Verification timed out for " + originUri); 1732 mPendingVerification.remove(verificationId); 1733 1734 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1735 1736 final UserHandle user = args.getUser(); 1737 if (getDefaultVerificationResponse(user) 1738 == PackageManager.VERIFICATION_ALLOW) { 1739 Slog.i(TAG, "Continuing with installation of " + originUri); 1740 state.setVerifierResponse(Binder.getCallingUid(), 1741 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1742 broadcastPackageVerified(verificationId, originUri, 1743 PackageManager.VERIFICATION_ALLOW, user); 1744 try { 1745 ret = args.copyApk(mContainerService, true); 1746 } catch (RemoteException e) { 1747 Slog.e(TAG, "Could not contact the ContainerService"); 1748 } 1749 } else { 1750 broadcastPackageVerified(verificationId, originUri, 1751 PackageManager.VERIFICATION_REJECT, user); 1752 } 1753 1754 Trace.asyncTraceEnd( 1755 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1756 1757 processPendingInstall(args, ret); 1758 mHandler.sendEmptyMessage(MCS_UNBIND); 1759 } 1760 break; 1761 } 1762 case PACKAGE_VERIFIED: { 1763 final int verificationId = msg.arg1; 1764 1765 final PackageVerificationState state = mPendingVerification.get(verificationId); 1766 if (state == null) { 1767 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1768 break; 1769 } 1770 1771 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1772 1773 state.setVerifierResponse(response.callerUid, response.code); 1774 1775 if (state.isVerificationComplete()) { 1776 mPendingVerification.remove(verificationId); 1777 1778 final InstallArgs args = state.getInstallArgs(); 1779 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1780 1781 int ret; 1782 if (state.isInstallAllowed()) { 1783 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1784 broadcastPackageVerified(verificationId, originUri, 1785 response.code, state.getInstallArgs().getUser()); 1786 try { 1787 ret = args.copyApk(mContainerService, true); 1788 } catch (RemoteException e) { 1789 Slog.e(TAG, "Could not contact the ContainerService"); 1790 } 1791 } else { 1792 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1793 } 1794 1795 Trace.asyncTraceEnd( 1796 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1797 1798 processPendingInstall(args, ret); 1799 mHandler.sendEmptyMessage(MCS_UNBIND); 1800 } 1801 1802 break; 1803 } 1804 case START_INTENT_FILTER_VERIFICATIONS: { 1805 IFVerificationParams params = (IFVerificationParams) msg.obj; 1806 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1807 params.replacing, params.pkg); 1808 break; 1809 } 1810 case INTENT_FILTER_VERIFIED: { 1811 final int verificationId = msg.arg1; 1812 1813 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1814 verificationId); 1815 if (state == null) { 1816 Slog.w(TAG, "Invalid IntentFilter verification token " 1817 + verificationId + " received"); 1818 break; 1819 } 1820 1821 final int userId = state.getUserId(); 1822 1823 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1824 "Processing IntentFilter verification with token:" 1825 + verificationId + " and userId:" + userId); 1826 1827 final IntentFilterVerificationResponse response = 1828 (IntentFilterVerificationResponse) msg.obj; 1829 1830 state.setVerifierResponse(response.callerUid, response.code); 1831 1832 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1833 "IntentFilter verification with token:" + verificationId 1834 + " and userId:" + userId 1835 + " is settings verifier response with response code:" 1836 + response.code); 1837 1838 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1839 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1840 + response.getFailedDomainsString()); 1841 } 1842 1843 if (state.isVerificationComplete()) { 1844 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1845 } else { 1846 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1847 "IntentFilter verification with token:" + verificationId 1848 + " was not said to be complete"); 1849 } 1850 1851 break; 1852 } 1853 case INSTANT_APP_RESOLUTION_PHASE_TWO: { 1854 InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext, 1855 mInstantAppResolverConnection, 1856 (InstantAppRequest) msg.obj, 1857 mInstantAppInstallerActivity, 1858 mHandler); 1859 } 1860 } 1861 } 1862 } 1863 1864 private PermissionCallback mPermissionCallback = new PermissionCallback() { 1865 @Override 1866 public void onGidsChanged(int appId, int userId) { 1867 mHandler.post(new Runnable() { 1868 @Override 1869 public void run() { 1870 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 1871 } 1872 }); 1873 } 1874 @Override 1875 public void onPermissionGranted(int uid, int userId) { 1876 mOnPermissionChangeListeners.onPermissionsChanged(uid); 1877 1878 // Not critical; if this is lost, the application has to request again. 1879 synchronized (mPackages) { 1880 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 1881 } 1882 } 1883 @Override 1884 public void onInstallPermissionGranted() { 1885 synchronized (mPackages) { 1886 scheduleWriteSettingsLocked(); 1887 } 1888 } 1889 @Override 1890 public void onPermissionRevoked(int uid, int userId) { 1891 mOnPermissionChangeListeners.onPermissionsChanged(uid); 1892 1893 synchronized (mPackages) { 1894 // Critical; after this call the application should never have the permission 1895 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 1896 } 1897 1898 final int appId = UserHandle.getAppId(uid); 1899 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 1900 } 1901 @Override 1902 public void onInstallPermissionRevoked() { 1903 synchronized (mPackages) { 1904 scheduleWriteSettingsLocked(); 1905 } 1906 } 1907 @Override 1908 public void onPermissionUpdated(int[] updatedUserIds, boolean sync) { 1909 synchronized (mPackages) { 1910 for (int userId : updatedUserIds) { 1911 mSettings.writeRuntimePermissionsForUserLPr(userId, sync); 1912 } 1913 } 1914 } 1915 @Override 1916 public void onInstallPermissionUpdated() { 1917 synchronized (mPackages) { 1918 scheduleWriteSettingsLocked(); 1919 } 1920 } 1921 @Override 1922 public void onPermissionRemoved() { 1923 synchronized (mPackages) { 1924 mSettings.writeLPr(); 1925 } 1926 } 1927 }; 1928 1929 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1930 boolean killApp, boolean virtualPreload, String[] grantedPermissions, 1931 boolean launchedForRestore, String installerPackage, 1932 IPackageInstallObserver2 installObserver) { 1933 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1934 // Send the removed broadcasts 1935 if (res.removedInfo != null) { 1936 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1937 } 1938 1939 // Now that we successfully installed the package, grant runtime 1940 // permissions if requested before broadcasting the install. Also 1941 // for legacy apps in permission review mode we clear the permission 1942 // review flag which is used to emulate runtime permissions for 1943 // legacy apps. 1944 if (grantPermissions) { 1945 final int callingUid = Binder.getCallingUid(); 1946 mPermissionManager.grantRequestedRuntimePermissions( 1947 res.pkg, res.newUsers, grantedPermissions, callingUid, 1948 mPermissionCallback); 1949 } 1950 1951 final boolean update = res.removedInfo != null 1952 && res.removedInfo.removedPackage != null; 1953 final String installerPackageName = 1954 res.installerPackageName != null 1955 ? res.installerPackageName 1956 : res.removedInfo != null 1957 ? res.removedInfo.installerPackageName 1958 : null; 1959 1960 // If this is the first time we have child packages for a disabled privileged 1961 // app that had no children, we grant requested runtime permissions to the new 1962 // children if the parent on the system image had them already granted. 1963 if (res.pkg.parentPackage != null) { 1964 final int callingUid = Binder.getCallingUid(); 1965 mPermissionManager.grantRuntimePermissionsGrantedToDisabledPackage( 1966 res.pkg, callingUid, mPermissionCallback); 1967 } 1968 1969 synchronized (mPackages) { 1970 mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers); 1971 } 1972 1973 final String packageName = res.pkg.applicationInfo.packageName; 1974 1975 // Determine the set of users who are adding this package for 1976 // the first time vs. those who are seeing an update. 1977 int[] firstUsers = EMPTY_INT_ARRAY; 1978 int[] updateUsers = EMPTY_INT_ARRAY; 1979 final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0; 1980 final PackageSetting ps = (PackageSetting) res.pkg.mExtras; 1981 for (int newUser : res.newUsers) { 1982 if (ps.getInstantApp(newUser)) { 1983 continue; 1984 } 1985 if (allNewUsers) { 1986 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1987 continue; 1988 } 1989 boolean isNew = true; 1990 for (int origUser : res.origUsers) { 1991 if (origUser == newUser) { 1992 isNew = false; 1993 break; 1994 } 1995 } 1996 if (isNew) { 1997 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1998 } else { 1999 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 2000 } 2001 } 2002 2003 // Send installed broadcasts if the package is not a static shared lib. 2004 if (res.pkg.staticSharedLibName == null) { 2005 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 2006 2007 // Send added for users that see the package for the first time 2008 // sendPackageAddedForNewUsers also deals with system apps 2009 int appId = UserHandle.getAppId(res.uid); 2010 boolean isSystem = res.pkg.applicationInfo.isSystemApp(); 2011 sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload, 2012 virtualPreload /*startReceiver*/, appId, firstUsers); 2013 2014 // Send added for users that don't see the package for the first time 2015 Bundle extras = new Bundle(1); 2016 extras.putInt(Intent.EXTRA_UID, res.uid); 2017 if (update) { 2018 extras.putBoolean(Intent.EXTRA_REPLACING, true); 2019 } 2020 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 2021 extras, 0 /*flags*/, 2022 null /*targetPackage*/, null /*finishedReceiver*/, updateUsers); 2023 if (installerPackageName != null) { 2024 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 2025 extras, 0 /*flags*/, 2026 installerPackageName, null /*finishedReceiver*/, updateUsers); 2027 } 2028 2029 // Send replaced for users that don't see the package for the first time 2030 if (update) { 2031 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 2032 packageName, extras, 0 /*flags*/, 2033 null /*targetPackage*/, null /*finishedReceiver*/, 2034 updateUsers); 2035 if (installerPackageName != null) { 2036 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 2037 extras, 0 /*flags*/, 2038 installerPackageName, null /*finishedReceiver*/, updateUsers); 2039 } 2040 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 2041 null /*package*/, null /*extras*/, 0 /*flags*/, 2042 packageName /*targetPackage*/, 2043 null /*finishedReceiver*/, updateUsers); 2044 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 2045 // First-install and we did a restore, so we're responsible for the 2046 // first-launch broadcast. 2047 if (DEBUG_BACKUP) { 2048 Slog.i(TAG, "Post-restore of " + packageName 2049 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers)); 2050 } 2051 sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers); 2052 } 2053 2054 // Send broadcast package appeared if forward locked/external for all users 2055 // treat asec-hosted packages like removable media on upgrade 2056 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 2057 if (DEBUG_INSTALL) { 2058 Slog.i(TAG, "upgrading pkg " + res.pkg 2059 + " is ASEC-hosted -> AVAILABLE"); 2060 } 2061 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 2062 ArrayList<String> pkgList = new ArrayList<>(1); 2063 pkgList.add(packageName); 2064 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 2065 } 2066 } 2067 2068 // Work that needs to happen on first install within each user 2069 if (firstUsers != null && firstUsers.length > 0) { 2070 synchronized (mPackages) { 2071 for (int userId : firstUsers) { 2072 // If this app is a browser and it's newly-installed for some 2073 // users, clear any default-browser state in those users. The 2074 // app's nature doesn't depend on the user, so we can just check 2075 // its browser nature in any user and generalize. 2076 if (packageIsBrowser(packageName, userId)) { 2077 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 2078 } 2079 2080 // We may also need to apply pending (restored) runtime 2081 // permission grants within these users. 2082 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 2083 } 2084 } 2085 } 2086 2087 // Log current value of "unknown sources" setting 2088 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 2089 getUnknownSourcesSettings()); 2090 2091 // Remove the replaced package's older resources safely now 2092 // We delete after a gc for applications on sdcard. 2093 if (res.removedInfo != null && res.removedInfo.args != null) { 2094 Runtime.getRuntime().gc(); 2095 synchronized (mInstallLock) { 2096 res.removedInfo.args.doPostDeleteLI(true); 2097 } 2098 } else { 2099 // Force a gc to clear up things. Ask for a background one, it's fine to go on 2100 // and not block here. 2101 VMRuntime.getRuntime().requestConcurrentGC(); 2102 } 2103 2104 // Notify DexManager that the package was installed for new users. 2105 // The updated users should already be indexed and the package code paths 2106 // should not change. 2107 // Don't notify the manager for ephemeral apps as they are not expected to 2108 // survive long enough to benefit of background optimizations. 2109 for (int userId : firstUsers) { 2110 PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId); 2111 // There's a race currently where some install events may interleave with an uninstall. 2112 // This can lead to package info being null (b/36642664). 2113 if (info != null) { 2114 mDexManager.notifyPackageInstalled(info, userId); 2115 } 2116 } 2117 } 2118 2119 // If someone is watching installs - notify them 2120 if (installObserver != null) { 2121 try { 2122 Bundle extras = extrasForInstallResult(res); 2123 installObserver.onPackageInstalled(res.name, res.returnCode, 2124 res.returnMsg, extras); 2125 } catch (RemoteException e) { 2126 Slog.i(TAG, "Observer no longer exists."); 2127 } 2128 } 2129 } 2130 2131 private StorageEventListener mStorageListener = new StorageEventListener() { 2132 @Override 2133 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 2134 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 2135 if (vol.state == VolumeInfo.STATE_MOUNTED) { 2136 final String volumeUuid = vol.getFsUuid(); 2137 2138 // Clean up any users or apps that were removed or recreated 2139 // while this volume was missing 2140 sUserManager.reconcileUsers(volumeUuid); 2141 reconcileApps(volumeUuid); 2142 2143 // Clean up any install sessions that expired or were 2144 // cancelled while this volume was missing 2145 mInstallerService.onPrivateVolumeMounted(volumeUuid); 2146 2147 loadPrivatePackages(vol); 2148 2149 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2150 unloadPrivatePackages(vol); 2151 } 2152 } 2153 } 2154 2155 @Override 2156 public void onVolumeForgotten(String fsUuid) { 2157 if (TextUtils.isEmpty(fsUuid)) { 2158 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 2159 return; 2160 } 2161 2162 // Remove any apps installed on the forgotten volume 2163 synchronized (mPackages) { 2164 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 2165 for (PackageSetting ps : packages) { 2166 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 2167 deletePackageVersioned(new VersionedPackage(ps.name, 2168 PackageManager.VERSION_CODE_HIGHEST), 2169 new LegacyPackageDeleteObserver(null).getBinder(), 2170 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 2171 // Try very hard to release any references to this package 2172 // so we don't risk the system server being killed due to 2173 // open FDs 2174 AttributeCache.instance().removePackage(ps.name); 2175 } 2176 2177 mSettings.onVolumeForgotten(fsUuid); 2178 mSettings.writeLPr(); 2179 } 2180 } 2181 }; 2182 2183 Bundle extrasForInstallResult(PackageInstalledInfo res) { 2184 Bundle extras = null; 2185 switch (res.returnCode) { 2186 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 2187 extras = new Bundle(); 2188 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 2189 res.origPermission); 2190 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 2191 res.origPackage); 2192 break; 2193 } 2194 case PackageManager.INSTALL_SUCCEEDED: { 2195 extras = new Bundle(); 2196 extras.putBoolean(Intent.EXTRA_REPLACING, 2197 res.removedInfo != null && res.removedInfo.removedPackage != null); 2198 break; 2199 } 2200 } 2201 return extras; 2202 } 2203 2204 void scheduleWriteSettingsLocked() { 2205 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2206 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2207 } 2208 } 2209 2210 void scheduleWritePackageListLocked(int userId) { 2211 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) { 2212 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST); 2213 msg.arg1 = userId; 2214 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY); 2215 } 2216 } 2217 2218 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2219 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2220 scheduleWritePackageRestrictionsLocked(userId); 2221 } 2222 2223 void scheduleWritePackageRestrictionsLocked(int userId) { 2224 final int[] userIds = (userId == UserHandle.USER_ALL) 2225 ? sUserManager.getUserIds() : new int[]{userId}; 2226 for (int nextUserId : userIds) { 2227 if (!sUserManager.exists(nextUserId)) return; 2228 mDirtyUsers.add(nextUserId); 2229 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2230 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2231 } 2232 } 2233 } 2234 2235 public static PackageManagerService main(Context context, Installer installer, 2236 boolean factoryTest, boolean onlyCore) { 2237 // Self-check for initial settings. 2238 PackageManagerServiceCompilerMapping.checkProperties(); 2239 2240 PackageManagerService m = new PackageManagerService(context, installer, 2241 factoryTest, onlyCore); 2242 m.enableSystemUserPackages(); 2243 ServiceManager.addService("package", m); 2244 final PackageManagerNative pmn = m.new PackageManagerNative(); 2245 ServiceManager.addService("package_native", pmn); 2246 return m; 2247 } 2248 2249 private void enableSystemUserPackages() { 2250 if (!UserManager.isSplitSystemUser()) { 2251 return; 2252 } 2253 // For system user, enable apps based on the following conditions: 2254 // - app is whitelisted or belong to one of these groups: 2255 // -- system app which has no launcher icons 2256 // -- system app which has INTERACT_ACROSS_USERS permission 2257 // -- system IME app 2258 // - app is not in the blacklist 2259 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2260 Set<String> enableApps = new ArraySet<>(); 2261 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2262 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2263 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2264 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2265 enableApps.addAll(wlApps); 2266 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2267 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2268 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2269 enableApps.removeAll(blApps); 2270 Log.i(TAG, "Applications installed for system user: " + enableApps); 2271 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2272 UserHandle.SYSTEM); 2273 final int allAppsSize = allAps.size(); 2274 synchronized (mPackages) { 2275 for (int i = 0; i < allAppsSize; i++) { 2276 String pName = allAps.get(i); 2277 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2278 // Should not happen, but we shouldn't be failing if it does 2279 if (pkgSetting == null) { 2280 continue; 2281 } 2282 boolean install = enableApps.contains(pName); 2283 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2284 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2285 + " for system user"); 2286 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2287 } 2288 } 2289 scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM); 2290 } 2291 } 2292 2293 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2294 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2295 Context.DISPLAY_SERVICE); 2296 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2297 } 2298 2299 /** 2300 * Requests that files preopted on a secondary system partition be copied to the data partition 2301 * if possible. Note that the actual copying of the files is accomplished by init for security 2302 * reasons. This simply requests that the copy takes place and awaits confirmation of its 2303 * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy. 2304 */ 2305 private static void requestCopyPreoptedFiles() { 2306 final int WAIT_TIME_MS = 100; 2307 final String CP_PREOPT_PROPERTY = "sys.cppreopt"; 2308 if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) { 2309 SystemProperties.set(CP_PREOPT_PROPERTY, "requested"); 2310 // We will wait for up to 100 seconds. 2311 final long timeStart = SystemClock.uptimeMillis(); 2312 final long timeEnd = timeStart + 100 * 1000; 2313 long timeNow = timeStart; 2314 while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) { 2315 try { 2316 Thread.sleep(WAIT_TIME_MS); 2317 } catch (InterruptedException e) { 2318 // Do nothing 2319 } 2320 timeNow = SystemClock.uptimeMillis(); 2321 if (timeNow > timeEnd) { 2322 SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out"); 2323 Slog.wtf(TAG, "cppreopt did not finish!"); 2324 break; 2325 } 2326 } 2327 2328 Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms"); 2329 } 2330 } 2331 2332 public PackageManagerService(Context context, Installer installer, 2333 boolean factoryTest, boolean onlyCore) { 2334 LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES); 2335 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager"); 2336 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2337 SystemClock.uptimeMillis()); 2338 2339 if (mSdkVersion <= 0) { 2340 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2341 } 2342 2343 mContext = context; 2344 2345 mFactoryTest = factoryTest; 2346 mOnlyCore = onlyCore; 2347 mMetrics = new DisplayMetrics(); 2348 mInstaller = installer; 2349 2350 // Create sub-components that provide services / data. Order here is important. 2351 synchronized (mInstallLock) { 2352 synchronized (mPackages) { 2353 // Expose private service for system components to use. 2354 LocalServices.addService( 2355 PackageManagerInternal.class, new PackageManagerInternalImpl()); 2356 sUserManager = new UserManagerService(context, this, 2357 new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages); 2358 mPermissionManager = PermissionManagerService.create(context, 2359 new DefaultPermissionGrantedCallback() { 2360 @Override 2361 public void onDefaultRuntimePermissionsGranted(int userId) { 2362 synchronized(mPackages) { 2363 mSettings.onDefaultRuntimePermissionsGrantedLPr(userId); 2364 } 2365 } 2366 }, mPackages /*externalLock*/); 2367 mDefaultPermissionPolicy = mPermissionManager.getDefaultPermissionGrantPolicy(); 2368 mSettings = new Settings(mPermissionManager.getPermissionSettings(), mPackages); 2369 } 2370 } 2371 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2372 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2373 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2374 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2375 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2376 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2377 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2378 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2379 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2380 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2381 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2382 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2383 2384 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2385 if (separateProcesses != null && separateProcesses.length() > 0) { 2386 if ("*".equals(separateProcesses)) { 2387 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2388 mSeparateProcesses = null; 2389 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2390 } else { 2391 mDefParseFlags = 0; 2392 mSeparateProcesses = separateProcesses.split(","); 2393 Slog.w(TAG, "Running with debug.separate_processes: " 2394 + separateProcesses); 2395 } 2396 } else { 2397 mDefParseFlags = 0; 2398 mSeparateProcesses = null; 2399 } 2400 2401 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2402 "*dexopt*"); 2403 mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock); 2404 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2405 2406 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2407 FgThread.get().getLooper()); 2408 2409 getDefaultDisplayMetrics(context, mMetrics); 2410 2411 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config"); 2412 SystemConfig systemConfig = SystemConfig.getInstance(); 2413 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2414 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2415 2416 mProtectedPackages = new ProtectedPackages(mContext); 2417 2418 synchronized (mInstallLock) { 2419 // writer 2420 synchronized (mPackages) { 2421 mHandlerThread = new ServiceThread(TAG, 2422 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2423 mHandlerThread.start(); 2424 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2425 mProcessLoggingHandler = new ProcessLoggingHandler(); 2426 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2427 mInstantAppRegistry = new InstantAppRegistry(this); 2428 2429 File dataDir = Environment.getDataDirectory(); 2430 mAppInstallDir = new File(dataDir, "app"); 2431 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2432 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2433 2434 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2435 final int builtInLibCount = libConfig.size(); 2436 for (int i = 0; i < builtInLibCount; i++) { 2437 String name = libConfig.keyAt(i); 2438 String path = libConfig.valueAt(i); 2439 addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED, 2440 SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0); 2441 } 2442 2443 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2444 2445 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings"); 2446 mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false)); 2447 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2448 2449 // Clean up orphaned packages for which the code path doesn't exist 2450 // and they are an update to a system app - caused by bug/32321269 2451 final int packageSettingCount = mSettings.mPackages.size(); 2452 for (int i = packageSettingCount - 1; i >= 0; i--) { 2453 PackageSetting ps = mSettings.mPackages.valueAt(i); 2454 if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists()) 2455 && mSettings.getDisabledSystemPkgLPr(ps.name) != null) { 2456 mSettings.mPackages.removeAt(i); 2457 mSettings.enableSystemPackageLPw(ps.name); 2458 } 2459 } 2460 2461 if (mFirstBoot) { 2462 requestCopyPreoptedFiles(); 2463 } 2464 2465 String customResolverActivity = Resources.getSystem().getString( 2466 R.string.config_customResolverActivity); 2467 if (TextUtils.isEmpty(customResolverActivity)) { 2468 customResolverActivity = null; 2469 } else { 2470 mCustomResolverComponentName = ComponentName.unflattenFromString( 2471 customResolverActivity); 2472 } 2473 2474 long startTime = SystemClock.uptimeMillis(); 2475 2476 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2477 startTime); 2478 2479 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2480 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2481 2482 if (bootClassPath == null) { 2483 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2484 } 2485 2486 if (systemServerClassPath == null) { 2487 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2488 } 2489 2490 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2491 2492 final VersionInfo ver = mSettings.getInternalVersion(); 2493 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2494 if (mIsUpgrade) { 2495 logCriticalInfo(Log.INFO, 2496 "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT); 2497 } 2498 2499 // when upgrading from pre-M, promote system app permissions from install to runtime 2500 mPromoteSystemApps = 2501 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2502 2503 // When upgrading from pre-N, we need to handle package extraction like first boot, 2504 // as there is no profiling data available. 2505 mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N; 2506 2507 mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1; 2508 2509 // save off the names of pre-existing system packages prior to scanning; we don't 2510 // want to automatically grant runtime permissions for new system apps 2511 if (mPromoteSystemApps) { 2512 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2513 while (pkgSettingIter.hasNext()) { 2514 PackageSetting ps = pkgSettingIter.next(); 2515 if (isSystemApp(ps)) { 2516 mExistingSystemPackages.add(ps.name); 2517 } 2518 } 2519 } 2520 2521 mCacheDir = preparePackageParserCache(mIsUpgrade); 2522 2523 // Set flag to monitor and not change apk file paths when 2524 // scanning install directories. 2525 int scanFlags = SCAN_BOOTING | SCAN_INITIAL; 2526 2527 if (mIsUpgrade || mFirstBoot) { 2528 scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE; 2529 } 2530 2531 // Collect vendor overlay packages. (Do this before scanning any apps.) 2532 // For security and version matching reason, only consider 2533 // overlay packages if they reside in the right directory. 2534 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags 2535 | PackageParser.PARSE_IS_SYSTEM 2536 | PackageParser.PARSE_IS_SYSTEM_DIR 2537 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2538 2539 mParallelPackageParserCallback.findStaticOverlayPackages(); 2540 2541 // Find base frameworks (resource packages without code). 2542 scanDirTracedLI(frameworkDir, mDefParseFlags 2543 | PackageParser.PARSE_IS_SYSTEM 2544 | PackageParser.PARSE_IS_SYSTEM_DIR 2545 | PackageParser.PARSE_IS_PRIVILEGED, 2546 scanFlags | SCAN_NO_DEX, 0); 2547 2548 // Collected privileged system packages. 2549 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2550 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2551 | PackageParser.PARSE_IS_SYSTEM 2552 | PackageParser.PARSE_IS_SYSTEM_DIR 2553 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2554 2555 // Collect ordinary system packages. 2556 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2557 scanDirTracedLI(systemAppDir, mDefParseFlags 2558 | PackageParser.PARSE_IS_SYSTEM 2559 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2560 2561 // Collect all vendor packages. 2562 File vendorAppDir = new File("/vendor/app"); 2563 try { 2564 vendorAppDir = vendorAppDir.getCanonicalFile(); 2565 } catch (IOException e) { 2566 // failed to look up canonical path, continue with original one 2567 } 2568 scanDirTracedLI(vendorAppDir, mDefParseFlags 2569 | PackageParser.PARSE_IS_SYSTEM 2570 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2571 2572 // Collect all OEM packages. 2573 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2574 scanDirTracedLI(oemAppDir, mDefParseFlags 2575 | PackageParser.PARSE_IS_SYSTEM 2576 | PackageParser.PARSE_IS_SYSTEM_DIR 2577 | PackageParser.PARSE_IS_OEM, scanFlags, 0); 2578 2579 // Prune any system packages that no longer exist. 2580 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>(); 2581 // Stub packages must either be replaced with full versions in the /data 2582 // partition or be disabled. 2583 final List<String> stubSystemApps = new ArrayList<>(); 2584 if (!mOnlyCore) { 2585 // do this first before mucking with mPackages for the "expecting better" case 2586 final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator(); 2587 while (pkgIterator.hasNext()) { 2588 final PackageParser.Package pkg = pkgIterator.next(); 2589 if (pkg.isStub) { 2590 stubSystemApps.add(pkg.packageName); 2591 } 2592 } 2593 2594 final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2595 while (psit.hasNext()) { 2596 PackageSetting ps = psit.next(); 2597 2598 /* 2599 * If this is not a system app, it can't be a 2600 * disable system app. 2601 */ 2602 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2603 continue; 2604 } 2605 2606 /* 2607 * If the package is scanned, it's not erased. 2608 */ 2609 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2610 if (scannedPkg != null) { 2611 /* 2612 * If the system app is both scanned and in the 2613 * disabled packages list, then it must have been 2614 * added via OTA. Remove it from the currently 2615 * scanned package so the previously user-installed 2616 * application can be scanned. 2617 */ 2618 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2619 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2620 + ps.name + "; removing system app. Last known codePath=" 2621 + ps.codePathString + ", installStatus=" + ps.installStatus 2622 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2623 + scannedPkg.mVersionCode); 2624 removePackageLI(scannedPkg, true); 2625 mExpectingBetter.put(ps.name, ps.codePath); 2626 } 2627 2628 continue; 2629 } 2630 2631 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2632 psit.remove(); 2633 logCriticalInfo(Log.WARN, "System package " + ps.name 2634 + " no longer exists; it's data will be wiped"); 2635 // Actual deletion of code and data will be handled by later 2636 // reconciliation step 2637 } else { 2638 // we still have a disabled system package, but, it still might have 2639 // been removed. check the code path still exists and check there's 2640 // still a package. the latter can happen if an OTA keeps the same 2641 // code path, but, changes the package name. 2642 final PackageSetting disabledPs = 2643 mSettings.getDisabledSystemPkgLPr(ps.name); 2644 if (disabledPs.codePath == null || !disabledPs.codePath.exists() 2645 || disabledPs.pkg == null) { 2646 possiblyDeletedUpdatedSystemApps.add(ps.name); 2647 } 2648 } 2649 } 2650 } 2651 2652 //look for any incomplete package installations 2653 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2654 for (int i = 0; i < deletePkgsList.size(); i++) { 2655 // Actual deletion of code and data will be handled by later 2656 // reconciliation step 2657 final String packageName = deletePkgsList.get(i).name; 2658 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2659 synchronized (mPackages) { 2660 mSettings.removePackageLPw(packageName); 2661 } 2662 } 2663 2664 //delete tmp files 2665 deleteTempPackageFiles(); 2666 2667 final int cachedSystemApps = PackageParser.sCachedPackageReadCount.get(); 2668 2669 // Remove any shared userIDs that have no associated packages 2670 mSettings.pruneSharedUsersLPw(); 2671 final long systemScanTime = SystemClock.uptimeMillis() - startTime; 2672 final int systemPackagesCount = mPackages.size(); 2673 Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime 2674 + " ms, packageCount: " + systemPackagesCount 2675 + " , timePerPackage: " 2676 + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount) 2677 + " , cached: " + cachedSystemApps); 2678 if (mIsUpgrade && systemPackagesCount > 0) { 2679 MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time", 2680 ((int) systemScanTime) / systemPackagesCount); 2681 } 2682 if (!mOnlyCore) { 2683 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2684 SystemClock.uptimeMillis()); 2685 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2686 2687 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2688 | PackageParser.PARSE_FORWARD_LOCK, 2689 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2690 2691 // Remove disable package settings for updated system apps that were 2692 // removed via an OTA. If the update is no longer present, remove the 2693 // app completely. Otherwise, revoke their system privileges. 2694 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2695 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2696 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2697 2698 final String msg; 2699 if (deletedPkg == null) { 2700 // should have found an update, but, we didn't; remove everything 2701 msg = "Updated system package " + deletedAppName 2702 + " no longer exists; removing its data"; 2703 // Actual deletion of code and data will be handled by later 2704 // reconciliation step 2705 } else { 2706 // found an update; revoke system privileges 2707 msg = "Updated system package + " + deletedAppName 2708 + " no longer exists; revoking system privileges"; 2709 2710 // Don't do anything if a stub is removed from the system image. If 2711 // we were to remove the uncompressed version from the /data partition, 2712 // this is where it'd be done. 2713 2714 final PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2715 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2716 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2717 } 2718 logCriticalInfo(Log.WARN, msg); 2719 } 2720 2721 /* 2722 * Make sure all system apps that we expected to appear on 2723 * the userdata partition actually showed up. If they never 2724 * appeared, crawl back and revive the system version. 2725 */ 2726 for (int i = 0; i < mExpectingBetter.size(); i++) { 2727 final String packageName = mExpectingBetter.keyAt(i); 2728 if (!mPackages.containsKey(packageName)) { 2729 final File scanFile = mExpectingBetter.valueAt(i); 2730 2731 logCriticalInfo(Log.WARN, "Expected better " + packageName 2732 + " but never showed up; reverting to system"); 2733 2734 int reparseFlags = mDefParseFlags; 2735 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2736 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2737 | PackageParser.PARSE_IS_SYSTEM_DIR 2738 | PackageParser.PARSE_IS_PRIVILEGED; 2739 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2740 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2741 | PackageParser.PARSE_IS_SYSTEM_DIR; 2742 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2743 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2744 | PackageParser.PARSE_IS_SYSTEM_DIR; 2745 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2746 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2747 | PackageParser.PARSE_IS_SYSTEM_DIR 2748 | PackageParser.PARSE_IS_OEM; 2749 } else { 2750 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2751 continue; 2752 } 2753 2754 mSettings.enableSystemPackageLPw(packageName); 2755 2756 try { 2757 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2758 } catch (PackageManagerException e) { 2759 Slog.e(TAG, "Failed to parse original system package: " 2760 + e.getMessage()); 2761 } 2762 } 2763 } 2764 2765 // Uncompress and install any stubbed system applications. 2766 // This must be done last to ensure all stubs are replaced or disabled. 2767 decompressSystemApplications(stubSystemApps, scanFlags); 2768 2769 final int cachedNonSystemApps = PackageParser.sCachedPackageReadCount.get() 2770 - cachedSystemApps; 2771 2772 final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime; 2773 final int dataPackagesCount = mPackages.size() - systemPackagesCount; 2774 Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime 2775 + " ms, packageCount: " + dataPackagesCount 2776 + " , timePerPackage: " 2777 + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount) 2778 + " , cached: " + cachedNonSystemApps); 2779 if (mIsUpgrade && dataPackagesCount > 0) { 2780 MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time", 2781 ((int) dataScanTime) / dataPackagesCount); 2782 } 2783 } 2784 mExpectingBetter.clear(); 2785 2786 // Resolve the storage manager. 2787 mStorageManagerPackage = getStorageManagerPackageName(); 2788 2789 // Resolve protected action filters. Only the setup wizard is allowed to 2790 // have a high priority filter for these actions. 2791 mSetupWizardPackage = getSetupWizardPackageName(); 2792 if (mProtectedFilters.size() > 0) { 2793 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2794 Slog.i(TAG, "No setup wizard;" 2795 + " All protected intents capped to priority 0"); 2796 } 2797 for (ActivityIntentInfo filter : mProtectedFilters) { 2798 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2799 if (DEBUG_FILTERS) { 2800 Slog.i(TAG, "Found setup wizard;" 2801 + " allow priority " + filter.getPriority() + ";" 2802 + " package: " + filter.activity.info.packageName 2803 + " activity: " + filter.activity.className 2804 + " priority: " + filter.getPriority()); 2805 } 2806 // skip setup wizard; allow it to keep the high priority filter 2807 continue; 2808 } 2809 if (DEBUG_FILTERS) { 2810 Slog.i(TAG, "Protected action; cap priority to 0;" 2811 + " package: " + filter.activity.info.packageName 2812 + " activity: " + filter.activity.className 2813 + " origPrio: " + filter.getPriority()); 2814 } 2815 filter.setPriority(0); 2816 } 2817 } 2818 mDeferProtectedFilters = false; 2819 mProtectedFilters.clear(); 2820 2821 // Now that we know all of the shared libraries, update all clients to have 2822 // the correct library paths. 2823 updateAllSharedLibrariesLPw(null); 2824 2825 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2826 // NOTE: We ignore potential failures here during a system scan (like 2827 // the rest of the commands above) because there's precious little we 2828 // can do about it. A settings error is reported, though. 2829 adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/); 2830 } 2831 2832 // Now that we know all the packages we are keeping, 2833 // read and update their last usage times. 2834 mPackageUsage.read(mPackages); 2835 mCompilerStats.read(); 2836 2837 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2838 SystemClock.uptimeMillis()); 2839 Slog.i(TAG, "Time to scan packages: " 2840 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2841 + " seconds"); 2842 2843 // If the platform SDK has changed since the last time we booted, 2844 // we need to re-grant app permission to catch any new ones that 2845 // appear. This is really a hack, and means that apps can in some 2846 // cases get permissions that the user didn't initially explicitly 2847 // allow... it would be nice to have some better way to handle 2848 // this situation. 2849 final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion); 2850 if (sdkUpdated) { 2851 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2852 + mSdkVersion + "; regranting permissions for internal storage"); 2853 } 2854 mPermissionManager.updateAllPermissions( 2855 StorageManager.UUID_PRIVATE_INTERNAL, sdkUpdated, mPackages.values(), 2856 mPermissionCallback); 2857 ver.sdkVersion = mSdkVersion; 2858 2859 // If this is the first boot or an update from pre-M, and it is a normal 2860 // boot, then we need to initialize the default preferred apps across 2861 // all defined users. 2862 if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) { 2863 for (UserInfo user : sUserManager.getUsers(true)) { 2864 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2865 applyFactoryDefaultBrowserLPw(user.id); 2866 primeDomainVerificationsLPw(user.id); 2867 } 2868 } 2869 2870 // Prepare storage for system user really early during boot, 2871 // since core system apps like SettingsProvider and SystemUI 2872 // can't wait for user to start 2873 final int storageFlags; 2874 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2875 storageFlags = StorageManager.FLAG_STORAGE_DE; 2876 } else { 2877 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2878 } 2879 List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, 2880 UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */, 2881 true /* onlyCoreApps */); 2882 mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> { 2883 TimingsTraceLog traceLog = new TimingsTraceLog("SystemServerTimingAsync", 2884 Trace.TRACE_TAG_PACKAGE_MANAGER); 2885 traceLog.traceBegin("AppDataFixup"); 2886 try { 2887 mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL, 2888 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 2889 } catch (InstallerException e) { 2890 Slog.w(TAG, "Trouble fixing GIDs", e); 2891 } 2892 traceLog.traceEnd(); 2893 2894 traceLog.traceBegin("AppDataPrepare"); 2895 if (deferPackages == null || deferPackages.isEmpty()) { 2896 return; 2897 } 2898 int count = 0; 2899 for (String pkgName : deferPackages) { 2900 PackageParser.Package pkg = null; 2901 synchronized (mPackages) { 2902 PackageSetting ps = mSettings.getPackageLPr(pkgName); 2903 if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) { 2904 pkg = ps.pkg; 2905 } 2906 } 2907 if (pkg != null) { 2908 synchronized (mInstallLock) { 2909 prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags, 2910 true /* maybeMigrateAppData */); 2911 } 2912 count++; 2913 } 2914 } 2915 traceLog.traceEnd(); 2916 Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages"); 2917 }, "prepareAppData"); 2918 2919 // If this is first boot after an OTA, and a normal boot, then 2920 // we need to clear code cache directories. 2921 // Note that we do *not* clear the application profiles. These remain valid 2922 // across OTAs and are used to drive profile verification (post OTA) and 2923 // profile compilation (without waiting to collect a fresh set of profiles). 2924 if (mIsUpgrade && !onlyCore) { 2925 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2926 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2927 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2928 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2929 // No apps are running this early, so no need to freeze 2930 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2931 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2932 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2933 } 2934 } 2935 ver.fingerprint = Build.FINGERPRINT; 2936 } 2937 2938 checkDefaultBrowser(); 2939 2940 // clear only after permissions and other defaults have been updated 2941 mExistingSystemPackages.clear(); 2942 mPromoteSystemApps = false; 2943 2944 // All the changes are done during package scanning. 2945 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2946 2947 // can downgrade to reader 2948 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings"); 2949 mSettings.writeLPr(); 2950 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2951 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2952 SystemClock.uptimeMillis()); 2953 2954 if (!mOnlyCore) { 2955 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2956 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2957 mRequiredUninstallerPackage = getRequiredUninstallerLPr(); 2958 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2959 if (mIntentFilterVerifierComponent != null) { 2960 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2961 mIntentFilterVerifierComponent); 2962 } else { 2963 mIntentFilterVerifier = null; 2964 } 2965 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2966 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES, 2967 SharedLibraryInfo.VERSION_UNDEFINED); 2968 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2969 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED, 2970 SharedLibraryInfo.VERSION_UNDEFINED); 2971 } else { 2972 mRequiredVerifierPackage = null; 2973 mRequiredInstallerPackage = null; 2974 mRequiredUninstallerPackage = null; 2975 mIntentFilterVerifierComponent = null; 2976 mIntentFilterVerifier = null; 2977 mServicesSystemSharedLibraryPackageName = null; 2978 mSharedSystemSharedLibraryPackageName = null; 2979 } 2980 2981 mInstallerService = new PackageInstallerService(context, this); 2982 final Pair<ComponentName, String> instantAppResolverComponent = 2983 getInstantAppResolverLPr(); 2984 if (instantAppResolverComponent != null) { 2985 if (DEBUG_EPHEMERAL) { 2986 Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent); 2987 } 2988 mInstantAppResolverConnection = new EphemeralResolverConnection( 2989 mContext, instantAppResolverComponent.first, 2990 instantAppResolverComponent.second); 2991 mInstantAppResolverSettingsComponent = 2992 getInstantAppResolverSettingsLPr(instantAppResolverComponent.first); 2993 } else { 2994 mInstantAppResolverConnection = null; 2995 mInstantAppResolverSettingsComponent = null; 2996 } 2997 updateInstantAppInstallerLocked(null); 2998 2999 // Read and update the usage of dex files. 3000 // Do this at the end of PM init so that all the packages have their 3001 // data directory reconciled. 3002 // At this point we know the code paths of the packages, so we can validate 3003 // the disk file and build the internal cache. 3004 // The usage file is expected to be small so loading and verifying it 3005 // should take a fairly small time compare to the other activities (e.g. package 3006 // scanning). 3007 final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>(); 3008 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 3009 for (int userId : currentUserIds) { 3010 userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList()); 3011 } 3012 mDexManager.load(userPackages); 3013 if (mIsUpgrade) { 3014 MetricsLogger.histogram(null, "ota_package_manager_init_time", 3015 (int) (SystemClock.uptimeMillis() - startTime)); 3016 } 3017 } // synchronized (mPackages) 3018 } // synchronized (mInstallLock) 3019 3020 // Now after opening every single application zip, make sure they 3021 // are all flushed. Not really needed, but keeps things nice and 3022 // tidy. 3023 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC"); 3024 Runtime.getRuntime().gc(); 3025 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 3026 3027 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks"); 3028 FallbackCategoryProvider.loadFallbacks(); 3029 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 3030 3031 // The initial scanning above does many calls into installd while 3032 // holding the mPackages lock, but we're mostly interested in yelling 3033 // once we have a booted system. 3034 mInstaller.setWarnIfHeld(mPackages); 3035 3036 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 3037 } 3038 3039 /** 3040 * Uncompress and install stub applications. 3041 * <p>In order to save space on the system partition, some applications are shipped in a 3042 * compressed form. In addition the compressed bits for the full application, the 3043 * system image contains a tiny stub comprised of only the Android manifest. 3044 * <p>During the first boot, attempt to uncompress and install the full application. If 3045 * the application can't be installed for any reason, disable the stub and prevent 3046 * uncompressing the full application during future boots. 3047 * <p>In order to forcefully attempt an installation of a full application, go to app 3048 * settings and enable the application. 3049 */ 3050 private void decompressSystemApplications(@NonNull List<String> stubSystemApps, int scanFlags) { 3051 for (int i = stubSystemApps.size() - 1; i >= 0; --i) { 3052 final String pkgName = stubSystemApps.get(i); 3053 // skip if the system package is already disabled 3054 if (mSettings.isDisabledSystemPackageLPr(pkgName)) { 3055 stubSystemApps.remove(i); 3056 continue; 3057 } 3058 // skip if the package isn't installed (?!); this should never happen 3059 final PackageParser.Package pkg = mPackages.get(pkgName); 3060 if (pkg == null) { 3061 stubSystemApps.remove(i); 3062 continue; 3063 } 3064 // skip if the package has been disabled by the user 3065 final PackageSetting ps = mSettings.mPackages.get(pkgName); 3066 if (ps != null) { 3067 final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM); 3068 if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) { 3069 stubSystemApps.remove(i); 3070 continue; 3071 } 3072 } 3073 3074 if (DEBUG_COMPRESSION) { 3075 Slog.i(TAG, "Uncompressing system stub; pkg: " + pkgName); 3076 } 3077 3078 // uncompress the binary to its eventual destination on /data 3079 final File scanFile = decompressPackage(pkg); 3080 if (scanFile == null) { 3081 continue; 3082 } 3083 3084 // install the package to replace the stub on /system 3085 try { 3086 mSettings.disableSystemPackageLPw(pkgName, true /*replaced*/); 3087 removePackageLI(pkg, true /*chatty*/); 3088 scanPackageTracedLI(scanFile, 0 /*reparseFlags*/, scanFlags, 0, null); 3089 ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT, 3090 UserHandle.USER_SYSTEM, "android"); 3091 stubSystemApps.remove(i); 3092 continue; 3093 } catch (PackageManagerException e) { 3094 Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage()); 3095 } 3096 3097 // any failed attempt to install the package will be cleaned up later 3098 } 3099 3100 // disable any stub still left; these failed to install the full application 3101 for (int i = stubSystemApps.size() - 1; i >= 0; --i) { 3102 final String pkgName = stubSystemApps.get(i); 3103 final PackageSetting ps = mSettings.mPackages.get(pkgName); 3104 ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED, 3105 UserHandle.USER_SYSTEM, "android"); 3106 logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName); 3107 } 3108 } 3109 3110 private int decompressFile(File srcFile, File dstFile) throws ErrnoException { 3111 if (DEBUG_COMPRESSION) { 3112 Slog.i(TAG, "Decompress file" 3113 + "; src: " + srcFile.getAbsolutePath() 3114 + ", dst: " + dstFile.getAbsolutePath()); 3115 } 3116 try ( 3117 InputStream fileIn = new GZIPInputStream(new FileInputStream(srcFile)); 3118 OutputStream fileOut = new FileOutputStream(dstFile, false /*append*/); 3119 ) { 3120 Streams.copy(fileIn, fileOut); 3121 Os.chmod(dstFile.getAbsolutePath(), 0644); 3122 return PackageManager.INSTALL_SUCCEEDED; 3123 } catch (IOException e) { 3124 logCriticalInfo(Log.ERROR, "Failed to decompress file" 3125 + "; src: " + srcFile.getAbsolutePath() 3126 + ", dst: " + dstFile.getAbsolutePath()); 3127 } 3128 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 3129 } 3130 3131 private File[] getCompressedFiles(String codePath) { 3132 final File stubCodePath = new File(codePath); 3133 final String stubName = stubCodePath.getName(); 3134 3135 // The layout of a compressed package on a given partition is as follows : 3136 // 3137 // Compressed artifacts: 3138 // 3139 // /partition/ModuleName/foo.gz 3140 // /partation/ModuleName/bar.gz 3141 // 3142 // Stub artifact: 3143 // 3144 // /partition/ModuleName-Stub/ModuleName-Stub.apk 3145 // 3146 // In other words, stub is on the same partition as the compressed artifacts 3147 // and in a directory that's suffixed with "-Stub". 3148 int idx = stubName.lastIndexOf(STUB_SUFFIX); 3149 if (idx < 0 || (stubName.length() != (idx + STUB_SUFFIX.length()))) { 3150 return null; 3151 } 3152 3153 final File stubParentDir = stubCodePath.getParentFile(); 3154 if (stubParentDir == null) { 3155 Slog.e(TAG, "Unable to determine stub parent dir for codePath: " + codePath); 3156 return null; 3157 } 3158 3159 final File compressedPath = new File(stubParentDir, stubName.substring(0, idx)); 3160 final File[] files = compressedPath.listFiles(new FilenameFilter() { 3161 @Override 3162 public boolean accept(File dir, String name) { 3163 return name.toLowerCase().endsWith(COMPRESSED_EXTENSION); 3164 } 3165 }); 3166 3167 if (DEBUG_COMPRESSION && files != null && files.length > 0) { 3168 Slog.i(TAG, "getCompressedFiles[" + codePath + "]: " + Arrays.toString(files)); 3169 } 3170 3171 return files; 3172 } 3173 3174 private boolean compressedFileExists(String codePath) { 3175 final File[] compressedFiles = getCompressedFiles(codePath); 3176 return compressedFiles != null && compressedFiles.length > 0; 3177 } 3178 3179 /** 3180 * Decompresses the given package on the system image onto 3181 * the /data partition. 3182 * @return The directory the package was decompressed into. Otherwise, {@code null}. 3183 */ 3184 private File decompressPackage(PackageParser.Package pkg) { 3185 final File[] compressedFiles = getCompressedFiles(pkg.codePath); 3186 if (compressedFiles == null || compressedFiles.length == 0) { 3187 if (DEBUG_COMPRESSION) { 3188 Slog.i(TAG, "No files to decompress: " + pkg.baseCodePath); 3189 } 3190 return null; 3191 } 3192 final File dstCodePath = 3193 getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName); 3194 int ret = PackageManager.INSTALL_SUCCEEDED; 3195 try { 3196 Os.mkdir(dstCodePath.getAbsolutePath(), 0755); 3197 Os.chmod(dstCodePath.getAbsolutePath(), 0755); 3198 for (File srcFile : compressedFiles) { 3199 final String srcFileName = srcFile.getName(); 3200 final String dstFileName = srcFileName.substring( 3201 0, srcFileName.length() - COMPRESSED_EXTENSION.length()); 3202 final File dstFile = new File(dstCodePath, dstFileName); 3203 ret = decompressFile(srcFile, dstFile); 3204 if (ret != PackageManager.INSTALL_SUCCEEDED) { 3205 logCriticalInfo(Log.ERROR, "Failed to decompress" 3206 + "; pkg: " + pkg.packageName 3207 + ", file: " + dstFileName); 3208 break; 3209 } 3210 } 3211 } catch (ErrnoException e) { 3212 logCriticalInfo(Log.ERROR, "Failed to decompress" 3213 + "; pkg: " + pkg.packageName 3214 + ", err: " + e.errno); 3215 } 3216 if (ret == PackageManager.INSTALL_SUCCEEDED) { 3217 final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME); 3218 NativeLibraryHelper.Handle handle = null; 3219 try { 3220 handle = NativeLibraryHelper.Handle.create(dstCodePath); 3221 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 3222 null /*abiOverride*/); 3223 } catch (IOException e) { 3224 logCriticalInfo(Log.ERROR, "Failed to extract native libraries" 3225 + "; pkg: " + pkg.packageName); 3226 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 3227 } finally { 3228 IoUtils.closeQuietly(handle); 3229 } 3230 } 3231 if (ret != PackageManager.INSTALL_SUCCEEDED) { 3232 if (dstCodePath == null || !dstCodePath.exists()) { 3233 return null; 3234 } 3235 removeCodePathLI(dstCodePath); 3236 return null; 3237 } 3238 3239 return dstCodePath; 3240 } 3241 3242 private void updateInstantAppInstallerLocked(String modifiedPackage) { 3243 // we're only interested in updating the installer appliction when 1) it's not 3244 // already set or 2) the modified package is the installer 3245 if (mInstantAppInstallerActivity != null 3246 && !mInstantAppInstallerActivity.getComponentName().getPackageName() 3247 .equals(modifiedPackage)) { 3248 return; 3249 } 3250 setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr()); 3251 } 3252 3253 private static File preparePackageParserCache(boolean isUpgrade) { 3254 if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) { 3255 return null; 3256 } 3257 3258 // Disable package parsing on eng builds to allow for faster incremental development. 3259 if (Build.IS_ENG) { 3260 return null; 3261 } 3262 3263 if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) { 3264 Slog.i(TAG, "Disabling package parser cache due to system property."); 3265 return null; 3266 } 3267 3268 // The base directory for the package parser cache lives under /data/system/. 3269 final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(), 3270 "package_cache"); 3271 if (cacheBaseDir == null) { 3272 return null; 3273 } 3274 3275 // If this is a system upgrade scenario, delete the contents of the package cache dir. 3276 // This also serves to "GC" unused entries when the package cache version changes (which 3277 // can only happen during upgrades). 3278 if (isUpgrade) { 3279 FileUtils.deleteContents(cacheBaseDir); 3280 } 3281 3282 3283 // Return the versioned package cache directory. This is something like 3284 // "/data/system/package_cache/1" 3285 File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION); 3286 3287 // The following is a workaround to aid development on non-numbered userdebug 3288 // builds or cases where "adb sync" is used on userdebug builds. If we detect that 3289 // the system partition is newer. 3290 // 3291 // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build 3292 // that starts with "eng." to signify that this is an engineering build and not 3293 // destined for release. 3294 if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) { 3295 Slog.w(TAG, "Wiping cache directory because the system partition changed."); 3296 3297 // Heuristic: If the /system directory has been modified recently due to an "adb sync" 3298 // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable 3299 // in general and should not be used for production changes. In this specific case, 3300 // we know that they will work. 3301 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 3302 if (cacheDir.lastModified() < frameworkDir.lastModified()) { 3303 FileUtils.deleteContents(cacheBaseDir); 3304 cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION); 3305 } 3306 } 3307 3308 return cacheDir; 3309 } 3310 3311 @Override 3312 public boolean isFirstBoot() { 3313 // allow instant applications 3314 return mFirstBoot; 3315 } 3316 3317 @Override 3318 public boolean isOnlyCoreApps() { 3319 // allow instant applications 3320 return mOnlyCore; 3321 } 3322 3323 @Override 3324 public boolean isUpgrade() { 3325 // allow instant applications 3326 // The system property allows testing ota flow when upgraded to the same image. 3327 return mIsUpgrade || SystemProperties.getBoolean( 3328 "persist.pm.mock-upgrade", false /* default */); 3329 } 3330 3331 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 3332 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 3333 3334 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 3335 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3336 UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/); 3337 if (matches.size() == 1) { 3338 return matches.get(0).getComponentInfo().packageName; 3339 } else if (matches.size() == 0) { 3340 Log.e(TAG, "There should probably be a verifier, but, none were found"); 3341 return null; 3342 } 3343 throw new RuntimeException("There must be exactly one verifier; found " + matches); 3344 } 3345 3346 private @NonNull String getRequiredSharedLibraryLPr(String name, int version) { 3347 synchronized (mPackages) { 3348 SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version); 3349 if (libraryEntry == null) { 3350 throw new IllegalStateException("Missing required shared library:" + name); 3351 } 3352 return libraryEntry.apk; 3353 } 3354 } 3355 3356 private @NonNull String getRequiredInstallerLPr() { 3357 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 3358 intent.addCategory(Intent.CATEGORY_DEFAULT); 3359 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 3360 3361 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3362 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3363 UserHandle.USER_SYSTEM); 3364 if (matches.size() == 1) { 3365 ResolveInfo resolveInfo = matches.get(0); 3366 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 3367 throw new RuntimeException("The installer must be a privileged app"); 3368 } 3369 return matches.get(0).getComponentInfo().packageName; 3370 } else { 3371 throw new RuntimeException("There must be exactly one installer; found " + matches); 3372 } 3373 } 3374 3375 private @NonNull String getRequiredUninstallerLPr() { 3376 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 3377 intent.addCategory(Intent.CATEGORY_DEFAULT); 3378 intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null)); 3379 3380 final ResolveInfo resolveInfo = resolveIntent(intent, null, 3381 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3382 UserHandle.USER_SYSTEM); 3383 if (resolveInfo == null || 3384 mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) { 3385 throw new RuntimeException("There must be exactly one uninstaller; found " 3386 + resolveInfo); 3387 } 3388 return resolveInfo.getComponentInfo().packageName; 3389 } 3390 3391 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 3392 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 3393 3394 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 3395 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3396 UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/); 3397 ResolveInfo best = null; 3398 final int N = matches.size(); 3399 for (int i = 0; i < N; i++) { 3400 final ResolveInfo cur = matches.get(i); 3401 final String packageName = cur.getComponentInfo().packageName; 3402 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 3403 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 3404 continue; 3405 } 3406 3407 if (best == null || cur.priority > best.priority) { 3408 best = cur; 3409 } 3410 } 3411 3412 if (best != null) { 3413 return best.getComponentInfo().getComponentName(); 3414 } 3415 Slog.w(TAG, "Intent filter verifier not found"); 3416 return null; 3417 } 3418 3419 @Override 3420 public @Nullable ComponentName getInstantAppResolverComponent() { 3421 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 3422 return null; 3423 } 3424 synchronized (mPackages) { 3425 final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr(); 3426 if (instantAppResolver == null) { 3427 return null; 3428 } 3429 return instantAppResolver.first; 3430 } 3431 } 3432 3433 private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() { 3434 final String[] packageArray = 3435 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 3436 if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) { 3437 if (DEBUG_EPHEMERAL) { 3438 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 3439 } 3440 return null; 3441 } 3442 3443 final int callingUid = Binder.getCallingUid(); 3444 final int resolveFlags = 3445 MATCH_DIRECT_BOOT_AWARE 3446 | MATCH_DIRECT_BOOT_UNAWARE 3447 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3448 String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE; 3449 final Intent resolverIntent = new Intent(actionName); 3450 List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 3451 resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/); 3452 // temporarily look for the old action 3453 if (resolvers.size() == 0) { 3454 if (DEBUG_EPHEMERAL) { 3455 Slog.d(TAG, "Ephemeral resolver not found with new action; try old one"); 3456 } 3457 actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE; 3458 resolverIntent.setAction(actionName); 3459 resolvers = queryIntentServicesInternal(resolverIntent, null, 3460 resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/); 3461 } 3462 final int N = resolvers.size(); 3463 if (N == 0) { 3464 if (DEBUG_EPHEMERAL) { 3465 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 3466 } 3467 return null; 3468 } 3469 3470 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 3471 for (int i = 0; i < N; i++) { 3472 final ResolveInfo info = resolvers.get(i); 3473 3474 if (info.serviceInfo == null) { 3475 continue; 3476 } 3477 3478 final String packageName = info.serviceInfo.packageName; 3479 if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) { 3480 if (DEBUG_EPHEMERAL) { 3481 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 3482 + " pkg: " + packageName + ", info:" + info); 3483 } 3484 continue; 3485 } 3486 3487 if (DEBUG_EPHEMERAL) { 3488 Slog.v(TAG, "Ephemeral resolver found;" 3489 + " pkg: " + packageName + ", info:" + info); 3490 } 3491 return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName); 3492 } 3493 if (DEBUG_EPHEMERAL) { 3494 Slog.v(TAG, "Ephemeral resolver NOT found"); 3495 } 3496 return null; 3497 } 3498 3499 private @Nullable ActivityInfo getInstantAppInstallerLPr() { 3500 final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE); 3501 intent.addCategory(Intent.CATEGORY_DEFAULT); 3502 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 3503 3504 final int resolveFlags = 3505 MATCH_DIRECT_BOOT_AWARE 3506 | MATCH_DIRECT_BOOT_UNAWARE 3507 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3508 List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3509 resolveFlags, UserHandle.USER_SYSTEM); 3510 // temporarily look for the old action 3511 if (matches.isEmpty()) { 3512 if (DEBUG_EPHEMERAL) { 3513 Slog.d(TAG, "Ephemeral installer not found with new action; try old one"); 3514 } 3515 intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 3516 matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3517 resolveFlags, UserHandle.USER_SYSTEM); 3518 } 3519 Iterator<ResolveInfo> iter = matches.iterator(); 3520 while (iter.hasNext()) { 3521 final ResolveInfo rInfo = iter.next(); 3522 final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName); 3523 if (ps != null) { 3524 final PermissionsState permissionsState = ps.getPermissionsState(); 3525 if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) { 3526 continue; 3527 } 3528 } 3529 iter.remove(); 3530 } 3531 if (matches.size() == 0) { 3532 return null; 3533 } else if (matches.size() == 1) { 3534 return (ActivityInfo) matches.get(0).getComponentInfo(); 3535 } else { 3536 throw new RuntimeException( 3537 "There must be at most one ephemeral installer; found " + matches); 3538 } 3539 } 3540 3541 private @Nullable ComponentName getInstantAppResolverSettingsLPr( 3542 @NonNull ComponentName resolver) { 3543 final Intent intent = new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS) 3544 .addCategory(Intent.CATEGORY_DEFAULT) 3545 .setPackage(resolver.getPackageName()); 3546 final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3547 List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags, 3548 UserHandle.USER_SYSTEM); 3549 // temporarily look for the old action 3550 if (matches.isEmpty()) { 3551 if (DEBUG_EPHEMERAL) { 3552 Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one"); 3553 } 3554 intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS); 3555 matches = queryIntentActivitiesInternal(intent, null, resolveFlags, 3556 UserHandle.USER_SYSTEM); 3557 } 3558 if (matches.isEmpty()) { 3559 return null; 3560 } 3561 return matches.get(0).getComponentInfo().getComponentName(); 3562 } 3563 3564 private void primeDomainVerificationsLPw(int userId) { 3565 if (DEBUG_DOMAIN_VERIFICATION) { 3566 Slog.d(TAG, "Priming domain verifications in user " + userId); 3567 } 3568 3569 SystemConfig systemConfig = SystemConfig.getInstance(); 3570 ArraySet<String> packages = systemConfig.getLinkedApps(); 3571 3572 for (String packageName : packages) { 3573 PackageParser.Package pkg = mPackages.get(packageName); 3574 if (pkg != null) { 3575 if (!pkg.isSystem()) { 3576 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 3577 continue; 3578 } 3579 3580 ArraySet<String> domains = null; 3581 for (PackageParser.Activity a : pkg.activities) { 3582 for (ActivityIntentInfo filter : a.intents) { 3583 if (hasValidDomains(filter)) { 3584 if (domains == null) { 3585 domains = new ArraySet<String>(); 3586 } 3587 domains.addAll(filter.getHostsList()); 3588 } 3589 } 3590 } 3591 3592 if (domains != null && domains.size() > 0) { 3593 if (DEBUG_DOMAIN_VERIFICATION) { 3594 Slog.v(TAG, " + " + packageName); 3595 } 3596 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 3597 // state w.r.t. the formal app-linkage "no verification attempted" state; 3598 // and then 'always' in the per-user state actually used for intent resolution. 3599 final IntentFilterVerificationInfo ivi; 3600 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains); 3601 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 3602 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 3603 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 3604 } else { 3605 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 3606 + "' does not handle web links"); 3607 } 3608 } else { 3609 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 3610 } 3611 } 3612 3613 scheduleWritePackageRestrictionsLocked(userId); 3614 scheduleWriteSettingsLocked(); 3615 } 3616 3617 private void applyFactoryDefaultBrowserLPw(int userId) { 3618 // The default browser app's package name is stored in a string resource, 3619 // with a product-specific overlay used for vendor customization. 3620 String browserPkg = mContext.getResources().getString( 3621 com.android.internal.R.string.default_browser); 3622 if (!TextUtils.isEmpty(browserPkg)) { 3623 // non-empty string => required to be a known package 3624 PackageSetting ps = mSettings.mPackages.get(browserPkg); 3625 if (ps == null) { 3626 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 3627 browserPkg = null; 3628 } else { 3629 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3630 } 3631 } 3632 3633 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3634 // default. If there's more than one, just leave everything alone. 3635 if (browserPkg == null) { 3636 calculateDefaultBrowserLPw(userId); 3637 } 3638 } 3639 3640 private void calculateDefaultBrowserLPw(int userId) { 3641 List<String> allBrowsers = resolveAllBrowserApps(userId); 3642 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3643 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3644 } 3645 3646 private List<String> resolveAllBrowserApps(int userId) { 3647 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3648 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3649 PackageManager.MATCH_ALL, userId); 3650 3651 final int count = list.size(); 3652 List<String> result = new ArrayList<String>(count); 3653 for (int i=0; i<count; i++) { 3654 ResolveInfo info = list.get(i); 3655 if (info.activityInfo == null 3656 || !info.handleAllWebDataURI 3657 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3658 || result.contains(info.activityInfo.packageName)) { 3659 continue; 3660 } 3661 result.add(info.activityInfo.packageName); 3662 } 3663 3664 return result; 3665 } 3666 3667 private boolean packageIsBrowser(String packageName, int userId) { 3668 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3669 PackageManager.MATCH_ALL, userId); 3670 final int N = list.size(); 3671 for (int i = 0; i < N; i++) { 3672 ResolveInfo info = list.get(i); 3673 if (packageName.equals(info.activityInfo.packageName)) { 3674 return true; 3675 } 3676 } 3677 return false; 3678 } 3679 3680 private void checkDefaultBrowser() { 3681 final int myUserId = UserHandle.myUserId(); 3682 final String packageName = getDefaultBrowserPackageName(myUserId); 3683 if (packageName != null) { 3684 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3685 if (info == null) { 3686 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3687 synchronized (mPackages) { 3688 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3689 } 3690 } 3691 } 3692 } 3693 3694 @Override 3695 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3696 throws RemoteException { 3697 try { 3698 return super.onTransact(code, data, reply, flags); 3699 } catch (RuntimeException e) { 3700 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3701 Slog.wtf(TAG, "Package Manager Crash", e); 3702 } 3703 throw e; 3704 } 3705 } 3706 3707 static int[] appendInts(int[] cur, int[] add) { 3708 if (add == null) return cur; 3709 if (cur == null) return add; 3710 final int N = add.length; 3711 for (int i=0; i<N; i++) { 3712 cur = appendInt(cur, add[i]); 3713 } 3714 return cur; 3715 } 3716 3717 /** 3718 * Returns whether or not a full application can see an instant application. 3719 * <p> 3720 * Currently, there are three cases in which this can occur: 3721 * <ol> 3722 * <li>The calling application is a "special" process. Special processes 3723 * are those with a UID < {@link Process#FIRST_APPLICATION_UID}.</li> 3724 * <li>The calling application has the permission 3725 * {@link android.Manifest.permission#ACCESS_INSTANT_APPS}.</li> 3726 * <li>The calling application is the default launcher on the 3727 * system partition.</li> 3728 * </ol> 3729 */ 3730 private boolean canViewInstantApps(int callingUid, int userId) { 3731 if (callingUid < Process.FIRST_APPLICATION_UID) { 3732 return true; 3733 } 3734 if (mContext.checkCallingOrSelfPermission( 3735 android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) { 3736 return true; 3737 } 3738 if (mContext.checkCallingOrSelfPermission( 3739 android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) { 3740 final ComponentName homeComponent = getDefaultHomeActivity(userId); 3741 if (homeComponent != null 3742 && isCallerSameApp(homeComponent.getPackageName(), callingUid)) { 3743 return true; 3744 } 3745 } 3746 return false; 3747 } 3748 3749 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3750 if (!sUserManager.exists(userId)) return null; 3751 if (ps == null) { 3752 return null; 3753 } 3754 PackageParser.Package p = ps.pkg; 3755 if (p == null) { 3756 return null; 3757 } 3758 final int callingUid = Binder.getCallingUid(); 3759 // Filter out ephemeral app metadata: 3760 // * The system/shell/root can see metadata for any app 3761 // * An installed app can see metadata for 1) other installed apps 3762 // and 2) ephemeral apps that have explicitly interacted with it 3763 // * Ephemeral apps can only see their own data and exposed installed apps 3764 // * Holding a signature permission allows seeing instant apps 3765 if (filterAppAccessLPr(ps, callingUid, userId)) { 3766 return null; 3767 } 3768 3769 final PermissionsState permissionsState = ps.getPermissionsState(); 3770 3771 // Compute GIDs only if requested 3772 final int[] gids = (flags & PackageManager.GET_GIDS) == 0 3773 ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId); 3774 // Compute granted permissions only if package has requested permissions 3775 final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions) 3776 ? Collections.<String>emptySet() : permissionsState.getPermissions(userId); 3777 final PackageUserState state = ps.readUserState(userId); 3778 3779 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0 3780 && ps.isSystem()) { 3781 flags |= MATCH_ANY_USER; 3782 } 3783 3784 PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags, 3785 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3786 3787 if (packageInfo == null) { 3788 return null; 3789 } 3790 3791 packageInfo.packageName = packageInfo.applicationInfo.packageName = 3792 resolveExternalPackageNameLPr(p); 3793 3794 return packageInfo; 3795 } 3796 3797 @Override 3798 public void checkPackageStartable(String packageName, int userId) { 3799 final int callingUid = Binder.getCallingUid(); 3800 if (getInstantAppPackageName(callingUid) != null) { 3801 throw new SecurityException("Instant applications don't have access to this method"); 3802 } 3803 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3804 synchronized (mPackages) { 3805 final PackageSetting ps = mSettings.mPackages.get(packageName); 3806 if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) { 3807 throw new SecurityException("Package " + packageName + " was not found!"); 3808 } 3809 3810 if (!ps.getInstalled(userId)) { 3811 throw new SecurityException( 3812 "Package " + packageName + " was not installed for user " + userId + "!"); 3813 } 3814 3815 if (mSafeMode && !ps.isSystem()) { 3816 throw new SecurityException("Package " + packageName + " not a system app!"); 3817 } 3818 3819 if (mFrozenPackages.contains(packageName)) { 3820 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3821 } 3822 3823 if (!userKeyUnlocked && !ps.pkg.applicationInfo.isEncryptionAware()) { 3824 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3825 } 3826 } 3827 } 3828 3829 @Override 3830 public boolean isPackageAvailable(String packageName, int userId) { 3831 if (!sUserManager.exists(userId)) return false; 3832 final int callingUid = Binder.getCallingUid(); 3833 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 3834 false /*requireFullPermission*/, false /*checkShell*/, "is package available"); 3835 synchronized (mPackages) { 3836 PackageParser.Package p = mPackages.get(packageName); 3837 if (p != null) { 3838 final PackageSetting ps = (PackageSetting) p.mExtras; 3839 if (filterAppAccessLPr(ps, callingUid, userId)) { 3840 return false; 3841 } 3842 if (ps != null) { 3843 final PackageUserState state = ps.readUserState(userId); 3844 if (state != null) { 3845 return PackageParser.isAvailable(state); 3846 } 3847 } 3848 } 3849 } 3850 return false; 3851 } 3852 3853 @Override 3854 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3855 return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST, 3856 flags, Binder.getCallingUid(), userId); 3857 } 3858 3859 @Override 3860 public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage, 3861 int flags, int userId) { 3862 return getPackageInfoInternal(versionedPackage.getPackageName(), 3863 versionedPackage.getVersionCode(), flags, Binder.getCallingUid(), userId); 3864 } 3865 3866 /** 3867 * Important: The provided filterCallingUid is used exclusively to filter out packages 3868 * that can be seen based on user state. It's typically the original caller uid prior 3869 * to clearing. Because it can only be provided by trusted code, it's value can be 3870 * trusted and will be used as-is; unlike userId which will be validated by this method. 3871 */ 3872 private PackageInfo getPackageInfoInternal(String packageName, int versionCode, 3873 int flags, int filterCallingUid, int userId) { 3874 if (!sUserManager.exists(userId)) return null; 3875 flags = updateFlagsForPackage(flags, userId, packageName); 3876 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 3877 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3878 3879 // reader 3880 synchronized (mPackages) { 3881 // Normalize package name to handle renamed packages and static libs 3882 packageName = resolveInternalPackageNameLPr(packageName, versionCode); 3883 3884 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3885 if (matchFactoryOnly) { 3886 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3887 if (ps != null) { 3888 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 3889 return null; 3890 } 3891 if (filterAppAccessLPr(ps, filterCallingUid, userId)) { 3892 return null; 3893 } 3894 return generatePackageInfo(ps, flags, userId); 3895 } 3896 } 3897 3898 PackageParser.Package p = mPackages.get(packageName); 3899 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3900 return null; 3901 } 3902 if (DEBUG_PACKAGE_INFO) 3903 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3904 if (p != null) { 3905 final PackageSetting ps = (PackageSetting) p.mExtras; 3906 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 3907 return null; 3908 } 3909 if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) { 3910 return null; 3911 } 3912 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3913 } 3914 if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) { 3915 final PackageSetting ps = mSettings.mPackages.get(packageName); 3916 if (ps == null) return null; 3917 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 3918 return null; 3919 } 3920 if (filterAppAccessLPr(ps, filterCallingUid, userId)) { 3921 return null; 3922 } 3923 return generatePackageInfo(ps, flags, userId); 3924 } 3925 } 3926 return null; 3927 } 3928 3929 private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) { 3930 if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) { 3931 return true; 3932 } 3933 if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) { 3934 return true; 3935 } 3936 if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) { 3937 return true; 3938 } 3939 return false; 3940 } 3941 3942 private boolean isComponentVisibleToInstantApp( 3943 @Nullable ComponentName component, @ComponentType int type) { 3944 if (type == TYPE_ACTIVITY) { 3945 final PackageParser.Activity activity = mActivities.mActivities.get(component); 3946 return activity != null 3947 ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0 3948 : false; 3949 } else if (type == TYPE_RECEIVER) { 3950 final PackageParser.Activity activity = mReceivers.mActivities.get(component); 3951 return activity != null 3952 ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0 3953 : false; 3954 } else if (type == TYPE_SERVICE) { 3955 final PackageParser.Service service = mServices.mServices.get(component); 3956 return service != null 3957 ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0 3958 : false; 3959 } else if (type == TYPE_PROVIDER) { 3960 final PackageParser.Provider provider = mProviders.mProviders.get(component); 3961 return provider != null 3962 ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0 3963 : false; 3964 } else if (type == TYPE_UNKNOWN) { 3965 return isComponentVisibleToInstantApp(component); 3966 } 3967 return false; 3968 } 3969 3970 /** 3971 * Returns whether or not access to the application should be filtered. 3972 * <p> 3973 * Access may be limited based upon whether the calling or target applications 3974 * are instant applications. 3975 * 3976 * @see #canAccessInstantApps(int) 3977 */ 3978 private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, 3979 @Nullable ComponentName component, @ComponentType int componentType, int userId) { 3980 // if we're in an isolated process, get the real calling UID 3981 if (Process.isIsolated(callingUid)) { 3982 callingUid = mIsolatedOwners.get(callingUid); 3983 } 3984 final String instantAppPkgName = getInstantAppPackageName(callingUid); 3985 final boolean callerIsInstantApp = instantAppPkgName != null; 3986 if (ps == null) { 3987 if (callerIsInstantApp) { 3988 // pretend the application exists, but, needs to be filtered 3989 return true; 3990 } 3991 return false; 3992 } 3993 // if the target and caller are the same application, don't filter 3994 if (isCallerSameApp(ps.name, callingUid)) { 3995 return false; 3996 } 3997 if (callerIsInstantApp) { 3998 // request for a specific component; if it hasn't been explicitly exposed, filter 3999 if (component != null) { 4000 return !isComponentVisibleToInstantApp(component, componentType); 4001 } 4002 // request for application; if no components have been explicitly exposed, filter 4003 return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps; 4004 } 4005 if (ps.getInstantApp(userId)) { 4006 // caller can see all components of all instant applications, don't filter 4007 if (canViewInstantApps(callingUid, userId)) { 4008 return false; 4009 } 4010 // request for a specific instant application component, filter 4011 if (component != null) { 4012 return true; 4013 } 4014 // request for an instant application; if the caller hasn't been granted access, filter 4015 return !mInstantAppRegistry.isInstantAccessGranted( 4016 userId, UserHandle.getAppId(callingUid), ps.appId); 4017 } 4018 return false; 4019 } 4020 4021 /** 4022 * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int) 4023 */ 4024 private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) { 4025 return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId); 4026 } 4027 4028 private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId, 4029 int flags) { 4030 // Callers can access only the libs they depend on, otherwise they need to explicitly 4031 // ask for the shared libraries given the caller is allowed to access all static libs. 4032 if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) { 4033 // System/shell/root get to see all static libs 4034 final int appId = UserHandle.getAppId(uid); 4035 if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID 4036 || appId == Process.ROOT_UID) { 4037 return false; 4038 } 4039 } 4040 4041 // No package means no static lib as it is always on internal storage 4042 if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) { 4043 return false; 4044 } 4045 4046 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName, 4047 ps.pkg.staticSharedLibVersion); 4048 if (libEntry == null) { 4049 return false; 4050 } 4051 4052 final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid)); 4053 final String[] uidPackageNames = getPackagesForUid(resolvedUid); 4054 if (uidPackageNames == null) { 4055 return true; 4056 } 4057 4058 for (String uidPackageName : uidPackageNames) { 4059 if (ps.name.equals(uidPackageName)) { 4060 return false; 4061 } 4062 PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName); 4063 if (uidPs != null) { 4064 final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries, 4065 libEntry.info.getName()); 4066 if (index < 0) { 4067 continue; 4068 } 4069 if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) { 4070 return false; 4071 } 4072 } 4073 } 4074 return true; 4075 } 4076 4077 @Override 4078 public String[] currentToCanonicalPackageNames(String[] names) { 4079 final int callingUid = Binder.getCallingUid(); 4080 if (getInstantAppPackageName(callingUid) != null) { 4081 return names; 4082 } 4083 final String[] out = new String[names.length]; 4084 // reader 4085 synchronized (mPackages) { 4086 final int callingUserId = UserHandle.getUserId(callingUid); 4087 final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId); 4088 for (int i=names.length-1; i>=0; i--) { 4089 final PackageSetting ps = mSettings.mPackages.get(names[i]); 4090 boolean translateName = false; 4091 if (ps != null && ps.realName != null) { 4092 final boolean targetIsInstantApp = ps.getInstantApp(callingUserId); 4093 translateName = !targetIsInstantApp 4094 || canViewInstantApps 4095 || mInstantAppRegistry.isInstantAccessGranted(callingUserId, 4096 UserHandle.getAppId(callingUid), ps.appId); 4097 } 4098 out[i] = translateName ? ps.realName : names[i]; 4099 } 4100 } 4101 return out; 4102 } 4103 4104 @Override 4105 public String[] canonicalToCurrentPackageNames(String[] names) { 4106 final int callingUid = Binder.getCallingUid(); 4107 if (getInstantAppPackageName(callingUid) != null) { 4108 return names; 4109 } 4110 final String[] out = new String[names.length]; 4111 // reader 4112 synchronized (mPackages) { 4113 final int callingUserId = UserHandle.getUserId(callingUid); 4114 final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId); 4115 for (int i=names.length-1; i>=0; i--) { 4116 final String cur = mSettings.getRenamedPackageLPr(names[i]); 4117 boolean translateName = false; 4118 if (cur != null) { 4119 final PackageSetting ps = mSettings.mPackages.get(names[i]); 4120 final boolean targetIsInstantApp = 4121 ps != null && ps.getInstantApp(callingUserId); 4122 translateName = !targetIsInstantApp 4123 || canViewInstantApps 4124 || mInstantAppRegistry.isInstantAccessGranted(callingUserId, 4125 UserHandle.getAppId(callingUid), ps.appId); 4126 } 4127 out[i] = translateName ? cur : names[i]; 4128 } 4129 } 4130 return out; 4131 } 4132 4133 @Override 4134 public int getPackageUid(String packageName, int flags, int userId) { 4135 if (!sUserManager.exists(userId)) return -1; 4136 final int callingUid = Binder.getCallingUid(); 4137 flags = updateFlagsForPackage(flags, userId, packageName); 4138 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 4139 false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid"); 4140 4141 // reader 4142 synchronized (mPackages) { 4143 final PackageParser.Package p = mPackages.get(packageName); 4144 if (p != null && p.isMatch(flags)) { 4145 PackageSetting ps = (PackageSetting) p.mExtras; 4146 if (filterAppAccessLPr(ps, callingUid, userId)) { 4147 return -1; 4148 } 4149 return UserHandle.getUid(userId, p.applicationInfo.uid); 4150 } 4151 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 4152 final PackageSetting ps = mSettings.mPackages.get(packageName); 4153 if (ps != null && ps.isMatch(flags) 4154 && !filterAppAccessLPr(ps, callingUid, userId)) { 4155 return UserHandle.getUid(userId, ps.appId); 4156 } 4157 } 4158 } 4159 4160 return -1; 4161 } 4162 4163 @Override 4164 public int[] getPackageGids(String packageName, int flags, int userId) { 4165 if (!sUserManager.exists(userId)) return null; 4166 final int callingUid = Binder.getCallingUid(); 4167 flags = updateFlagsForPackage(flags, userId, packageName); 4168 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 4169 false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids"); 4170 4171 // reader 4172 synchronized (mPackages) { 4173 final PackageParser.Package p = mPackages.get(packageName); 4174 if (p != null && p.isMatch(flags)) { 4175 PackageSetting ps = (PackageSetting) p.mExtras; 4176 if (filterAppAccessLPr(ps, callingUid, userId)) { 4177 return null; 4178 } 4179 // TODO: Shouldn't this be checking for package installed state for userId and 4180 // return null? 4181 return ps.getPermissionsState().computeGids(userId); 4182 } 4183 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 4184 final PackageSetting ps = mSettings.mPackages.get(packageName); 4185 if (ps != null && ps.isMatch(flags) 4186 && !filterAppAccessLPr(ps, callingUid, userId)) { 4187 return ps.getPermissionsState().computeGids(userId); 4188 } 4189 } 4190 } 4191 4192 return null; 4193 } 4194 4195 @Override 4196 public PermissionInfo getPermissionInfo(String name, String packageName, int flags) { 4197 return mPermissionManager.getPermissionInfo(name, packageName, flags, getCallingUid()); 4198 } 4199 4200 @Override 4201 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String groupName, 4202 int flags) { 4203 final List<PermissionInfo> permissionList = 4204 mPermissionManager.getPermissionInfoByGroup(groupName, flags, getCallingUid()); 4205 return (permissionList == null) ? null : new ParceledListSlice<>(permissionList); 4206 } 4207 4208 @Override 4209 public PermissionGroupInfo getPermissionGroupInfo(String groupName, int flags) { 4210 return mPermissionManager.getPermissionGroupInfo(groupName, flags, getCallingUid()); 4211 } 4212 4213 @Override 4214 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 4215 final List<PermissionGroupInfo> permissionList = 4216 mPermissionManager.getAllPermissionGroups(flags, getCallingUid()); 4217 return (permissionList == null) 4218 ? ParceledListSlice.emptyList() : new ParceledListSlice<>(permissionList); 4219 } 4220 4221 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 4222 int filterCallingUid, int userId) { 4223 if (!sUserManager.exists(userId)) return null; 4224 PackageSetting ps = mSettings.mPackages.get(packageName); 4225 if (ps != null) { 4226 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 4227 return null; 4228 } 4229 if (filterAppAccessLPr(ps, filterCallingUid, userId)) { 4230 return null; 4231 } 4232 if (ps.pkg == null) { 4233 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 4234 if (pInfo != null) { 4235 return pInfo.applicationInfo; 4236 } 4237 return null; 4238 } 4239 ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 4240 ps.readUserState(userId), userId); 4241 if (ai != null) { 4242 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 4243 } 4244 return ai; 4245 } 4246 return null; 4247 } 4248 4249 @Override 4250 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 4251 return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId); 4252 } 4253 4254 /** 4255 * Important: The provided filterCallingUid is used exclusively to filter out applications 4256 * that can be seen based on user state. It's typically the original caller uid prior 4257 * to clearing. Because it can only be provided by trusted code, it's value can be 4258 * trusted and will be used as-is; unlike userId which will be validated by this method. 4259 */ 4260 private ApplicationInfo getApplicationInfoInternal(String packageName, int flags, 4261 int filterCallingUid, int userId) { 4262 if (!sUserManager.exists(userId)) return null; 4263 flags = updateFlagsForApplication(flags, userId, packageName); 4264 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 4265 false /* requireFullPermission */, false /* checkShell */, "get application info"); 4266 4267 // writer 4268 synchronized (mPackages) { 4269 // Normalize package name to handle renamed packages and static libs 4270 packageName = resolveInternalPackageNameLPr(packageName, 4271 PackageManager.VERSION_CODE_HIGHEST); 4272 4273 PackageParser.Package p = mPackages.get(packageName); 4274 if (DEBUG_PACKAGE_INFO) Log.v( 4275 TAG, "getApplicationInfo " + packageName 4276 + ": " + p); 4277 if (p != null) { 4278 PackageSetting ps = mSettings.mPackages.get(packageName); 4279 if (ps == null) return null; 4280 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 4281 return null; 4282 } 4283 if (filterAppAccessLPr(ps, filterCallingUid, userId)) { 4284 return null; 4285 } 4286 // Note: isEnabledLP() does not apply here - always return info 4287 ApplicationInfo ai = PackageParser.generateApplicationInfo( 4288 p, flags, ps.readUserState(userId), userId); 4289 if (ai != null) { 4290 ai.packageName = resolveExternalPackageNameLPr(p); 4291 } 4292 return ai; 4293 } 4294 if ("android".equals(packageName)||"system".equals(packageName)) { 4295 return mAndroidApplication; 4296 } 4297 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 4298 // Already generates the external package name 4299 return generateApplicationInfoFromSettingsLPw(packageName, 4300 flags, filterCallingUid, userId); 4301 } 4302 } 4303 return null; 4304 } 4305 4306 private String normalizePackageNameLPr(String packageName) { 4307 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 4308 return normalizedPackageName != null ? normalizedPackageName : packageName; 4309 } 4310 4311 @Override 4312 public void deletePreloadsFileCache() { 4313 if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) { 4314 throw new SecurityException("Only system or settings may call deletePreloadsFileCache"); 4315 } 4316 File dir = Environment.getDataPreloadsFileCacheDirectory(); 4317 Slog.i(TAG, "Deleting preloaded file cache " + dir); 4318 FileUtils.deleteContents(dir); 4319 } 4320 4321 @Override 4322 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 4323 final int storageFlags, final IPackageDataObserver observer) { 4324 mContext.enforceCallingOrSelfPermission( 4325 android.Manifest.permission.CLEAR_APP_CACHE, null); 4326 mHandler.post(() -> { 4327 boolean success = false; 4328 try { 4329 freeStorage(volumeUuid, freeStorageSize, storageFlags); 4330 success = true; 4331 } catch (IOException e) { 4332 Slog.w(TAG, e); 4333 } 4334 if (observer != null) { 4335 try { 4336 observer.onRemoveCompleted(null, success); 4337 } catch (RemoteException e) { 4338 Slog.w(TAG, e); 4339 } 4340 } 4341 }); 4342 } 4343 4344 @Override 4345 public void freeStorage(final String volumeUuid, final long freeStorageSize, 4346 final int storageFlags, final IntentSender pi) { 4347 mContext.enforceCallingOrSelfPermission( 4348 android.Manifest.permission.CLEAR_APP_CACHE, TAG); 4349 mHandler.post(() -> { 4350 boolean success = false; 4351 try { 4352 freeStorage(volumeUuid, freeStorageSize, storageFlags); 4353 success = true; 4354 } catch (IOException e) { 4355 Slog.w(TAG, e); 4356 } 4357 if (pi != null) { 4358 try { 4359 pi.sendIntent(null, success ? 1 : 0, null, null, null); 4360 } catch (SendIntentException e) { 4361 Slog.w(TAG, e); 4362 } 4363 } 4364 }); 4365 } 4366 4367 /** 4368 * Blocking call to clear various types of cached data across the system 4369 * until the requested bytes are available. 4370 */ 4371 public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException { 4372 final StorageManager storage = mContext.getSystemService(StorageManager.class); 4373 final File file = storage.findPathForUuid(volumeUuid); 4374 if (file.getUsableSpace() >= bytes) return; 4375 4376 if (ENABLE_FREE_CACHE_V2) { 4377 final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, 4378 volumeUuid); 4379 final boolean aggressive = (storageFlags 4380 & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0; 4381 final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags); 4382 4383 // 1. Pre-flight to determine if we have any chance to succeed 4384 // 2. Consider preloaded data (after 1w honeymoon, unless aggressive) 4385 if (internalVolume && (aggressive || SystemProperties 4386 .getBoolean("persist.sys.preloads.file_cache_expired", false))) { 4387 deletePreloadsFileCache(); 4388 if (file.getUsableSpace() >= bytes) return; 4389 } 4390 4391 // 3. Consider parsed APK data (aggressive only) 4392 if (internalVolume && aggressive) { 4393 FileUtils.deleteContents(mCacheDir); 4394 if (file.getUsableSpace() >= bytes) return; 4395 } 4396 4397 // 4. Consider cached app data (above quotas) 4398 try { 4399 mInstaller.freeCache(volumeUuid, bytes, reservedBytes, 4400 Installer.FLAG_FREE_CACHE_V2); 4401 } catch (InstallerException ignored) { 4402 } 4403 if (file.getUsableSpace() >= bytes) return; 4404 4405 // 5. Consider shared libraries with refcount=0 and age>min cache period 4406 if (internalVolume && pruneUnusedStaticSharedLibraries(bytes, 4407 android.provider.Settings.Global.getLong(mContext.getContentResolver(), 4408 Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD, 4409 DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) { 4410 return; 4411 } 4412 4413 // 6. Consider dexopt output (aggressive only) 4414 // TODO: Implement 4415 4416 // 7. Consider installed instant apps unused longer than min cache period 4417 if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes, 4418 android.provider.Settings.Global.getLong(mContext.getContentResolver(), 4419 Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD, 4420 InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) { 4421 return; 4422 } 4423 4424 // 8. Consider cached app data (below quotas) 4425 try { 4426 mInstaller.freeCache(volumeUuid, bytes, reservedBytes, 4427 Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA); 4428 } catch (InstallerException ignored) { 4429 } 4430 if (file.getUsableSpace() >= bytes) return; 4431 4432 // 9. Consider DropBox entries 4433 // TODO: Implement 4434 4435 // 10. Consider instant meta-data (uninstalled apps) older that min cache period 4436 if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes, 4437 android.provider.Settings.Global.getLong(mContext.getContentResolver(), 4438 Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD, 4439 InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) { 4440 return; 4441 } 4442 } else { 4443 try { 4444 mInstaller.freeCache(volumeUuid, bytes, 0, 0); 4445 } catch (InstallerException ignored) { 4446 } 4447 if (file.getUsableSpace() >= bytes) return; 4448 } 4449 4450 throw new IOException("Failed to free " + bytes + " on storage device at " + file); 4451 } 4452 4453 private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod) 4454 throws IOException { 4455 final StorageManager storage = mContext.getSystemService(StorageManager.class); 4456 final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL); 4457 4458 List<VersionedPackage> packagesToDelete = null; 4459 final long now = System.currentTimeMillis(); 4460 4461 synchronized (mPackages) { 4462 final int[] allUsers = sUserManager.getUserIds(); 4463 final int libCount = mSharedLibraries.size(); 4464 for (int i = 0; i < libCount; i++) { 4465 final SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 4466 if (versionedLib == null) { 4467 continue; 4468 } 4469 final int versionCount = versionedLib.size(); 4470 for (int j = 0; j < versionCount; j++) { 4471 SharedLibraryInfo libInfo = versionedLib.valueAt(j).info; 4472 // Skip packages that are not static shared libs. 4473 if (!libInfo.isStatic()) { 4474 break; 4475 } 4476 // Important: We skip static shared libs used for some user since 4477 // in such a case we need to keep the APK on the device. The check for 4478 // a lib being used for any user is performed by the uninstall call. 4479 final VersionedPackage declaringPackage = libInfo.getDeclaringPackage(); 4480 // Resolve the package name - we use synthetic package names internally 4481 final String internalPackageName = resolveInternalPackageNameLPr( 4482 declaringPackage.getPackageName(), declaringPackage.getVersionCode()); 4483 final PackageSetting ps = mSettings.getPackageLPr(internalPackageName); 4484 // Skip unused static shared libs cached less than the min period 4485 // to prevent pruning a lib needed by a subsequently installed package. 4486 if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) { 4487 continue; 4488 } 4489 if (packagesToDelete == null) { 4490 packagesToDelete = new ArrayList<>(); 4491 } 4492 packagesToDelete.add(new VersionedPackage(internalPackageName, 4493 declaringPackage.getVersionCode())); 4494 } 4495 } 4496 } 4497 4498 if (packagesToDelete != null) { 4499 final int packageCount = packagesToDelete.size(); 4500 for (int i = 0; i < packageCount; i++) { 4501 final VersionedPackage pkgToDelete = packagesToDelete.get(i); 4502 // Delete the package synchronously (will fail of the lib used for any user). 4503 if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getVersionCode(), 4504 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS) 4505 == PackageManager.DELETE_SUCCEEDED) { 4506 if (volume.getUsableSpace() >= neededSpace) { 4507 return true; 4508 } 4509 } 4510 } 4511 } 4512 4513 return false; 4514 } 4515 4516 /** 4517 * Update given flags based on encryption status of current user. 4518 */ 4519 private int updateFlags(int flags, int userId) { 4520 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 4521 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 4522 // Caller expressed an explicit opinion about what encryption 4523 // aware/unaware components they want to see, so fall through and 4524 // give them what they want 4525 } else { 4526 // Caller expressed no opinion, so match based on user state 4527 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 4528 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 4529 } else { 4530 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 4531 } 4532 } 4533 return flags; 4534 } 4535 4536 private UserManagerInternal getUserManagerInternal() { 4537 if (mUserManagerInternal == null) { 4538 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 4539 } 4540 return mUserManagerInternal; 4541 } 4542 4543 private DeviceIdleController.LocalService getDeviceIdleController() { 4544 if (mDeviceIdleController == null) { 4545 mDeviceIdleController = 4546 LocalServices.getService(DeviceIdleController.LocalService.class); 4547 } 4548 return mDeviceIdleController; 4549 } 4550 4551 /** 4552 * Update given flags when being used to request {@link PackageInfo}. 4553 */ 4554 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 4555 final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM; 4556 boolean triaged = true; 4557 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 4558 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 4559 // Caller is asking for component details, so they'd better be 4560 // asking for specific encryption matching behavior, or be triaged 4561 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 4562 | PackageManager.MATCH_DIRECT_BOOT_AWARE 4563 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 4564 triaged = false; 4565 } 4566 } 4567 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 4568 | PackageManager.MATCH_SYSTEM_ONLY 4569 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 4570 triaged = false; 4571 } 4572 if ((flags & PackageManager.MATCH_ANY_USER) != 0) { 4573 mPermissionManager.enforceCrossUserPermission( 4574 Binder.getCallingUid(), userId, false, false, 4575 "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at " 4576 + Debug.getCallers(5)); 4577 } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser 4578 && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) { 4579 // If the caller wants all packages and has a restricted profile associated with it, 4580 // then match all users. This is to make sure that launchers that need to access work 4581 // profile apps don't start breaking. TODO: Remove this hack when launchers stop using 4582 // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380 4583 flags |= PackageManager.MATCH_ANY_USER; 4584 } 4585 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 4586 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 4587 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 4588 } 4589 return updateFlags(flags, userId); 4590 } 4591 4592 /** 4593 * Update given flags when being used to request {@link ApplicationInfo}. 4594 */ 4595 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 4596 return updateFlagsForPackage(flags, userId, cookie); 4597 } 4598 4599 /** 4600 * Update given flags when being used to request {@link ComponentInfo}. 4601 */ 4602 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 4603 if (cookie instanceof Intent) { 4604 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 4605 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 4606 } 4607 } 4608 4609 boolean triaged = true; 4610 // Caller is asking for component details, so they'd better be 4611 // asking for specific encryption matching behavior, or be triaged 4612 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 4613 | PackageManager.MATCH_DIRECT_BOOT_AWARE 4614 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 4615 triaged = false; 4616 } 4617 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 4618 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 4619 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 4620 } 4621 4622 return updateFlags(flags, userId); 4623 } 4624 4625 /** 4626 * Update given intent when being used to request {@link ResolveInfo}. 4627 */ 4628 private Intent updateIntentForResolve(Intent intent) { 4629 if (intent.getSelector() != null) { 4630 intent = intent.getSelector(); 4631 } 4632 if (DEBUG_PREFERRED) { 4633 intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4634 } 4635 return intent; 4636 } 4637 4638 /** 4639 * Update given flags when being used to request {@link ResolveInfo}. 4640 * <p>Instant apps are resolved specially, depending upon context. Minimally, 4641 * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT} 4642 * flag set. However, this flag is only honoured in three circumstances: 4643 * <ul> 4644 * <li>when called from a system process</li> 4645 * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li> 4646 * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW} 4647 * action and a {@code android.intent.category.BROWSABLE} category</li> 4648 * </ul> 4649 */ 4650 int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) { 4651 return updateFlagsForResolve(flags, userId, intent, callingUid, 4652 false /*wantInstantApps*/, false /*onlyExposedExplicitly*/); 4653 } 4654 int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid, 4655 boolean wantInstantApps) { 4656 return updateFlagsForResolve(flags, userId, intent, callingUid, 4657 wantInstantApps, false /*onlyExposedExplicitly*/); 4658 } 4659 int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid, 4660 boolean wantInstantApps, boolean onlyExposedExplicitly) { 4661 // Safe mode means we shouldn't match any third-party components 4662 if (mSafeMode) { 4663 flags |= PackageManager.MATCH_SYSTEM_ONLY; 4664 } 4665 if (getInstantAppPackageName(callingUid) != null) { 4666 // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components 4667 if (onlyExposedExplicitly) { 4668 flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY; 4669 } 4670 flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY; 4671 flags |= PackageManager.MATCH_INSTANT; 4672 } else { 4673 final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0; 4674 final boolean allowMatchInstant = 4675 (wantInstantApps 4676 && Intent.ACTION_VIEW.equals(intent.getAction()) 4677 && hasWebURI(intent)) 4678 || (wantMatchInstant && canViewInstantApps(callingUid, userId)); 4679 flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY 4680 | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY); 4681 if (!allowMatchInstant) { 4682 flags &= ~PackageManager.MATCH_INSTANT; 4683 } 4684 } 4685 return updateFlagsForComponent(flags, userId, intent /*cookie*/); 4686 } 4687 4688 @Override 4689 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 4690 return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId); 4691 } 4692 4693 /** 4694 * Important: The provided filterCallingUid is used exclusively to filter out activities 4695 * that can be seen based on user state. It's typically the original caller uid prior 4696 * to clearing. Because it can only be provided by trusted code, it's value can be 4697 * trusted and will be used as-is; unlike userId which will be validated by this method. 4698 */ 4699 private ActivityInfo getActivityInfoInternal(ComponentName component, int flags, 4700 int filterCallingUid, int userId) { 4701 if (!sUserManager.exists(userId)) return null; 4702 flags = updateFlagsForComponent(flags, userId, component); 4703 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 4704 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 4705 synchronized (mPackages) { 4706 PackageParser.Activity a = mActivities.mActivities.get(component); 4707 4708 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 4709 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 4710 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4711 if (ps == null) return null; 4712 if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) { 4713 return null; 4714 } 4715 return PackageParser.generateActivityInfo( 4716 a, flags, ps.readUserState(userId), userId); 4717 } 4718 if (mResolveComponentName.equals(component)) { 4719 return PackageParser.generateActivityInfo( 4720 mResolveActivity, flags, new PackageUserState(), userId); 4721 } 4722 } 4723 return null; 4724 } 4725 4726 @Override 4727 public boolean activitySupportsIntent(ComponentName component, Intent intent, 4728 String resolvedType) { 4729 synchronized (mPackages) { 4730 if (component.equals(mResolveComponentName)) { 4731 // The resolver supports EVERYTHING! 4732 return true; 4733 } 4734 final int callingUid = Binder.getCallingUid(); 4735 final int callingUserId = UserHandle.getUserId(callingUid); 4736 PackageParser.Activity a = mActivities.mActivities.get(component); 4737 if (a == null) { 4738 return false; 4739 } 4740 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4741 if (ps == null) { 4742 return false; 4743 } 4744 if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) { 4745 return false; 4746 } 4747 for (int i=0; i<a.intents.size(); i++) { 4748 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 4749 intent.getData(), intent.getCategories(), TAG) >= 0) { 4750 return true; 4751 } 4752 } 4753 return false; 4754 } 4755 } 4756 4757 @Override 4758 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 4759 if (!sUserManager.exists(userId)) return null; 4760 final int callingUid = Binder.getCallingUid(); 4761 flags = updateFlagsForComponent(flags, userId, component); 4762 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 4763 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 4764 synchronized (mPackages) { 4765 PackageParser.Activity a = mReceivers.mActivities.get(component); 4766 if (DEBUG_PACKAGE_INFO) Log.v( 4767 TAG, "getReceiverInfo " + component + ": " + a); 4768 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 4769 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4770 if (ps == null) return null; 4771 if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) { 4772 return null; 4773 } 4774 return PackageParser.generateActivityInfo( 4775 a, flags, ps.readUserState(userId), userId); 4776 } 4777 } 4778 return null; 4779 } 4780 4781 @Override 4782 public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName, 4783 int flags, int userId) { 4784 if (!sUserManager.exists(userId)) return null; 4785 Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0"); 4786 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 4787 return null; 4788 } 4789 4790 flags = updateFlagsForPackage(flags, userId, null); 4791 4792 final boolean canSeeStaticLibraries = 4793 mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES) 4794 == PERMISSION_GRANTED 4795 || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES) 4796 == PERMISSION_GRANTED 4797 || canRequestPackageInstallsInternal(packageName, 4798 PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId, 4799 false /* throwIfPermNotDeclared*/) 4800 || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES) 4801 == PERMISSION_GRANTED; 4802 4803 synchronized (mPackages) { 4804 List<SharedLibraryInfo> result = null; 4805 4806 final int libCount = mSharedLibraries.size(); 4807 for (int i = 0; i < libCount; i++) { 4808 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 4809 if (versionedLib == null) { 4810 continue; 4811 } 4812 4813 final int versionCount = versionedLib.size(); 4814 for (int j = 0; j < versionCount; j++) { 4815 SharedLibraryInfo libInfo = versionedLib.valueAt(j).info; 4816 if (!canSeeStaticLibraries && libInfo.isStatic()) { 4817 break; 4818 } 4819 final long identity = Binder.clearCallingIdentity(); 4820 try { 4821 PackageInfo packageInfo = getPackageInfoVersioned( 4822 libInfo.getDeclaringPackage(), flags 4823 | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId); 4824 if (packageInfo == null) { 4825 continue; 4826 } 4827 } finally { 4828 Binder.restoreCallingIdentity(identity); 4829 } 4830 4831 SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(), 4832 libInfo.getVersion(), libInfo.getType(), 4833 libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo, 4834 flags, userId)); 4835 4836 if (result == null) { 4837 result = new ArrayList<>(); 4838 } 4839 result.add(resLibInfo); 4840 } 4841 } 4842 4843 return result != null ? new ParceledListSlice<>(result) : null; 4844 } 4845 } 4846 4847 private List<VersionedPackage> getPackagesUsingSharedLibraryLPr( 4848 SharedLibraryInfo libInfo, int flags, int userId) { 4849 List<VersionedPackage> versionedPackages = null; 4850 final int packageCount = mSettings.mPackages.size(); 4851 for (int i = 0; i < packageCount; i++) { 4852 PackageSetting ps = mSettings.mPackages.valueAt(i); 4853 4854 if (ps == null) { 4855 continue; 4856 } 4857 4858 if (!ps.getUserState().get(userId).isAvailable(flags)) { 4859 continue; 4860 } 4861 4862 final String libName = libInfo.getName(); 4863 if (libInfo.isStatic()) { 4864 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 4865 if (libIdx < 0) { 4866 continue; 4867 } 4868 if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) { 4869 continue; 4870 } 4871 if (versionedPackages == null) { 4872 versionedPackages = new ArrayList<>(); 4873 } 4874 // If the dependent is a static shared lib, use the public package name 4875 String dependentPackageName = ps.name; 4876 if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) { 4877 dependentPackageName = ps.pkg.manifestPackageName; 4878 } 4879 versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode)); 4880 } else if (ps.pkg != null) { 4881 if (ArrayUtils.contains(ps.pkg.usesLibraries, libName) 4882 || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) { 4883 if (versionedPackages == null) { 4884 versionedPackages = new ArrayList<>(); 4885 } 4886 versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode)); 4887 } 4888 } 4889 } 4890 4891 return versionedPackages; 4892 } 4893 4894 @Override 4895 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 4896 if (!sUserManager.exists(userId)) return null; 4897 final int callingUid = Binder.getCallingUid(); 4898 flags = updateFlagsForComponent(flags, userId, component); 4899 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 4900 false /* requireFullPermission */, false /* checkShell */, "get service info"); 4901 synchronized (mPackages) { 4902 PackageParser.Service s = mServices.mServices.get(component); 4903 if (DEBUG_PACKAGE_INFO) Log.v( 4904 TAG, "getServiceInfo " + component + ": " + s); 4905 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 4906 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4907 if (ps == null) return null; 4908 if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) { 4909 return null; 4910 } 4911 return PackageParser.generateServiceInfo( 4912 s, flags, ps.readUserState(userId), userId); 4913 } 4914 } 4915 return null; 4916 } 4917 4918 @Override 4919 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 4920 if (!sUserManager.exists(userId)) return null; 4921 final int callingUid = Binder.getCallingUid(); 4922 flags = updateFlagsForComponent(flags, userId, component); 4923 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 4924 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 4925 synchronized (mPackages) { 4926 PackageParser.Provider p = mProviders.mProviders.get(component); 4927 if (DEBUG_PACKAGE_INFO) Log.v( 4928 TAG, "getProviderInfo " + component + ": " + p); 4929 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 4930 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4931 if (ps == null) return null; 4932 if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) { 4933 return null; 4934 } 4935 return PackageParser.generateProviderInfo( 4936 p, flags, ps.readUserState(userId), userId); 4937 } 4938 } 4939 return null; 4940 } 4941 4942 @Override 4943 public String[] getSystemSharedLibraryNames() { 4944 // allow instant applications 4945 synchronized (mPackages) { 4946 Set<String> libs = null; 4947 final int libCount = mSharedLibraries.size(); 4948 for (int i = 0; i < libCount; i++) { 4949 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 4950 if (versionedLib == null) { 4951 continue; 4952 } 4953 final int versionCount = versionedLib.size(); 4954 for (int j = 0; j < versionCount; j++) { 4955 SharedLibraryEntry libEntry = versionedLib.valueAt(j); 4956 if (!libEntry.info.isStatic()) { 4957 if (libs == null) { 4958 libs = new ArraySet<>(); 4959 } 4960 libs.add(libEntry.info.getName()); 4961 break; 4962 } 4963 PackageSetting ps = mSettings.getPackageLPr(libEntry.apk); 4964 if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(), 4965 UserHandle.getUserId(Binder.getCallingUid()), 4966 PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) { 4967 if (libs == null) { 4968 libs = new ArraySet<>(); 4969 } 4970 libs.add(libEntry.info.getName()); 4971 break; 4972 } 4973 } 4974 } 4975 4976 if (libs != null) { 4977 String[] libsArray = new String[libs.size()]; 4978 libs.toArray(libsArray); 4979 return libsArray; 4980 } 4981 4982 return null; 4983 } 4984 } 4985 4986 @Override 4987 public @NonNull String getServicesSystemSharedLibraryPackageName() { 4988 // allow instant applications 4989 synchronized (mPackages) { 4990 return mServicesSystemSharedLibraryPackageName; 4991 } 4992 } 4993 4994 @Override 4995 public @NonNull String getSharedSystemSharedLibraryPackageName() { 4996 // allow instant applications 4997 synchronized (mPackages) { 4998 return mSharedSystemSharedLibraryPackageName; 4999 } 5000 } 5001 5002 private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) { 5003 for (int i = userList.length - 1; i >= 0; --i) { 5004 final int userId = userList[i]; 5005 // don't add instant app to the list of updates 5006 if (pkgSetting.getInstantApp(userId)) { 5007 continue; 5008 } 5009 SparseArray<String> changedPackages = mChangedPackages.get(userId); 5010 if (changedPackages == null) { 5011 changedPackages = new SparseArray<>(); 5012 mChangedPackages.put(userId, changedPackages); 5013 } 5014 Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId); 5015 if (sequenceNumbers == null) { 5016 sequenceNumbers = new HashMap<>(); 5017 mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers); 5018 } 5019 final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name); 5020 if (sequenceNumber != null) { 5021 changedPackages.remove(sequenceNumber); 5022 } 5023 changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name); 5024 sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber); 5025 } 5026 mChangedPackagesSequenceNumber++; 5027 } 5028 5029 @Override 5030 public ChangedPackages getChangedPackages(int sequenceNumber, int userId) { 5031 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5032 return null; 5033 } 5034 synchronized (mPackages) { 5035 if (sequenceNumber >= mChangedPackagesSequenceNumber) { 5036 return null; 5037 } 5038 final SparseArray<String> changedPackages = mChangedPackages.get(userId); 5039 if (changedPackages == null) { 5040 return null; 5041 } 5042 final List<String> packageNames = 5043 new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber); 5044 for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) { 5045 final String packageName = changedPackages.get(i); 5046 if (packageName != null) { 5047 packageNames.add(packageName); 5048 } 5049 } 5050 return packageNames.isEmpty() 5051 ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames); 5052 } 5053 } 5054 5055 @Override 5056 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 5057 // allow instant applications 5058 ArrayList<FeatureInfo> res; 5059 synchronized (mAvailableFeatures) { 5060 res = new ArrayList<>(mAvailableFeatures.size() + 1); 5061 res.addAll(mAvailableFeatures.values()); 5062 } 5063 final FeatureInfo fi = new FeatureInfo(); 5064 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 5065 FeatureInfo.GL_ES_VERSION_UNDEFINED); 5066 res.add(fi); 5067 5068 return new ParceledListSlice<>(res); 5069 } 5070 5071 @Override 5072 public boolean hasSystemFeature(String name, int version) { 5073 // allow instant applications 5074 synchronized (mAvailableFeatures) { 5075 final FeatureInfo feat = mAvailableFeatures.get(name); 5076 if (feat == null) { 5077 return false; 5078 } else { 5079 return feat.version >= version; 5080 } 5081 } 5082 } 5083 5084 @Override 5085 public int checkPermission(String permName, String pkgName, int userId) { 5086 return mPermissionManager.checkPermission(permName, pkgName, getCallingUid(), userId); 5087 } 5088 5089 @Override 5090 public int checkUidPermission(String permName, int uid) { 5091 return mPermissionManager.checkUidPermission(permName, uid, getCallingUid()); 5092 } 5093 5094 @Override 5095 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 5096 if (UserHandle.getCallingUserId() != userId) { 5097 mContext.enforceCallingPermission( 5098 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5099 "isPermissionRevokedByPolicy for user " + userId); 5100 } 5101 5102 if (checkPermission(permission, packageName, userId) 5103 == PackageManager.PERMISSION_GRANTED) { 5104 return false; 5105 } 5106 5107 final int callingUid = Binder.getCallingUid(); 5108 if (getInstantAppPackageName(callingUid) != null) { 5109 if (!isCallerSameApp(packageName, callingUid)) { 5110 return false; 5111 } 5112 } else { 5113 if (isInstantApp(packageName, userId)) { 5114 return false; 5115 } 5116 } 5117 5118 final long identity = Binder.clearCallingIdentity(); 5119 try { 5120 final int flags = getPermissionFlags(permission, packageName, userId); 5121 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 5122 } finally { 5123 Binder.restoreCallingIdentity(identity); 5124 } 5125 } 5126 5127 @Override 5128 public String getPermissionControllerPackageName() { 5129 synchronized (mPackages) { 5130 return mRequiredInstallerPackage; 5131 } 5132 } 5133 5134 private boolean addDynamicPermission(PermissionInfo info, final boolean async) { 5135 return mPermissionManager.addDynamicPermission( 5136 info, async, getCallingUid(), new PermissionCallback() { 5137 @Override 5138 public void onPermissionChanged() { 5139 if (!async) { 5140 mSettings.writeLPr(); 5141 } else { 5142 scheduleWriteSettingsLocked(); 5143 } 5144 } 5145 }); 5146 } 5147 5148 @Override 5149 public boolean addPermission(PermissionInfo info) { 5150 synchronized (mPackages) { 5151 return addDynamicPermission(info, false); 5152 } 5153 } 5154 5155 @Override 5156 public boolean addPermissionAsync(PermissionInfo info) { 5157 synchronized (mPackages) { 5158 return addDynamicPermission(info, true); 5159 } 5160 } 5161 5162 @Override 5163 public void removePermission(String permName) { 5164 mPermissionManager.removeDynamicPermission(permName, getCallingUid(), mPermissionCallback); 5165 } 5166 5167 @Override 5168 public void grantRuntimePermission(String packageName, String permName, final int userId) { 5169 mPermissionManager.grantRuntimePermission(permName, packageName, false /*overridePolicy*/, 5170 getCallingUid(), userId, mPermissionCallback); 5171 } 5172 5173 @Override 5174 public void revokeRuntimePermission(String packageName, String permName, int userId) { 5175 mPermissionManager.revokeRuntimePermission(permName, packageName, false /*overridePolicy*/, 5176 getCallingUid(), userId, mPermissionCallback); 5177 } 5178 5179 /** 5180 * Get the first event id for the permission. 5181 * 5182 * <p>There are four events for each permission: <ul> 5183 * <li>Request permission: first id + 0</li> 5184 * <li>Grant permission: first id + 1</li> 5185 * <li>Request for permission denied: first id + 2</li> 5186 * <li>Revoke permission: first id + 3</li> 5187 * </ul></p> 5188 * 5189 * @param name name of the permission 5190 * 5191 * @return The first event id for the permission 5192 */ 5193 private static int getBaseEventId(@NonNull String name) { 5194 int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name); 5195 5196 if (eventIdIndex == -1) { 5197 if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE 5198 || Build.IS_USER) { 5199 Log.i(TAG, "Unknown permission " + name); 5200 5201 return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN; 5202 } else { 5203 // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated. 5204 // 5205 // Also update 5206 // - EventLogger#ALL_DANGEROUS_PERMISSIONS 5207 // - metrics_constants.proto 5208 throw new IllegalStateException("Unknown permission " + name); 5209 } 5210 } 5211 5212 return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4; 5213 } 5214 5215 /** 5216 * Log that a permission was revoked. 5217 * 5218 * @param context Context of the caller 5219 * @param name name of the permission 5220 * @param packageName package permission if for 5221 */ 5222 private static void logPermissionRevoked(@NonNull Context context, @NonNull String name, 5223 @NonNull String packageName) { 5224 MetricsLogger.action(context, getBaseEventId(name) + 3, packageName); 5225 } 5226 5227 /** 5228 * Log that a permission request was granted. 5229 * 5230 * @param context Context of the caller 5231 * @param name name of the permission 5232 * @param packageName package permission if for 5233 */ 5234 private static void logPermissionGranted(@NonNull Context context, @NonNull String name, 5235 @NonNull String packageName) { 5236 MetricsLogger.action(context, getBaseEventId(name) + 1, packageName); 5237 } 5238 5239 @Override 5240 public void resetRuntimePermissions() { 5241 mContext.enforceCallingOrSelfPermission( 5242 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 5243 "revokeRuntimePermission"); 5244 5245 int callingUid = Binder.getCallingUid(); 5246 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 5247 mContext.enforceCallingOrSelfPermission( 5248 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5249 "resetRuntimePermissions"); 5250 } 5251 5252 synchronized (mPackages) { 5253 mPermissionManager.updateAllPermissions( 5254 StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(), 5255 mPermissionCallback); 5256 for (int userId : UserManagerService.getInstance().getUserIds()) { 5257 final int packageCount = mPackages.size(); 5258 for (int i = 0; i < packageCount; i++) { 5259 PackageParser.Package pkg = mPackages.valueAt(i); 5260 if (!(pkg.mExtras instanceof PackageSetting)) { 5261 continue; 5262 } 5263 PackageSetting ps = (PackageSetting) pkg.mExtras; 5264 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 5265 } 5266 } 5267 } 5268 } 5269 5270 @Override 5271 public int getPermissionFlags(String permName, String packageName, int userId) { 5272 return mPermissionManager.getPermissionFlags( 5273 permName, packageName, getCallingUid(), userId); 5274 } 5275 5276 @Override 5277 public void updatePermissionFlags(String permName, String packageName, int flagMask, 5278 int flagValues, int userId) { 5279 mPermissionManager.updatePermissionFlags( 5280 permName, packageName, flagMask, flagValues, getCallingUid(), userId, 5281 mPermissionCallback); 5282 } 5283 5284 /** 5285 * Update the permission flags for all packages and runtime permissions of a user in order 5286 * to allow device or profile owner to remove POLICY_FIXED. 5287 */ 5288 @Override 5289 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 5290 synchronized (mPackages) { 5291 final boolean changed = mPermissionManager.updatePermissionFlagsForAllApps( 5292 flagMask, flagValues, getCallingUid(), userId, mPackages.values(), 5293 mPermissionCallback); 5294 if (changed) { 5295 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 5296 } 5297 } 5298 } 5299 5300 @Override 5301 public boolean shouldShowRequestPermissionRationale(String permissionName, 5302 String packageName, int userId) { 5303 if (UserHandle.getCallingUserId() != userId) { 5304 mContext.enforceCallingPermission( 5305 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5306 "canShowRequestPermissionRationale for user " + userId); 5307 } 5308 5309 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 5310 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 5311 return false; 5312 } 5313 5314 if (checkPermission(permissionName, packageName, userId) 5315 == PackageManager.PERMISSION_GRANTED) { 5316 return false; 5317 } 5318 5319 final int flags; 5320 5321 final long identity = Binder.clearCallingIdentity(); 5322 try { 5323 flags = getPermissionFlags(permissionName, 5324 packageName, userId); 5325 } finally { 5326 Binder.restoreCallingIdentity(identity); 5327 } 5328 5329 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 5330 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 5331 | PackageManager.FLAG_PERMISSION_USER_FIXED; 5332 5333 if ((flags & fixedFlags) != 0) { 5334 return false; 5335 } 5336 5337 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 5338 } 5339 5340 @Override 5341 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 5342 mContext.enforceCallingOrSelfPermission( 5343 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 5344 "addOnPermissionsChangeListener"); 5345 5346 synchronized (mPackages) { 5347 mOnPermissionChangeListeners.addListenerLocked(listener); 5348 } 5349 } 5350 5351 @Override 5352 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 5353 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5354 throw new SecurityException("Instant applications don't have access to this method"); 5355 } 5356 synchronized (mPackages) { 5357 mOnPermissionChangeListeners.removeListenerLocked(listener); 5358 } 5359 } 5360 5361 @Override 5362 public boolean isProtectedBroadcast(String actionName) { 5363 // allow instant applications 5364 synchronized (mProtectedBroadcasts) { 5365 if (mProtectedBroadcasts.contains(actionName)) { 5366 return true; 5367 } else if (actionName != null) { 5368 // TODO: remove these terrible hacks 5369 if (actionName.startsWith("android.net.netmon.lingerExpired") 5370 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 5371 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 5372 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 5373 return true; 5374 } 5375 } 5376 } 5377 return false; 5378 } 5379 5380 @Override 5381 public int checkSignatures(String pkg1, String pkg2) { 5382 synchronized (mPackages) { 5383 final PackageParser.Package p1 = mPackages.get(pkg1); 5384 final PackageParser.Package p2 = mPackages.get(pkg2); 5385 if (p1 == null || p1.mExtras == null 5386 || p2 == null || p2.mExtras == null) { 5387 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5388 } 5389 final int callingUid = Binder.getCallingUid(); 5390 final int callingUserId = UserHandle.getUserId(callingUid); 5391 final PackageSetting ps1 = (PackageSetting) p1.mExtras; 5392 final PackageSetting ps2 = (PackageSetting) p2.mExtras; 5393 if (filterAppAccessLPr(ps1, callingUid, callingUserId) 5394 || filterAppAccessLPr(ps2, callingUid, callingUserId)) { 5395 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5396 } 5397 return compareSignatures(p1.mSignatures, p2.mSignatures); 5398 } 5399 } 5400 5401 @Override 5402 public int checkUidSignatures(int uid1, int uid2) { 5403 final int callingUid = Binder.getCallingUid(); 5404 final int callingUserId = UserHandle.getUserId(callingUid); 5405 final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null; 5406 // Map to base uids. 5407 uid1 = UserHandle.getAppId(uid1); 5408 uid2 = UserHandle.getAppId(uid2); 5409 // reader 5410 synchronized (mPackages) { 5411 Signature[] s1; 5412 Signature[] s2; 5413 Object obj = mSettings.getUserIdLPr(uid1); 5414 if (obj != null) { 5415 if (obj instanceof SharedUserSetting) { 5416 if (isCallerInstantApp) { 5417 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5418 } 5419 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 5420 } else if (obj instanceof PackageSetting) { 5421 final PackageSetting ps = (PackageSetting) obj; 5422 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 5423 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5424 } 5425 s1 = ps.signatures.mSignatures; 5426 } else { 5427 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5428 } 5429 } else { 5430 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5431 } 5432 obj = mSettings.getUserIdLPr(uid2); 5433 if (obj != null) { 5434 if (obj instanceof SharedUserSetting) { 5435 if (isCallerInstantApp) { 5436 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5437 } 5438 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 5439 } else if (obj instanceof PackageSetting) { 5440 final PackageSetting ps = (PackageSetting) obj; 5441 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 5442 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5443 } 5444 s2 = ps.signatures.mSignatures; 5445 } else { 5446 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5447 } 5448 } else { 5449 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5450 } 5451 return compareSignatures(s1, s2); 5452 } 5453 } 5454 5455 /** 5456 * This method should typically only be used when granting or revoking 5457 * permissions, since the app may immediately restart after this call. 5458 * <p> 5459 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 5460 * guard your work against the app being relaunched. 5461 */ 5462 private void killUid(int appId, int userId, String reason) { 5463 final long identity = Binder.clearCallingIdentity(); 5464 try { 5465 IActivityManager am = ActivityManager.getService(); 5466 if (am != null) { 5467 try { 5468 am.killUid(appId, userId, reason); 5469 } catch (RemoteException e) { 5470 /* ignore - same process */ 5471 } 5472 } 5473 } finally { 5474 Binder.restoreCallingIdentity(identity); 5475 } 5476 } 5477 5478 /** 5479 * Compares two sets of signatures. Returns: 5480 * <br /> 5481 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 5482 * <br /> 5483 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 5484 * <br /> 5485 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 5486 * <br /> 5487 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 5488 * <br /> 5489 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 5490 */ 5491 public static int compareSignatures(Signature[] s1, Signature[] s2) { 5492 if (s1 == null) { 5493 return s2 == null 5494 ? PackageManager.SIGNATURE_NEITHER_SIGNED 5495 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 5496 } 5497 5498 if (s2 == null) { 5499 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 5500 } 5501 5502 if (s1.length != s2.length) { 5503 return PackageManager.SIGNATURE_NO_MATCH; 5504 } 5505 5506 // Since both signature sets are of size 1, we can compare without HashSets. 5507 if (s1.length == 1) { 5508 return s1[0].equals(s2[0]) ? 5509 PackageManager.SIGNATURE_MATCH : 5510 PackageManager.SIGNATURE_NO_MATCH; 5511 } 5512 5513 ArraySet<Signature> set1 = new ArraySet<Signature>(); 5514 for (Signature sig : s1) { 5515 set1.add(sig); 5516 } 5517 ArraySet<Signature> set2 = new ArraySet<Signature>(); 5518 for (Signature sig : s2) { 5519 set2.add(sig); 5520 } 5521 // Make sure s2 contains all signatures in s1. 5522 if (set1.equals(set2)) { 5523 return PackageManager.SIGNATURE_MATCH; 5524 } 5525 return PackageManager.SIGNATURE_NO_MATCH; 5526 } 5527 5528 /** 5529 * If the database version for this type of package (internal storage or 5530 * external storage) is less than the version where package signatures 5531 * were updated, return true. 5532 */ 5533 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 5534 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 5535 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 5536 } 5537 5538 /** 5539 * Used for backward compatibility to make sure any packages with 5540 * certificate chains get upgraded to the new style. {@code existingSigs} 5541 * will be in the old format (since they were stored on disk from before the 5542 * system upgrade) and {@code scannedSigs} will be in the newer format. 5543 */ 5544 private int compareSignaturesCompat(PackageSignatures existingSigs, 5545 PackageParser.Package scannedPkg) { 5546 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 5547 return PackageManager.SIGNATURE_NO_MATCH; 5548 } 5549 5550 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 5551 for (Signature sig : existingSigs.mSignatures) { 5552 existingSet.add(sig); 5553 } 5554 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 5555 for (Signature sig : scannedPkg.mSignatures) { 5556 try { 5557 Signature[] chainSignatures = sig.getChainSignatures(); 5558 for (Signature chainSig : chainSignatures) { 5559 scannedCompatSet.add(chainSig); 5560 } 5561 } catch (CertificateEncodingException e) { 5562 scannedCompatSet.add(sig); 5563 } 5564 } 5565 /* 5566 * Make sure the expanded scanned set contains all signatures in the 5567 * existing one. 5568 */ 5569 if (scannedCompatSet.equals(existingSet)) { 5570 // Migrate the old signatures to the new scheme. 5571 existingSigs.assignSignatures(scannedPkg.mSignatures); 5572 // The new KeySets will be re-added later in the scanning process. 5573 synchronized (mPackages) { 5574 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 5575 } 5576 return PackageManager.SIGNATURE_MATCH; 5577 } 5578 return PackageManager.SIGNATURE_NO_MATCH; 5579 } 5580 5581 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 5582 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 5583 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 5584 } 5585 5586 private int compareSignaturesRecover(PackageSignatures existingSigs, 5587 PackageParser.Package scannedPkg) { 5588 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 5589 return PackageManager.SIGNATURE_NO_MATCH; 5590 } 5591 5592 String msg = null; 5593 try { 5594 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 5595 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 5596 + scannedPkg.packageName); 5597 return PackageManager.SIGNATURE_MATCH; 5598 } 5599 } catch (CertificateException e) { 5600 msg = e.getMessage(); 5601 } 5602 5603 logCriticalInfo(Log.INFO, 5604 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 5605 return PackageManager.SIGNATURE_NO_MATCH; 5606 } 5607 5608 @Override 5609 public List<String> getAllPackages() { 5610 final int callingUid = Binder.getCallingUid(); 5611 final int callingUserId = UserHandle.getUserId(callingUid); 5612 synchronized (mPackages) { 5613 if (canViewInstantApps(callingUid, callingUserId)) { 5614 return new ArrayList<String>(mPackages.keySet()); 5615 } 5616 final String instantAppPkgName = getInstantAppPackageName(callingUid); 5617 final List<String> result = new ArrayList<>(); 5618 if (instantAppPkgName != null) { 5619 // caller is an instant application; filter unexposed applications 5620 for (PackageParser.Package pkg : mPackages.values()) { 5621 if (!pkg.visibleToInstantApps) { 5622 continue; 5623 } 5624 result.add(pkg.packageName); 5625 } 5626 } else { 5627 // caller is a normal application; filter instant applications 5628 for (PackageParser.Package pkg : mPackages.values()) { 5629 final PackageSetting ps = 5630 pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null; 5631 if (ps != null 5632 && ps.getInstantApp(callingUserId) 5633 && !mInstantAppRegistry.isInstantAccessGranted( 5634 callingUserId, UserHandle.getAppId(callingUid), ps.appId)) { 5635 continue; 5636 } 5637 result.add(pkg.packageName); 5638 } 5639 } 5640 return result; 5641 } 5642 } 5643 5644 @Override 5645 public String[] getPackagesForUid(int uid) { 5646 final int callingUid = Binder.getCallingUid(); 5647 final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null; 5648 final int userId = UserHandle.getUserId(uid); 5649 uid = UserHandle.getAppId(uid); 5650 // reader 5651 synchronized (mPackages) { 5652 Object obj = mSettings.getUserIdLPr(uid); 5653 if (obj instanceof SharedUserSetting) { 5654 if (isCallerInstantApp) { 5655 return null; 5656 } 5657 final SharedUserSetting sus = (SharedUserSetting) obj; 5658 final int N = sus.packages.size(); 5659 String[] res = new String[N]; 5660 final Iterator<PackageSetting> it = sus.packages.iterator(); 5661 int i = 0; 5662 while (it.hasNext()) { 5663 PackageSetting ps = it.next(); 5664 if (ps.getInstalled(userId)) { 5665 res[i++] = ps.name; 5666 } else { 5667 res = ArrayUtils.removeElement(String.class, res, res[i]); 5668 } 5669 } 5670 return res; 5671 } else if (obj instanceof PackageSetting) { 5672 final PackageSetting ps = (PackageSetting) obj; 5673 if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) { 5674 return new String[]{ps.name}; 5675 } 5676 } 5677 } 5678 return null; 5679 } 5680 5681 @Override 5682 public String getNameForUid(int uid) { 5683 final int callingUid = Binder.getCallingUid(); 5684 if (getInstantAppPackageName(callingUid) != null) { 5685 return null; 5686 } 5687 synchronized (mPackages) { 5688 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5689 if (obj instanceof SharedUserSetting) { 5690 final SharedUserSetting sus = (SharedUserSetting) obj; 5691 return sus.name + ":" + sus.userId; 5692 } else if (obj instanceof PackageSetting) { 5693 final PackageSetting ps = (PackageSetting) obj; 5694 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 5695 return null; 5696 } 5697 return ps.name; 5698 } 5699 return null; 5700 } 5701 } 5702 5703 @Override 5704 public String[] getNamesForUids(int[] uids) { 5705 if (uids == null || uids.length == 0) { 5706 return null; 5707 } 5708 final int callingUid = Binder.getCallingUid(); 5709 if (getInstantAppPackageName(callingUid) != null) { 5710 return null; 5711 } 5712 final String[] names = new String[uids.length]; 5713 synchronized (mPackages) { 5714 for (int i = uids.length - 1; i >= 0; i--) { 5715 final int uid = uids[i]; 5716 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5717 if (obj instanceof SharedUserSetting) { 5718 final SharedUserSetting sus = (SharedUserSetting) obj; 5719 names[i] = "shared:" + sus.name; 5720 } else if (obj instanceof PackageSetting) { 5721 final PackageSetting ps = (PackageSetting) obj; 5722 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 5723 names[i] = null; 5724 } else { 5725 names[i] = ps.name; 5726 } 5727 } else { 5728 names[i] = null; 5729 } 5730 } 5731 } 5732 return names; 5733 } 5734 5735 @Override 5736 public int getUidForSharedUser(String sharedUserName) { 5737 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5738 return -1; 5739 } 5740 if (sharedUserName == null) { 5741 return -1; 5742 } 5743 // reader 5744 synchronized (mPackages) { 5745 SharedUserSetting suid; 5746 try { 5747 suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 5748 if (suid != null) { 5749 return suid.userId; 5750 } 5751 } catch (PackageManagerException ignore) { 5752 // can't happen, but, still need to catch it 5753 } 5754 return -1; 5755 } 5756 } 5757 5758 @Override 5759 public int getFlagsForUid(int uid) { 5760 final int callingUid = Binder.getCallingUid(); 5761 if (getInstantAppPackageName(callingUid) != null) { 5762 return 0; 5763 } 5764 synchronized (mPackages) { 5765 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5766 if (obj instanceof SharedUserSetting) { 5767 final SharedUserSetting sus = (SharedUserSetting) obj; 5768 return sus.pkgFlags; 5769 } else if (obj instanceof PackageSetting) { 5770 final PackageSetting ps = (PackageSetting) obj; 5771 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 5772 return 0; 5773 } 5774 return ps.pkgFlags; 5775 } 5776 } 5777 return 0; 5778 } 5779 5780 @Override 5781 public int getPrivateFlagsForUid(int uid) { 5782 final int callingUid = Binder.getCallingUid(); 5783 if (getInstantAppPackageName(callingUid) != null) { 5784 return 0; 5785 } 5786 synchronized (mPackages) { 5787 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5788 if (obj instanceof SharedUserSetting) { 5789 final SharedUserSetting sus = (SharedUserSetting) obj; 5790 return sus.pkgPrivateFlags; 5791 } else if (obj instanceof PackageSetting) { 5792 final PackageSetting ps = (PackageSetting) obj; 5793 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 5794 return 0; 5795 } 5796 return ps.pkgPrivateFlags; 5797 } 5798 } 5799 return 0; 5800 } 5801 5802 @Override 5803 public boolean isUidPrivileged(int uid) { 5804 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5805 return false; 5806 } 5807 uid = UserHandle.getAppId(uid); 5808 // reader 5809 synchronized (mPackages) { 5810 Object obj = mSettings.getUserIdLPr(uid); 5811 if (obj instanceof SharedUserSetting) { 5812 final SharedUserSetting sus = (SharedUserSetting) obj; 5813 final Iterator<PackageSetting> it = sus.packages.iterator(); 5814 while (it.hasNext()) { 5815 if (it.next().isPrivileged()) { 5816 return true; 5817 } 5818 } 5819 } else if (obj instanceof PackageSetting) { 5820 final PackageSetting ps = (PackageSetting) obj; 5821 return ps.isPrivileged(); 5822 } 5823 } 5824 return false; 5825 } 5826 5827 @Override 5828 public String[] getAppOpPermissionPackages(String permName) { 5829 return mPermissionManager.getAppOpPermissionPackages(permName); 5830 } 5831 5832 @Override 5833 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 5834 int flags, int userId) { 5835 return resolveIntentInternal( 5836 intent, resolvedType, flags, userId, false /*resolveForStart*/); 5837 } 5838 5839 /** 5840 * Normally instant apps can only be resolved when they're visible to the caller. 5841 * However, if {@code resolveForStart} is {@code true}, all instant apps are visible 5842 * since we need to allow the system to start any installed application. 5843 */ 5844 private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType, 5845 int flags, int userId, boolean resolveForStart) { 5846 try { 5847 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 5848 5849 if (!sUserManager.exists(userId)) return null; 5850 final int callingUid = Binder.getCallingUid(); 5851 flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart); 5852 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 5853 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 5854 5855 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5856 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 5857 flags, callingUid, userId, resolveForStart, true /*allowDynamicSplits*/); 5858 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5859 5860 final ResolveInfo bestChoice = 5861 chooseBestActivity(intent, resolvedType, flags, query, userId); 5862 return bestChoice; 5863 } finally { 5864 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5865 } 5866 } 5867 5868 @Override 5869 public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) { 5870 if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) { 5871 throw new SecurityException( 5872 "findPersistentPreferredActivity can only be run by the system"); 5873 } 5874 if (!sUserManager.exists(userId)) { 5875 return null; 5876 } 5877 final int callingUid = Binder.getCallingUid(); 5878 intent = updateIntentForResolve(intent); 5879 final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver()); 5880 final int flags = updateFlagsForResolve( 5881 0, userId, intent, callingUid, false /*includeInstantApps*/); 5882 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5883 userId); 5884 synchronized (mPackages) { 5885 return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false, 5886 userId); 5887 } 5888 } 5889 5890 @Override 5891 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 5892 IntentFilter filter, int match, ComponentName activity) { 5893 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5894 return; 5895 } 5896 final int userId = UserHandle.getCallingUserId(); 5897 if (DEBUG_PREFERRED) { 5898 Log.v(TAG, "setLastChosenActivity intent=" + intent 5899 + " resolvedType=" + resolvedType 5900 + " flags=" + flags 5901 + " filter=" + filter 5902 + " match=" + match 5903 + " activity=" + activity); 5904 filter.dump(new PrintStreamPrinter(System.out), " "); 5905 } 5906 intent.setComponent(null); 5907 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5908 userId); 5909 // Find any earlier preferred or last chosen entries and nuke them 5910 findPreferredActivity(intent, resolvedType, 5911 flags, query, 0, false, true, false, userId); 5912 // Add the new activity as the last chosen for this filter 5913 addPreferredActivityInternal(filter, match, null, activity, false, userId, 5914 "Setting last chosen"); 5915 } 5916 5917 @Override 5918 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 5919 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5920 return null; 5921 } 5922 final int userId = UserHandle.getCallingUserId(); 5923 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 5924 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5925 userId); 5926 return findPreferredActivity(intent, resolvedType, flags, query, 0, 5927 false, false, false, userId); 5928 } 5929 5930 /** 5931 * Returns whether or not instant apps have been disabled remotely. 5932 */ 5933 private boolean isEphemeralDisabled() { 5934 return mEphemeralAppsDisabled; 5935 } 5936 5937 private boolean isInstantAppAllowed( 5938 Intent intent, List<ResolveInfo> resolvedActivities, int userId, 5939 boolean skipPackageCheck) { 5940 if (mInstantAppResolverConnection == null) { 5941 return false; 5942 } 5943 if (mInstantAppInstallerActivity == null) { 5944 return false; 5945 } 5946 if (intent.getComponent() != null) { 5947 return false; 5948 } 5949 if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) { 5950 return false; 5951 } 5952 if (!skipPackageCheck && intent.getPackage() != null) { 5953 return false; 5954 } 5955 final boolean isWebUri = hasWebURI(intent); 5956 if (!isWebUri || intent.getData().getHost() == null) { 5957 return false; 5958 } 5959 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 5960 // Or if there's already an ephemeral app installed that handles the action 5961 synchronized (mPackages) { 5962 final int count = (resolvedActivities == null ? 0 : resolvedActivities.size()); 5963 for (int n = 0; n < count; n++) { 5964 final ResolveInfo info = resolvedActivities.get(n); 5965 final String packageName = info.activityInfo.packageName; 5966 final PackageSetting ps = mSettings.mPackages.get(packageName); 5967 if (ps != null) { 5968 // only check domain verification status if the app is not a browser 5969 if (!info.handleAllWebDataURI) { 5970 // Try to get the status from User settings first 5971 final long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5972 final int status = (int) (packedStatus >> 32); 5973 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 5974 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5975 if (DEBUG_EPHEMERAL) { 5976 Slog.v(TAG, "DENY instant app;" 5977 + " pkg: " + packageName + ", status: " + status); 5978 } 5979 return false; 5980 } 5981 } 5982 if (ps.getInstantApp(userId)) { 5983 if (DEBUG_EPHEMERAL) { 5984 Slog.v(TAG, "DENY instant app installed;" 5985 + " pkg: " + packageName); 5986 } 5987 return false; 5988 } 5989 } 5990 } 5991 } 5992 // We've exhausted all ways to deny ephemeral application; let the system look for them. 5993 return true; 5994 } 5995 5996 private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj, 5997 Intent origIntent, String resolvedType, String callingPackage, 5998 Bundle verificationBundle, int userId) { 5999 final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO, 6000 new InstantAppRequest(responseObj, origIntent, resolvedType, 6001 callingPackage, userId, verificationBundle, false /*resolveForStart*/)); 6002 mHandler.sendMessage(msg); 6003 } 6004 6005 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 6006 int flags, List<ResolveInfo> query, int userId) { 6007 if (query != null) { 6008 final int N = query.size(); 6009 if (N == 1) { 6010 return query.get(0); 6011 } else if (N > 1) { 6012 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 6013 // If there is more than one activity with the same priority, 6014 // then let the user decide between them. 6015 ResolveInfo r0 = query.get(0); 6016 ResolveInfo r1 = query.get(1); 6017 if (DEBUG_INTENT_MATCHING || debug) { 6018 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 6019 + r1.activityInfo.name + "=" + r1.priority); 6020 } 6021 // If the first activity has a higher priority, or a different 6022 // default, then it is always desirable to pick it. 6023 if (r0.priority != r1.priority 6024 || r0.preferredOrder != r1.preferredOrder 6025 || r0.isDefault != r1.isDefault) { 6026 return query.get(0); 6027 } 6028 // If we have saved a preference for a preferred activity for 6029 // this Intent, use that. 6030 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 6031 flags, query, r0.priority, true, false, debug, userId); 6032 if (ri != null) { 6033 return ri; 6034 } 6035 // If we have an ephemeral app, use it 6036 for (int i = 0; i < N; i++) { 6037 ri = query.get(i); 6038 if (ri.activityInfo.applicationInfo.isInstantApp()) { 6039 final String packageName = ri.activityInfo.packageName; 6040 final PackageSetting ps = mSettings.mPackages.get(packageName); 6041 final long packedStatus = getDomainVerificationStatusLPr(ps, userId); 6042 final int status = (int)(packedStatus >> 32); 6043 if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 6044 return ri; 6045 } 6046 } 6047 } 6048 ri = new ResolveInfo(mResolveInfo); 6049 ri.activityInfo = new ActivityInfo(ri.activityInfo); 6050 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 6051 // If all of the options come from the same package, show the application's 6052 // label and icon instead of the generic resolver's. 6053 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 6054 // and then throw away the ResolveInfo itself, meaning that the caller loses 6055 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 6056 // a fallback for this case; we only set the target package's resources on 6057 // the ResolveInfo, not the ActivityInfo. 6058 final String intentPackage = intent.getPackage(); 6059 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 6060 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 6061 ri.resolvePackageName = intentPackage; 6062 if (userNeedsBadging(userId)) { 6063 ri.noResourceId = true; 6064 } else { 6065 ri.icon = appi.icon; 6066 } 6067 ri.iconResourceId = appi.icon; 6068 ri.labelRes = appi.labelRes; 6069 } 6070 ri.activityInfo.applicationInfo = new ApplicationInfo( 6071 ri.activityInfo.applicationInfo); 6072 if (userId != 0) { 6073 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 6074 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 6075 } 6076 // Make sure that the resolver is displayable in car mode 6077 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 6078 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 6079 return ri; 6080 } 6081 } 6082 return null; 6083 } 6084 6085 /** 6086 * Return true if the given list is not empty and all of its contents have 6087 * an activityInfo with the given package name. 6088 */ 6089 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 6090 if (ArrayUtils.isEmpty(list)) { 6091 return false; 6092 } 6093 for (int i = 0, N = list.size(); i < N; i++) { 6094 final ResolveInfo ri = list.get(i); 6095 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 6096 if (ai == null || !packageName.equals(ai.packageName)) { 6097 return false; 6098 } 6099 } 6100 return true; 6101 } 6102 6103 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 6104 int flags, List<ResolveInfo> query, boolean debug, int userId) { 6105 final int N = query.size(); 6106 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 6107 .get(userId); 6108 // Get the list of persistent preferred activities that handle the intent 6109 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 6110 List<PersistentPreferredActivity> pprefs = ppir != null 6111 ? ppir.queryIntent(intent, resolvedType, 6112 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 6113 userId) 6114 : null; 6115 if (pprefs != null && pprefs.size() > 0) { 6116 final int M = pprefs.size(); 6117 for (int i=0; i<M; i++) { 6118 final PersistentPreferredActivity ppa = pprefs.get(i); 6119 if (DEBUG_PREFERRED || debug) { 6120 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 6121 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 6122 + "\n component=" + ppa.mComponent); 6123 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6124 } 6125 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 6126 flags | MATCH_DISABLED_COMPONENTS, userId); 6127 if (DEBUG_PREFERRED || debug) { 6128 Slog.v(TAG, "Found persistent preferred activity:"); 6129 if (ai != null) { 6130 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6131 } else { 6132 Slog.v(TAG, " null"); 6133 } 6134 } 6135 if (ai == null) { 6136 // This previously registered persistent preferred activity 6137 // component is no longer known. Ignore it and do NOT remove it. 6138 continue; 6139 } 6140 for (int j=0; j<N; j++) { 6141 final ResolveInfo ri = query.get(j); 6142 if (!ri.activityInfo.applicationInfo.packageName 6143 .equals(ai.applicationInfo.packageName)) { 6144 continue; 6145 } 6146 if (!ri.activityInfo.name.equals(ai.name)) { 6147 continue; 6148 } 6149 // Found a persistent preference that can handle the intent. 6150 if (DEBUG_PREFERRED || debug) { 6151 Slog.v(TAG, "Returning persistent preferred activity: " + 6152 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 6153 } 6154 return ri; 6155 } 6156 } 6157 } 6158 return null; 6159 } 6160 6161 // TODO: handle preferred activities missing while user has amnesia 6162 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 6163 List<ResolveInfo> query, int priority, boolean always, 6164 boolean removeMatches, boolean debug, int userId) { 6165 if (!sUserManager.exists(userId)) return null; 6166 final int callingUid = Binder.getCallingUid(); 6167 flags = updateFlagsForResolve( 6168 flags, userId, intent, callingUid, false /*includeInstantApps*/); 6169 intent = updateIntentForResolve(intent); 6170 // writer 6171 synchronized (mPackages) { 6172 // Try to find a matching persistent preferred activity. 6173 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 6174 debug, userId); 6175 6176 // If a persistent preferred activity matched, use it. 6177 if (pri != null) { 6178 return pri; 6179 } 6180 6181 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 6182 // Get the list of preferred activities that handle the intent 6183 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 6184 List<PreferredActivity> prefs = pir != null 6185 ? pir.queryIntent(intent, resolvedType, 6186 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 6187 userId) 6188 : null; 6189 if (prefs != null && prefs.size() > 0) { 6190 boolean changed = false; 6191 try { 6192 // First figure out how good the original match set is. 6193 // We will only allow preferred activities that came 6194 // from the same match quality. 6195 int match = 0; 6196 6197 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 6198 6199 final int N = query.size(); 6200 for (int j=0; j<N; j++) { 6201 final ResolveInfo ri = query.get(j); 6202 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 6203 + ": 0x" + Integer.toHexString(match)); 6204 if (ri.match > match) { 6205 match = ri.match; 6206 } 6207 } 6208 6209 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 6210 + Integer.toHexString(match)); 6211 6212 match &= IntentFilter.MATCH_CATEGORY_MASK; 6213 final int M = prefs.size(); 6214 for (int i=0; i<M; i++) { 6215 final PreferredActivity pa = prefs.get(i); 6216 if (DEBUG_PREFERRED || debug) { 6217 Slog.v(TAG, "Checking PreferredActivity ds=" 6218 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 6219 + "\n component=" + pa.mPref.mComponent); 6220 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6221 } 6222 if (pa.mPref.mMatch != match) { 6223 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 6224 + Integer.toHexString(pa.mPref.mMatch)); 6225 continue; 6226 } 6227 // If it's not an "always" type preferred activity and that's what we're 6228 // looking for, skip it. 6229 if (always && !pa.mPref.mAlways) { 6230 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 6231 continue; 6232 } 6233 final ActivityInfo ai = getActivityInfo( 6234 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 6235 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 6236 userId); 6237 if (DEBUG_PREFERRED || debug) { 6238 Slog.v(TAG, "Found preferred activity:"); 6239 if (ai != null) { 6240 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6241 } else { 6242 Slog.v(TAG, " null"); 6243 } 6244 } 6245 if (ai == null) { 6246 // This previously registered preferred activity 6247 // component is no longer known. Most likely an update 6248 // to the app was installed and in the new version this 6249 // component no longer exists. Clean it up by removing 6250 // it from the preferred activities list, and skip it. 6251 Slog.w(TAG, "Removing dangling preferred activity: " 6252 + pa.mPref.mComponent); 6253 pir.removeFilter(pa); 6254 changed = true; 6255 continue; 6256 } 6257 for (int j=0; j<N; j++) { 6258 final ResolveInfo ri = query.get(j); 6259 if (!ri.activityInfo.applicationInfo.packageName 6260 .equals(ai.applicationInfo.packageName)) { 6261 continue; 6262 } 6263 if (!ri.activityInfo.name.equals(ai.name)) { 6264 continue; 6265 } 6266 6267 if (removeMatches) { 6268 pir.removeFilter(pa); 6269 changed = true; 6270 if (DEBUG_PREFERRED) { 6271 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 6272 } 6273 break; 6274 } 6275 6276 // Okay we found a previously set preferred or last chosen app. 6277 // If the result set is different from when this 6278 // was created, and is not a subset of the preferred set, we need to 6279 // clear it and re-ask the user their preference, if we're looking for 6280 // an "always" type entry. 6281 if (always && !pa.mPref.sameSet(query)) { 6282 if (pa.mPref.isSuperset(query)) { 6283 // some components of the set are no longer present in 6284 // the query, but the preferred activity can still be reused 6285 if (DEBUG_PREFERRED) { 6286 Slog.i(TAG, "Result set changed, but PreferredActivity is" 6287 + " still valid as only non-preferred components" 6288 + " were removed for " + intent + " type " 6289 + resolvedType); 6290 } 6291 // remove obsolete components and re-add the up-to-date filter 6292 PreferredActivity freshPa = new PreferredActivity(pa, 6293 pa.mPref.mMatch, 6294 pa.mPref.discardObsoleteComponents(query), 6295 pa.mPref.mComponent, 6296 pa.mPref.mAlways); 6297 pir.removeFilter(pa); 6298 pir.addFilter(freshPa); 6299 changed = true; 6300 } else { 6301 Slog.i(TAG, 6302 "Result set changed, dropping preferred activity for " 6303 + intent + " type " + resolvedType); 6304 if (DEBUG_PREFERRED) { 6305 Slog.v(TAG, "Removing preferred activity since set changed " 6306 + pa.mPref.mComponent); 6307 } 6308 pir.removeFilter(pa); 6309 // Re-add the filter as a "last chosen" entry (!always) 6310 PreferredActivity lastChosen = new PreferredActivity( 6311 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 6312 pir.addFilter(lastChosen); 6313 changed = true; 6314 return null; 6315 } 6316 } 6317 6318 // Yay! Either the set matched or we're looking for the last chosen 6319 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 6320 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 6321 return ri; 6322 } 6323 } 6324 } finally { 6325 if (changed) { 6326 if (DEBUG_PREFERRED) { 6327 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 6328 } 6329 scheduleWritePackageRestrictionsLocked(userId); 6330 } 6331 } 6332 } 6333 } 6334 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 6335 return null; 6336 } 6337 6338 /* 6339 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 6340 */ 6341 @Override 6342 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 6343 int targetUserId) { 6344 mContext.enforceCallingOrSelfPermission( 6345 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 6346 List<CrossProfileIntentFilter> matches = 6347 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 6348 if (matches != null) { 6349 int size = matches.size(); 6350 for (int i = 0; i < size; i++) { 6351 if (matches.get(i).getTargetUserId() == targetUserId) return true; 6352 } 6353 } 6354 if (hasWebURI(intent)) { 6355 // cross-profile app linking works only towards the parent. 6356 final int callingUid = Binder.getCallingUid(); 6357 final UserInfo parent = getProfileParent(sourceUserId); 6358 synchronized(mPackages) { 6359 int flags = updateFlagsForResolve(0, parent.id, intent, callingUid, 6360 false /*includeInstantApps*/); 6361 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 6362 intent, resolvedType, flags, sourceUserId, parent.id); 6363 return xpDomainInfo != null; 6364 } 6365 } 6366 return false; 6367 } 6368 6369 private UserInfo getProfileParent(int userId) { 6370 final long identity = Binder.clearCallingIdentity(); 6371 try { 6372 return sUserManager.getProfileParent(userId); 6373 } finally { 6374 Binder.restoreCallingIdentity(identity); 6375 } 6376 } 6377 6378 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 6379 String resolvedType, int userId) { 6380 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 6381 if (resolver != null) { 6382 return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId); 6383 } 6384 return null; 6385 } 6386 6387 @Override 6388 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 6389 String resolvedType, int flags, int userId) { 6390 try { 6391 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 6392 6393 return new ParceledListSlice<>( 6394 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 6395 } finally { 6396 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6397 } 6398 } 6399 6400 /** 6401 * Returns the package name of the calling Uid if it's an instant app. If it isn't 6402 * instant, returns {@code null}. 6403 */ 6404 private String getInstantAppPackageName(int callingUid) { 6405 synchronized (mPackages) { 6406 // If the caller is an isolated app use the owner's uid for the lookup. 6407 if (Process.isIsolated(callingUid)) { 6408 callingUid = mIsolatedOwners.get(callingUid); 6409 } 6410 final int appId = UserHandle.getAppId(callingUid); 6411 final Object obj = mSettings.getUserIdLPr(appId); 6412 if (obj instanceof PackageSetting) { 6413 final PackageSetting ps = (PackageSetting) obj; 6414 final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid)); 6415 return isInstantApp ? ps.pkg.packageName : null; 6416 } 6417 } 6418 return null; 6419 } 6420 6421 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 6422 String resolvedType, int flags, int userId) { 6423 return queryIntentActivitiesInternal( 6424 intent, resolvedType, flags, Binder.getCallingUid(), userId, 6425 false /*resolveForStart*/, true /*allowDynamicSplits*/); 6426 } 6427 6428 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 6429 String resolvedType, int flags, int filterCallingUid, int userId, 6430 boolean resolveForStart, boolean allowDynamicSplits) { 6431 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6432 final String instantAppPkgName = getInstantAppPackageName(filterCallingUid); 6433 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 6434 false /* requireFullPermission */, false /* checkShell */, 6435 "query intent activities"); 6436 final String pkgName = intent.getPackage(); 6437 ComponentName comp = intent.getComponent(); 6438 if (comp == null) { 6439 if (intent.getSelector() != null) { 6440 intent = intent.getSelector(); 6441 comp = intent.getComponent(); 6442 } 6443 } 6444 6445 flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart, 6446 comp != null || pkgName != null /*onlyExposedExplicitly*/); 6447 if (comp != null) { 6448 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6449 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 6450 if (ai != null) { 6451 // When specifying an explicit component, we prevent the activity from being 6452 // used when either 1) the calling package is normal and the activity is within 6453 // an ephemeral application or 2) the calling package is ephemeral and the 6454 // activity is not visible to ephemeral applications. 6455 final boolean matchInstantApp = 6456 (flags & PackageManager.MATCH_INSTANT) != 0; 6457 final boolean matchVisibleToInstantAppOnly = 6458 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 6459 final boolean matchExplicitlyVisibleOnly = 6460 (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0; 6461 final boolean isCallerInstantApp = 6462 instantAppPkgName != null; 6463 final boolean isTargetSameInstantApp = 6464 comp.getPackageName().equals(instantAppPkgName); 6465 final boolean isTargetInstantApp = 6466 (ai.applicationInfo.privateFlags 6467 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 6468 final boolean isTargetVisibleToInstantApp = 6469 (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0; 6470 final boolean isTargetExplicitlyVisibleToInstantApp = 6471 isTargetVisibleToInstantApp 6472 && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0; 6473 final boolean isTargetHiddenFromInstantApp = 6474 !isTargetVisibleToInstantApp 6475 || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp); 6476 final boolean blockResolution = 6477 !isTargetSameInstantApp 6478 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 6479 || (matchVisibleToInstantAppOnly && isCallerInstantApp 6480 && isTargetHiddenFromInstantApp)); 6481 if (!blockResolution) { 6482 final ResolveInfo ri = new ResolveInfo(); 6483 ri.activityInfo = ai; 6484 list.add(ri); 6485 } 6486 } 6487 return applyPostResolutionFilter( 6488 list, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId); 6489 } 6490 6491 // reader 6492 boolean sortResult = false; 6493 boolean addEphemeral = false; 6494 List<ResolveInfo> result; 6495 final boolean ephemeralDisabled = isEphemeralDisabled(); 6496 synchronized (mPackages) { 6497 if (pkgName == null) { 6498 List<CrossProfileIntentFilter> matchingFilters = 6499 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 6500 // Check for results that need to skip the current profile. 6501 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 6502 resolvedType, flags, userId); 6503 if (xpResolveInfo != null) { 6504 List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1); 6505 xpResult.add(xpResolveInfo); 6506 return applyPostResolutionFilter( 6507 filterIfNotSystemUser(xpResult, userId), instantAppPkgName, 6508 allowDynamicSplits, filterCallingUid, userId); 6509 } 6510 6511 // Check for results in the current profile. 6512 result = filterIfNotSystemUser(mActivities.queryIntent( 6513 intent, resolvedType, flags, userId), userId); 6514 addEphemeral = !ephemeralDisabled 6515 && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/); 6516 // Check for cross profile results. 6517 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 6518 xpResolveInfo = queryCrossProfileIntents( 6519 matchingFilters, intent, resolvedType, flags, userId, 6520 hasNonNegativePriorityResult); 6521 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 6522 boolean isVisibleToUser = filterIfNotSystemUser( 6523 Collections.singletonList(xpResolveInfo), userId).size() > 0; 6524 if (isVisibleToUser) { 6525 result.add(xpResolveInfo); 6526 sortResult = true; 6527 } 6528 } 6529 if (hasWebURI(intent)) { 6530 CrossProfileDomainInfo xpDomainInfo = null; 6531 final UserInfo parent = getProfileParent(userId); 6532 if (parent != null) { 6533 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 6534 flags, userId, parent.id); 6535 } 6536 if (xpDomainInfo != null) { 6537 if (xpResolveInfo != null) { 6538 // If we didn't remove it, the cross-profile ResolveInfo would be twice 6539 // in the result. 6540 result.remove(xpResolveInfo); 6541 } 6542 if (result.size() == 0 && !addEphemeral) { 6543 // No result in current profile, but found candidate in parent user. 6544 // And we are not going to add emphemeral app, so we can return the 6545 // result straight away. 6546 result.add(xpDomainInfo.resolveInfo); 6547 return applyPostResolutionFilter(result, instantAppPkgName, 6548 allowDynamicSplits, filterCallingUid, userId); 6549 } 6550 } else if (result.size() <= 1 && !addEphemeral) { 6551 // No result in parent user and <= 1 result in current profile, and we 6552 // are not going to add emphemeral app, so we can return the result without 6553 // further processing. 6554 return applyPostResolutionFilter(result, instantAppPkgName, 6555 allowDynamicSplits, filterCallingUid, userId); 6556 } 6557 // We have more than one candidate (combining results from current and parent 6558 // profile), so we need filtering and sorting. 6559 result = filterCandidatesWithDomainPreferredActivitiesLPr( 6560 intent, flags, result, xpDomainInfo, userId); 6561 sortResult = true; 6562 } 6563 } else { 6564 final PackageParser.Package pkg = mPackages.get(pkgName); 6565 result = null; 6566 if (pkg != null) { 6567 result = filterIfNotSystemUser( 6568 mActivities.queryIntentForPackage( 6569 intent, resolvedType, flags, pkg.activities, userId), 6570 userId); 6571 } 6572 if (result == null || result.size() == 0) { 6573 // the caller wants to resolve for a particular package; however, there 6574 // were no installed results, so, try to find an ephemeral result 6575 addEphemeral = !ephemeralDisabled 6576 && isInstantAppAllowed( 6577 intent, null /*result*/, userId, true /*skipPackageCheck*/); 6578 if (result == null) { 6579 result = new ArrayList<>(); 6580 } 6581 } 6582 } 6583 } 6584 if (addEphemeral) { 6585 result = maybeAddInstantAppInstaller( 6586 result, intent, resolvedType, flags, userId, resolveForStart); 6587 } 6588 if (sortResult) { 6589 Collections.sort(result, mResolvePrioritySorter); 6590 } 6591 return applyPostResolutionFilter( 6592 result, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId); 6593 } 6594 6595 private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent, 6596 String resolvedType, int flags, int userId, boolean resolveForStart) { 6597 // first, check to see if we've got an instant app already installed 6598 final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0; 6599 ResolveInfo localInstantApp = null; 6600 boolean blockResolution = false; 6601 if (!alreadyResolvedLocally) { 6602 final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType, 6603 flags 6604 | PackageManager.GET_RESOLVED_FILTER 6605 | PackageManager.MATCH_INSTANT 6606 | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY, 6607 userId); 6608 for (int i = instantApps.size() - 1; i >= 0; --i) { 6609 final ResolveInfo info = instantApps.get(i); 6610 final String packageName = info.activityInfo.packageName; 6611 final PackageSetting ps = mSettings.mPackages.get(packageName); 6612 if (ps.getInstantApp(userId)) { 6613 final long packedStatus = getDomainVerificationStatusLPr(ps, userId); 6614 final int status = (int)(packedStatus >> 32); 6615 final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 6616 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6617 // there's a local instant application installed, but, the user has 6618 // chosen to never use it; skip resolution and don't acknowledge 6619 // an instant application is even available 6620 if (DEBUG_EPHEMERAL) { 6621 Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName); 6622 } 6623 blockResolution = true; 6624 break; 6625 } else { 6626 // we have a locally installed instant application; skip resolution 6627 // but acknowledge there's an instant application available 6628 if (DEBUG_EPHEMERAL) { 6629 Slog.v(TAG, "Found installed instant app; pkg: " + packageName); 6630 } 6631 localInstantApp = info; 6632 break; 6633 } 6634 } 6635 } 6636 } 6637 // no app installed, let's see if one's available 6638 AuxiliaryResolveInfo auxiliaryResponse = null; 6639 if (!blockResolution) { 6640 if (localInstantApp == null) { 6641 // we don't have an instant app locally, resolve externally 6642 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 6643 final InstantAppRequest requestObject = new InstantAppRequest( 6644 null /*responseObj*/, intent /*origIntent*/, resolvedType, 6645 null /*callingPackage*/, userId, null /*verificationBundle*/, 6646 resolveForStart); 6647 auxiliaryResponse = 6648 InstantAppResolver.doInstantAppResolutionPhaseOne( 6649 mContext, mInstantAppResolverConnection, requestObject); 6650 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6651 } else { 6652 // we have an instant application locally, but, we can't admit that since 6653 // callers shouldn't be able to determine prior browsing. create a dummy 6654 // auxiliary response so the downstream code behaves as if there's an 6655 // instant application available externally. when it comes time to start 6656 // the instant application, we'll do the right thing. 6657 final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo; 6658 auxiliaryResponse = new AuxiliaryResolveInfo( 6659 ai.packageName, null /*splitName*/, null /*failureActivity*/, 6660 ai.versionCode, null /*failureIntent*/); 6661 } 6662 } 6663 if (auxiliaryResponse != null) { 6664 if (DEBUG_EPHEMERAL) { 6665 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 6666 } 6667 final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo); 6668 final PackageSetting ps = 6669 mSettings.mPackages.get(mInstantAppInstallerActivity.packageName); 6670 if (ps != null) { 6671 ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo( 6672 mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId); 6673 ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token; 6674 ephemeralInstaller.auxiliaryInfo = auxiliaryResponse; 6675 // make sure this resolver is the default 6676 ephemeralInstaller.isDefault = true; 6677 ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 6678 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 6679 // add a non-generic filter 6680 ephemeralInstaller.filter = new IntentFilter(intent.getAction()); 6681 ephemeralInstaller.filter.addDataPath( 6682 intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL); 6683 ephemeralInstaller.isInstantAppAvailable = true; 6684 result.add(ephemeralInstaller); 6685 } 6686 } 6687 return result; 6688 } 6689 6690 private static class CrossProfileDomainInfo { 6691 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 6692 ResolveInfo resolveInfo; 6693 /* Best domain verification status of the activities found in the other profile */ 6694 int bestDomainVerificationStatus; 6695 } 6696 6697 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 6698 String resolvedType, int flags, int sourceUserId, int parentUserId) { 6699 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 6700 sourceUserId)) { 6701 return null; 6702 } 6703 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 6704 resolvedType, flags, parentUserId); 6705 6706 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 6707 return null; 6708 } 6709 CrossProfileDomainInfo result = null; 6710 int size = resultTargetUser.size(); 6711 for (int i = 0; i < size; i++) { 6712 ResolveInfo riTargetUser = resultTargetUser.get(i); 6713 // Intent filter verification is only for filters that specify a host. So don't return 6714 // those that handle all web uris. 6715 if (riTargetUser.handleAllWebDataURI) { 6716 continue; 6717 } 6718 String packageName = riTargetUser.activityInfo.packageName; 6719 PackageSetting ps = mSettings.mPackages.get(packageName); 6720 if (ps == null) { 6721 continue; 6722 } 6723 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 6724 int status = (int)(verificationState >> 32); 6725 if (result == null) { 6726 result = new CrossProfileDomainInfo(); 6727 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 6728 sourceUserId, parentUserId); 6729 result.bestDomainVerificationStatus = status; 6730 } else { 6731 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 6732 result.bestDomainVerificationStatus); 6733 } 6734 } 6735 // Don't consider matches with status NEVER across profiles. 6736 if (result != null && result.bestDomainVerificationStatus 6737 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6738 return null; 6739 } 6740 return result; 6741 } 6742 6743 /** 6744 * Verification statuses are ordered from the worse to the best, except for 6745 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 6746 */ 6747 private int bestDomainVerificationStatus(int status1, int status2) { 6748 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6749 return status2; 6750 } 6751 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6752 return status1; 6753 } 6754 return (int) MathUtils.max(status1, status2); 6755 } 6756 6757 private boolean isUserEnabled(int userId) { 6758 long callingId = Binder.clearCallingIdentity(); 6759 try { 6760 UserInfo userInfo = sUserManager.getUserInfo(userId); 6761 return userInfo != null && userInfo.isEnabled(); 6762 } finally { 6763 Binder.restoreCallingIdentity(callingId); 6764 } 6765 } 6766 6767 /** 6768 * Filter out activities with systemUserOnly flag set, when current user is not System. 6769 * 6770 * @return filtered list 6771 */ 6772 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 6773 if (userId == UserHandle.USER_SYSTEM) { 6774 return resolveInfos; 6775 } 6776 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 6777 ResolveInfo info = resolveInfos.get(i); 6778 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 6779 resolveInfos.remove(i); 6780 } 6781 } 6782 return resolveInfos; 6783 } 6784 6785 /** 6786 * Filters out ephemeral activities. 6787 * <p>When resolving for an ephemeral app, only activities that 1) are defined in the 6788 * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned. 6789 * 6790 * @param resolveInfos The pre-filtered list of resolved activities 6791 * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering 6792 * is performed. 6793 * @return A filtered list of resolved activities. 6794 */ 6795 private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos, 6796 String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, int userId) { 6797 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 6798 final ResolveInfo info = resolveInfos.get(i); 6799 // allow activities that are defined in the provided package 6800 if (allowDynamicSplits 6801 && info.activityInfo.splitName != null 6802 && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames, 6803 info.activityInfo.splitName)) { 6804 if (mInstantAppInstallerInfo == null) { 6805 if (DEBUG_INSTALL) { 6806 Slog.v(TAG, "No installer - not adding it to the ResolveInfo list"); 6807 } 6808 resolveInfos.remove(i); 6809 continue; 6810 } 6811 // requested activity is defined in a split that hasn't been installed yet. 6812 // add the installer to the resolve list 6813 if (DEBUG_INSTALL) { 6814 Slog.v(TAG, "Adding installer to the ResolveInfo list"); 6815 } 6816 final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo); 6817 final ComponentName installFailureActivity = findInstallFailureActivity( 6818 info.activityInfo.packageName, filterCallingUid, userId); 6819 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 6820 info.activityInfo.packageName, info.activityInfo.splitName, 6821 installFailureActivity, 6822 info.activityInfo.applicationInfo.versionCode, 6823 null /*failureIntent*/); 6824 installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 6825 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 6826 // add a non-generic filter 6827 installerInfo.filter = new IntentFilter(); 6828 6829 // This resolve info may appear in the chooser UI, so let us make it 6830 // look as the one it replaces as far as the user is concerned which 6831 // requires loading the correct label and icon for the resolve info. 6832 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 6833 installerInfo.labelRes = info.resolveLabelResId(); 6834 installerInfo.icon = info.resolveIconResId(); 6835 6836 // propagate priority/preferred order/default 6837 installerInfo.priority = info.priority; 6838 installerInfo.preferredOrder = info.preferredOrder; 6839 installerInfo.isDefault = info.isDefault; 6840 resolveInfos.set(i, installerInfo); 6841 continue; 6842 } 6843 // caller is a full app, don't need to apply any other filtering 6844 if (ephemeralPkgName == null) { 6845 continue; 6846 } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) { 6847 // caller is same app; don't need to apply any other filtering 6848 continue; 6849 } 6850 // allow activities that have been explicitly exposed to ephemeral apps 6851 final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp(); 6852 if (!isEphemeralApp 6853 && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) { 6854 continue; 6855 } 6856 resolveInfos.remove(i); 6857 } 6858 return resolveInfos; 6859 } 6860 6861 /** 6862 * Returns the activity component that can handle install failures. 6863 * <p>By default, the instant application installer handles failures. However, an 6864 * application may want to handle failures on its own. Applications do this by 6865 * creating an activity with an intent filter that handles the action 6866 * {@link Intent#ACTION_INSTALL_FAILURE}. 6867 */ 6868 private @Nullable ComponentName findInstallFailureActivity( 6869 String packageName, int filterCallingUid, int userId) { 6870 final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE); 6871 failureActivityIntent.setPackage(packageName); 6872 // IMPORTANT: disallow dynamic splits to avoid an infinite loop 6873 final List<ResolveInfo> result = queryIntentActivitiesInternal( 6874 failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId, 6875 false /*resolveForStart*/, false /*allowDynamicSplits*/); 6876 final int NR = result.size(); 6877 if (NR > 0) { 6878 for (int i = 0; i < NR; i++) { 6879 final ResolveInfo info = result.get(i); 6880 if (info.activityInfo.splitName != null) { 6881 continue; 6882 } 6883 return new ComponentName(packageName, info.activityInfo.name); 6884 } 6885 } 6886 return null; 6887 } 6888 6889 /** 6890 * @param resolveInfos list of resolve infos in descending priority order 6891 * @return if the list contains a resolve info with non-negative priority 6892 */ 6893 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 6894 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 6895 } 6896 6897 private static boolean hasWebURI(Intent intent) { 6898 if (intent.getData() == null) { 6899 return false; 6900 } 6901 final String scheme = intent.getScheme(); 6902 if (TextUtils.isEmpty(scheme)) { 6903 return false; 6904 } 6905 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 6906 } 6907 6908 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 6909 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 6910 int userId) { 6911 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 6912 6913 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 6914 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 6915 candidates.size()); 6916 } 6917 6918 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 6919 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 6920 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 6921 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 6922 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 6923 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 6924 6925 synchronized (mPackages) { 6926 final int count = candidates.size(); 6927 // First, try to use linked apps. Partition the candidates into four lists: 6928 // one for the final results, one for the "do not use ever", one for "undefined status" 6929 // and finally one for "browser app type". 6930 for (int n=0; n<count; n++) { 6931 ResolveInfo info = candidates.get(n); 6932 String packageName = info.activityInfo.packageName; 6933 PackageSetting ps = mSettings.mPackages.get(packageName); 6934 if (ps != null) { 6935 // Add to the special match all list (Browser use case) 6936 if (info.handleAllWebDataURI) { 6937 matchAllList.add(info); 6938 continue; 6939 } 6940 // Try to get the status from User settings first 6941 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 6942 int status = (int)(packedStatus >> 32); 6943 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 6944 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 6945 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6946 Slog.i(TAG, " + always: " + info.activityInfo.packageName 6947 + " : linkgen=" + linkGeneration); 6948 } 6949 // Use link-enabled generation as preferredOrder, i.e. 6950 // prefer newly-enabled over earlier-enabled. 6951 info.preferredOrder = linkGeneration; 6952 alwaysList.add(info); 6953 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6954 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6955 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 6956 } 6957 neverList.add(info); 6958 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 6959 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6960 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 6961 } 6962 alwaysAskList.add(info); 6963 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 6964 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 6965 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6966 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 6967 } 6968 undefinedList.add(info); 6969 } 6970 } 6971 } 6972 6973 // We'll want to include browser possibilities in a few cases 6974 boolean includeBrowser = false; 6975 6976 // First try to add the "always" resolution(s) for the current user, if any 6977 if (alwaysList.size() > 0) { 6978 result.addAll(alwaysList); 6979 } else { 6980 // Add all undefined apps as we want them to appear in the disambiguation dialog. 6981 result.addAll(undefinedList); 6982 // Maybe add one for the other profile. 6983 if (xpDomainInfo != null && ( 6984 xpDomainInfo.bestDomainVerificationStatus 6985 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 6986 result.add(xpDomainInfo.resolveInfo); 6987 } 6988 includeBrowser = true; 6989 } 6990 6991 // The presence of any 'always ask' alternatives means we'll also offer browsers. 6992 // If there were 'always' entries their preferred order has been set, so we also 6993 // back that off to make the alternatives equivalent 6994 if (alwaysAskList.size() > 0) { 6995 for (ResolveInfo i : result) { 6996 i.preferredOrder = 0; 6997 } 6998 result.addAll(alwaysAskList); 6999 includeBrowser = true; 7000 } 7001 7002 if (includeBrowser) { 7003 // Also add browsers (all of them or only the default one) 7004 if (DEBUG_DOMAIN_VERIFICATION) { 7005 Slog.v(TAG, " ...including browsers in candidate set"); 7006 } 7007 if ((matchFlags & MATCH_ALL) != 0) { 7008 result.addAll(matchAllList); 7009 } else { 7010 // Browser/generic handling case. If there's a default browser, go straight 7011 // to that (but only if there is no other higher-priority match). 7012 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 7013 int maxMatchPrio = 0; 7014 ResolveInfo defaultBrowserMatch = null; 7015 final int numCandidates = matchAllList.size(); 7016 for (int n = 0; n < numCandidates; n++) { 7017 ResolveInfo info = matchAllList.get(n); 7018 // track the highest overall match priority... 7019 if (info.priority > maxMatchPrio) { 7020 maxMatchPrio = info.priority; 7021 } 7022 // ...and the highest-priority default browser match 7023 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 7024 if (defaultBrowserMatch == null 7025 || (defaultBrowserMatch.priority < info.priority)) { 7026 if (debug) { 7027 Slog.v(TAG, "Considering default browser match " + info); 7028 } 7029 defaultBrowserMatch = info; 7030 } 7031 } 7032 } 7033 if (defaultBrowserMatch != null 7034 && defaultBrowserMatch.priority >= maxMatchPrio 7035 && !TextUtils.isEmpty(defaultBrowserPackageName)) 7036 { 7037 if (debug) { 7038 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 7039 } 7040 result.add(defaultBrowserMatch); 7041 } else { 7042 result.addAll(matchAllList); 7043 } 7044 } 7045 7046 // If there is nothing selected, add all candidates and remove the ones that the user 7047 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 7048 if (result.size() == 0) { 7049 result.addAll(candidates); 7050 result.removeAll(neverList); 7051 } 7052 } 7053 } 7054 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 7055 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 7056 result.size()); 7057 for (ResolveInfo info : result) { 7058 Slog.v(TAG, " + " + info.activityInfo); 7059 } 7060 } 7061 return result; 7062 } 7063 7064 // Returns a packed value as a long: 7065 // 7066 // high 'int'-sized word: link status: undefined/ask/never/always. 7067 // low 'int'-sized word: relative priority among 'always' results. 7068 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 7069 long result = ps.getDomainVerificationStatusForUser(userId); 7070 // if none available, get the master status 7071 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 7072 if (ps.getIntentFilterVerificationInfo() != null) { 7073 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 7074 } 7075 } 7076 return result; 7077 } 7078 7079 private ResolveInfo querySkipCurrentProfileIntents( 7080 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 7081 int flags, int sourceUserId) { 7082 if (matchingFilters != null) { 7083 int size = matchingFilters.size(); 7084 for (int i = 0; i < size; i ++) { 7085 CrossProfileIntentFilter filter = matchingFilters.get(i); 7086 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 7087 // Checking if there are activities in the target user that can handle the 7088 // intent. 7089 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 7090 resolvedType, flags, sourceUserId); 7091 if (resolveInfo != null) { 7092 return resolveInfo; 7093 } 7094 } 7095 } 7096 } 7097 return null; 7098 } 7099 7100 // Return matching ResolveInfo in target user if any. 7101 private ResolveInfo queryCrossProfileIntents( 7102 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 7103 int flags, int sourceUserId, boolean matchInCurrentProfile) { 7104 if (matchingFilters != null) { 7105 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 7106 // match the same intent. For performance reasons, it is better not to 7107 // run queryIntent twice for the same userId 7108 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 7109 int size = matchingFilters.size(); 7110 for (int i = 0; i < size; i++) { 7111 CrossProfileIntentFilter filter = matchingFilters.get(i); 7112 int targetUserId = filter.getTargetUserId(); 7113 boolean skipCurrentProfile = 7114 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 7115 boolean skipCurrentProfileIfNoMatchFound = 7116 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 7117 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 7118 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 7119 // Checking if there are activities in the target user that can handle the 7120 // intent. 7121 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 7122 resolvedType, flags, sourceUserId); 7123 if (resolveInfo != null) return resolveInfo; 7124 alreadyTriedUserIds.put(targetUserId, true); 7125 } 7126 } 7127 } 7128 return null; 7129 } 7130 7131 /** 7132 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 7133 * will forward the intent to the filter's target user. 7134 * Otherwise, returns null. 7135 */ 7136 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 7137 String resolvedType, int flags, int sourceUserId) { 7138 int targetUserId = filter.getTargetUserId(); 7139 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 7140 resolvedType, flags, targetUserId); 7141 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 7142 // If all the matches in the target profile are suspended, return null. 7143 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 7144 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 7145 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 7146 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 7147 targetUserId); 7148 } 7149 } 7150 } 7151 return null; 7152 } 7153 7154 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 7155 int sourceUserId, int targetUserId) { 7156 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 7157 long ident = Binder.clearCallingIdentity(); 7158 boolean targetIsProfile; 7159 try { 7160 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 7161 } finally { 7162 Binder.restoreCallingIdentity(ident); 7163 } 7164 String className; 7165 if (targetIsProfile) { 7166 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 7167 } else { 7168 className = FORWARD_INTENT_TO_PARENT; 7169 } 7170 ComponentName forwardingActivityComponentName = new ComponentName( 7171 mAndroidApplication.packageName, className); 7172 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 7173 sourceUserId); 7174 if (!targetIsProfile) { 7175 forwardingActivityInfo.showUserIcon = targetUserId; 7176 forwardingResolveInfo.noResourceId = true; 7177 } 7178 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 7179 forwardingResolveInfo.priority = 0; 7180 forwardingResolveInfo.preferredOrder = 0; 7181 forwardingResolveInfo.match = 0; 7182 forwardingResolveInfo.isDefault = true; 7183 forwardingResolveInfo.filter = filter; 7184 forwardingResolveInfo.targetUserId = targetUserId; 7185 return forwardingResolveInfo; 7186 } 7187 7188 @Override 7189 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 7190 Intent[] specifics, String[] specificTypes, Intent intent, 7191 String resolvedType, int flags, int userId) { 7192 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 7193 specificTypes, intent, resolvedType, flags, userId)); 7194 } 7195 7196 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 7197 Intent[] specifics, String[] specificTypes, Intent intent, 7198 String resolvedType, int flags, int userId) { 7199 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7200 final int callingUid = Binder.getCallingUid(); 7201 flags = updateFlagsForResolve(flags, userId, intent, callingUid, 7202 false /*includeInstantApps*/); 7203 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 7204 false /*requireFullPermission*/, false /*checkShell*/, 7205 "query intent activity options"); 7206 final String resultsAction = intent.getAction(); 7207 7208 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 7209 | PackageManager.GET_RESOLVED_FILTER, userId); 7210 7211 if (DEBUG_INTENT_MATCHING) { 7212 Log.v(TAG, "Query " + intent + ": " + results); 7213 } 7214 7215 int specificsPos = 0; 7216 int N; 7217 7218 // todo: note that the algorithm used here is O(N^2). This 7219 // isn't a problem in our current environment, but if we start running 7220 // into situations where we have more than 5 or 10 matches then this 7221 // should probably be changed to something smarter... 7222 7223 // First we go through and resolve each of the specific items 7224 // that were supplied, taking care of removing any corresponding 7225 // duplicate items in the generic resolve list. 7226 if (specifics != null) { 7227 for (int i=0; i<specifics.length; i++) { 7228 final Intent sintent = specifics[i]; 7229 if (sintent == null) { 7230 continue; 7231 } 7232 7233 if (DEBUG_INTENT_MATCHING) { 7234 Log.v(TAG, "Specific #" + i + ": " + sintent); 7235 } 7236 7237 String action = sintent.getAction(); 7238 if (resultsAction != null && resultsAction.equals(action)) { 7239 // If this action was explicitly requested, then don't 7240 // remove things that have it. 7241 action = null; 7242 } 7243 7244 ResolveInfo ri = null; 7245 ActivityInfo ai = null; 7246 7247 ComponentName comp = sintent.getComponent(); 7248 if (comp == null) { 7249 ri = resolveIntent( 7250 sintent, 7251 specificTypes != null ? specificTypes[i] : null, 7252 flags, userId); 7253 if (ri == null) { 7254 continue; 7255 } 7256 if (ri == mResolveInfo) { 7257 // ACK! Must do something better with this. 7258 } 7259 ai = ri.activityInfo; 7260 comp = new ComponentName(ai.applicationInfo.packageName, 7261 ai.name); 7262 } else { 7263 ai = getActivityInfo(comp, flags, userId); 7264 if (ai == null) { 7265 continue; 7266 } 7267 } 7268 7269 // Look for any generic query activities that are duplicates 7270 // of this specific one, and remove them from the results. 7271 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 7272 N = results.size(); 7273 int j; 7274 for (j=specificsPos; j<N; j++) { 7275 ResolveInfo sri = results.get(j); 7276 if ((sri.activityInfo.name.equals(comp.getClassName()) 7277 && sri.activityInfo.applicationInfo.packageName.equals( 7278 comp.getPackageName())) 7279 || (action != null && sri.filter.matchAction(action))) { 7280 results.remove(j); 7281 if (DEBUG_INTENT_MATCHING) Log.v( 7282 TAG, "Removing duplicate item from " + j 7283 + " due to specific " + specificsPos); 7284 if (ri == null) { 7285 ri = sri; 7286 } 7287 j--; 7288 N--; 7289 } 7290 } 7291 7292 // Add this specific item to its proper place. 7293 if (ri == null) { 7294 ri = new ResolveInfo(); 7295 ri.activityInfo = ai; 7296 } 7297 results.add(specificsPos, ri); 7298 ri.specificIndex = i; 7299 specificsPos++; 7300 } 7301 } 7302 7303 // Now we go through the remaining generic results and remove any 7304 // duplicate actions that are found here. 7305 N = results.size(); 7306 for (int i=specificsPos; i<N-1; i++) { 7307 final ResolveInfo rii = results.get(i); 7308 if (rii.filter == null) { 7309 continue; 7310 } 7311 7312 // Iterate over all of the actions of this result's intent 7313 // filter... typically this should be just one. 7314 final Iterator<String> it = rii.filter.actionsIterator(); 7315 if (it == null) { 7316 continue; 7317 } 7318 while (it.hasNext()) { 7319 final String action = it.next(); 7320 if (resultsAction != null && resultsAction.equals(action)) { 7321 // If this action was explicitly requested, then don't 7322 // remove things that have it. 7323 continue; 7324 } 7325 for (int j=i+1; j<N; j++) { 7326 final ResolveInfo rij = results.get(j); 7327 if (rij.filter != null && rij.filter.hasAction(action)) { 7328 results.remove(j); 7329 if (DEBUG_INTENT_MATCHING) Log.v( 7330 TAG, "Removing duplicate item from " + j 7331 + " due to action " + action + " at " + i); 7332 j--; 7333 N--; 7334 } 7335 } 7336 } 7337 7338 // If the caller didn't request filter information, drop it now 7339 // so we don't have to marshall/unmarshall it. 7340 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 7341 rii.filter = null; 7342 } 7343 } 7344 7345 // Filter out the caller activity if so requested. 7346 if (caller != null) { 7347 N = results.size(); 7348 for (int i=0; i<N; i++) { 7349 ActivityInfo ainfo = results.get(i).activityInfo; 7350 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 7351 && caller.getClassName().equals(ainfo.name)) { 7352 results.remove(i); 7353 break; 7354 } 7355 } 7356 } 7357 7358 // If the caller didn't request filter information, 7359 // drop them now so we don't have to 7360 // marshall/unmarshall it. 7361 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 7362 N = results.size(); 7363 for (int i=0; i<N; i++) { 7364 results.get(i).filter = null; 7365 } 7366 } 7367 7368 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 7369 return results; 7370 } 7371 7372 @Override 7373 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 7374 String resolvedType, int flags, int userId) { 7375 return new ParceledListSlice<>( 7376 queryIntentReceiversInternal(intent, resolvedType, flags, userId, 7377 false /*allowDynamicSplits*/)); 7378 } 7379 7380 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 7381 String resolvedType, int flags, int userId, boolean allowDynamicSplits) { 7382 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7383 final int callingUid = Binder.getCallingUid(); 7384 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 7385 false /*requireFullPermission*/, false /*checkShell*/, 7386 "query intent receivers"); 7387 final String instantAppPkgName = getInstantAppPackageName(callingUid); 7388 flags = updateFlagsForResolve(flags, userId, intent, callingUid, 7389 false /*includeInstantApps*/); 7390 ComponentName comp = intent.getComponent(); 7391 if (comp == null) { 7392 if (intent.getSelector() != null) { 7393 intent = intent.getSelector(); 7394 comp = intent.getComponent(); 7395 } 7396 } 7397 if (comp != null) { 7398 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7399 final ActivityInfo ai = getReceiverInfo(comp, flags, userId); 7400 if (ai != null) { 7401 // When specifying an explicit component, we prevent the activity from being 7402 // used when either 1) the calling package is normal and the activity is within 7403 // an instant application or 2) the calling package is ephemeral and the 7404 // activity is not visible to instant applications. 7405 final boolean matchInstantApp = 7406 (flags & PackageManager.MATCH_INSTANT) != 0; 7407 final boolean matchVisibleToInstantAppOnly = 7408 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 7409 final boolean matchExplicitlyVisibleOnly = 7410 (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0; 7411 final boolean isCallerInstantApp = 7412 instantAppPkgName != null; 7413 final boolean isTargetSameInstantApp = 7414 comp.getPackageName().equals(instantAppPkgName); 7415 final boolean isTargetInstantApp = 7416 (ai.applicationInfo.privateFlags 7417 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 7418 final boolean isTargetVisibleToInstantApp = 7419 (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0; 7420 final boolean isTargetExplicitlyVisibleToInstantApp = 7421 isTargetVisibleToInstantApp 7422 && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0; 7423 final boolean isTargetHiddenFromInstantApp = 7424 !isTargetVisibleToInstantApp 7425 || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp); 7426 final boolean blockResolution = 7427 !isTargetSameInstantApp 7428 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 7429 || (matchVisibleToInstantAppOnly && isCallerInstantApp 7430 && isTargetHiddenFromInstantApp)); 7431 if (!blockResolution) { 7432 ResolveInfo ri = new ResolveInfo(); 7433 ri.activityInfo = ai; 7434 list.add(ri); 7435 } 7436 } 7437 return applyPostResolutionFilter( 7438 list, instantAppPkgName, allowDynamicSplits, callingUid, userId); 7439 } 7440 7441 // reader 7442 synchronized (mPackages) { 7443 String pkgName = intent.getPackage(); 7444 if (pkgName == null) { 7445 final List<ResolveInfo> result = 7446 mReceivers.queryIntent(intent, resolvedType, flags, userId); 7447 return applyPostResolutionFilter( 7448 result, instantAppPkgName, allowDynamicSplits, callingUid, userId); 7449 } 7450 final PackageParser.Package pkg = mPackages.get(pkgName); 7451 if (pkg != null) { 7452 final List<ResolveInfo> result = mReceivers.queryIntentForPackage( 7453 intent, resolvedType, flags, pkg.receivers, userId); 7454 return applyPostResolutionFilter( 7455 result, instantAppPkgName, allowDynamicSplits, callingUid, userId); 7456 } 7457 return Collections.emptyList(); 7458 } 7459 } 7460 7461 @Override 7462 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 7463 final int callingUid = Binder.getCallingUid(); 7464 return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid); 7465 } 7466 7467 private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags, 7468 int userId, int callingUid) { 7469 if (!sUserManager.exists(userId)) return null; 7470 flags = updateFlagsForResolve( 7471 flags, userId, intent, callingUid, false /*includeInstantApps*/); 7472 List<ResolveInfo> query = queryIntentServicesInternal( 7473 intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/); 7474 if (query != null) { 7475 if (query.size() >= 1) { 7476 // If there is more than one service with the same priority, 7477 // just arbitrarily pick the first one. 7478 return query.get(0); 7479 } 7480 } 7481 return null; 7482 } 7483 7484 @Override 7485 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 7486 String resolvedType, int flags, int userId) { 7487 final int callingUid = Binder.getCallingUid(); 7488 return new ParceledListSlice<>(queryIntentServicesInternal( 7489 intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/)); 7490 } 7491 7492 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 7493 String resolvedType, int flags, int userId, int callingUid, 7494 boolean includeInstantApps) { 7495 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7496 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 7497 false /*requireFullPermission*/, false /*checkShell*/, 7498 "query intent receivers"); 7499 final String instantAppPkgName = getInstantAppPackageName(callingUid); 7500 flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps); 7501 ComponentName comp = intent.getComponent(); 7502 if (comp == null) { 7503 if (intent.getSelector() != null) { 7504 intent = intent.getSelector(); 7505 comp = intent.getComponent(); 7506 } 7507 } 7508 if (comp != null) { 7509 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7510 final ServiceInfo si = getServiceInfo(comp, flags, userId); 7511 if (si != null) { 7512 // When specifying an explicit component, we prevent the service from being 7513 // used when either 1) the service is in an instant application and the 7514 // caller is not the same instant application or 2) the calling package is 7515 // ephemeral and the activity is not visible to ephemeral applications. 7516 final boolean matchInstantApp = 7517 (flags & PackageManager.MATCH_INSTANT) != 0; 7518 final boolean matchVisibleToInstantAppOnly = 7519 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 7520 final boolean isCallerInstantApp = 7521 instantAppPkgName != null; 7522 final boolean isTargetSameInstantApp = 7523 comp.getPackageName().equals(instantAppPkgName); 7524 final boolean isTargetInstantApp = 7525 (si.applicationInfo.privateFlags 7526 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 7527 final boolean isTargetHiddenFromInstantApp = 7528 (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0; 7529 final boolean blockResolution = 7530 !isTargetSameInstantApp 7531 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 7532 || (matchVisibleToInstantAppOnly && isCallerInstantApp 7533 && isTargetHiddenFromInstantApp)); 7534 if (!blockResolution) { 7535 final ResolveInfo ri = new ResolveInfo(); 7536 ri.serviceInfo = si; 7537 list.add(ri); 7538 } 7539 } 7540 return list; 7541 } 7542 7543 // reader 7544 synchronized (mPackages) { 7545 String pkgName = intent.getPackage(); 7546 if (pkgName == null) { 7547 return applyPostServiceResolutionFilter( 7548 mServices.queryIntent(intent, resolvedType, flags, userId), 7549 instantAppPkgName); 7550 } 7551 final PackageParser.Package pkg = mPackages.get(pkgName); 7552 if (pkg != null) { 7553 return applyPostServiceResolutionFilter( 7554 mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 7555 userId), 7556 instantAppPkgName); 7557 } 7558 return Collections.emptyList(); 7559 } 7560 } 7561 7562 private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos, 7563 String instantAppPkgName) { 7564 if (instantAppPkgName == null) { 7565 return resolveInfos; 7566 } 7567 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 7568 final ResolveInfo info = resolveInfos.get(i); 7569 final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp(); 7570 // allow services that are defined in the provided package 7571 if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) { 7572 if (info.serviceInfo.splitName != null 7573 && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames, 7574 info.serviceInfo.splitName)) { 7575 // requested service is defined in a split that hasn't been installed yet. 7576 // add the installer to the resolve list 7577 if (DEBUG_EPHEMERAL) { 7578 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 7579 } 7580 final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo); 7581 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 7582 info.serviceInfo.packageName, info.serviceInfo.splitName, 7583 null /*failureActivity*/, info.serviceInfo.applicationInfo.versionCode, 7584 null /*failureIntent*/); 7585 // make sure this resolver is the default 7586 installerInfo.isDefault = true; 7587 installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 7588 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 7589 // add a non-generic filter 7590 installerInfo.filter = new IntentFilter(); 7591 // load resources from the correct package 7592 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 7593 resolveInfos.set(i, installerInfo); 7594 } 7595 continue; 7596 } 7597 // allow services that have been explicitly exposed to ephemeral apps 7598 if (!isEphemeralApp 7599 && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) { 7600 continue; 7601 } 7602 resolveInfos.remove(i); 7603 } 7604 return resolveInfos; 7605 } 7606 7607 @Override 7608 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 7609 String resolvedType, int flags, int userId) { 7610 return new ParceledListSlice<>( 7611 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 7612 } 7613 7614 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 7615 Intent intent, String resolvedType, int flags, int userId) { 7616 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7617 final int callingUid = Binder.getCallingUid(); 7618 final String instantAppPkgName = getInstantAppPackageName(callingUid); 7619 flags = updateFlagsForResolve(flags, userId, intent, callingUid, 7620 false /*includeInstantApps*/); 7621 ComponentName comp = intent.getComponent(); 7622 if (comp == null) { 7623 if (intent.getSelector() != null) { 7624 intent = intent.getSelector(); 7625 comp = intent.getComponent(); 7626 } 7627 } 7628 if (comp != null) { 7629 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7630 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 7631 if (pi != null) { 7632 // When specifying an explicit component, we prevent the provider from being 7633 // used when either 1) the provider is in an instant application and the 7634 // caller is not the same instant application or 2) the calling package is an 7635 // instant application and the provider is not visible to instant applications. 7636 final boolean matchInstantApp = 7637 (flags & PackageManager.MATCH_INSTANT) != 0; 7638 final boolean matchVisibleToInstantAppOnly = 7639 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 7640 final boolean isCallerInstantApp = 7641 instantAppPkgName != null; 7642 final boolean isTargetSameInstantApp = 7643 comp.getPackageName().equals(instantAppPkgName); 7644 final boolean isTargetInstantApp = 7645 (pi.applicationInfo.privateFlags 7646 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 7647 final boolean isTargetHiddenFromInstantApp = 7648 (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0; 7649 final boolean blockResolution = 7650 !isTargetSameInstantApp 7651 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 7652 || (matchVisibleToInstantAppOnly && isCallerInstantApp 7653 && isTargetHiddenFromInstantApp)); 7654 if (!blockResolution) { 7655 final ResolveInfo ri = new ResolveInfo(); 7656 ri.providerInfo = pi; 7657 list.add(ri); 7658 } 7659 } 7660 return list; 7661 } 7662 7663 // reader 7664 synchronized (mPackages) { 7665 String pkgName = intent.getPackage(); 7666 if (pkgName == null) { 7667 return applyPostContentProviderResolutionFilter( 7668 mProviders.queryIntent(intent, resolvedType, flags, userId), 7669 instantAppPkgName); 7670 } 7671 final PackageParser.Package pkg = mPackages.get(pkgName); 7672 if (pkg != null) { 7673 return applyPostContentProviderResolutionFilter( 7674 mProviders.queryIntentForPackage( 7675 intent, resolvedType, flags, pkg.providers, userId), 7676 instantAppPkgName); 7677 } 7678 return Collections.emptyList(); 7679 } 7680 } 7681 7682 private List<ResolveInfo> applyPostContentProviderResolutionFilter( 7683 List<ResolveInfo> resolveInfos, String instantAppPkgName) { 7684 if (instantAppPkgName == null) { 7685 return resolveInfos; 7686 } 7687 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 7688 final ResolveInfo info = resolveInfos.get(i); 7689 final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp(); 7690 // allow providers that are defined in the provided package 7691 if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) { 7692 if (info.providerInfo.splitName != null 7693 && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames, 7694 info.providerInfo.splitName)) { 7695 // requested provider is defined in a split that hasn't been installed yet. 7696 // add the installer to the resolve list 7697 if (DEBUG_EPHEMERAL) { 7698 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 7699 } 7700 final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo); 7701 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 7702 info.providerInfo.packageName, info.providerInfo.splitName, 7703 null /*failureActivity*/, info.providerInfo.applicationInfo.versionCode, 7704 null /*failureIntent*/); 7705 // make sure this resolver is the default 7706 installerInfo.isDefault = true; 7707 installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 7708 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 7709 // add a non-generic filter 7710 installerInfo.filter = new IntentFilter(); 7711 // load resources from the correct package 7712 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 7713 resolveInfos.set(i, installerInfo); 7714 } 7715 continue; 7716 } 7717 // allow providers that have been explicitly exposed to instant applications 7718 if (!isEphemeralApp 7719 && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) { 7720 continue; 7721 } 7722 resolveInfos.remove(i); 7723 } 7724 return resolveInfos; 7725 } 7726 7727 @Override 7728 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 7729 final int callingUid = Binder.getCallingUid(); 7730 if (getInstantAppPackageName(callingUid) != null) { 7731 return ParceledListSlice.emptyList(); 7732 } 7733 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7734 flags = updateFlagsForPackage(flags, userId, null); 7735 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7736 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 7737 true /* requireFullPermission */, false /* checkShell */, 7738 "get installed packages"); 7739 7740 // writer 7741 synchronized (mPackages) { 7742 ArrayList<PackageInfo> list; 7743 if (listUninstalled) { 7744 list = new ArrayList<>(mSettings.mPackages.size()); 7745 for (PackageSetting ps : mSettings.mPackages.values()) { 7746 if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) { 7747 continue; 7748 } 7749 if (filterAppAccessLPr(ps, callingUid, userId)) { 7750 continue; 7751 } 7752 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 7753 if (pi != null) { 7754 list.add(pi); 7755 } 7756 } 7757 } else { 7758 list = new ArrayList<>(mPackages.size()); 7759 for (PackageParser.Package p : mPackages.values()) { 7760 final PackageSetting ps = (PackageSetting) p.mExtras; 7761 if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) { 7762 continue; 7763 } 7764 if (filterAppAccessLPr(ps, callingUid, userId)) { 7765 continue; 7766 } 7767 final PackageInfo pi = generatePackageInfo((PackageSetting) 7768 p.mExtras, flags, userId); 7769 if (pi != null) { 7770 list.add(pi); 7771 } 7772 } 7773 } 7774 7775 return new ParceledListSlice<>(list); 7776 } 7777 } 7778 7779 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 7780 String[] permissions, boolean[] tmp, int flags, int userId) { 7781 int numMatch = 0; 7782 final PermissionsState permissionsState = ps.getPermissionsState(); 7783 for (int i=0; i<permissions.length; i++) { 7784 final String permission = permissions[i]; 7785 if (permissionsState.hasPermission(permission, userId)) { 7786 tmp[i] = true; 7787 numMatch++; 7788 } else { 7789 tmp[i] = false; 7790 } 7791 } 7792 if (numMatch == 0) { 7793 return; 7794 } 7795 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 7796 7797 // The above might return null in cases of uninstalled apps or install-state 7798 // skew across users/profiles. 7799 if (pi != null) { 7800 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 7801 if (numMatch == permissions.length) { 7802 pi.requestedPermissions = permissions; 7803 } else { 7804 pi.requestedPermissions = new String[numMatch]; 7805 numMatch = 0; 7806 for (int i=0; i<permissions.length; i++) { 7807 if (tmp[i]) { 7808 pi.requestedPermissions[numMatch] = permissions[i]; 7809 numMatch++; 7810 } 7811 } 7812 } 7813 } 7814 list.add(pi); 7815 } 7816 } 7817 7818 @Override 7819 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 7820 String[] permissions, int flags, int userId) { 7821 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7822 flags = updateFlagsForPackage(flags, userId, permissions); 7823 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 7824 true /* requireFullPermission */, false /* checkShell */, 7825 "get packages holding permissions"); 7826 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7827 7828 // writer 7829 synchronized (mPackages) { 7830 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 7831 boolean[] tmpBools = new boolean[permissions.length]; 7832 if (listUninstalled) { 7833 for (PackageSetting ps : mSettings.mPackages.values()) { 7834 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 7835 userId); 7836 } 7837 } else { 7838 for (PackageParser.Package pkg : mPackages.values()) { 7839 PackageSetting ps = (PackageSetting)pkg.mExtras; 7840 if (ps != null) { 7841 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 7842 userId); 7843 } 7844 } 7845 } 7846 7847 return new ParceledListSlice<PackageInfo>(list); 7848 } 7849 } 7850 7851 @Override 7852 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 7853 final int callingUid = Binder.getCallingUid(); 7854 if (getInstantAppPackageName(callingUid) != null) { 7855 return ParceledListSlice.emptyList(); 7856 } 7857 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7858 flags = updateFlagsForApplication(flags, userId, null); 7859 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7860 7861 // writer 7862 synchronized (mPackages) { 7863 ArrayList<ApplicationInfo> list; 7864 if (listUninstalled) { 7865 list = new ArrayList<>(mSettings.mPackages.size()); 7866 for (PackageSetting ps : mSettings.mPackages.values()) { 7867 ApplicationInfo ai; 7868 int effectiveFlags = flags; 7869 if (ps.isSystem()) { 7870 effectiveFlags |= PackageManager.MATCH_ANY_USER; 7871 } 7872 if (ps.pkg != null) { 7873 if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) { 7874 continue; 7875 } 7876 if (filterAppAccessLPr(ps, callingUid, userId)) { 7877 continue; 7878 } 7879 ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags, 7880 ps.readUserState(userId), userId); 7881 if (ai != null) { 7882 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 7883 } 7884 } else { 7885 // Shared lib filtering done in generateApplicationInfoFromSettingsLPw 7886 // and already converts to externally visible package name 7887 ai = generateApplicationInfoFromSettingsLPw(ps.name, 7888 callingUid, effectiveFlags, userId); 7889 } 7890 if (ai != null) { 7891 list.add(ai); 7892 } 7893 } 7894 } else { 7895 list = new ArrayList<>(mPackages.size()); 7896 for (PackageParser.Package p : mPackages.values()) { 7897 if (p.mExtras != null) { 7898 PackageSetting ps = (PackageSetting) p.mExtras; 7899 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) { 7900 continue; 7901 } 7902 if (filterAppAccessLPr(ps, callingUid, userId)) { 7903 continue; 7904 } 7905 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 7906 ps.readUserState(userId), userId); 7907 if (ai != null) { 7908 ai.packageName = resolveExternalPackageNameLPr(p); 7909 list.add(ai); 7910 } 7911 } 7912 } 7913 } 7914 7915 return new ParceledListSlice<>(list); 7916 } 7917 } 7918 7919 @Override 7920 public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) { 7921 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7922 return null; 7923 } 7924 if (!canViewInstantApps(Binder.getCallingUid(), userId)) { 7925 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS, 7926 "getEphemeralApplications"); 7927 } 7928 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 7929 true /* requireFullPermission */, false /* checkShell */, 7930 "getEphemeralApplications"); 7931 synchronized (mPackages) { 7932 List<InstantAppInfo> instantApps = mInstantAppRegistry 7933 .getInstantAppsLPr(userId); 7934 if (instantApps != null) { 7935 return new ParceledListSlice<>(instantApps); 7936 } 7937 } 7938 return null; 7939 } 7940 7941 @Override 7942 public boolean isInstantApp(String packageName, int userId) { 7943 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 7944 true /* requireFullPermission */, false /* checkShell */, 7945 "isInstantApp"); 7946 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7947 return false; 7948 } 7949 7950 synchronized (mPackages) { 7951 int callingUid = Binder.getCallingUid(); 7952 if (Process.isIsolated(callingUid)) { 7953 callingUid = mIsolatedOwners.get(callingUid); 7954 } 7955 final PackageSetting ps = mSettings.mPackages.get(packageName); 7956 PackageParser.Package pkg = mPackages.get(packageName); 7957 final boolean returnAllowed = 7958 ps != null 7959 && (isCallerSameApp(packageName, callingUid) 7960 || canViewInstantApps(callingUid, userId) 7961 || mInstantAppRegistry.isInstantAccessGranted( 7962 userId, UserHandle.getAppId(callingUid), ps.appId)); 7963 if (returnAllowed) { 7964 return ps.getInstantApp(userId); 7965 } 7966 } 7967 return false; 7968 } 7969 7970 @Override 7971 public byte[] getInstantAppCookie(String packageName, int userId) { 7972 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7973 return null; 7974 } 7975 7976 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 7977 true /* requireFullPermission */, false /* checkShell */, 7978 "getInstantAppCookie"); 7979 if (!isCallerSameApp(packageName, Binder.getCallingUid())) { 7980 return null; 7981 } 7982 synchronized (mPackages) { 7983 return mInstantAppRegistry.getInstantAppCookieLPw( 7984 packageName, userId); 7985 } 7986 } 7987 7988 @Override 7989 public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) { 7990 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7991 return true; 7992 } 7993 7994 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 7995 true /* requireFullPermission */, true /* checkShell */, 7996 "setInstantAppCookie"); 7997 if (!isCallerSameApp(packageName, Binder.getCallingUid())) { 7998 return false; 7999 } 8000 synchronized (mPackages) { 8001 return mInstantAppRegistry.setInstantAppCookieLPw( 8002 packageName, cookie, userId); 8003 } 8004 } 8005 8006 @Override 8007 public Bitmap getInstantAppIcon(String packageName, int userId) { 8008 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 8009 return null; 8010 } 8011 8012 if (!canViewInstantApps(Binder.getCallingUid(), userId)) { 8013 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS, 8014 "getInstantAppIcon"); 8015 } 8016 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 8017 true /* requireFullPermission */, false /* checkShell */, 8018 "getInstantAppIcon"); 8019 8020 synchronized (mPackages) { 8021 return mInstantAppRegistry.getInstantAppIconLPw( 8022 packageName, userId); 8023 } 8024 } 8025 8026 private boolean isCallerSameApp(String packageName, int uid) { 8027 PackageParser.Package pkg = mPackages.get(packageName); 8028 return pkg != null 8029 && UserHandle.getAppId(uid) == pkg.applicationInfo.uid; 8030 } 8031 8032 @Override 8033 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 8034 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 8035 return ParceledListSlice.emptyList(); 8036 } 8037 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 8038 } 8039 8040 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 8041 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 8042 8043 // reader 8044 synchronized (mPackages) { 8045 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 8046 final int userId = UserHandle.getCallingUserId(); 8047 while (i.hasNext()) { 8048 final PackageParser.Package p = i.next(); 8049 if (p.applicationInfo == null) continue; 8050 8051 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 8052 && !p.applicationInfo.isDirectBootAware(); 8053 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 8054 && p.applicationInfo.isDirectBootAware(); 8055 8056 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 8057 && (!mSafeMode || isSystemApp(p)) 8058 && (matchesUnaware || matchesAware)) { 8059 PackageSetting ps = mSettings.mPackages.get(p.packageName); 8060 if (ps != null) { 8061 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 8062 ps.readUserState(userId), userId); 8063 if (ai != null) { 8064 finalList.add(ai); 8065 } 8066 } 8067 } 8068 } 8069 } 8070 8071 return finalList; 8072 } 8073 8074 @Override 8075 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 8076 return resolveContentProviderInternal(name, flags, userId); 8077 } 8078 8079 private ProviderInfo resolveContentProviderInternal(String name, int flags, int userId) { 8080 if (!sUserManager.exists(userId)) return null; 8081 flags = updateFlagsForComponent(flags, userId, name); 8082 final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid()); 8083 // reader 8084 synchronized (mPackages) { 8085 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 8086 PackageSetting ps = provider != null 8087 ? mSettings.mPackages.get(provider.owner.packageName) 8088 : null; 8089 if (ps != null) { 8090 final boolean isInstantApp = ps.getInstantApp(userId); 8091 // normal application; filter out instant application provider 8092 if (instantAppPkgName == null && isInstantApp) { 8093 return null; 8094 } 8095 // instant application; filter out other instant applications 8096 if (instantAppPkgName != null 8097 && isInstantApp 8098 && !provider.owner.packageName.equals(instantAppPkgName)) { 8099 return null; 8100 } 8101 // instant application; filter out non-exposed provider 8102 if (instantAppPkgName != null 8103 && !isInstantApp 8104 && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) { 8105 return null; 8106 } 8107 // provider not enabled 8108 if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) { 8109 return null; 8110 } 8111 return PackageParser.generateProviderInfo( 8112 provider, flags, ps.readUserState(userId), userId); 8113 } 8114 return null; 8115 } 8116 } 8117 8118 /** 8119 * @deprecated 8120 */ 8121 @Deprecated 8122 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 8123 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 8124 return; 8125 } 8126 // reader 8127 synchronized (mPackages) { 8128 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 8129 .entrySet().iterator(); 8130 final int userId = UserHandle.getCallingUserId(); 8131 while (i.hasNext()) { 8132 Map.Entry<String, PackageParser.Provider> entry = i.next(); 8133 PackageParser.Provider p = entry.getValue(); 8134 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 8135 8136 if (ps != null && p.syncable 8137 && (!mSafeMode || (p.info.applicationInfo.flags 8138 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 8139 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 8140 ps.readUserState(userId), userId); 8141 if (info != null) { 8142 outNames.add(entry.getKey()); 8143 outInfo.add(info); 8144 } 8145 } 8146 } 8147 } 8148 } 8149 8150 @Override 8151 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 8152 int uid, int flags, String metaDataKey) { 8153 final int callingUid = Binder.getCallingUid(); 8154 final int userId = processName != null ? UserHandle.getUserId(uid) 8155 : UserHandle.getCallingUserId(); 8156 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 8157 flags = updateFlagsForComponent(flags, userId, processName); 8158 ArrayList<ProviderInfo> finalList = null; 8159 // reader 8160 synchronized (mPackages) { 8161 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 8162 while (i.hasNext()) { 8163 final PackageParser.Provider p = i.next(); 8164 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 8165 if (ps != null && p.info.authority != null 8166 && (processName == null 8167 || (p.info.processName.equals(processName) 8168 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 8169 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 8170 8171 // See PM.queryContentProviders()'s javadoc for why we have the metaData 8172 // parameter. 8173 if (metaDataKey != null 8174 && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) { 8175 continue; 8176 } 8177 final ComponentName component = 8178 new ComponentName(p.info.packageName, p.info.name); 8179 if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) { 8180 continue; 8181 } 8182 if (finalList == null) { 8183 finalList = new ArrayList<ProviderInfo>(3); 8184 } 8185 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 8186 ps.readUserState(userId), userId); 8187 if (info != null) { 8188 finalList.add(info); 8189 } 8190 } 8191 } 8192 } 8193 8194 if (finalList != null) { 8195 Collections.sort(finalList, mProviderInitOrderSorter); 8196 return new ParceledListSlice<ProviderInfo>(finalList); 8197 } 8198 8199 return ParceledListSlice.emptyList(); 8200 } 8201 8202 @Override 8203 public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) { 8204 // reader 8205 synchronized (mPackages) { 8206 final int callingUid = Binder.getCallingUid(); 8207 final int callingUserId = UserHandle.getUserId(callingUid); 8208 final PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 8209 if (ps == null) return null; 8210 if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) { 8211 return null; 8212 } 8213 final PackageParser.Instrumentation i = mInstrumentation.get(component); 8214 return PackageParser.generateInstrumentationInfo(i, flags); 8215 } 8216 } 8217 8218 @Override 8219 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 8220 String targetPackage, int flags) { 8221 final int callingUid = Binder.getCallingUid(); 8222 final int callingUserId = UserHandle.getUserId(callingUid); 8223 final PackageSetting ps = mSettings.mPackages.get(targetPackage); 8224 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 8225 return ParceledListSlice.emptyList(); 8226 } 8227 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 8228 } 8229 8230 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 8231 int flags) { 8232 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 8233 8234 // reader 8235 synchronized (mPackages) { 8236 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 8237 while (i.hasNext()) { 8238 final PackageParser.Instrumentation p = i.next(); 8239 if (targetPackage == null 8240 || targetPackage.equals(p.info.targetPackage)) { 8241 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 8242 flags); 8243 if (ii != null) { 8244 finalList.add(ii); 8245 } 8246 } 8247 } 8248 } 8249 8250 return finalList; 8251 } 8252 8253 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 8254 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]"); 8255 try { 8256 scanDirLI(dir, parseFlags, scanFlags, currentTime); 8257 } finally { 8258 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8259 } 8260 } 8261 8262 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 8263 final File[] files = dir.listFiles(); 8264 if (ArrayUtils.isEmpty(files)) { 8265 Log.d(TAG, "No files in app dir " + dir); 8266 return; 8267 } 8268 8269 if (DEBUG_PACKAGE_SCANNING) { 8270 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 8271 + " flags=0x" + Integer.toHexString(parseFlags)); 8272 } 8273 ParallelPackageParser parallelPackageParser = new ParallelPackageParser( 8274 mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir, 8275 mParallelPackageParserCallback); 8276 8277 // Submit files for parsing in parallel 8278 int fileCount = 0; 8279 for (File file : files) { 8280 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 8281 && !PackageInstallerService.isStageName(file.getName()); 8282 if (!isPackage) { 8283 // Ignore entries which are not packages 8284 continue; 8285 } 8286 parallelPackageParser.submit(file, parseFlags); 8287 fileCount++; 8288 } 8289 8290 // Process results one by one 8291 for (; fileCount > 0; fileCount--) { 8292 ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take(); 8293 Throwable throwable = parseResult.throwable; 8294 int errorCode = PackageManager.INSTALL_SUCCEEDED; 8295 8296 if (throwable == null) { 8297 // Static shared libraries have synthetic package names 8298 if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) { 8299 renameStaticSharedLibraryPackage(parseResult.pkg); 8300 } 8301 try { 8302 if (errorCode == PackageManager.INSTALL_SUCCEEDED) { 8303 scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags, 8304 currentTime, null); 8305 } 8306 } catch (PackageManagerException e) { 8307 errorCode = e.error; 8308 Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage()); 8309 } 8310 } else if (throwable instanceof PackageParser.PackageParserException) { 8311 PackageParser.PackageParserException e = (PackageParser.PackageParserException) 8312 throwable; 8313 errorCode = e.error; 8314 Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage()); 8315 } else { 8316 throw new IllegalStateException("Unexpected exception occurred while parsing " 8317 + parseResult.scanFile, throwable); 8318 } 8319 8320 // Delete invalid userdata apps 8321 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 8322 errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) { 8323 logCriticalInfo(Log.WARN, 8324 "Deleting invalid package at " + parseResult.scanFile); 8325 removeCodePathLI(parseResult.scanFile); 8326 } 8327 } 8328 parallelPackageParser.close(); 8329 } 8330 8331 private static File getSettingsProblemFile() { 8332 File dataDir = Environment.getDataDirectory(); 8333 File systemDir = new File(dataDir, "system"); 8334 File fname = new File(systemDir, "uiderrors.txt"); 8335 return fname; 8336 } 8337 8338 public static void reportSettingsProblem(int priority, String msg) { 8339 logCriticalInfo(priority, msg); 8340 } 8341 8342 public static void logCriticalInfo(int priority, String msg) { 8343 Slog.println(priority, TAG, msg); 8344 EventLogTags.writePmCriticalInfo(msg); 8345 try { 8346 File fname = getSettingsProblemFile(); 8347 FileOutputStream out = new FileOutputStream(fname, true); 8348 PrintWriter pw = new FastPrintWriter(out); 8349 SimpleDateFormat formatter = new SimpleDateFormat(); 8350 String dateString = formatter.format(new Date(System.currentTimeMillis())); 8351 pw.println(dateString + ": " + msg); 8352 pw.close(); 8353 FileUtils.setPermissions( 8354 fname.toString(), 8355 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 8356 -1, -1); 8357 } catch (java.io.IOException e) { 8358 } 8359 } 8360 8361 private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) { 8362 if (srcFile.isDirectory()) { 8363 final File baseFile = new File(pkg.baseCodePath); 8364 long maxModifiedTime = baseFile.lastModified(); 8365 if (pkg.splitCodePaths != null) { 8366 for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) { 8367 final File splitFile = new File(pkg.splitCodePaths[i]); 8368 maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified()); 8369 } 8370 } 8371 return maxModifiedTime; 8372 } 8373 return srcFile.lastModified(); 8374 } 8375 8376 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 8377 final int policyFlags) throws PackageManagerException { 8378 // When upgrading from pre-N MR1, verify the package time stamp using the package 8379 // directory and not the APK file. 8380 final long lastModifiedTime = mIsPreNMR1Upgrade 8381 ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile); 8382 if (ps != null 8383 && ps.codePath.equals(srcFile) 8384 && ps.timeStamp == lastModifiedTime 8385 && !isCompatSignatureUpdateNeeded(pkg) 8386 && !isRecoverSignatureUpdateNeeded(pkg)) { 8387 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 8388 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8389 ArraySet<PublicKey> signingKs; 8390 synchronized (mPackages) { 8391 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 8392 } 8393 if (ps.signatures.mSignatures != null 8394 && ps.signatures.mSignatures.length != 0 8395 && signingKs != null) { 8396 // Optimization: reuse the existing cached certificates 8397 // if the package appears to be unchanged. 8398 pkg.mSignatures = ps.signatures.mSignatures; 8399 pkg.mSigningKeys = signingKs; 8400 return; 8401 } 8402 8403 Slog.w(TAG, "PackageSetting for " + ps.name 8404 + " is missing signatures. Collecting certs again to recover them."); 8405 } else { 8406 Slog.i(TAG, srcFile.toString() + " changed; collecting certs"); 8407 } 8408 8409 try { 8410 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 8411 PackageParser.collectCertificates(pkg, policyFlags); 8412 } catch (PackageParserException e) { 8413 throw PackageManagerException.from(e); 8414 } finally { 8415 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8416 } 8417 } 8418 8419 /** 8420 * Traces a package scan. 8421 * @see #scanPackageLI(File, int, int, long, UserHandle) 8422 */ 8423 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 8424 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 8425 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]"); 8426 try { 8427 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 8428 } finally { 8429 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8430 } 8431 } 8432 8433 /** 8434 * Scans a package and returns the newly parsed package. 8435 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 8436 */ 8437 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 8438 long currentTime, UserHandle user) throws PackageManagerException { 8439 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 8440 PackageParser pp = new PackageParser(); 8441 pp.setSeparateProcesses(mSeparateProcesses); 8442 pp.setOnlyCoreApps(mOnlyCore); 8443 pp.setDisplayMetrics(mMetrics); 8444 pp.setCallback(mPackageParserCallback); 8445 8446 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 8447 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 8448 } 8449 8450 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 8451 final PackageParser.Package pkg; 8452 try { 8453 pkg = pp.parsePackage(scanFile, parseFlags); 8454 } catch (PackageParserException e) { 8455 throw PackageManagerException.from(e); 8456 } finally { 8457 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8458 } 8459 8460 // Static shared libraries have synthetic package names 8461 if (pkg.applicationInfo.isStaticSharedLibrary()) { 8462 renameStaticSharedLibraryPackage(pkg); 8463 } 8464 8465 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 8466 } 8467 8468 /** 8469 * Scans a package and returns the newly parsed package. 8470 * @throws PackageManagerException on a parse error. 8471 */ 8472 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 8473 final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user) 8474 throws PackageManagerException { 8475 // If the package has children and this is the first dive in the function 8476 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 8477 // packages (parent and children) would be successfully scanned before the 8478 // actual scan since scanning mutates internal state and we want to atomically 8479 // install the package and its children. 8480 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8481 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 8482 scanFlags |= SCAN_CHECK_ONLY; 8483 } 8484 } else { 8485 scanFlags &= ~SCAN_CHECK_ONLY; 8486 } 8487 8488 // Scan the parent 8489 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 8490 scanFlags, currentTime, user); 8491 8492 // Scan the children 8493 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8494 for (int i = 0; i < childCount; i++) { 8495 PackageParser.Package childPackage = pkg.childPackages.get(i); 8496 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 8497 currentTime, user); 8498 } 8499 8500 8501 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8502 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 8503 } 8504 8505 return scannedPkg; 8506 } 8507 8508 /** 8509 * Scans a package and returns the newly parsed package. 8510 * @throws PackageManagerException on a parse error. 8511 */ 8512 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 8513 int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user) 8514 throws PackageManagerException { 8515 PackageSetting ps = null; 8516 PackageSetting updatedPkg; 8517 // reader 8518 synchronized (mPackages) { 8519 // Look to see if we already know about this package. 8520 String oldName = mSettings.getRenamedPackageLPr(pkg.packageName); 8521 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 8522 // This package has been renamed to its original name. Let's 8523 // use that. 8524 ps = mSettings.getPackageLPr(oldName); 8525 } 8526 // If there was no original package, see one for the real package name. 8527 if (ps == null) { 8528 ps = mSettings.getPackageLPr(pkg.packageName); 8529 } 8530 // Check to see if this package could be hiding/updating a system 8531 // package. Must look for it either under the original or real 8532 // package name depending on our state. 8533 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 8534 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 8535 8536 // If this is a package we don't know about on the system partition, we 8537 // may need to remove disabled child packages on the system partition 8538 // or may need to not add child packages if the parent apk is updated 8539 // on the data partition and no longer defines this child package. 8540 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 8541 // If this is a parent package for an updated system app and this system 8542 // app got an OTA update which no longer defines some of the child packages 8543 // we have to prune them from the disabled system packages. 8544 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 8545 if (disabledPs != null) { 8546 final int scannedChildCount = (pkg.childPackages != null) 8547 ? pkg.childPackages.size() : 0; 8548 final int disabledChildCount = disabledPs.childPackageNames != null 8549 ? disabledPs.childPackageNames.size() : 0; 8550 for (int i = 0; i < disabledChildCount; i++) { 8551 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 8552 boolean disabledPackageAvailable = false; 8553 for (int j = 0; j < scannedChildCount; j++) { 8554 PackageParser.Package childPkg = pkg.childPackages.get(j); 8555 if (childPkg.packageName.equals(disabledChildPackageName)) { 8556 disabledPackageAvailable = true; 8557 break; 8558 } 8559 } 8560 if (!disabledPackageAvailable) { 8561 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 8562 } 8563 } 8564 } 8565 } 8566 } 8567 8568 final boolean isUpdatedPkg = updatedPkg != null; 8569 final boolean isUpdatedSystemPkg = isUpdatedPkg 8570 && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0; 8571 boolean isUpdatedPkgBetter = false; 8572 // First check if this is a system package that may involve an update 8573 if (isUpdatedSystemPkg) { 8574 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 8575 // it needs to drop FLAG_PRIVILEGED. 8576 if (locationIsPrivileged(scanFile)) { 8577 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 8578 } else { 8579 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 8580 } 8581 // If new package is not located in "/oem" (e.g. due to an OTA), 8582 // it needs to drop FLAG_OEM. 8583 if (locationIsOem(scanFile)) { 8584 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM; 8585 } else { 8586 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_OEM; 8587 } 8588 8589 if (ps != null && !ps.codePath.equals(scanFile)) { 8590 // The path has changed from what was last scanned... check the 8591 // version of the new path against what we have stored to determine 8592 // what to do. 8593 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 8594 if (pkg.mVersionCode <= ps.versionCode) { 8595 // The system package has been updated and the code path does not match 8596 // Ignore entry. Skip it. 8597 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 8598 + " ignored: updated version " + ps.versionCode 8599 + " better than this " + pkg.mVersionCode); 8600 if (!updatedPkg.codePath.equals(scanFile)) { 8601 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 8602 + ps.name + " changing from " + updatedPkg.codePathString 8603 + " to " + scanFile); 8604 updatedPkg.codePath = scanFile; 8605 updatedPkg.codePathString = scanFile.toString(); 8606 updatedPkg.resourcePath = scanFile; 8607 updatedPkg.resourcePathString = scanFile.toString(); 8608 } 8609 updatedPkg.pkg = pkg; 8610 updatedPkg.versionCode = pkg.mVersionCode; 8611 8612 // Update the disabled system child packages to point to the package too. 8613 final int childCount = updatedPkg.childPackageNames != null 8614 ? updatedPkg.childPackageNames.size() : 0; 8615 for (int i = 0; i < childCount; i++) { 8616 String childPackageName = updatedPkg.childPackageNames.get(i); 8617 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 8618 childPackageName); 8619 if (updatedChildPkg != null) { 8620 updatedChildPkg.pkg = pkg; 8621 updatedChildPkg.versionCode = pkg.mVersionCode; 8622 } 8623 } 8624 } else { 8625 // The current app on the system partition is better than 8626 // what we have updated to on the data partition; switch 8627 // back to the system partition version. 8628 // At this point, its safely assumed that package installation for 8629 // apps in system partition will go through. If not there won't be a working 8630 // version of the app 8631 // writer 8632 synchronized (mPackages) { 8633 // Just remove the loaded entries from package lists. 8634 mPackages.remove(ps.name); 8635 } 8636 8637 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 8638 + " reverting from " + ps.codePathString 8639 + ": new version " + pkg.mVersionCode 8640 + " better than installed " + ps.versionCode); 8641 8642 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 8643 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 8644 synchronized (mInstallLock) { 8645 args.cleanUpResourcesLI(); 8646 } 8647 synchronized (mPackages) { 8648 mSettings.enableSystemPackageLPw(ps.name); 8649 } 8650 isUpdatedPkgBetter = true; 8651 } 8652 } 8653 } 8654 8655 String resourcePath = null; 8656 String baseResourcePath = null; 8657 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !isUpdatedPkgBetter) { 8658 if (ps != null && ps.resourcePathString != null) { 8659 resourcePath = ps.resourcePathString; 8660 baseResourcePath = ps.resourcePathString; 8661 } else { 8662 // Should not happen at all. Just log an error. 8663 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 8664 } 8665 } else { 8666 resourcePath = pkg.codePath; 8667 baseResourcePath = pkg.baseCodePath; 8668 } 8669 8670 // Set application objects path explicitly. 8671 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 8672 pkg.setApplicationInfoCodePath(pkg.codePath); 8673 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 8674 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 8675 pkg.setApplicationInfoResourcePath(resourcePath); 8676 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 8677 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 8678 8679 // throw an exception if we have an update to a system application, but, it's not more 8680 // recent than the package we've already scanned 8681 if (isUpdatedSystemPkg && !isUpdatedPkgBetter) { 8682 // Set CPU Abis to application info. 8683 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) { 8684 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, updatedPkg); 8685 derivePackageAbi(pkg, scanFile, cpuAbiOverride, false, mAppLib32InstallDir); 8686 } else { 8687 pkg.applicationInfo.primaryCpuAbi = updatedPkg.primaryCpuAbiString; 8688 pkg.applicationInfo.secondaryCpuAbi = updatedPkg.secondaryCpuAbiString; 8689 } 8690 pkg.mExtras = updatedPkg; 8691 8692 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 8693 + scanFile + " ignored: updated version " + ps.versionCode 8694 + " better than this " + pkg.mVersionCode); 8695 } 8696 8697 if (isUpdatedPkg) { 8698 // An updated system app will not have the PARSE_IS_SYSTEM flag set 8699 // initially 8700 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 8701 8702 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 8703 // flag set initially 8704 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 8705 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 8706 } 8707 8708 // An updated OEM app will not have the PARSE_IS_OEM 8709 // flag set initially 8710 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0) { 8711 policyFlags |= PackageParser.PARSE_IS_OEM; 8712 } 8713 } 8714 8715 // Verify certificates against what was last scanned 8716 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 8717 8718 /* 8719 * A new system app appeared, but we already had a non-system one of the 8720 * same name installed earlier. 8721 */ 8722 boolean shouldHideSystemApp = false; 8723 if (!isUpdatedPkg && ps != null 8724 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 8725 /* 8726 * Check to make sure the signatures match first. If they don't, 8727 * wipe the installed application and its data. 8728 */ 8729 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 8730 != PackageManager.SIGNATURE_MATCH) { 8731 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 8732 + " signatures don't match existing userdata copy; removing"); 8733 try (PackageFreezer freezer = freezePackage(pkg.packageName, 8734 "scanPackageInternalLI")) { 8735 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 8736 } 8737 ps = null; 8738 } else { 8739 /* 8740 * If the newly-added system app is an older version than the 8741 * already installed version, hide it. It will be scanned later 8742 * and re-added like an update. 8743 */ 8744 if (pkg.mVersionCode <= ps.versionCode) { 8745 shouldHideSystemApp = true; 8746 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 8747 + " but new version " + pkg.mVersionCode + " better than installed " 8748 + ps.versionCode + "; hiding system"); 8749 } else { 8750 /* 8751 * The newly found system app is a newer version that the 8752 * one previously installed. Simply remove the 8753 * already-installed application and replace it with our own 8754 * while keeping the application data. 8755 */ 8756 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 8757 + " reverting from " + ps.codePathString + ": new version " 8758 + pkg.mVersionCode + " better than installed " + ps.versionCode); 8759 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 8760 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 8761 synchronized (mInstallLock) { 8762 args.cleanUpResourcesLI(); 8763 } 8764 } 8765 } 8766 } 8767 8768 // The apk is forward locked (not public) if its code and resources 8769 // are kept in different files. (except for app in either system or 8770 // vendor path). 8771 // TODO grab this value from PackageSettings 8772 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8773 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 8774 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 8775 } 8776 } 8777 8778 final int userId = ((user == null) ? 0 : user.getIdentifier()); 8779 if (ps != null && ps.getInstantApp(userId)) { 8780 scanFlags |= SCAN_AS_INSTANT_APP; 8781 } 8782 if (ps != null && ps.getVirtulalPreload(userId)) { 8783 scanFlags |= SCAN_AS_VIRTUAL_PRELOAD; 8784 } 8785 8786 // Note that we invoke the following method only if we are about to unpack an application 8787 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 8788 | SCAN_UPDATE_SIGNATURE, currentTime, user); 8789 8790 /* 8791 * If the system app should be overridden by a previously installed 8792 * data, hide the system app now and let the /data/app scan pick it up 8793 * again. 8794 */ 8795 if (shouldHideSystemApp) { 8796 synchronized (mPackages) { 8797 mSettings.disableSystemPackageLPw(pkg.packageName, true); 8798 } 8799 } 8800 8801 return scannedPkg; 8802 } 8803 8804 private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) { 8805 // Derive the new package synthetic package name 8806 pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER 8807 + pkg.staticSharedLibVersion); 8808 } 8809 8810 private static String fixProcessName(String defProcessName, 8811 String processName) { 8812 if (processName == null) { 8813 return defProcessName; 8814 } 8815 return processName; 8816 } 8817 8818 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 8819 throws PackageManagerException { 8820 if (pkgSetting.signatures.mSignatures != null) { 8821 // Already existing package. Make sure signatures match 8822 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 8823 == PackageManager.SIGNATURE_MATCH; 8824 if (!match) { 8825 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 8826 == PackageManager.SIGNATURE_MATCH; 8827 } 8828 if (!match) { 8829 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 8830 == PackageManager.SIGNATURE_MATCH; 8831 } 8832 if (!match) { 8833 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 8834 + pkg.packageName + " signatures do not match the " 8835 + "previously installed version; ignoring!"); 8836 } 8837 } 8838 8839 // Check for shared user signatures 8840 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 8841 // Already existing package. Make sure signatures match 8842 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8843 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 8844 if (!match) { 8845 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 8846 == PackageManager.SIGNATURE_MATCH; 8847 } 8848 if (!match) { 8849 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 8850 == PackageManager.SIGNATURE_MATCH; 8851 } 8852 if (!match) { 8853 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 8854 "Package " + pkg.packageName 8855 + " has no signatures that match those in shared user " 8856 + pkgSetting.sharedUser.name + "; ignoring!"); 8857 } 8858 } 8859 } 8860 8861 /** 8862 * Enforces that only the system UID or root's UID can call a method exposed 8863 * via Binder. 8864 * 8865 * @param message used as message if SecurityException is thrown 8866 * @throws SecurityException if the caller is not system or root 8867 */ 8868 private static final void enforceSystemOrRoot(String message) { 8869 final int uid = Binder.getCallingUid(); 8870 if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) { 8871 throw new SecurityException(message); 8872 } 8873 } 8874 8875 @Override 8876 public void performFstrimIfNeeded() { 8877 enforceSystemOrRoot("Only the system can request fstrim"); 8878 8879 // Before everything else, see whether we need to fstrim. 8880 try { 8881 IStorageManager sm = PackageHelper.getStorageManager(); 8882 if (sm != null) { 8883 boolean doTrim = false; 8884 final long interval = android.provider.Settings.Global.getLong( 8885 mContext.getContentResolver(), 8886 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 8887 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 8888 if (interval > 0) { 8889 final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance(); 8890 if (timeSinceLast > interval) { 8891 doTrim = true; 8892 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 8893 + "; running immediately"); 8894 } 8895 } 8896 if (doTrim) { 8897 final boolean dexOptDialogShown; 8898 synchronized (mPackages) { 8899 dexOptDialogShown = mDexOptDialogShown; 8900 } 8901 if (!isFirstBoot() && dexOptDialogShown) { 8902 try { 8903 ActivityManager.getService().showBootMessage( 8904 mContext.getResources().getString( 8905 R.string.android_upgrading_fstrim), true); 8906 } catch (RemoteException e) { 8907 } 8908 } 8909 sm.runMaintenance(); 8910 } 8911 } else { 8912 Slog.e(TAG, "storageManager service unavailable!"); 8913 } 8914 } catch (RemoteException e) { 8915 // Can't happen; StorageManagerService is local 8916 } 8917 } 8918 8919 @Override 8920 public void updatePackagesIfNeeded() { 8921 enforceSystemOrRoot("Only the system can request package update"); 8922 8923 // We need to re-extract after an OTA. 8924 boolean causeUpgrade = isUpgrade(); 8925 8926 // First boot or factory reset. 8927 // Note: we also handle devices that are upgrading to N right now as if it is their 8928 // first boot, as they do not have profile data. 8929 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 8930 8931 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 8932 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 8933 8934 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 8935 return; 8936 } 8937 8938 List<PackageParser.Package> pkgs; 8939 synchronized (mPackages) { 8940 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 8941 } 8942 8943 final long startTime = System.nanoTime(); 8944 final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */, 8945 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT), 8946 false /* bootComplete */); 8947 8948 final int elapsedTimeSeconds = 8949 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 8950 8951 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]); 8952 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]); 8953 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]); 8954 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 8955 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 8956 } 8957 8958 /* 8959 * Return the prebuilt profile path given a package base code path. 8960 */ 8961 private static String getPrebuildProfilePath(PackageParser.Package pkg) { 8962 return pkg.baseCodePath + ".prof"; 8963 } 8964 8965 /** 8966 * Performs dexopt on the set of packages in {@code packages} and returns an int array 8967 * containing statistics about the invocation. The array consists of three elements, 8968 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped} 8969 * and {@code numberOfPackagesFailed}. 8970 */ 8971 private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog, 8972 final String compilerFilter, boolean bootComplete) { 8973 8974 int numberOfPackagesVisited = 0; 8975 int numberOfPackagesOptimized = 0; 8976 int numberOfPackagesSkipped = 0; 8977 int numberOfPackagesFailed = 0; 8978 final int numberOfPackagesToDexopt = pkgs.size(); 8979 8980 for (PackageParser.Package pkg : pkgs) { 8981 numberOfPackagesVisited++; 8982 8983 boolean useProfileForDexopt = false; 8984 8985 if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) { 8986 // Copy over initial preopt profiles since we won't get any JIT samples for methods 8987 // that are already compiled. 8988 File profileFile = new File(getPrebuildProfilePath(pkg)); 8989 // Copy profile if it exists. 8990 if (profileFile.exists()) { 8991 try { 8992 // We could also do this lazily before calling dexopt in 8993 // PackageDexOptimizer to prevent this happening on first boot. The issue 8994 // is that we don't have a good way to say "do this only once". 8995 if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(), 8996 pkg.applicationInfo.uid, pkg.packageName)) { 8997 Log.e(TAG, "Installer failed to copy system profile!"); 8998 } else { 8999 // Disabled as this causes speed-profile compilation during first boot 9000 // even if things are already compiled. 9001 // useProfileForDexopt = true; 9002 } 9003 } catch (Exception e) { 9004 Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ", 9005 e); 9006 } 9007 } else { 9008 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 9009 // Handle compressed APKs in this path. Only do this for stubs with profiles to 9010 // minimize the number off apps being speed-profile compiled during first boot. 9011 // The other paths will not change the filter. 9012 if (disabledPs != null && disabledPs.pkg.isStub) { 9013 // The package is the stub one, remove the stub suffix to get the normal 9014 // package and APK names. 9015 String systemProfilePath = 9016 getPrebuildProfilePath(disabledPs.pkg).replace(STUB_SUFFIX, ""); 9017 profileFile = new File(systemProfilePath); 9018 // If we have a profile for a compressed APK, copy it to the reference 9019 // location. 9020 // Note that copying the profile here will cause it to override the 9021 // reference profile every OTA even though the existing reference profile 9022 // may have more data. We can't copy during decompression since the 9023 // directories are not set up at that point. 9024 if (profileFile.exists()) { 9025 try { 9026 // We could also do this lazily before calling dexopt in 9027 // PackageDexOptimizer to prevent this happening on first boot. The 9028 // issue is that we don't have a good way to say "do this only 9029 // once". 9030 if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(), 9031 pkg.applicationInfo.uid, pkg.packageName)) { 9032 Log.e(TAG, "Failed to copy system profile for stub package!"); 9033 } else { 9034 useProfileForDexopt = true; 9035 } 9036 } catch (Exception e) { 9037 Log.e(TAG, "Failed to copy profile " + 9038 profileFile.getAbsolutePath() + " ", e); 9039 } 9040 } 9041 } 9042 } 9043 } 9044 9045 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 9046 if (DEBUG_DEXOPT) { 9047 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 9048 } 9049 numberOfPackagesSkipped++; 9050 continue; 9051 } 9052 9053 if (DEBUG_DEXOPT) { 9054 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 9055 numberOfPackagesToDexopt + ": " + pkg.packageName); 9056 } 9057 9058 if (showDialog) { 9059 try { 9060 ActivityManager.getService().showBootMessage( 9061 mContext.getResources().getString(R.string.android_upgrading_apk, 9062 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 9063 } catch (RemoteException e) { 9064 } 9065 synchronized (mPackages) { 9066 mDexOptDialogShown = true; 9067 } 9068 } 9069 9070 String pkgCompilerFilter = compilerFilter; 9071 if (useProfileForDexopt) { 9072 // Use background dexopt mode to try and use the profile. Note that this does not 9073 // guarantee usage of the profile. 9074 pkgCompilerFilter = 9075 PackageManagerServiceCompilerMapping.getCompilerFilterForReason( 9076 PackageManagerService.REASON_BACKGROUND_DEXOPT); 9077 } 9078 9079 // checkProfiles is false to avoid merging profiles during boot which 9080 // might interfere with background compilation (b/28612421). 9081 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 9082 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 9083 // trade-off worth doing to save boot time work. 9084 int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0; 9085 int primaryDexOptStaus = performDexOptTraced(new DexoptOptions( 9086 pkg.packageName, 9087 pkgCompilerFilter, 9088 dexoptFlags)); 9089 9090 switch (primaryDexOptStaus) { 9091 case PackageDexOptimizer.DEX_OPT_PERFORMED: 9092 numberOfPackagesOptimized++; 9093 break; 9094 case PackageDexOptimizer.DEX_OPT_SKIPPED: 9095 numberOfPackagesSkipped++; 9096 break; 9097 case PackageDexOptimizer.DEX_OPT_FAILED: 9098 numberOfPackagesFailed++; 9099 break; 9100 default: 9101 Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus); 9102 break; 9103 } 9104 } 9105 9106 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped, 9107 numberOfPackagesFailed }; 9108 } 9109 9110 @Override 9111 public void notifyPackageUse(String packageName, int reason) { 9112 synchronized (mPackages) { 9113 final int callingUid = Binder.getCallingUid(); 9114 final int callingUserId = UserHandle.getUserId(callingUid); 9115 if (getInstantAppPackageName(callingUid) != null) { 9116 if (!isCallerSameApp(packageName, callingUid)) { 9117 return; 9118 } 9119 } else { 9120 if (isInstantApp(packageName, callingUserId)) { 9121 return; 9122 } 9123 } 9124 notifyPackageUseLocked(packageName, reason); 9125 } 9126 } 9127 9128 private void notifyPackageUseLocked(String packageName, int reason) { 9129 final PackageParser.Package p = mPackages.get(packageName); 9130 if (p == null) { 9131 return; 9132 } 9133 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 9134 } 9135 9136 @Override 9137 public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames, 9138 List<String> classPaths, String loaderIsa) { 9139 int userId = UserHandle.getCallingUserId(); 9140 ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId); 9141 if (ai == null) { 9142 Slog.w(TAG, "Loading a package that does not exist for the calling user. package=" 9143 + loadingPackageName + ", user=" + userId); 9144 return; 9145 } 9146 mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId); 9147 } 9148 9149 @Override 9150 public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule, 9151 IDexModuleRegisterCallback callback) { 9152 int userId = UserHandle.getCallingUserId(); 9153 ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId); 9154 DexManager.RegisterDexModuleResult result; 9155 if (ai == null) { 9156 Slog.w(TAG, "Registering a dex module for a package that does not exist for the" + 9157 " calling user. package=" + packageName + ", user=" + userId); 9158 result = new DexManager.RegisterDexModuleResult(false, "Package not installed"); 9159 } else { 9160 result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId); 9161 } 9162 9163 if (callback != null) { 9164 mHandler.post(() -> { 9165 try { 9166 callback.onDexModuleRegistered(dexModulePath, result.success, result.message); 9167 } catch (RemoteException e) { 9168 Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e); 9169 } 9170 }); 9171 } 9172 } 9173 9174 /** 9175 * Ask the package manager to perform a dex-opt with the given compiler filter. 9176 * 9177 * Note: exposed only for the shell command to allow moving packages explicitly to a 9178 * definite state. 9179 */ 9180 @Override 9181 public boolean performDexOptMode(String packageName, 9182 boolean checkProfiles, String targetCompilerFilter, boolean force, 9183 boolean bootComplete, String splitName) { 9184 int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) | 9185 (force ? DexoptOptions.DEXOPT_FORCE : 0) | 9186 (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0); 9187 return performDexOpt(new DexoptOptions(packageName, targetCompilerFilter, 9188 splitName, flags)); 9189 } 9190 9191 /** 9192 * Ask the package manager to perform a dex-opt with the given compiler filter on the 9193 * secondary dex files belonging to the given package. 9194 * 9195 * Note: exposed only for the shell command to allow moving packages explicitly to a 9196 * definite state. 9197 */ 9198 @Override 9199 public boolean performDexOptSecondary(String packageName, String compilerFilter, 9200 boolean force) { 9201 int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX | 9202 DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES | 9203 DexoptOptions.DEXOPT_BOOT_COMPLETE | 9204 (force ? DexoptOptions.DEXOPT_FORCE : 0); 9205 return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags)); 9206 } 9207 9208 /*package*/ boolean performDexOpt(DexoptOptions options) { 9209 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 9210 return false; 9211 } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) { 9212 return false; 9213 } 9214 9215 if (options.isDexoptOnlySecondaryDex()) { 9216 return mDexManager.dexoptSecondaryDex(options); 9217 } else { 9218 int dexoptStatus = performDexOptWithStatus(options); 9219 return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 9220 } 9221 } 9222 9223 /** 9224 * Perform dexopt on the given package and return one of following result: 9225 * {@link PackageDexOptimizer#DEX_OPT_SKIPPED} 9226 * {@link PackageDexOptimizer#DEX_OPT_PERFORMED} 9227 * {@link PackageDexOptimizer#DEX_OPT_FAILED} 9228 */ 9229 /* package */ int performDexOptWithStatus(DexoptOptions options) { 9230 return performDexOptTraced(options); 9231 } 9232 9233 private int performDexOptTraced(DexoptOptions options) { 9234 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 9235 try { 9236 return performDexOptInternal(options); 9237 } finally { 9238 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9239 } 9240 } 9241 9242 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 9243 // if the package can now be considered up to date for the given filter. 9244 private int performDexOptInternal(DexoptOptions options) { 9245 PackageParser.Package p; 9246 synchronized (mPackages) { 9247 p = mPackages.get(options.getPackageName()); 9248 if (p == null) { 9249 // Package could not be found. Report failure. 9250 return PackageDexOptimizer.DEX_OPT_FAILED; 9251 } 9252 mPackageUsage.maybeWriteAsync(mPackages); 9253 mCompilerStats.maybeWriteAsync(); 9254 } 9255 long callingId = Binder.clearCallingIdentity(); 9256 try { 9257 synchronized (mInstallLock) { 9258 return performDexOptInternalWithDependenciesLI(p, options); 9259 } 9260 } finally { 9261 Binder.restoreCallingIdentity(callingId); 9262 } 9263 } 9264 9265 public ArraySet<String> getOptimizablePackages() { 9266 ArraySet<String> pkgs = new ArraySet<String>(); 9267 synchronized (mPackages) { 9268 for (PackageParser.Package p : mPackages.values()) { 9269 if (PackageDexOptimizer.canOptimizePackage(p)) { 9270 pkgs.add(p.packageName); 9271 } 9272 } 9273 } 9274 return pkgs; 9275 } 9276 9277 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 9278 DexoptOptions options) { 9279 // Select the dex optimizer based on the force parameter. 9280 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 9281 // allocate an object here. 9282 PackageDexOptimizer pdo = options.isForce() 9283 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 9284 : mPackageDexOptimizer; 9285 9286 // Dexopt all dependencies first. Note: we ignore the return value and march on 9287 // on errors. 9288 // Note that we are going to call performDexOpt on those libraries as many times as 9289 // they are referenced in packages. When we do a batch of performDexOpt (for example 9290 // at boot, or background job), the passed 'targetCompilerFilter' stays the same, 9291 // and the first package that uses the library will dexopt it. The 9292 // others will see that the compiled code for the library is up to date. 9293 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 9294 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 9295 if (!deps.isEmpty()) { 9296 DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(), 9297 options.getCompilerFilter(), options.getSplitName(), 9298 options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY); 9299 for (PackageParser.Package depPackage : deps) { 9300 // TODO: Analyze and investigate if we (should) profile libraries. 9301 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 9302 getOrCreateCompilerPackageStats(depPackage), 9303 mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions); 9304 } 9305 } 9306 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, 9307 getOrCreateCompilerPackageStats(p), 9308 mDexManager.getPackageUseInfoOrDefault(p.packageName), options); 9309 } 9310 9311 /** 9312 * Reconcile the information we have about the secondary dex files belonging to 9313 * {@code packagName} and the actual dex files. For all dex files that were 9314 * deleted, update the internal records and delete the generated oat files. 9315 */ 9316 @Override 9317 public void reconcileSecondaryDexFiles(String packageName) { 9318 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 9319 return; 9320 } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) { 9321 return; 9322 } 9323 mDexManager.reconcileSecondaryDexFiles(packageName); 9324 } 9325 9326 // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject 9327 // a reference there. 9328 /*package*/ DexManager getDexManager() { 9329 return mDexManager; 9330 } 9331 9332 /** 9333 * Execute the background dexopt job immediately. 9334 */ 9335 @Override 9336 public boolean runBackgroundDexoptJob() { 9337 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 9338 return false; 9339 } 9340 return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext); 9341 } 9342 9343 List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 9344 if (p.usesLibraries != null || p.usesOptionalLibraries != null 9345 || p.usesStaticLibraries != null) { 9346 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 9347 Set<String> collectedNames = new HashSet<>(); 9348 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 9349 9350 retValue.remove(p); 9351 9352 return retValue; 9353 } else { 9354 return Collections.emptyList(); 9355 } 9356 } 9357 9358 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 9359 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) { 9360 if (!collectedNames.contains(p.packageName)) { 9361 collectedNames.add(p.packageName); 9362 collected.add(p); 9363 9364 if (p.usesLibraries != null) { 9365 findSharedNonSystemLibrariesRecursive(p.usesLibraries, 9366 null, collected, collectedNames); 9367 } 9368 if (p.usesOptionalLibraries != null) { 9369 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, 9370 null, collected, collectedNames); 9371 } 9372 if (p.usesStaticLibraries != null) { 9373 findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries, 9374 p.usesStaticLibrariesVersions, collected, collectedNames); 9375 } 9376 } 9377 } 9378 9379 private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions, 9380 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) { 9381 final int libNameCount = libs.size(); 9382 for (int i = 0; i < libNameCount; i++) { 9383 String libName = libs.get(i); 9384 int version = (versions != null && versions.length == libNameCount) 9385 ? versions[i] : PackageManager.VERSION_CODE_HIGHEST; 9386 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version); 9387 if (libPkg != null) { 9388 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 9389 } 9390 } 9391 } 9392 9393 private PackageParser.Package findSharedNonSystemLibrary(String name, int version) { 9394 synchronized (mPackages) { 9395 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version); 9396 if (libEntry != null) { 9397 return mPackages.get(libEntry.apk); 9398 } 9399 return null; 9400 } 9401 } 9402 9403 private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) { 9404 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 9405 if (versionedLib == null) { 9406 return null; 9407 } 9408 return versionedLib.get(version); 9409 } 9410 9411 private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) { 9412 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get( 9413 pkg.staticSharedLibName); 9414 if (versionedLib == null) { 9415 return null; 9416 } 9417 int previousLibVersion = -1; 9418 final int versionCount = versionedLib.size(); 9419 for (int i = 0; i < versionCount; i++) { 9420 final int libVersion = versionedLib.keyAt(i); 9421 if (libVersion < pkg.staticSharedLibVersion) { 9422 previousLibVersion = Math.max(previousLibVersion, libVersion); 9423 } 9424 } 9425 if (previousLibVersion >= 0) { 9426 return versionedLib.get(previousLibVersion); 9427 } 9428 return null; 9429 } 9430 9431 public void shutdown() { 9432 mPackageUsage.writeNow(mPackages); 9433 mCompilerStats.writeNow(); 9434 mDexManager.writePackageDexUsageNow(); 9435 } 9436 9437 @Override 9438 public void dumpProfiles(String packageName) { 9439 PackageParser.Package pkg; 9440 synchronized (mPackages) { 9441 pkg = mPackages.get(packageName); 9442 if (pkg == null) { 9443 throw new IllegalArgumentException("Unknown package: " + packageName); 9444 } 9445 } 9446 /* Only the shell, root, or the app user should be able to dump profiles. */ 9447 int callingUid = Binder.getCallingUid(); 9448 if (callingUid != Process.SHELL_UID && 9449 callingUid != Process.ROOT_UID && 9450 callingUid != pkg.applicationInfo.uid) { 9451 throw new SecurityException("dumpProfiles"); 9452 } 9453 9454 synchronized (mInstallLock) { 9455 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles"); 9456 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 9457 try { 9458 List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly(); 9459 String codePaths = TextUtils.join(";", allCodePaths); 9460 mInstaller.dumpProfiles(sharedGid, packageName, codePaths); 9461 } catch (InstallerException e) { 9462 Slog.w(TAG, "Failed to dump profiles", e); 9463 } 9464 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9465 } 9466 } 9467 9468 @Override 9469 public void forceDexOpt(String packageName) { 9470 enforceSystemOrRoot("forceDexOpt"); 9471 9472 PackageParser.Package pkg; 9473 synchronized (mPackages) { 9474 pkg = mPackages.get(packageName); 9475 if (pkg == null) { 9476 throw new IllegalArgumentException("Unknown package: " + packageName); 9477 } 9478 } 9479 9480 synchronized (mInstallLock) { 9481 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 9482 9483 // Whoever is calling forceDexOpt wants a compiled package. 9484 // Don't use profiles since that may cause compilation to be skipped. 9485 final int res = performDexOptInternalWithDependenciesLI( 9486 pkg, 9487 new DexoptOptions(packageName, 9488 getDefaultCompilerFilter(), 9489 DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE)); 9490 9491 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9492 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 9493 throw new IllegalStateException("Failed to dexopt: " + res); 9494 } 9495 } 9496 } 9497 9498 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 9499 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 9500 Slog.w(TAG, "Unable to update from " + oldPkg.name 9501 + " to " + newPkg.packageName 9502 + ": old package not in system partition"); 9503 return false; 9504 } else if (mPackages.get(oldPkg.name) != null) { 9505 Slog.w(TAG, "Unable to update from " + oldPkg.name 9506 + " to " + newPkg.packageName 9507 + ": old package still exists"); 9508 return false; 9509 } 9510 return true; 9511 } 9512 9513 void removeCodePathLI(File codePath) { 9514 if (codePath.isDirectory()) { 9515 try { 9516 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 9517 } catch (InstallerException e) { 9518 Slog.w(TAG, "Failed to remove code path", e); 9519 } 9520 } else { 9521 codePath.delete(); 9522 } 9523 } 9524 9525 private int[] resolveUserIds(int userId) { 9526 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 9527 } 9528 9529 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 9530 if (pkg == null) { 9531 Slog.wtf(TAG, "Package was null!", new Throwable()); 9532 return; 9533 } 9534 clearAppDataLeafLIF(pkg, userId, flags); 9535 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9536 for (int i = 0; i < childCount; i++) { 9537 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 9538 } 9539 } 9540 9541 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 9542 final PackageSetting ps; 9543 synchronized (mPackages) { 9544 ps = mSettings.mPackages.get(pkg.packageName); 9545 } 9546 for (int realUserId : resolveUserIds(userId)) { 9547 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 9548 try { 9549 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 9550 ceDataInode); 9551 } catch (InstallerException e) { 9552 Slog.w(TAG, String.valueOf(e)); 9553 } 9554 } 9555 } 9556 9557 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 9558 if (pkg == null) { 9559 Slog.wtf(TAG, "Package was null!", new Throwable()); 9560 return; 9561 } 9562 destroyAppDataLeafLIF(pkg, userId, flags); 9563 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9564 for (int i = 0; i < childCount; i++) { 9565 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 9566 } 9567 } 9568 9569 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 9570 final PackageSetting ps; 9571 synchronized (mPackages) { 9572 ps = mSettings.mPackages.get(pkg.packageName); 9573 } 9574 for (int realUserId : resolveUserIds(userId)) { 9575 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 9576 try { 9577 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 9578 ceDataInode); 9579 } catch (InstallerException e) { 9580 Slog.w(TAG, String.valueOf(e)); 9581 } 9582 mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId); 9583 } 9584 } 9585 9586 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 9587 if (pkg == null) { 9588 Slog.wtf(TAG, "Package was null!", new Throwable()); 9589 return; 9590 } 9591 destroyAppProfilesLeafLIF(pkg); 9592 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9593 for (int i = 0; i < childCount; i++) { 9594 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 9595 } 9596 } 9597 9598 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 9599 try { 9600 mInstaller.destroyAppProfiles(pkg.packageName); 9601 } catch (InstallerException e) { 9602 Slog.w(TAG, String.valueOf(e)); 9603 } 9604 } 9605 9606 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 9607 if (pkg == null) { 9608 Slog.wtf(TAG, "Package was null!", new Throwable()); 9609 return; 9610 } 9611 clearAppProfilesLeafLIF(pkg); 9612 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9613 for (int i = 0; i < childCount; i++) { 9614 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 9615 } 9616 } 9617 9618 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 9619 try { 9620 mInstaller.clearAppProfiles(pkg.packageName); 9621 } catch (InstallerException e) { 9622 Slog.w(TAG, String.valueOf(e)); 9623 } 9624 } 9625 9626 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 9627 long lastUpdateTime) { 9628 // Set parent install/update time 9629 PackageSetting ps = (PackageSetting) pkg.mExtras; 9630 if (ps != null) { 9631 ps.firstInstallTime = firstInstallTime; 9632 ps.lastUpdateTime = lastUpdateTime; 9633 } 9634 // Set children install/update time 9635 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9636 for (int i = 0; i < childCount; i++) { 9637 PackageParser.Package childPkg = pkg.childPackages.get(i); 9638 ps = (PackageSetting) childPkg.mExtras; 9639 if (ps != null) { 9640 ps.firstInstallTime = firstInstallTime; 9641 ps.lastUpdateTime = lastUpdateTime; 9642 } 9643 } 9644 } 9645 9646 private void addSharedLibraryLPr(Set<String> usesLibraryFiles, 9647 SharedLibraryEntry file, 9648 PackageParser.Package changingLib) { 9649 if (file.path != null) { 9650 usesLibraryFiles.add(file.path); 9651 return; 9652 } 9653 PackageParser.Package p = mPackages.get(file.apk); 9654 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 9655 // If we are doing this while in the middle of updating a library apk, 9656 // then we need to make sure to use that new apk for determining the 9657 // dependencies here. (We haven't yet finished committing the new apk 9658 // to the package manager state.) 9659 if (p == null || p.packageName.equals(changingLib.packageName)) { 9660 p = changingLib; 9661 } 9662 } 9663 if (p != null) { 9664 usesLibraryFiles.addAll(p.getAllCodePaths()); 9665 if (p.usesLibraryFiles != null) { 9666 Collections.addAll(usesLibraryFiles, p.usesLibraryFiles); 9667 } 9668 } 9669 } 9670 9671 private void updateSharedLibrariesLPr(PackageParser.Package pkg, 9672 PackageParser.Package changingLib) throws PackageManagerException { 9673 if (pkg == null) { 9674 return; 9675 } 9676 // The collection used here must maintain the order of addition (so 9677 // that libraries are searched in the correct order) and must have no 9678 // duplicates. 9679 Set<String> usesLibraryFiles = null; 9680 if (pkg.usesLibraries != null) { 9681 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries, 9682 null, null, pkg.packageName, changingLib, true, 9683 pkg.applicationInfo.targetSdkVersion, null); 9684 } 9685 if (pkg.usesStaticLibraries != null) { 9686 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries, 9687 pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests, 9688 pkg.packageName, changingLib, true, 9689 pkg.applicationInfo.targetSdkVersion, usesLibraryFiles); 9690 } 9691 if (pkg.usesOptionalLibraries != null) { 9692 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries, 9693 null, null, pkg.packageName, changingLib, false, 9694 pkg.applicationInfo.targetSdkVersion, usesLibraryFiles); 9695 } 9696 if (!ArrayUtils.isEmpty(usesLibraryFiles)) { 9697 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]); 9698 } else { 9699 pkg.usesLibraryFiles = null; 9700 } 9701 } 9702 9703 private Set<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries, 9704 @Nullable int[] requiredVersions, @Nullable String[][] requiredCertDigests, 9705 @NonNull String packageName, @Nullable PackageParser.Package changingLib, 9706 boolean required, int targetSdk, @Nullable Set<String> outUsedLibraries) 9707 throws PackageManagerException { 9708 final int libCount = requestedLibraries.size(); 9709 for (int i = 0; i < libCount; i++) { 9710 final String libName = requestedLibraries.get(i); 9711 final int libVersion = requiredVersions != null ? requiredVersions[i] 9712 : SharedLibraryInfo.VERSION_UNDEFINED; 9713 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion); 9714 if (libEntry == null) { 9715 if (required) { 9716 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9717 "Package " + packageName + " requires unavailable shared library " 9718 + libName + "; failing!"); 9719 } else if (DEBUG_SHARED_LIBRARIES) { 9720 Slog.i(TAG, "Package " + packageName 9721 + " desires unavailable shared library " 9722 + libName + "; ignoring!"); 9723 } 9724 } else { 9725 if (requiredVersions != null && requiredCertDigests != null) { 9726 if (libEntry.info.getVersion() != requiredVersions[i]) { 9727 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9728 "Package " + packageName + " requires unavailable static shared" 9729 + " library " + libName + " version " 9730 + libEntry.info.getVersion() + "; failing!"); 9731 } 9732 9733 PackageParser.Package libPkg = mPackages.get(libEntry.apk); 9734 if (libPkg == null) { 9735 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9736 "Package " + packageName + " requires unavailable static shared" 9737 + " library; failing!"); 9738 } 9739 9740 final String[] expectedCertDigests = requiredCertDigests[i]; 9741 // For apps targeting O MR1 we require explicit enumeration of all certs. 9742 final String[] libCertDigests = (targetSdk > Build.VERSION_CODES.O) 9743 ? PackageUtils.computeSignaturesSha256Digests(libPkg.mSignatures) 9744 : PackageUtils.computeSignaturesSha256Digests( 9745 new Signature[]{libPkg.mSignatures[0]}); 9746 9747 // Take a shortcut if sizes don't match. Note that if an app doesn't 9748 // target O we don't parse the "additional-certificate" tags similarly 9749 // how we only consider all certs only for apps targeting O (see above). 9750 // Therefore, the size check is safe to make. 9751 if (expectedCertDigests.length != libCertDigests.length) { 9752 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9753 "Package " + packageName + " requires differently signed" + 9754 " static sDexLoadReporter.java:45.19hared library; failing!"); 9755 } 9756 9757 // Use a predictable order as signature order may vary 9758 Arrays.sort(libCertDigests); 9759 Arrays.sort(expectedCertDigests); 9760 9761 final int certCount = libCertDigests.length; 9762 for (int j = 0; j < certCount; j++) { 9763 if (!libCertDigests[j].equalsIgnoreCase(expectedCertDigests[j])) { 9764 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9765 "Package " + packageName + " requires differently signed" + 9766 " static shared library; failing!"); 9767 } 9768 } 9769 } 9770 9771 if (outUsedLibraries == null) { 9772 // Use LinkedHashSet to preserve the order of files added to 9773 // usesLibraryFiles while eliminating duplicates. 9774 outUsedLibraries = new LinkedHashSet<>(); 9775 } 9776 addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib); 9777 } 9778 } 9779 return outUsedLibraries; 9780 } 9781 9782 private static boolean hasString(List<String> list, List<String> which) { 9783 if (list == null) { 9784 return false; 9785 } 9786 for (int i=list.size()-1; i>=0; i--) { 9787 for (int j=which.size()-1; j>=0; j--) { 9788 if (which.get(j).equals(list.get(i))) { 9789 return true; 9790 } 9791 } 9792 } 9793 return false; 9794 } 9795 9796 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 9797 PackageParser.Package changingPkg) { 9798 ArrayList<PackageParser.Package> res = null; 9799 for (PackageParser.Package pkg : mPackages.values()) { 9800 if (changingPkg != null 9801 && !hasString(pkg.usesLibraries, changingPkg.libraryNames) 9802 && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames) 9803 && !ArrayUtils.contains(pkg.usesStaticLibraries, 9804 changingPkg.staticSharedLibName)) { 9805 return null; 9806 } 9807 if (res == null) { 9808 res = new ArrayList<>(); 9809 } 9810 res.add(pkg); 9811 try { 9812 updateSharedLibrariesLPr(pkg, changingPkg); 9813 } catch (PackageManagerException e) { 9814 // If a system app update or an app and a required lib missing we 9815 // delete the package and for updated system apps keep the data as 9816 // it is better for the user to reinstall than to be in an limbo 9817 // state. Also libs disappearing under an app should never happen 9818 // - just in case. 9819 if (!pkg.isSystem() || pkg.isUpdatedSystemApp()) { 9820 final int flags = pkg.isUpdatedSystemApp() 9821 ? PackageManager.DELETE_KEEP_DATA : 0; 9822 deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(), 9823 flags , null, true, null); 9824 } 9825 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 9826 } 9827 } 9828 return res; 9829 } 9830 9831 /** 9832 * Derive the value of the {@code cpuAbiOverride} based on the provided 9833 * value and an optional stored value from the package settings. 9834 */ 9835 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 9836 String cpuAbiOverride = null; 9837 9838 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 9839 cpuAbiOverride = null; 9840 } else if (abiOverride != null) { 9841 cpuAbiOverride = abiOverride; 9842 } else if (settings != null) { 9843 cpuAbiOverride = settings.cpuAbiOverrideString; 9844 } 9845 9846 return cpuAbiOverride; 9847 } 9848 9849 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 9850 final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user) 9851 throws PackageManagerException { 9852 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 9853 // If the package has children and this is the first dive in the function 9854 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 9855 // whether all packages (parent and children) would be successfully scanned 9856 // before the actual scan since scanning mutates internal state and we want 9857 // to atomically install the package and its children. 9858 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 9859 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 9860 scanFlags |= SCAN_CHECK_ONLY; 9861 } 9862 } else { 9863 scanFlags &= ~SCAN_CHECK_ONLY; 9864 } 9865 9866 final PackageParser.Package scannedPkg; 9867 try { 9868 // Scan the parent 9869 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 9870 // Scan the children 9871 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9872 for (int i = 0; i < childCount; i++) { 9873 PackageParser.Package childPkg = pkg.childPackages.get(i); 9874 scanPackageLI(childPkg, policyFlags, 9875 scanFlags, currentTime, user); 9876 } 9877 } finally { 9878 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9879 } 9880 9881 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 9882 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 9883 } 9884 9885 return scannedPkg; 9886 } 9887 9888 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 9889 int scanFlags, long currentTime, @Nullable UserHandle user) 9890 throws PackageManagerException { 9891 boolean success = false; 9892 try { 9893 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 9894 currentTime, user); 9895 success = true; 9896 return res; 9897 } finally { 9898 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 9899 // DELETE_DATA_ON_FAILURES is only used by frozen paths 9900 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 9901 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 9902 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 9903 } 9904 } 9905 } 9906 9907 /** 9908 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 9909 */ 9910 private static boolean apkHasCode(String fileName) { 9911 StrictJarFile jarFile = null; 9912 try { 9913 jarFile = new StrictJarFile(fileName, 9914 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 9915 return jarFile.findEntry("classes.dex") != null; 9916 } catch (IOException ignore) { 9917 } finally { 9918 try { 9919 if (jarFile != null) { 9920 jarFile.close(); 9921 } 9922 } catch (IOException ignore) {} 9923 } 9924 return false; 9925 } 9926 9927 /** 9928 * Enforces code policy for the package. This ensures that if an APK has 9929 * declared hasCode="true" in its manifest that the APK actually contains 9930 * code. 9931 * 9932 * @throws PackageManagerException If bytecode could not be found when it should exist 9933 */ 9934 private static void assertCodePolicy(PackageParser.Package pkg) 9935 throws PackageManagerException { 9936 final boolean shouldHaveCode = 9937 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 9938 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 9939 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 9940 "Package " + pkg.baseCodePath + " code is missing"); 9941 } 9942 9943 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 9944 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 9945 final boolean splitShouldHaveCode = 9946 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 9947 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 9948 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 9949 "Package " + pkg.splitCodePaths[i] + " code is missing"); 9950 } 9951 } 9952 } 9953 } 9954 9955 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 9956 final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user) 9957 throws PackageManagerException { 9958 if (DEBUG_PACKAGE_SCANNING) { 9959 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 9960 Log.d(TAG, "Scanning package " + pkg.packageName); 9961 } 9962 9963 applyPolicy(pkg, policyFlags); 9964 9965 assertPackageIsValid(pkg, policyFlags, scanFlags); 9966 9967 if (Build.IS_DEBUGGABLE && 9968 pkg.isPrivileged() && 9969 !SystemProperties.getBoolean("pm.dexopt.priv-apps", true)) { 9970 PackageManagerServiceUtils.logPackageHasUncompressedCode(pkg); 9971 } 9972 9973 // Initialize package source and resource directories 9974 final File scanFile = new File(pkg.codePath); 9975 final File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 9976 final File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 9977 9978 SharedUserSetting suid = null; 9979 PackageSetting pkgSetting = null; 9980 9981 // Getting the package setting may have a side-effect, so if we 9982 // are only checking if scan would succeed, stash a copy of the 9983 // old setting to restore at the end. 9984 PackageSetting nonMutatedPs = null; 9985 9986 // We keep references to the derived CPU Abis from settings in oder to reuse 9987 // them in the case where we're not upgrading or booting for the first time. 9988 String primaryCpuAbiFromSettings = null; 9989 String secondaryCpuAbiFromSettings = null; 9990 9991 // writer 9992 synchronized (mPackages) { 9993 if (pkg.mSharedUserId != null) { 9994 // SIDE EFFECTS; may potentially allocate a new shared user 9995 suid = mSettings.getSharedUserLPw( 9996 pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/); 9997 if (DEBUG_PACKAGE_SCANNING) { 9998 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 9999 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 10000 + "): packages=" + suid.packages); 10001 } 10002 } 10003 10004 // Check if we are renaming from an original package name. 10005 PackageSetting origPackage = null; 10006 String realName = null; 10007 if (pkg.mOriginalPackages != null) { 10008 // This package may need to be renamed to a previously 10009 // installed name. Let's check on that... 10010 final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage); 10011 if (pkg.mOriginalPackages.contains(renamed)) { 10012 // This package had originally been installed as the 10013 // original name, and we have already taken care of 10014 // transitioning to the new one. Just update the new 10015 // one to continue using the old name. 10016 realName = pkg.mRealPackage; 10017 if (!pkg.packageName.equals(renamed)) { 10018 // Callers into this function may have already taken 10019 // care of renaming the package; only do it here if 10020 // it is not already done. 10021 pkg.setPackageName(renamed); 10022 } 10023 } else { 10024 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 10025 if ((origPackage = mSettings.getPackageLPr( 10026 pkg.mOriginalPackages.get(i))) != null) { 10027 // We do have the package already installed under its 10028 // original name... should we use it? 10029 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 10030 // New package is not compatible with original. 10031 origPackage = null; 10032 continue; 10033 } else if (origPackage.sharedUser != null) { 10034 // Make sure uid is compatible between packages. 10035 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 10036 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 10037 + " to " + pkg.packageName + ": old uid " 10038 + origPackage.sharedUser.name 10039 + " differs from " + pkg.mSharedUserId); 10040 origPackage = null; 10041 continue; 10042 } 10043 // TODO: Add case when shared user id is added [b/28144775] 10044 } else { 10045 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 10046 + pkg.packageName + " to old name " + origPackage.name); 10047 } 10048 break; 10049 } 10050 } 10051 } 10052 } 10053 10054 if (mTransferedPackages.contains(pkg.packageName)) { 10055 Slog.w(TAG, "Package " + pkg.packageName 10056 + " was transferred to another, but its .apk remains"); 10057 } 10058 10059 // See comments in nonMutatedPs declaration 10060 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 10061 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName); 10062 if (foundPs != null) { 10063 nonMutatedPs = new PackageSetting(foundPs); 10064 } 10065 } 10066 10067 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) { 10068 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName); 10069 if (foundPs != null) { 10070 primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString; 10071 secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString; 10072 } 10073 } 10074 10075 pkgSetting = mSettings.getPackageLPr(pkg.packageName); 10076 if (pkgSetting != null && pkgSetting.sharedUser != suid) { 10077 PackageManagerService.reportSettingsProblem(Log.WARN, 10078 "Package " + pkg.packageName + " shared user changed from " 10079 + (pkgSetting.sharedUser != null 10080 ? pkgSetting.sharedUser.name : "<nothing>") 10081 + " to " 10082 + (suid != null ? suid.name : "<nothing>") 10083 + "; replacing with new"); 10084 pkgSetting = null; 10085 } 10086 final PackageSetting oldPkgSetting = 10087 pkgSetting == null ? null : new PackageSetting(pkgSetting); 10088 final PackageSetting disabledPkgSetting = 10089 mSettings.getDisabledSystemPkgLPr(pkg.packageName); 10090 10091 String[] usesStaticLibraries = null; 10092 if (pkg.usesStaticLibraries != null) { 10093 usesStaticLibraries = new String[pkg.usesStaticLibraries.size()]; 10094 pkg.usesStaticLibraries.toArray(usesStaticLibraries); 10095 } 10096 10097 if (pkgSetting == null) { 10098 final String parentPackageName = (pkg.parentPackage != null) 10099 ? pkg.parentPackage.packageName : null; 10100 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 10101 final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0; 10102 // REMOVE SharedUserSetting from method; update in a separate call 10103 pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage, 10104 disabledPkgSetting, realName, suid, destCodeFile, destResourceFile, 10105 pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi, 10106 pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode, 10107 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user, 10108 true /*allowInstall*/, instantApp, virtualPreload, 10109 parentPackageName, pkg.getChildPackageNames(), 10110 UserManagerService.getInstance(), usesStaticLibraries, 10111 pkg.usesStaticLibrariesVersions); 10112 // SIDE EFFECTS; updates system state; move elsewhere 10113 if (origPackage != null) { 10114 mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name); 10115 } 10116 mSettings.addUserToSettingLPw(pkgSetting); 10117 } else { 10118 // REMOVE SharedUserSetting from method; update in a separate call. 10119 // 10120 // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi, 10121 // secondaryCpuAbi are not known at this point so we always update them 10122 // to null here, only to reset them at a later point. 10123 Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile, 10124 pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi, 10125 pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags, 10126 pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(), 10127 UserManagerService.getInstance(), usesStaticLibraries, 10128 pkg.usesStaticLibrariesVersions); 10129 } 10130 // SIDE EFFECTS; persists system state to files on disk; move elsewhere 10131 mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting); 10132 10133 // SIDE EFFECTS; modifies system state; move elsewhere 10134 if (pkgSetting.origPackage != null) { 10135 // If we are first transitioning from an original package, 10136 // fix up the new package's name now. We need to do this after 10137 // looking up the package under its new name, so getPackageLP 10138 // can take care of fiddling things correctly. 10139 pkg.setPackageName(origPackage.name); 10140 10141 // File a report about this. 10142 String msg = "New package " + pkgSetting.realName 10143 + " renamed to replace old package " + pkgSetting.name; 10144 reportSettingsProblem(Log.WARN, msg); 10145 10146 // Make a note of it. 10147 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 10148 mTransferedPackages.add(origPackage.name); 10149 } 10150 10151 // No longer need to retain this. 10152 pkgSetting.origPackage = null; 10153 } 10154 10155 // SIDE EFFECTS; modifies system state; move elsewhere 10156 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 10157 // Make a note of it. 10158 mTransferedPackages.add(pkg.packageName); 10159 } 10160 10161 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 10162 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 10163 } 10164 10165 if ((scanFlags & SCAN_BOOTING) == 0 10166 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 10167 // Check all shared libraries and map to their actual file path. 10168 // We only do this here for apps not on a system dir, because those 10169 // are the only ones that can fail an install due to this. We 10170 // will take care of the system apps by updating all of their 10171 // library paths after the scan is done. Also during the initial 10172 // scan don't update any libs as we do this wholesale after all 10173 // apps are scanned to avoid dependency based scanning. 10174 updateSharedLibrariesLPr(pkg, null); 10175 } 10176 10177 if (mFoundPolicyFile) { 10178 SELinuxMMAC.assignSeInfoValue(pkg); 10179 } 10180 pkg.applicationInfo.uid = pkgSetting.appId; 10181 pkg.mExtras = pkgSetting; 10182 10183 10184 // Static shared libs have same package with different versions where 10185 // we internally use a synthetic package name to allow multiple versions 10186 // of the same package, therefore we need to compare signatures against 10187 // the package setting for the latest library version. 10188 PackageSetting signatureCheckPs = pkgSetting; 10189 if (pkg.applicationInfo.isStaticSharedLibrary()) { 10190 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg); 10191 if (libraryEntry != null) { 10192 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk); 10193 } 10194 } 10195 10196 if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) { 10197 if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) { 10198 // We just determined the app is signed correctly, so bring 10199 // over the latest parsed certs. 10200 pkgSetting.signatures.mSignatures = pkg.mSignatures; 10201 } else { 10202 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 10203 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 10204 "Package " + pkg.packageName + " upgrade keys do not match the " 10205 + "previously installed version"); 10206 } else { 10207 pkgSetting.signatures.mSignatures = pkg.mSignatures; 10208 String msg = "System package " + pkg.packageName 10209 + " signature changed; retaining data."; 10210 reportSettingsProblem(Log.WARN, msg); 10211 } 10212 } 10213 } else { 10214 try { 10215 // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService 10216 verifySignaturesLP(signatureCheckPs, pkg); 10217 // We just determined the app is signed correctly, so bring 10218 // over the latest parsed certs. 10219 pkgSetting.signatures.mSignatures = pkg.mSignatures; 10220 } catch (PackageManagerException e) { 10221 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 10222 throw e; 10223 } 10224 // The signature has changed, but this package is in the system 10225 // image... let's recover! 10226 pkgSetting.signatures.mSignatures = pkg.mSignatures; 10227 // However... if this package is part of a shared user, but it 10228 // doesn't match the signature of the shared user, let's fail. 10229 // What this means is that you can't change the signatures 10230 // associated with an overall shared user, which doesn't seem all 10231 // that unreasonable. 10232 if (signatureCheckPs.sharedUser != null) { 10233 if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures, 10234 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 10235 throw new PackageManagerException( 10236 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 10237 "Signature mismatch for shared user: " 10238 + pkgSetting.sharedUser); 10239 } 10240 } 10241 // File a report about this. 10242 String msg = "System package " + pkg.packageName 10243 + " signature changed; retaining data."; 10244 reportSettingsProblem(Log.WARN, msg); 10245 } 10246 } 10247 10248 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 10249 // This package wants to adopt ownership of permissions from 10250 // another package. 10251 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 10252 final String origName = pkg.mAdoptPermissions.get(i); 10253 final PackageSetting orig = mSettings.getPackageLPr(origName); 10254 if (orig != null) { 10255 if (verifyPackageUpdateLPr(orig, pkg)) { 10256 Slog.i(TAG, "Adopting permissions from " + origName + " to " 10257 + pkg.packageName); 10258 // SIDE EFFECTS; updates permissions system state; move elsewhere 10259 mSettings.mPermissions.transferPermissions(origName, pkg.packageName); 10260 } 10261 } 10262 } 10263 } 10264 } 10265 10266 pkg.applicationInfo.processName = fixProcessName( 10267 pkg.applicationInfo.packageName, 10268 pkg.applicationInfo.processName); 10269 10270 if (pkg != mPlatformPackage) { 10271 // Get all of our default paths setup 10272 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 10273 } 10274 10275 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 10276 10277 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 10278 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) { 10279 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi"); 10280 final boolean extractNativeLibs = !pkg.isLibrary(); 10281 derivePackageAbi(pkg, scanFile, cpuAbiOverride, extractNativeLibs, 10282 mAppLib32InstallDir); 10283 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10284 10285 // Some system apps still use directory structure for native libraries 10286 // in which case we might end up not detecting abi solely based on apk 10287 // structure. Try to detect abi based on directory structure. 10288 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 10289 pkg.applicationInfo.primaryCpuAbi == null) { 10290 setBundledAppAbisAndRoots(pkg, pkgSetting); 10291 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 10292 } 10293 } else { 10294 // This is not a first boot or an upgrade, don't bother deriving the 10295 // ABI during the scan. Instead, trust the value that was stored in the 10296 // package setting. 10297 pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings; 10298 pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings; 10299 10300 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 10301 10302 if (DEBUG_ABI_SELECTION) { 10303 Slog.i(TAG, "Using ABIS and native lib paths from settings : " + 10304 pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " + 10305 pkg.applicationInfo.secondaryCpuAbi); 10306 } 10307 } 10308 } else { 10309 if ((scanFlags & SCAN_MOVE) != 0) { 10310 // We haven't run dex-opt for this move (since we've moved the compiled output too) 10311 // but we already have this packages package info in the PackageSetting. We just 10312 // use that and derive the native library path based on the new codepath. 10313 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 10314 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 10315 } 10316 10317 // Set native library paths again. For moves, the path will be updated based on the 10318 // ABIs we've determined above. For non-moves, the path will be updated based on the 10319 // ABIs we determined during compilation, but the path will depend on the final 10320 // package path (after the rename away from the stage path). 10321 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 10322 } 10323 10324 // This is a special case for the "system" package, where the ABI is 10325 // dictated by the zygote configuration (and init.rc). We should keep track 10326 // of this ABI so that we can deal with "normal" applications that run under 10327 // the same UID correctly. 10328 if (mPlatformPackage == pkg) { 10329 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 10330 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 10331 } 10332 10333 // If there's a mismatch between the abi-override in the package setting 10334 // and the abiOverride specified for the install. Warn about this because we 10335 // would've already compiled the app without taking the package setting into 10336 // account. 10337 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 10338 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 10339 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 10340 " for package " + pkg.packageName); 10341 } 10342 } 10343 10344 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 10345 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 10346 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 10347 10348 // Copy the derived override back to the parsed package, so that we can 10349 // update the package settings accordingly. 10350 pkg.cpuAbiOverride = cpuAbiOverride; 10351 10352 if (DEBUG_ABI_SELECTION) { 10353 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 10354 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 10355 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 10356 } 10357 10358 // Push the derived path down into PackageSettings so we know what to 10359 // clean up at uninstall time. 10360 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 10361 10362 if (DEBUG_ABI_SELECTION) { 10363 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 10364 " primary=" + pkg.applicationInfo.primaryCpuAbi + 10365 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 10366 } 10367 10368 // SIDE EFFECTS; removes DEX files from disk; move elsewhere 10369 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 10370 // We don't do this here during boot because we can do it all 10371 // at once after scanning all existing packages. 10372 // 10373 // We also do this *before* we perform dexopt on this package, so that 10374 // we can avoid redundant dexopts, and also to make sure we've got the 10375 // code and package path correct. 10376 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg); 10377 } 10378 10379 if (mFactoryTest && pkg.requestedPermissions.contains( 10380 android.Manifest.permission.FACTORY_TEST)) { 10381 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 10382 } 10383 10384 if (isSystemApp(pkg)) { 10385 pkgSetting.isOrphaned = true; 10386 } 10387 10388 // Take care of first install / last update times. 10389 final long scanFileTime = getLastModifiedTime(pkg, scanFile); 10390 if (currentTime != 0) { 10391 if (pkgSetting.firstInstallTime == 0) { 10392 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 10393 } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) { 10394 pkgSetting.lastUpdateTime = currentTime; 10395 } 10396 } else if (pkgSetting.firstInstallTime == 0) { 10397 // We need *something*. Take time time stamp of the file. 10398 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 10399 } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 10400 if (scanFileTime != pkgSetting.timeStamp) { 10401 // A package on the system image has changed; consider this 10402 // to be an update. 10403 pkgSetting.lastUpdateTime = scanFileTime; 10404 } 10405 } 10406 pkgSetting.setTimeStamp(scanFileTime); 10407 10408 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 10409 if (nonMutatedPs != null) { 10410 synchronized (mPackages) { 10411 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 10412 } 10413 } 10414 } else { 10415 final int userId = user == null ? 0 : user.getIdentifier(); 10416 // Modify state for the given package setting 10417 commitPackageSettings(pkg, pkgSetting, user, scanFlags, 10418 (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/); 10419 if (pkgSetting.getInstantApp(userId)) { 10420 mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId); 10421 } 10422 } 10423 return pkg; 10424 } 10425 10426 /** 10427 * Applies policy to the parsed package based upon the given policy flags. 10428 * Ensures the package is in a good state. 10429 * <p> 10430 * Implementation detail: This method must NOT have any side effect. It would 10431 * ideally be static, but, it requires locks to read system state. 10432 */ 10433 private void applyPolicy(PackageParser.Package pkg, int policyFlags) { 10434 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 10435 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 10436 if (pkg.applicationInfo.isDirectBootAware()) { 10437 // we're direct boot aware; set for all components 10438 for (PackageParser.Service s : pkg.services) { 10439 s.info.encryptionAware = s.info.directBootAware = true; 10440 } 10441 for (PackageParser.Provider p : pkg.providers) { 10442 p.info.encryptionAware = p.info.directBootAware = true; 10443 } 10444 for (PackageParser.Activity a : pkg.activities) { 10445 a.info.encryptionAware = a.info.directBootAware = true; 10446 } 10447 for (PackageParser.Activity r : pkg.receivers) { 10448 r.info.encryptionAware = r.info.directBootAware = true; 10449 } 10450 } 10451 if (compressedFileExists(pkg.codePath)) { 10452 pkg.isStub = true; 10453 } 10454 } else { 10455 // Only allow system apps to be flagged as core apps. 10456 pkg.coreApp = false; 10457 // clear flags not applicable to regular apps 10458 pkg.applicationInfo.privateFlags &= 10459 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 10460 pkg.applicationInfo.privateFlags &= 10461 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 10462 } 10463 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 10464 10465 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 10466 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 10467 } 10468 10469 if ((policyFlags&PackageParser.PARSE_IS_OEM) != 0) { 10470 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM; 10471 } 10472 10473 if (!isSystemApp(pkg)) { 10474 // Only system apps can use these features. 10475 pkg.mOriginalPackages = null; 10476 pkg.mRealPackage = null; 10477 pkg.mAdoptPermissions = null; 10478 } 10479 } 10480 10481 /** 10482 * Asserts the parsed package is valid according to the given policy. If the 10483 * package is invalid, for whatever reason, throws {@link PackageManagerException}. 10484 * <p> 10485 * Implementation detail: This method must NOT have any side effects. It would 10486 * ideally be static, but, it requires locks to read system state. 10487 * 10488 * @throws PackageManagerException If the package fails any of the validation checks 10489 */ 10490 private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags) 10491 throws PackageManagerException { 10492 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 10493 assertCodePolicy(pkg); 10494 } 10495 10496 if (pkg.applicationInfo.getCodePath() == null || 10497 pkg.applicationInfo.getResourcePath() == null) { 10498 // Bail out. The resource and code paths haven't been set. 10499 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 10500 "Code and resource paths haven't been set correctly"); 10501 } 10502 10503 // Make sure we're not adding any bogus keyset info 10504 KeySetManagerService ksms = mSettings.mKeySetManagerService; 10505 ksms.assertScannedPackageValid(pkg); 10506 10507 synchronized (mPackages) { 10508 // The special "android" package can only be defined once 10509 if (pkg.packageName.equals("android")) { 10510 if (mAndroidApplication != null) { 10511 Slog.w(TAG, "*************************************************"); 10512 Slog.w(TAG, "Core android package being redefined. Skipping."); 10513 Slog.w(TAG, " codePath=" + pkg.codePath); 10514 Slog.w(TAG, "*************************************************"); 10515 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 10516 "Core android package being redefined. Skipping."); 10517 } 10518 } 10519 10520 // A package name must be unique; don't allow duplicates 10521 if (mPackages.containsKey(pkg.packageName)) { 10522 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 10523 "Application package " + pkg.packageName 10524 + " already installed. Skipping duplicate."); 10525 } 10526 10527 if (pkg.applicationInfo.isStaticSharedLibrary()) { 10528 // Static libs have a synthetic package name containing the version 10529 // but we still want the base name to be unique. 10530 if (mPackages.containsKey(pkg.manifestPackageName)) { 10531 throw new PackageManagerException( 10532 "Duplicate static shared lib provider package"); 10533 } 10534 10535 // Static shared libraries should have at least O target SDK 10536 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) { 10537 throw new PackageManagerException( 10538 "Packages declaring static-shared libs must target O SDK or higher"); 10539 } 10540 10541 // Package declaring static a shared lib cannot be instant apps 10542 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 10543 throw new PackageManagerException( 10544 "Packages declaring static-shared libs cannot be instant apps"); 10545 } 10546 10547 // Package declaring static a shared lib cannot be renamed since the package 10548 // name is synthetic and apps can't code around package manager internals. 10549 if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) { 10550 throw new PackageManagerException( 10551 "Packages declaring static-shared libs cannot be renamed"); 10552 } 10553 10554 // Package declaring static a shared lib cannot declare child packages 10555 if (!ArrayUtils.isEmpty(pkg.childPackages)) { 10556 throw new PackageManagerException( 10557 "Packages declaring static-shared libs cannot have child packages"); 10558 } 10559 10560 // Package declaring static a shared lib cannot declare dynamic libs 10561 if (!ArrayUtils.isEmpty(pkg.libraryNames)) { 10562 throw new PackageManagerException( 10563 "Packages declaring static-shared libs cannot declare dynamic libs"); 10564 } 10565 10566 // Package declaring static a shared lib cannot declare shared users 10567 if (pkg.mSharedUserId != null) { 10568 throw new PackageManagerException( 10569 "Packages declaring static-shared libs cannot declare shared users"); 10570 } 10571 10572 // Static shared libs cannot declare activities 10573 if (!pkg.activities.isEmpty()) { 10574 throw new PackageManagerException( 10575 "Static shared libs cannot declare activities"); 10576 } 10577 10578 // Static shared libs cannot declare services 10579 if (!pkg.services.isEmpty()) { 10580 throw new PackageManagerException( 10581 "Static shared libs cannot declare services"); 10582 } 10583 10584 // Static shared libs cannot declare providers 10585 if (!pkg.providers.isEmpty()) { 10586 throw new PackageManagerException( 10587 "Static shared libs cannot declare content providers"); 10588 } 10589 10590 // Static shared libs cannot declare receivers 10591 if (!pkg.receivers.isEmpty()) { 10592 throw new PackageManagerException( 10593 "Static shared libs cannot declare broadcast receivers"); 10594 } 10595 10596 // Static shared libs cannot declare permission groups 10597 if (!pkg.permissionGroups.isEmpty()) { 10598 throw new PackageManagerException( 10599 "Static shared libs cannot declare permission groups"); 10600 } 10601 10602 // Static shared libs cannot declare permissions 10603 if (!pkg.permissions.isEmpty()) { 10604 throw new PackageManagerException( 10605 "Static shared libs cannot declare permissions"); 10606 } 10607 10608 // Static shared libs cannot declare protected broadcasts 10609 if (pkg.protectedBroadcasts != null) { 10610 throw new PackageManagerException( 10611 "Static shared libs cannot declare protected broadcasts"); 10612 } 10613 10614 // Static shared libs cannot be overlay targets 10615 if (pkg.mOverlayTarget != null) { 10616 throw new PackageManagerException( 10617 "Static shared libs cannot be overlay targets"); 10618 } 10619 10620 // The version codes must be ordered as lib versions 10621 int minVersionCode = Integer.MIN_VALUE; 10622 int maxVersionCode = Integer.MAX_VALUE; 10623 10624 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get( 10625 pkg.staticSharedLibName); 10626 if (versionedLib != null) { 10627 final int versionCount = versionedLib.size(); 10628 for (int i = 0; i < versionCount; i++) { 10629 SharedLibraryInfo libInfo = versionedLib.valueAt(i).info; 10630 final int libVersionCode = libInfo.getDeclaringPackage() 10631 .getVersionCode(); 10632 if (libInfo.getVersion() < pkg.staticSharedLibVersion) { 10633 minVersionCode = Math.max(minVersionCode, libVersionCode + 1); 10634 } else if (libInfo.getVersion() > pkg.staticSharedLibVersion) { 10635 maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1); 10636 } else { 10637 minVersionCode = maxVersionCode = libVersionCode; 10638 break; 10639 } 10640 } 10641 } 10642 if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) { 10643 throw new PackageManagerException("Static shared" 10644 + " lib version codes must be ordered as lib versions"); 10645 } 10646 } 10647 10648 // Only privileged apps and updated privileged apps can add child packages. 10649 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 10650 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 10651 throw new PackageManagerException("Only privileged apps can add child " 10652 + "packages. Ignoring package " + pkg.packageName); 10653 } 10654 final int childCount = pkg.childPackages.size(); 10655 for (int i = 0; i < childCount; i++) { 10656 PackageParser.Package childPkg = pkg.childPackages.get(i); 10657 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 10658 childPkg.packageName)) { 10659 throw new PackageManagerException("Can't override child of " 10660 + "another disabled app. Ignoring package " + pkg.packageName); 10661 } 10662 } 10663 } 10664 10665 // If we're only installing presumed-existing packages, require that the 10666 // scanned APK is both already known and at the path previously established 10667 // for it. Previously unknown packages we pick up normally, but if we have an 10668 // a priori expectation about this package's install presence, enforce it. 10669 // With a singular exception for new system packages. When an OTA contains 10670 // a new system package, we allow the codepath to change from a system location 10671 // to the user-installed location. If we don't allow this change, any newer, 10672 // user-installed version of the application will be ignored. 10673 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 10674 if (mExpectingBetter.containsKey(pkg.packageName)) { 10675 logCriticalInfo(Log.WARN, 10676 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 10677 } else { 10678 PackageSetting known = mSettings.getPackageLPr(pkg.packageName); 10679 if (known != null) { 10680 if (DEBUG_PACKAGE_SCANNING) { 10681 Log.d(TAG, "Examining " + pkg.codePath 10682 + " and requiring known paths " + known.codePathString 10683 + " & " + known.resourcePathString); 10684 } 10685 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 10686 || !pkg.applicationInfo.getResourcePath().equals( 10687 known.resourcePathString)) { 10688 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 10689 "Application package " + pkg.packageName 10690 + " found at " + pkg.applicationInfo.getCodePath() 10691 + " but expected at " + known.codePathString 10692 + "; ignoring."); 10693 } 10694 } else { 10695 throw new PackageManagerException(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 10696 "Application package " + pkg.packageName 10697 + " not found; ignoring."); 10698 } 10699 } 10700 } 10701 10702 // Verify that this new package doesn't have any content providers 10703 // that conflict with existing packages. Only do this if the 10704 // package isn't already installed, since we don't want to break 10705 // things that are installed. 10706 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 10707 final int N = pkg.providers.size(); 10708 int i; 10709 for (i=0; i<N; i++) { 10710 PackageParser.Provider p = pkg.providers.get(i); 10711 if (p.info.authority != null) { 10712 String names[] = p.info.authority.split(";"); 10713 for (int j = 0; j < names.length; j++) { 10714 if (mProvidersByAuthority.containsKey(names[j])) { 10715 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 10716 final String otherPackageName = 10717 ((other != null && other.getComponentName() != null) ? 10718 other.getComponentName().getPackageName() : "?"); 10719 throw new PackageManagerException( 10720 INSTALL_FAILED_CONFLICTING_PROVIDER, 10721 "Can't install because provider name " + names[j] 10722 + " (in package " + pkg.applicationInfo.packageName 10723 + ") is already used by " + otherPackageName); 10724 } 10725 } 10726 } 10727 } 10728 } 10729 } 10730 } 10731 10732 private boolean addSharedLibraryLPw(String path, String apk, String name, int version, 10733 int type, String declaringPackageName, int declaringVersionCode) { 10734 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 10735 if (versionedLib == null) { 10736 versionedLib = new SparseArray<>(); 10737 mSharedLibraries.put(name, versionedLib); 10738 if (type == SharedLibraryInfo.TYPE_STATIC) { 10739 mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib); 10740 } 10741 } else if (versionedLib.indexOfKey(version) >= 0) { 10742 return false; 10743 } 10744 SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name, 10745 version, type, declaringPackageName, declaringVersionCode); 10746 versionedLib.put(version, libEntry); 10747 return true; 10748 } 10749 10750 private boolean removeSharedLibraryLPw(String name, int version) { 10751 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 10752 if (versionedLib == null) { 10753 return false; 10754 } 10755 final int libIdx = versionedLib.indexOfKey(version); 10756 if (libIdx < 0) { 10757 return false; 10758 } 10759 SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx); 10760 versionedLib.remove(version); 10761 if (versionedLib.size() <= 0) { 10762 mSharedLibraries.remove(name); 10763 if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) { 10764 mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage() 10765 .getPackageName()); 10766 } 10767 } 10768 return true; 10769 } 10770 10771 /** 10772 * Adds a scanned package to the system. When this method is finished, the package will 10773 * be available for query, resolution, etc... 10774 */ 10775 private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting, 10776 UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException { 10777 final String pkgName = pkg.packageName; 10778 if (mCustomResolverComponentName != null && 10779 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 10780 setUpCustomResolverActivity(pkg); 10781 } 10782 10783 if (pkg.packageName.equals("android")) { 10784 synchronized (mPackages) { 10785 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 10786 // Set up information for our fall-back user intent resolution activity. 10787 mPlatformPackage = pkg; 10788 pkg.mVersionCode = mSdkVersion; 10789 mAndroidApplication = pkg.applicationInfo; 10790 if (!mResolverReplaced) { 10791 mResolveActivity.applicationInfo = mAndroidApplication; 10792 mResolveActivity.name = ResolverActivity.class.getName(); 10793 mResolveActivity.packageName = mAndroidApplication.packageName; 10794 mResolveActivity.processName = "system:ui"; 10795 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 10796 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 10797 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 10798 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 10799 mResolveActivity.exported = true; 10800 mResolveActivity.enabled = true; 10801 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 10802 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 10803 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 10804 | ActivityInfo.CONFIG_SCREEN_LAYOUT 10805 | ActivityInfo.CONFIG_ORIENTATION 10806 | ActivityInfo.CONFIG_KEYBOARD 10807 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 10808 mResolveInfo.activityInfo = mResolveActivity; 10809 mResolveInfo.priority = 0; 10810 mResolveInfo.preferredOrder = 0; 10811 mResolveInfo.match = 0; 10812 mResolveComponentName = new ComponentName( 10813 mAndroidApplication.packageName, mResolveActivity.name); 10814 } 10815 } 10816 } 10817 } 10818 10819 ArrayList<PackageParser.Package> clientLibPkgs = null; 10820 // writer 10821 synchronized (mPackages) { 10822 boolean hasStaticSharedLibs = false; 10823 10824 // Any app can add new static shared libraries 10825 if (pkg.staticSharedLibName != null) { 10826 // Static shared libs don't allow renaming as they have synthetic package 10827 // names to allow install of multiple versions, so use name from manifest. 10828 if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName, 10829 pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC, 10830 pkg.manifestPackageName, pkg.mVersionCode)) { 10831 hasStaticSharedLibs = true; 10832 } else { 10833 Slog.w(TAG, "Package " + pkg.packageName + " library " 10834 + pkg.staticSharedLibName + " already exists; skipping"); 10835 } 10836 // Static shared libs cannot be updated once installed since they 10837 // use synthetic package name which includes the version code, so 10838 // not need to update other packages's shared lib dependencies. 10839 } 10840 10841 if (!hasStaticSharedLibs 10842 && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 10843 // Only system apps can add new dynamic shared libraries. 10844 if (pkg.libraryNames != null) { 10845 for (int i = 0; i < pkg.libraryNames.size(); i++) { 10846 String name = pkg.libraryNames.get(i); 10847 boolean allowed = false; 10848 if (pkg.isUpdatedSystemApp()) { 10849 // New library entries can only be added through the 10850 // system image. This is important to get rid of a lot 10851 // of nasty edge cases: for example if we allowed a non- 10852 // system update of the app to add a library, then uninstalling 10853 // the update would make the library go away, and assumptions 10854 // we made such as through app install filtering would now 10855 // have allowed apps on the device which aren't compatible 10856 // with it. Better to just have the restriction here, be 10857 // conservative, and create many fewer cases that can negatively 10858 // impact the user experience. 10859 final PackageSetting sysPs = mSettings 10860 .getDisabledSystemPkgLPr(pkg.packageName); 10861 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 10862 for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) { 10863 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 10864 allowed = true; 10865 break; 10866 } 10867 } 10868 } 10869 } else { 10870 allowed = true; 10871 } 10872 if (allowed) { 10873 if (!addSharedLibraryLPw(null, pkg.packageName, name, 10874 SharedLibraryInfo.VERSION_UNDEFINED, 10875 SharedLibraryInfo.TYPE_DYNAMIC, 10876 pkg.packageName, pkg.mVersionCode)) { 10877 Slog.w(TAG, "Package " + pkg.packageName + " library " 10878 + name + " already exists; skipping"); 10879 } 10880 } else { 10881 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 10882 + name + " that is not declared on system image; skipping"); 10883 } 10884 } 10885 10886 if ((scanFlags & SCAN_BOOTING) == 0) { 10887 // If we are not booting, we need to update any applications 10888 // that are clients of our shared library. If we are booting, 10889 // this will all be done once the scan is complete. 10890 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 10891 } 10892 } 10893 } 10894 } 10895 10896 if ((scanFlags & SCAN_BOOTING) != 0) { 10897 // No apps can run during boot scan, so they don't need to be frozen 10898 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 10899 // Caller asked to not kill app, so it's probably not frozen 10900 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 10901 // Caller asked us to ignore frozen check for some reason; they 10902 // probably didn't know the package name 10903 } else { 10904 // We're doing major surgery on this package, so it better be frozen 10905 // right now to keep it from launching 10906 checkPackageFrozen(pkgName); 10907 } 10908 10909 // Also need to kill any apps that are dependent on the library. 10910 if (clientLibPkgs != null) { 10911 for (int i=0; i<clientLibPkgs.size(); i++) { 10912 PackageParser.Package clientPkg = clientLibPkgs.get(i); 10913 killApplication(clientPkg.applicationInfo.packageName, 10914 clientPkg.applicationInfo.uid, "update lib"); 10915 } 10916 } 10917 10918 // writer 10919 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 10920 10921 synchronized (mPackages) { 10922 // We don't expect installation to fail beyond this point 10923 10924 // Add the new setting to mSettings 10925 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 10926 // Add the new setting to mPackages 10927 mPackages.put(pkg.applicationInfo.packageName, pkg); 10928 // Make sure we don't accidentally delete its data. 10929 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 10930 while (iter.hasNext()) { 10931 PackageCleanItem item = iter.next(); 10932 if (pkgName.equals(item.packageName)) { 10933 iter.remove(); 10934 } 10935 } 10936 10937 // Add the package's KeySets to the global KeySetManagerService 10938 KeySetManagerService ksms = mSettings.mKeySetManagerService; 10939 ksms.addScannedPackageLPw(pkg); 10940 10941 int N = pkg.providers.size(); 10942 StringBuilder r = null; 10943 int i; 10944 for (i=0; i<N; i++) { 10945 PackageParser.Provider p = pkg.providers.get(i); 10946 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 10947 p.info.processName); 10948 mProviders.addProvider(p); 10949 p.syncable = p.info.isSyncable; 10950 if (p.info.authority != null) { 10951 String names[] = p.info.authority.split(";"); 10952 p.info.authority = null; 10953 for (int j = 0; j < names.length; j++) { 10954 if (j == 1 && p.syncable) { 10955 // We only want the first authority for a provider to possibly be 10956 // syncable, so if we already added this provider using a different 10957 // authority clear the syncable flag. We copy the provider before 10958 // changing it because the mProviders object contains a reference 10959 // to a provider that we don't want to change. 10960 // Only do this for the second authority since the resulting provider 10961 // object can be the same for all future authorities for this provider. 10962 p = new PackageParser.Provider(p); 10963 p.syncable = false; 10964 } 10965 if (!mProvidersByAuthority.containsKey(names[j])) { 10966 mProvidersByAuthority.put(names[j], p); 10967 if (p.info.authority == null) { 10968 p.info.authority = names[j]; 10969 } else { 10970 p.info.authority = p.info.authority + ";" + names[j]; 10971 } 10972 if (DEBUG_PACKAGE_SCANNING) { 10973 if (chatty) 10974 Log.d(TAG, "Registered content provider: " + names[j] 10975 + ", className = " + p.info.name + ", isSyncable = " 10976 + p.info.isSyncable); 10977 } 10978 } else { 10979 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 10980 Slog.w(TAG, "Skipping provider name " + names[j] + 10981 " (in package " + pkg.applicationInfo.packageName + 10982 "): name already used by " 10983 + ((other != null && other.getComponentName() != null) 10984 ? other.getComponentName().getPackageName() : "?")); 10985 } 10986 } 10987 } 10988 if (chatty) { 10989 if (r == null) { 10990 r = new StringBuilder(256); 10991 } else { 10992 r.append(' '); 10993 } 10994 r.append(p.info.name); 10995 } 10996 } 10997 if (r != null) { 10998 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 10999 } 11000 11001 N = pkg.services.size(); 11002 r = null; 11003 for (i=0; i<N; i++) { 11004 PackageParser.Service s = pkg.services.get(i); 11005 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 11006 s.info.processName); 11007 mServices.addService(s); 11008 if (chatty) { 11009 if (r == null) { 11010 r = new StringBuilder(256); 11011 } else { 11012 r.append(' '); 11013 } 11014 r.append(s.info.name); 11015 } 11016 } 11017 if (r != null) { 11018 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 11019 } 11020 11021 N = pkg.receivers.size(); 11022 r = null; 11023 for (i=0; i<N; i++) { 11024 PackageParser.Activity a = pkg.receivers.get(i); 11025 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 11026 a.info.processName); 11027 mReceivers.addActivity(a, "receiver"); 11028 if (chatty) { 11029 if (r == null) { 11030 r = new StringBuilder(256); 11031 } else { 11032 r.append(' '); 11033 } 11034 r.append(a.info.name); 11035 } 11036 } 11037 if (r != null) { 11038 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 11039 } 11040 11041 N = pkg.activities.size(); 11042 r = null; 11043 for (i=0; i<N; i++) { 11044 PackageParser.Activity a = pkg.activities.get(i); 11045 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 11046 a.info.processName); 11047 mActivities.addActivity(a, "activity"); 11048 if (chatty) { 11049 if (r == null) { 11050 r = new StringBuilder(256); 11051 } else { 11052 r.append(' '); 11053 } 11054 r.append(a.info.name); 11055 } 11056 } 11057 if (r != null) { 11058 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 11059 } 11060 11061 // Don't allow ephemeral applications to define new permissions groups. 11062 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 11063 Slog.w(TAG, "Permission groups from package " + pkg.packageName 11064 + " ignored: instant apps cannot define new permission groups."); 11065 } else { 11066 mPermissionManager.addAllPermissionGroups(pkg, chatty); 11067 } 11068 11069 // Don't allow ephemeral applications to define new permissions. 11070 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 11071 Slog.w(TAG, "Permissions from package " + pkg.packageName 11072 + " ignored: instant apps cannot define new permissions."); 11073 } else { 11074 mPermissionManager.addAllPermissions(pkg, chatty); 11075 } 11076 11077 N = pkg.instrumentation.size(); 11078 r = null; 11079 for (i=0; i<N; i++) { 11080 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 11081 a.info.packageName = pkg.applicationInfo.packageName; 11082 a.info.sourceDir = pkg.applicationInfo.sourceDir; 11083 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 11084 a.info.splitNames = pkg.splitNames; 11085 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 11086 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 11087 a.info.splitDependencies = pkg.applicationInfo.splitDependencies; 11088 a.info.dataDir = pkg.applicationInfo.dataDir; 11089 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 11090 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 11091 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 11092 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 11093 mInstrumentation.put(a.getComponentName(), a); 11094 if (chatty) { 11095 if (r == null) { 11096 r = new StringBuilder(256); 11097 } else { 11098 r.append(' '); 11099 } 11100 r.append(a.info.name); 11101 } 11102 } 11103 if (r != null) { 11104 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 11105 } 11106 11107 if (pkg.protectedBroadcasts != null) { 11108 N = pkg.protectedBroadcasts.size(); 11109 synchronized (mProtectedBroadcasts) { 11110 for (i = 0; i < N; i++) { 11111 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 11112 } 11113 } 11114 } 11115 } 11116 11117 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11118 } 11119 11120 /** 11121 * Derive the ABI of a non-system package located at {@code scanFile}. This information 11122 * is derived purely on the basis of the contents of {@code scanFile} and 11123 * {@code cpuAbiOverride}. 11124 * 11125 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 11126 */ 11127 private static void derivePackageAbi(PackageParser.Package pkg, File scanFile, 11128 String cpuAbiOverride, boolean extractLibs, 11129 File appLib32InstallDir) 11130 throws PackageManagerException { 11131 // Give ourselves some initial paths; we'll come back for another 11132 // pass once we've determined ABI below. 11133 setNativeLibraryPaths(pkg, appLib32InstallDir); 11134 11135 // We would never need to extract libs for forward-locked and external packages, 11136 // since the container service will do it for us. We shouldn't attempt to 11137 // extract libs from system app when it was not updated. 11138 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 11139 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 11140 extractLibs = false; 11141 } 11142 11143 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 11144 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 11145 11146 NativeLibraryHelper.Handle handle = null; 11147 try { 11148 handle = NativeLibraryHelper.Handle.create(pkg); 11149 // TODO(multiArch): This can be null for apps that didn't go through the 11150 // usual installation process. We can calculate it again, like we 11151 // do during install time. 11152 // 11153 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 11154 // unnecessary. 11155 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 11156 11157 // Null out the abis so that they can be recalculated. 11158 pkg.applicationInfo.primaryCpuAbi = null; 11159 pkg.applicationInfo.secondaryCpuAbi = null; 11160 if (isMultiArch(pkg.applicationInfo)) { 11161 // Warn if we've set an abiOverride for multi-lib packages.. 11162 // By definition, we need to copy both 32 and 64 bit libraries for 11163 // such packages. 11164 if (pkg.cpuAbiOverride != null 11165 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 11166 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 11167 } 11168 11169 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 11170 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 11171 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 11172 if (extractLibs) { 11173 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 11174 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 11175 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 11176 useIsaSpecificSubdirs); 11177 } else { 11178 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 11179 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 11180 } 11181 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11182 } 11183 11184 // Shared library native code should be in the APK zip aligned 11185 if (abi32 >= 0 && pkg.isLibrary() && extractLibs) { 11186 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 11187 "Shared library native lib extraction not supported"); 11188 } 11189 11190 maybeThrowExceptionForMultiArchCopy( 11191 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 11192 11193 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 11194 if (extractLibs) { 11195 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 11196 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 11197 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 11198 useIsaSpecificSubdirs); 11199 } else { 11200 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 11201 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 11202 } 11203 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11204 } 11205 11206 maybeThrowExceptionForMultiArchCopy( 11207 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 11208 11209 if (abi64 >= 0) { 11210 // Shared library native libs should be in the APK zip aligned 11211 if (extractLibs && pkg.isLibrary()) { 11212 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 11213 "Shared library native lib extraction not supported"); 11214 } 11215 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 11216 } 11217 11218 if (abi32 >= 0) { 11219 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 11220 if (abi64 >= 0) { 11221 if (pkg.use32bitAbi) { 11222 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 11223 pkg.applicationInfo.primaryCpuAbi = abi; 11224 } else { 11225 pkg.applicationInfo.secondaryCpuAbi = abi; 11226 } 11227 } else { 11228 pkg.applicationInfo.primaryCpuAbi = abi; 11229 } 11230 } 11231 } else { 11232 String[] abiList = (cpuAbiOverride != null) ? 11233 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 11234 11235 // Enable gross and lame hacks for apps that are built with old 11236 // SDK tools. We must scan their APKs for renderscript bitcode and 11237 // not launch them if it's present. Don't bother checking on devices 11238 // that don't have 64 bit support. 11239 boolean needsRenderScriptOverride = false; 11240 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 11241 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 11242 abiList = Build.SUPPORTED_32_BIT_ABIS; 11243 needsRenderScriptOverride = true; 11244 } 11245 11246 final int copyRet; 11247 if (extractLibs) { 11248 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 11249 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 11250 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 11251 } else { 11252 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 11253 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 11254 } 11255 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11256 11257 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 11258 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 11259 "Error unpackaging native libs for app, errorCode=" + copyRet); 11260 } 11261 11262 if (copyRet >= 0) { 11263 // Shared libraries that have native libs must be multi-architecture 11264 if (pkg.isLibrary()) { 11265 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 11266 "Shared library with native libs must be multiarch"); 11267 } 11268 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 11269 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 11270 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 11271 } else if (needsRenderScriptOverride) { 11272 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 11273 } 11274 } 11275 } catch (IOException ioe) { 11276 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 11277 } finally { 11278 IoUtils.closeQuietly(handle); 11279 } 11280 11281 // Now that we've calculated the ABIs and determined if it's an internal app, 11282 // we will go ahead and populate the nativeLibraryPath. 11283 setNativeLibraryPaths(pkg, appLib32InstallDir); 11284 } 11285 11286 /** 11287 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 11288 * i.e, so that all packages can be run inside a single process if required. 11289 * 11290 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 11291 * this function will either try and make the ABI for all packages in {@code packagesForUser} 11292 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 11293 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 11294 * updating a package that belongs to a shared user. 11295 * 11296 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 11297 * adds unnecessary complexity. 11298 */ 11299 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 11300 PackageParser.Package scannedPackage) { 11301 String requiredInstructionSet = null; 11302 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 11303 requiredInstructionSet = VMRuntime.getInstructionSet( 11304 scannedPackage.applicationInfo.primaryCpuAbi); 11305 } 11306 11307 PackageSetting requirer = null; 11308 for (PackageSetting ps : packagesForUser) { 11309 // If packagesForUser contains scannedPackage, we skip it. This will happen 11310 // when scannedPackage is an update of an existing package. Without this check, 11311 // we will never be able to change the ABI of any package belonging to a shared 11312 // user, even if it's compatible with other packages. 11313 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 11314 if (ps.primaryCpuAbiString == null) { 11315 continue; 11316 } 11317 11318 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 11319 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 11320 // We have a mismatch between instruction sets (say arm vs arm64) warn about 11321 // this but there's not much we can do. 11322 String errorMessage = "Instruction set mismatch, " 11323 + ((requirer == null) ? "[caller]" : requirer) 11324 + " requires " + requiredInstructionSet + " whereas " + ps 11325 + " requires " + instructionSet; 11326 Slog.w(TAG, errorMessage); 11327 } 11328 11329 if (requiredInstructionSet == null) { 11330 requiredInstructionSet = instructionSet; 11331 requirer = ps; 11332 } 11333 } 11334 } 11335 11336 if (requiredInstructionSet != null) { 11337 String adjustedAbi; 11338 if (requirer != null) { 11339 // requirer != null implies that either scannedPackage was null or that scannedPackage 11340 // did not require an ABI, in which case we have to adjust scannedPackage to match 11341 // the ABI of the set (which is the same as requirer's ABI) 11342 adjustedAbi = requirer.primaryCpuAbiString; 11343 if (scannedPackage != null) { 11344 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 11345 } 11346 } else { 11347 // requirer == null implies that we're updating all ABIs in the set to 11348 // match scannedPackage. 11349 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 11350 } 11351 11352 for (PackageSetting ps : packagesForUser) { 11353 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 11354 if (ps.primaryCpuAbiString != null) { 11355 continue; 11356 } 11357 11358 ps.primaryCpuAbiString = adjustedAbi; 11359 if (ps.pkg != null && ps.pkg.applicationInfo != null && 11360 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 11361 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 11362 if (DEBUG_ABI_SELECTION) { 11363 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 11364 + " (requirer=" 11365 + (requirer != null ? requirer.pkg : "null") 11366 + ", scannedPackage=" 11367 + (scannedPackage != null ? scannedPackage : "null") 11368 + ")"); 11369 } 11370 try { 11371 mInstaller.rmdex(ps.codePathString, 11372 getDexCodeInstructionSet(getPreferredInstructionSet())); 11373 } catch (InstallerException ignored) { 11374 } 11375 } 11376 } 11377 } 11378 } 11379 } 11380 11381 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 11382 synchronized (mPackages) { 11383 mResolverReplaced = true; 11384 // Set up information for custom user intent resolution activity. 11385 mResolveActivity.applicationInfo = pkg.applicationInfo; 11386 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 11387 mResolveActivity.packageName = pkg.applicationInfo.packageName; 11388 mResolveActivity.processName = pkg.applicationInfo.packageName; 11389 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 11390 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 11391 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 11392 mResolveActivity.theme = 0; 11393 mResolveActivity.exported = true; 11394 mResolveActivity.enabled = true; 11395 mResolveInfo.activityInfo = mResolveActivity; 11396 mResolveInfo.priority = 0; 11397 mResolveInfo.preferredOrder = 0; 11398 mResolveInfo.match = 0; 11399 mResolveComponentName = mCustomResolverComponentName; 11400 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 11401 mResolveComponentName); 11402 } 11403 } 11404 11405 private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) { 11406 if (installerActivity == null) { 11407 if (DEBUG_EPHEMERAL) { 11408 Slog.d(TAG, "Clear ephemeral installer activity"); 11409 } 11410 mInstantAppInstallerActivity = null; 11411 return; 11412 } 11413 11414 if (DEBUG_EPHEMERAL) { 11415 Slog.d(TAG, "Set ephemeral installer activity: " 11416 + installerActivity.getComponentName()); 11417 } 11418 // Set up information for ephemeral installer activity 11419 mInstantAppInstallerActivity = installerActivity; 11420 mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS 11421 | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 11422 mInstantAppInstallerActivity.exported = true; 11423 mInstantAppInstallerActivity.enabled = true; 11424 mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity; 11425 mInstantAppInstallerInfo.priority = 0; 11426 mInstantAppInstallerInfo.preferredOrder = 1; 11427 mInstantAppInstallerInfo.isDefault = true; 11428 mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 11429 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 11430 } 11431 11432 private static String calculateBundledApkRoot(final String codePathString) { 11433 final File codePath = new File(codePathString); 11434 final File codeRoot; 11435 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 11436 codeRoot = Environment.getRootDirectory(); 11437 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 11438 codeRoot = Environment.getOemDirectory(); 11439 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 11440 codeRoot = Environment.getVendorDirectory(); 11441 } else { 11442 // Unrecognized code path; take its top real segment as the apk root: 11443 // e.g. /something/app/blah.apk => /something 11444 try { 11445 File f = codePath.getCanonicalFile(); 11446 File parent = f.getParentFile(); // non-null because codePath is a file 11447 File tmp; 11448 while ((tmp = parent.getParentFile()) != null) { 11449 f = parent; 11450 parent = tmp; 11451 } 11452 codeRoot = f; 11453 Slog.w(TAG, "Unrecognized code path " 11454 + codePath + " - using " + codeRoot); 11455 } catch (IOException e) { 11456 // Can't canonicalize the code path -- shenanigans? 11457 Slog.w(TAG, "Can't canonicalize code path " + codePath); 11458 return Environment.getRootDirectory().getPath(); 11459 } 11460 } 11461 return codeRoot.getPath(); 11462 } 11463 11464 /** 11465 * Derive and set the location of native libraries for the given package, 11466 * which varies depending on where and how the package was installed. 11467 */ 11468 private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) { 11469 final ApplicationInfo info = pkg.applicationInfo; 11470 final String codePath = pkg.codePath; 11471 final File codeFile = new File(codePath); 11472 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 11473 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 11474 11475 info.nativeLibraryRootDir = null; 11476 info.nativeLibraryRootRequiresIsa = false; 11477 info.nativeLibraryDir = null; 11478 info.secondaryNativeLibraryDir = null; 11479 11480 if (isApkFile(codeFile)) { 11481 // Monolithic install 11482 if (bundledApp) { 11483 // If "/system/lib64/apkname" exists, assume that is the per-package 11484 // native library directory to use; otherwise use "/system/lib/apkname". 11485 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 11486 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 11487 getPrimaryInstructionSet(info)); 11488 11489 // This is a bundled system app so choose the path based on the ABI. 11490 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 11491 // is just the default path. 11492 final String apkName = deriveCodePathName(codePath); 11493 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 11494 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 11495 apkName).getAbsolutePath(); 11496 11497 if (info.secondaryCpuAbi != null) { 11498 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 11499 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 11500 secondaryLibDir, apkName).getAbsolutePath(); 11501 } 11502 } else if (asecApp) { 11503 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 11504 .getAbsolutePath(); 11505 } else { 11506 final String apkName = deriveCodePathName(codePath); 11507 info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName) 11508 .getAbsolutePath(); 11509 } 11510 11511 info.nativeLibraryRootRequiresIsa = false; 11512 info.nativeLibraryDir = info.nativeLibraryRootDir; 11513 } else { 11514 // Cluster install 11515 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 11516 info.nativeLibraryRootRequiresIsa = true; 11517 11518 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 11519 getPrimaryInstructionSet(info)).getAbsolutePath(); 11520 11521 if (info.secondaryCpuAbi != null) { 11522 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 11523 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 11524 } 11525 } 11526 } 11527 11528 /** 11529 * Calculate the abis and roots for a bundled app. These can uniquely 11530 * be determined from the contents of the system partition, i.e whether 11531 * it contains 64 or 32 bit shared libraries etc. We do not validate any 11532 * of this information, and instead assume that the system was built 11533 * sensibly. 11534 */ 11535 private static void setBundledAppAbisAndRoots(PackageParser.Package pkg, 11536 PackageSetting pkgSetting) { 11537 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 11538 11539 // If "/system/lib64/apkname" exists, assume that is the per-package 11540 // native library directory to use; otherwise use "/system/lib/apkname". 11541 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 11542 setBundledAppAbi(pkg, apkRoot, apkName); 11543 // pkgSetting might be null during rescan following uninstall of updates 11544 // to a bundled app, so accommodate that possibility. The settings in 11545 // that case will be established later from the parsed package. 11546 // 11547 // If the settings aren't null, sync them up with what we've just derived. 11548 // note that apkRoot isn't stored in the package settings. 11549 if (pkgSetting != null) { 11550 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 11551 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 11552 } 11553 } 11554 11555 /** 11556 * Deduces the ABI of a bundled app and sets the relevant fields on the 11557 * parsed pkg object. 11558 * 11559 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 11560 * under which system libraries are installed. 11561 * @param apkName the name of the installed package. 11562 */ 11563 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 11564 final File codeFile = new File(pkg.codePath); 11565 11566 final boolean has64BitLibs; 11567 final boolean has32BitLibs; 11568 if (isApkFile(codeFile)) { 11569 // Monolithic install 11570 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 11571 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 11572 } else { 11573 // Cluster install 11574 final File rootDir = new File(codeFile, LIB_DIR_NAME); 11575 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 11576 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 11577 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 11578 has64BitLibs = (new File(rootDir, isa)).exists(); 11579 } else { 11580 has64BitLibs = false; 11581 } 11582 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 11583 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 11584 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 11585 has32BitLibs = (new File(rootDir, isa)).exists(); 11586 } else { 11587 has32BitLibs = false; 11588 } 11589 } 11590 11591 if (has64BitLibs && !has32BitLibs) { 11592 // The package has 64 bit libs, but not 32 bit libs. Its primary 11593 // ABI should be 64 bit. We can safely assume here that the bundled 11594 // native libraries correspond to the most preferred ABI in the list. 11595 11596 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 11597 pkg.applicationInfo.secondaryCpuAbi = null; 11598 } else if (has32BitLibs && !has64BitLibs) { 11599 // The package has 32 bit libs but not 64 bit libs. Its primary 11600 // ABI should be 32 bit. 11601 11602 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 11603 pkg.applicationInfo.secondaryCpuAbi = null; 11604 } else if (has32BitLibs && has64BitLibs) { 11605 // The application has both 64 and 32 bit bundled libraries. We check 11606 // here that the app declares multiArch support, and warn if it doesn't. 11607 // 11608 // We will be lenient here and record both ABIs. The primary will be the 11609 // ABI that's higher on the list, i.e, a device that's configured to prefer 11610 // 64 bit apps will see a 64 bit primary ABI, 11611 11612 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 11613 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 11614 } 11615 11616 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 11617 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 11618 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 11619 } else { 11620 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 11621 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 11622 } 11623 } else { 11624 pkg.applicationInfo.primaryCpuAbi = null; 11625 pkg.applicationInfo.secondaryCpuAbi = null; 11626 } 11627 } 11628 11629 private void killApplication(String pkgName, int appId, String reason) { 11630 killApplication(pkgName, appId, UserHandle.USER_ALL, reason); 11631 } 11632 11633 private void killApplication(String pkgName, int appId, int userId, String reason) { 11634 // Request the ActivityManager to kill the process(only for existing packages) 11635 // so that we do not end up in a confused state while the user is still using the older 11636 // version of the application while the new one gets installed. 11637 final long token = Binder.clearCallingIdentity(); 11638 try { 11639 IActivityManager am = ActivityManager.getService(); 11640 if (am != null) { 11641 try { 11642 am.killApplication(pkgName, appId, userId, reason); 11643 } catch (RemoteException e) { 11644 } 11645 } 11646 } finally { 11647 Binder.restoreCallingIdentity(token); 11648 } 11649 } 11650 11651 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 11652 // Remove the parent package setting 11653 PackageSetting ps = (PackageSetting) pkg.mExtras; 11654 if (ps != null) { 11655 removePackageLI(ps, chatty); 11656 } 11657 // Remove the child package setting 11658 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 11659 for (int i = 0; i < childCount; i++) { 11660 PackageParser.Package childPkg = pkg.childPackages.get(i); 11661 ps = (PackageSetting) childPkg.mExtras; 11662 if (ps != null) { 11663 removePackageLI(ps, chatty); 11664 } 11665 } 11666 } 11667 11668 void removePackageLI(PackageSetting ps, boolean chatty) { 11669 if (DEBUG_INSTALL) { 11670 if (chatty) 11671 Log.d(TAG, "Removing package " + ps.name); 11672 } 11673 11674 // writer 11675 synchronized (mPackages) { 11676 mPackages.remove(ps.name); 11677 final PackageParser.Package pkg = ps.pkg; 11678 if (pkg != null) { 11679 cleanPackageDataStructuresLILPw(pkg, chatty); 11680 } 11681 } 11682 } 11683 11684 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 11685 if (DEBUG_INSTALL) { 11686 if (chatty) 11687 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 11688 } 11689 11690 // writer 11691 synchronized (mPackages) { 11692 // Remove the parent package 11693 mPackages.remove(pkg.applicationInfo.packageName); 11694 cleanPackageDataStructuresLILPw(pkg, chatty); 11695 11696 // Remove the child packages 11697 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 11698 for (int i = 0; i < childCount; i++) { 11699 PackageParser.Package childPkg = pkg.childPackages.get(i); 11700 mPackages.remove(childPkg.applicationInfo.packageName); 11701 cleanPackageDataStructuresLILPw(childPkg, chatty); 11702 } 11703 } 11704 } 11705 11706 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 11707 int N = pkg.providers.size(); 11708 StringBuilder r = null; 11709 int i; 11710 for (i=0; i<N; i++) { 11711 PackageParser.Provider p = pkg.providers.get(i); 11712 mProviders.removeProvider(p); 11713 if (p.info.authority == null) { 11714 11715 /* There was another ContentProvider with this authority when 11716 * this app was installed so this authority is null, 11717 * Ignore it as we don't have to unregister the provider. 11718 */ 11719 continue; 11720 } 11721 String names[] = p.info.authority.split(";"); 11722 for (int j = 0; j < names.length; j++) { 11723 if (mProvidersByAuthority.get(names[j]) == p) { 11724 mProvidersByAuthority.remove(names[j]); 11725 if (DEBUG_REMOVE) { 11726 if (chatty) 11727 Log.d(TAG, "Unregistered content provider: " + names[j] 11728 + ", className = " + p.info.name + ", isSyncable = " 11729 + p.info.isSyncable); 11730 } 11731 } 11732 } 11733 if (DEBUG_REMOVE && chatty) { 11734 if (r == null) { 11735 r = new StringBuilder(256); 11736 } else { 11737 r.append(' '); 11738 } 11739 r.append(p.info.name); 11740 } 11741 } 11742 if (r != null) { 11743 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 11744 } 11745 11746 N = pkg.services.size(); 11747 r = null; 11748 for (i=0; i<N; i++) { 11749 PackageParser.Service s = pkg.services.get(i); 11750 mServices.removeService(s); 11751 if (chatty) { 11752 if (r == null) { 11753 r = new StringBuilder(256); 11754 } else { 11755 r.append(' '); 11756 } 11757 r.append(s.info.name); 11758 } 11759 } 11760 if (r != null) { 11761 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 11762 } 11763 11764 N = pkg.receivers.size(); 11765 r = null; 11766 for (i=0; i<N; i++) { 11767 PackageParser.Activity a = pkg.receivers.get(i); 11768 mReceivers.removeActivity(a, "receiver"); 11769 if (DEBUG_REMOVE && chatty) { 11770 if (r == null) { 11771 r = new StringBuilder(256); 11772 } else { 11773 r.append(' '); 11774 } 11775 r.append(a.info.name); 11776 } 11777 } 11778 if (r != null) { 11779 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 11780 } 11781 11782 N = pkg.activities.size(); 11783 r = null; 11784 for (i=0; i<N; i++) { 11785 PackageParser.Activity a = pkg.activities.get(i); 11786 mActivities.removeActivity(a, "activity"); 11787 if (DEBUG_REMOVE && chatty) { 11788 if (r == null) { 11789 r = new StringBuilder(256); 11790 } else { 11791 r.append(' '); 11792 } 11793 r.append(a.info.name); 11794 } 11795 } 11796 if (r != null) { 11797 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 11798 } 11799 11800 mPermissionManager.removeAllPermissions(pkg, chatty); 11801 11802 N = pkg.instrumentation.size(); 11803 r = null; 11804 for (i=0; i<N; i++) { 11805 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 11806 mInstrumentation.remove(a.getComponentName()); 11807 if (DEBUG_REMOVE && chatty) { 11808 if (r == null) { 11809 r = new StringBuilder(256); 11810 } else { 11811 r.append(' '); 11812 } 11813 r.append(a.info.name); 11814 } 11815 } 11816 if (r != null) { 11817 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 11818 } 11819 11820 r = null; 11821 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 11822 // Only system apps can hold shared libraries. 11823 if (pkg.libraryNames != null) { 11824 for (i = 0; i < pkg.libraryNames.size(); i++) { 11825 String name = pkg.libraryNames.get(i); 11826 if (removeSharedLibraryLPw(name, 0)) { 11827 if (DEBUG_REMOVE && chatty) { 11828 if (r == null) { 11829 r = new StringBuilder(256); 11830 } else { 11831 r.append(' '); 11832 } 11833 r.append(name); 11834 } 11835 } 11836 } 11837 } 11838 } 11839 11840 r = null; 11841 11842 // Any package can hold static shared libraries. 11843 if (pkg.staticSharedLibName != null) { 11844 if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) { 11845 if (DEBUG_REMOVE && chatty) { 11846 if (r == null) { 11847 r = new StringBuilder(256); 11848 } else { 11849 r.append(' '); 11850 } 11851 r.append(pkg.staticSharedLibName); 11852 } 11853 } 11854 } 11855 11856 if (r != null) { 11857 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 11858 } 11859 } 11860 11861 11862 final class ActivityIntentResolver 11863 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 11864 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 11865 boolean defaultOnly, int userId) { 11866 if (!sUserManager.exists(userId)) return null; 11867 mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0); 11868 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 11869 } 11870 11871 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 11872 int userId) { 11873 if (!sUserManager.exists(userId)) return null; 11874 mFlags = flags; 11875 return super.queryIntent(intent, resolvedType, 11876 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 11877 userId); 11878 } 11879 11880 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 11881 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 11882 if (!sUserManager.exists(userId)) return null; 11883 if (packageActivities == null) { 11884 return null; 11885 } 11886 mFlags = flags; 11887 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 11888 final int N = packageActivities.size(); 11889 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 11890 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 11891 11892 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 11893 for (int i = 0; i < N; ++i) { 11894 intentFilters = packageActivities.get(i).intents; 11895 if (intentFilters != null && intentFilters.size() > 0) { 11896 PackageParser.ActivityIntentInfo[] array = 11897 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 11898 intentFilters.toArray(array); 11899 listCut.add(array); 11900 } 11901 } 11902 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 11903 } 11904 11905 /** 11906 * Finds a privileged activity that matches the specified activity names. 11907 */ 11908 private PackageParser.Activity findMatchingActivity( 11909 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 11910 for (PackageParser.Activity sysActivity : activityList) { 11911 if (sysActivity.info.name.equals(activityInfo.name)) { 11912 return sysActivity; 11913 } 11914 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 11915 return sysActivity; 11916 } 11917 if (sysActivity.info.targetActivity != null) { 11918 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 11919 return sysActivity; 11920 } 11921 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 11922 return sysActivity; 11923 } 11924 } 11925 } 11926 return null; 11927 } 11928 11929 public class IterGenerator<E> { 11930 public Iterator<E> generate(ActivityIntentInfo info) { 11931 return null; 11932 } 11933 } 11934 11935 public class ActionIterGenerator extends IterGenerator<String> { 11936 @Override 11937 public Iterator<String> generate(ActivityIntentInfo info) { 11938 return info.actionsIterator(); 11939 } 11940 } 11941 11942 public class CategoriesIterGenerator extends IterGenerator<String> { 11943 @Override 11944 public Iterator<String> generate(ActivityIntentInfo info) { 11945 return info.categoriesIterator(); 11946 } 11947 } 11948 11949 public class SchemesIterGenerator extends IterGenerator<String> { 11950 @Override 11951 public Iterator<String> generate(ActivityIntentInfo info) { 11952 return info.schemesIterator(); 11953 } 11954 } 11955 11956 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 11957 @Override 11958 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 11959 return info.authoritiesIterator(); 11960 } 11961 } 11962 11963 /** 11964 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 11965 * MODIFIED. Do not pass in a list that should not be changed. 11966 */ 11967 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 11968 IterGenerator<T> generator, Iterator<T> searchIterator) { 11969 // loop through the set of actions; every one must be found in the intent filter 11970 while (searchIterator.hasNext()) { 11971 // we must have at least one filter in the list to consider a match 11972 if (intentList.size() == 0) { 11973 break; 11974 } 11975 11976 final T searchAction = searchIterator.next(); 11977 11978 // loop through the set of intent filters 11979 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 11980 while (intentIter.hasNext()) { 11981 final ActivityIntentInfo intentInfo = intentIter.next(); 11982 boolean selectionFound = false; 11983 11984 // loop through the intent filter's selection criteria; at least one 11985 // of them must match the searched criteria 11986 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 11987 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 11988 final T intentSelection = intentSelectionIter.next(); 11989 if (intentSelection != null && intentSelection.equals(searchAction)) { 11990 selectionFound = true; 11991 break; 11992 } 11993 } 11994 11995 // the selection criteria wasn't found in this filter's set; this filter 11996 // is not a potential match 11997 if (!selectionFound) { 11998 intentIter.remove(); 11999 } 12000 } 12001 } 12002 } 12003 12004 private boolean isProtectedAction(ActivityIntentInfo filter) { 12005 final Iterator<String> actionsIter = filter.actionsIterator(); 12006 while (actionsIter != null && actionsIter.hasNext()) { 12007 final String filterAction = actionsIter.next(); 12008 if (PROTECTED_ACTIONS.contains(filterAction)) { 12009 return true; 12010 } 12011 } 12012 return false; 12013 } 12014 12015 /** 12016 * Adjusts the priority of the given intent filter according to policy. 12017 * <p> 12018 * <ul> 12019 * <li>The priority for non privileged applications is capped to '0'</li> 12020 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 12021 * <li>The priority for unbundled updates to privileged applications is capped to the 12022 * priority defined on the system partition</li> 12023 * </ul> 12024 * <p> 12025 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 12026 * allowed to obtain any priority on any action. 12027 */ 12028 private void adjustPriority( 12029 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 12030 // nothing to do; priority is fine as-is 12031 if (intent.getPriority() <= 0) { 12032 return; 12033 } 12034 12035 final ActivityInfo activityInfo = intent.activity.info; 12036 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 12037 12038 final boolean privilegedApp = 12039 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 12040 if (!privilegedApp) { 12041 // non-privileged applications can never define a priority >0 12042 if (DEBUG_FILTERS) { 12043 Slog.i(TAG, "Non-privileged app; cap priority to 0;" 12044 + " package: " + applicationInfo.packageName 12045 + " activity: " + intent.activity.className 12046 + " origPrio: " + intent.getPriority()); 12047 } 12048 intent.setPriority(0); 12049 return; 12050 } 12051 12052 if (systemActivities == null) { 12053 // the system package is not disabled; we're parsing the system partition 12054 if (isProtectedAction(intent)) { 12055 if (mDeferProtectedFilters) { 12056 // We can't deal with these just yet. No component should ever obtain a 12057 // >0 priority for a protected actions, with ONE exception -- the setup 12058 // wizard. The setup wizard, however, cannot be known until we're able to 12059 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 12060 // until all intent filters have been processed. Chicken, meet egg. 12061 // Let the filter temporarily have a high priority and rectify the 12062 // priorities after all system packages have been scanned. 12063 mProtectedFilters.add(intent); 12064 if (DEBUG_FILTERS) { 12065 Slog.i(TAG, "Protected action; save for later;" 12066 + " package: " + applicationInfo.packageName 12067 + " activity: " + intent.activity.className 12068 + " origPrio: " + intent.getPriority()); 12069 } 12070 return; 12071 } else { 12072 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 12073 Slog.i(TAG, "No setup wizard;" 12074 + " All protected intents capped to priority 0"); 12075 } 12076 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 12077 if (DEBUG_FILTERS) { 12078 Slog.i(TAG, "Found setup wizard;" 12079 + " allow priority " + intent.getPriority() + ";" 12080 + " package: " + intent.activity.info.packageName 12081 + " activity: " + intent.activity.className 12082 + " priority: " + intent.getPriority()); 12083 } 12084 // setup wizard gets whatever it wants 12085 return; 12086 } 12087 if (DEBUG_FILTERS) { 12088 Slog.i(TAG, "Protected action; cap priority to 0;" 12089 + " package: " + intent.activity.info.packageName 12090 + " activity: " + intent.activity.className 12091 + " origPrio: " + intent.getPriority()); 12092 } 12093 intent.setPriority(0); 12094 return; 12095 } 12096 } 12097 // privileged apps on the system image get whatever priority they request 12098 return; 12099 } 12100 12101 // privileged app unbundled update ... try to find the same activity 12102 final PackageParser.Activity foundActivity = 12103 findMatchingActivity(systemActivities, activityInfo); 12104 if (foundActivity == null) { 12105 // this is a new activity; it cannot obtain >0 priority 12106 if (DEBUG_FILTERS) { 12107 Slog.i(TAG, "New activity; cap priority to 0;" 12108 + " package: " + applicationInfo.packageName 12109 + " activity: " + intent.activity.className 12110 + " origPrio: " + intent.getPriority()); 12111 } 12112 intent.setPriority(0); 12113 return; 12114 } 12115 12116 // found activity, now check for filter equivalence 12117 12118 // a shallow copy is enough; we modify the list, not its contents 12119 final List<ActivityIntentInfo> intentListCopy = 12120 new ArrayList<>(foundActivity.intents); 12121 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 12122 12123 // find matching action subsets 12124 final Iterator<String> actionsIterator = intent.actionsIterator(); 12125 if (actionsIterator != null) { 12126 getIntentListSubset( 12127 intentListCopy, new ActionIterGenerator(), actionsIterator); 12128 if (intentListCopy.size() == 0) { 12129 // no more intents to match; we're not equivalent 12130 if (DEBUG_FILTERS) { 12131 Slog.i(TAG, "Mismatched action; cap priority to 0;" 12132 + " package: " + applicationInfo.packageName 12133 + " activity: " + intent.activity.className 12134 + " origPrio: " + intent.getPriority()); 12135 } 12136 intent.setPriority(0); 12137 return; 12138 } 12139 } 12140 12141 // find matching category subsets 12142 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 12143 if (categoriesIterator != null) { 12144 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 12145 categoriesIterator); 12146 if (intentListCopy.size() == 0) { 12147 // no more intents to match; we're not equivalent 12148 if (DEBUG_FILTERS) { 12149 Slog.i(TAG, "Mismatched category; cap priority to 0;" 12150 + " package: " + applicationInfo.packageName 12151 + " activity: " + intent.activity.className 12152 + " origPrio: " + intent.getPriority()); 12153 } 12154 intent.setPriority(0); 12155 return; 12156 } 12157 } 12158 12159 // find matching schemes subsets 12160 final Iterator<String> schemesIterator = intent.schemesIterator(); 12161 if (schemesIterator != null) { 12162 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 12163 schemesIterator); 12164 if (intentListCopy.size() == 0) { 12165 // no more intents to match; we're not equivalent 12166 if (DEBUG_FILTERS) { 12167 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 12168 + " package: " + applicationInfo.packageName 12169 + " activity: " + intent.activity.className 12170 + " origPrio: " + intent.getPriority()); 12171 } 12172 intent.setPriority(0); 12173 return; 12174 } 12175 } 12176 12177 // find matching authorities subsets 12178 final Iterator<IntentFilter.AuthorityEntry> 12179 authoritiesIterator = intent.authoritiesIterator(); 12180 if (authoritiesIterator != null) { 12181 getIntentListSubset(intentListCopy, 12182 new AuthoritiesIterGenerator(), 12183 authoritiesIterator); 12184 if (intentListCopy.size() == 0) { 12185 // no more intents to match; we're not equivalent 12186 if (DEBUG_FILTERS) { 12187 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 12188 + " package: " + applicationInfo.packageName 12189 + " activity: " + intent.activity.className 12190 + " origPrio: " + intent.getPriority()); 12191 } 12192 intent.setPriority(0); 12193 return; 12194 } 12195 } 12196 12197 // we found matching filter(s); app gets the max priority of all intents 12198 int cappedPriority = 0; 12199 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 12200 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 12201 } 12202 if (intent.getPriority() > cappedPriority) { 12203 if (DEBUG_FILTERS) { 12204 Slog.i(TAG, "Found matching filter(s);" 12205 + " cap priority to " + cappedPriority + ";" 12206 + " package: " + applicationInfo.packageName 12207 + " activity: " + intent.activity.className 12208 + " origPrio: " + intent.getPriority()); 12209 } 12210 intent.setPriority(cappedPriority); 12211 return; 12212 } 12213 // all this for nothing; the requested priority was <= what was on the system 12214 } 12215 12216 public final void addActivity(PackageParser.Activity a, String type) { 12217 mActivities.put(a.getComponentName(), a); 12218 if (DEBUG_SHOW_INFO) 12219 Log.v( 12220 TAG, " " + type + " " + 12221 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 12222 if (DEBUG_SHOW_INFO) 12223 Log.v(TAG, " Class=" + a.info.name); 12224 final int NI = a.intents.size(); 12225 for (int j=0; j<NI; j++) { 12226 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 12227 if ("activity".equals(type)) { 12228 final PackageSetting ps = 12229 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 12230 final List<PackageParser.Activity> systemActivities = 12231 ps != null && ps.pkg != null ? ps.pkg.activities : null; 12232 adjustPriority(systemActivities, intent); 12233 } 12234 if (DEBUG_SHOW_INFO) { 12235 Log.v(TAG, " IntentFilter:"); 12236 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12237 } 12238 if (!intent.debugCheck()) { 12239 Log.w(TAG, "==> For Activity " + a.info.name); 12240 } 12241 addFilter(intent); 12242 } 12243 } 12244 12245 public final void removeActivity(PackageParser.Activity a, String type) { 12246 mActivities.remove(a.getComponentName()); 12247 if (DEBUG_SHOW_INFO) { 12248 Log.v(TAG, " " + type + " " 12249 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 12250 : a.info.name) + ":"); 12251 Log.v(TAG, " Class=" + a.info.name); 12252 } 12253 final int NI = a.intents.size(); 12254 for (int j=0; j<NI; j++) { 12255 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 12256 if (DEBUG_SHOW_INFO) { 12257 Log.v(TAG, " IntentFilter:"); 12258 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12259 } 12260 removeFilter(intent); 12261 } 12262 } 12263 12264 @Override 12265 protected boolean allowFilterResult( 12266 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 12267 ActivityInfo filterAi = filter.activity.info; 12268 for (int i=dest.size()-1; i>=0; i--) { 12269 ActivityInfo destAi = dest.get(i).activityInfo; 12270 if (destAi.name == filterAi.name 12271 && destAi.packageName == filterAi.packageName) { 12272 return false; 12273 } 12274 } 12275 return true; 12276 } 12277 12278 @Override 12279 protected ActivityIntentInfo[] newArray(int size) { 12280 return new ActivityIntentInfo[size]; 12281 } 12282 12283 @Override 12284 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 12285 if (!sUserManager.exists(userId)) return true; 12286 PackageParser.Package p = filter.activity.owner; 12287 if (p != null) { 12288 PackageSetting ps = (PackageSetting)p.mExtras; 12289 if (ps != null) { 12290 // System apps are never considered stopped for purposes of 12291 // filtering, because there may be no way for the user to 12292 // actually re-launch them. 12293 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 12294 && ps.getStopped(userId); 12295 } 12296 } 12297 return false; 12298 } 12299 12300 @Override 12301 protected boolean isPackageForFilter(String packageName, 12302 PackageParser.ActivityIntentInfo info) { 12303 return packageName.equals(info.activity.owner.packageName); 12304 } 12305 12306 @Override 12307 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 12308 int match, int userId) { 12309 if (!sUserManager.exists(userId)) return null; 12310 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 12311 return null; 12312 } 12313 final PackageParser.Activity activity = info.activity; 12314 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 12315 if (ps == null) { 12316 return null; 12317 } 12318 final PackageUserState userState = ps.readUserState(userId); 12319 ActivityInfo ai = 12320 PackageParser.generateActivityInfo(activity, mFlags, userState, userId); 12321 if (ai == null) { 12322 return null; 12323 } 12324 final boolean matchExplicitlyVisibleOnly = 12325 (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0; 12326 final boolean matchVisibleToInstantApp = 12327 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 12328 final boolean componentVisible = 12329 matchVisibleToInstantApp 12330 && info.isVisibleToInstantApp() 12331 && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp()); 12332 final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 12333 // throw out filters that aren't visible to ephemeral apps 12334 if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) { 12335 return null; 12336 } 12337 // throw out instant app filters if we're not explicitly requesting them 12338 if (!matchInstantApp && userState.instantApp) { 12339 return null; 12340 } 12341 // throw out instant app filters if updates are available; will trigger 12342 // instant app resolution 12343 if (userState.instantApp && ps.isUpdateAvailable()) { 12344 return null; 12345 } 12346 final ResolveInfo res = new ResolveInfo(); 12347 res.activityInfo = ai; 12348 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 12349 res.filter = info; 12350 } 12351 if (info != null) { 12352 res.handleAllWebDataURI = info.handleAllWebDataURI(); 12353 } 12354 res.priority = info.getPriority(); 12355 res.preferredOrder = activity.owner.mPreferredOrder; 12356 //System.out.println("Result: " + res.activityInfo.className + 12357 // " = " + res.priority); 12358 res.match = match; 12359 res.isDefault = info.hasDefault; 12360 res.labelRes = info.labelRes; 12361 res.nonLocalizedLabel = info.nonLocalizedLabel; 12362 if (userNeedsBadging(userId)) { 12363 res.noResourceId = true; 12364 } else { 12365 res.icon = info.icon; 12366 } 12367 res.iconResourceId = info.icon; 12368 res.system = res.activityInfo.applicationInfo.isSystemApp(); 12369 res.isInstantAppAvailable = userState.instantApp; 12370 return res; 12371 } 12372 12373 @Override 12374 protected void sortResults(List<ResolveInfo> results) { 12375 Collections.sort(results, mResolvePrioritySorter); 12376 } 12377 12378 @Override 12379 protected void dumpFilter(PrintWriter out, String prefix, 12380 PackageParser.ActivityIntentInfo filter) { 12381 out.print(prefix); out.print( 12382 Integer.toHexString(System.identityHashCode(filter.activity))); 12383 out.print(' '); 12384 filter.activity.printComponentShortName(out); 12385 out.print(" filter "); 12386 out.println(Integer.toHexString(System.identityHashCode(filter))); 12387 } 12388 12389 @Override 12390 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 12391 return filter.activity; 12392 } 12393 12394 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12395 PackageParser.Activity activity = (PackageParser.Activity)label; 12396 out.print(prefix); out.print( 12397 Integer.toHexString(System.identityHashCode(activity))); 12398 out.print(' '); 12399 activity.printComponentShortName(out); 12400 if (count > 1) { 12401 out.print(" ("); out.print(count); out.print(" filters)"); 12402 } 12403 out.println(); 12404 } 12405 12406 // Keys are String (activity class name), values are Activity. 12407 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 12408 = new ArrayMap<ComponentName, PackageParser.Activity>(); 12409 private int mFlags; 12410 } 12411 12412 private final class ServiceIntentResolver 12413 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 12414 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12415 boolean defaultOnly, int userId) { 12416 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 12417 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 12418 } 12419 12420 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12421 int userId) { 12422 if (!sUserManager.exists(userId)) return null; 12423 mFlags = flags; 12424 return super.queryIntent(intent, resolvedType, 12425 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12426 userId); 12427 } 12428 12429 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12430 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 12431 if (!sUserManager.exists(userId)) return null; 12432 if (packageServices == null) { 12433 return null; 12434 } 12435 mFlags = flags; 12436 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 12437 final int N = packageServices.size(); 12438 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 12439 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 12440 12441 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 12442 for (int i = 0; i < N; ++i) { 12443 intentFilters = packageServices.get(i).intents; 12444 if (intentFilters != null && intentFilters.size() > 0) { 12445 PackageParser.ServiceIntentInfo[] array = 12446 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 12447 intentFilters.toArray(array); 12448 listCut.add(array); 12449 } 12450 } 12451 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 12452 } 12453 12454 public final void addService(PackageParser.Service s) { 12455 mServices.put(s.getComponentName(), s); 12456 if (DEBUG_SHOW_INFO) { 12457 Log.v(TAG, " " 12458 + (s.info.nonLocalizedLabel != null 12459 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 12460 Log.v(TAG, " Class=" + s.info.name); 12461 } 12462 final int NI = s.intents.size(); 12463 int j; 12464 for (j=0; j<NI; j++) { 12465 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 12466 if (DEBUG_SHOW_INFO) { 12467 Log.v(TAG, " IntentFilter:"); 12468 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12469 } 12470 if (!intent.debugCheck()) { 12471 Log.w(TAG, "==> For Service " + s.info.name); 12472 } 12473 addFilter(intent); 12474 } 12475 } 12476 12477 public final void removeService(PackageParser.Service s) { 12478 mServices.remove(s.getComponentName()); 12479 if (DEBUG_SHOW_INFO) { 12480 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 12481 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 12482 Log.v(TAG, " Class=" + s.info.name); 12483 } 12484 final int NI = s.intents.size(); 12485 int j; 12486 for (j=0; j<NI; j++) { 12487 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 12488 if (DEBUG_SHOW_INFO) { 12489 Log.v(TAG, " IntentFilter:"); 12490 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12491 } 12492 removeFilter(intent); 12493 } 12494 } 12495 12496 @Override 12497 protected boolean allowFilterResult( 12498 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 12499 ServiceInfo filterSi = filter.service.info; 12500 for (int i=dest.size()-1; i>=0; i--) { 12501 ServiceInfo destAi = dest.get(i).serviceInfo; 12502 if (destAi.name == filterSi.name 12503 && destAi.packageName == filterSi.packageName) { 12504 return false; 12505 } 12506 } 12507 return true; 12508 } 12509 12510 @Override 12511 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 12512 return new PackageParser.ServiceIntentInfo[size]; 12513 } 12514 12515 @Override 12516 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 12517 if (!sUserManager.exists(userId)) return true; 12518 PackageParser.Package p = filter.service.owner; 12519 if (p != null) { 12520 PackageSetting ps = (PackageSetting)p.mExtras; 12521 if (ps != null) { 12522 // System apps are never considered stopped for purposes of 12523 // filtering, because there may be no way for the user to 12524 // actually re-launch them. 12525 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 12526 && ps.getStopped(userId); 12527 } 12528 } 12529 return false; 12530 } 12531 12532 @Override 12533 protected boolean isPackageForFilter(String packageName, 12534 PackageParser.ServiceIntentInfo info) { 12535 return packageName.equals(info.service.owner.packageName); 12536 } 12537 12538 @Override 12539 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 12540 int match, int userId) { 12541 if (!sUserManager.exists(userId)) return null; 12542 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 12543 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 12544 return null; 12545 } 12546 final PackageParser.Service service = info.service; 12547 PackageSetting ps = (PackageSetting) service.owner.mExtras; 12548 if (ps == null) { 12549 return null; 12550 } 12551 final PackageUserState userState = ps.readUserState(userId); 12552 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 12553 userState, userId); 12554 if (si == null) { 12555 return null; 12556 } 12557 final boolean matchVisibleToInstantApp = 12558 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 12559 final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 12560 // throw out filters that aren't visible to ephemeral apps 12561 if (matchVisibleToInstantApp 12562 && !(info.isVisibleToInstantApp() || userState.instantApp)) { 12563 return null; 12564 } 12565 // throw out ephemeral filters if we're not explicitly requesting them 12566 if (!isInstantApp && userState.instantApp) { 12567 return null; 12568 } 12569 // throw out instant app filters if updates are available; will trigger 12570 // instant app resolution 12571 if (userState.instantApp && ps.isUpdateAvailable()) { 12572 return null; 12573 } 12574 final ResolveInfo res = new ResolveInfo(); 12575 res.serviceInfo = si; 12576 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 12577 res.filter = filter; 12578 } 12579 res.priority = info.getPriority(); 12580 res.preferredOrder = service.owner.mPreferredOrder; 12581 res.match = match; 12582 res.isDefault = info.hasDefault; 12583 res.labelRes = info.labelRes; 12584 res.nonLocalizedLabel = info.nonLocalizedLabel; 12585 res.icon = info.icon; 12586 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 12587 return res; 12588 } 12589 12590 @Override 12591 protected void sortResults(List<ResolveInfo> results) { 12592 Collections.sort(results, mResolvePrioritySorter); 12593 } 12594 12595 @Override 12596 protected void dumpFilter(PrintWriter out, String prefix, 12597 PackageParser.ServiceIntentInfo filter) { 12598 out.print(prefix); out.print( 12599 Integer.toHexString(System.identityHashCode(filter.service))); 12600 out.print(' '); 12601 filter.service.printComponentShortName(out); 12602 out.print(" filter "); 12603 out.println(Integer.toHexString(System.identityHashCode(filter))); 12604 } 12605 12606 @Override 12607 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 12608 return filter.service; 12609 } 12610 12611 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12612 PackageParser.Service service = (PackageParser.Service)label; 12613 out.print(prefix); out.print( 12614 Integer.toHexString(System.identityHashCode(service))); 12615 out.print(' '); 12616 service.printComponentShortName(out); 12617 if (count > 1) { 12618 out.print(" ("); out.print(count); out.print(" filters)"); 12619 } 12620 out.println(); 12621 } 12622 12623// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 12624// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 12625// final List<ResolveInfo> retList = Lists.newArrayList(); 12626// while (i.hasNext()) { 12627// final ResolveInfo resolveInfo = (ResolveInfo) i; 12628// if (isEnabledLP(resolveInfo.serviceInfo)) { 12629// retList.add(resolveInfo); 12630// } 12631// } 12632// return retList; 12633// } 12634 12635 // Keys are String (activity class name), values are Activity. 12636 private final ArrayMap<ComponentName, PackageParser.Service> mServices 12637 = new ArrayMap<ComponentName, PackageParser.Service>(); 12638 private int mFlags; 12639 } 12640 12641 private final class ProviderIntentResolver 12642 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 12643 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12644 boolean defaultOnly, int userId) { 12645 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 12646 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 12647 } 12648 12649 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12650 int userId) { 12651 if (!sUserManager.exists(userId)) 12652 return null; 12653 mFlags = flags; 12654 return super.queryIntent(intent, resolvedType, 12655 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12656 userId); 12657 } 12658 12659 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12660 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 12661 if (!sUserManager.exists(userId)) 12662 return null; 12663 if (packageProviders == null) { 12664 return null; 12665 } 12666 mFlags = flags; 12667 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 12668 final int N = packageProviders.size(); 12669 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 12670 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 12671 12672 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 12673 for (int i = 0; i < N; ++i) { 12674 intentFilters = packageProviders.get(i).intents; 12675 if (intentFilters != null && intentFilters.size() > 0) { 12676 PackageParser.ProviderIntentInfo[] array = 12677 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 12678 intentFilters.toArray(array); 12679 listCut.add(array); 12680 } 12681 } 12682 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 12683 } 12684 12685 public final void addProvider(PackageParser.Provider p) { 12686 if (mProviders.containsKey(p.getComponentName())) { 12687 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 12688 return; 12689 } 12690 12691 mProviders.put(p.getComponentName(), p); 12692 if (DEBUG_SHOW_INFO) { 12693 Log.v(TAG, " " 12694 + (p.info.nonLocalizedLabel != null 12695 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 12696 Log.v(TAG, " Class=" + p.info.name); 12697 } 12698 final int NI = p.intents.size(); 12699 int j; 12700 for (j = 0; j < NI; j++) { 12701 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 12702 if (DEBUG_SHOW_INFO) { 12703 Log.v(TAG, " IntentFilter:"); 12704 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12705 } 12706 if (!intent.debugCheck()) { 12707 Log.w(TAG, "==> For Provider " + p.info.name); 12708 } 12709 addFilter(intent); 12710 } 12711 } 12712 12713 public final void removeProvider(PackageParser.Provider p) { 12714 mProviders.remove(p.getComponentName()); 12715 if (DEBUG_SHOW_INFO) { 12716 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 12717 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 12718 Log.v(TAG, " Class=" + p.info.name); 12719 } 12720 final int NI = p.intents.size(); 12721 int j; 12722 for (j = 0; j < NI; j++) { 12723 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 12724 if (DEBUG_SHOW_INFO) { 12725 Log.v(TAG, " IntentFilter:"); 12726 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12727 } 12728 removeFilter(intent); 12729 } 12730 } 12731 12732 @Override 12733 protected boolean allowFilterResult( 12734 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 12735 ProviderInfo filterPi = filter.provider.info; 12736 for (int i = dest.size() - 1; i >= 0; i--) { 12737 ProviderInfo destPi = dest.get(i).providerInfo; 12738 if (destPi.name == filterPi.name 12739 && destPi.packageName == filterPi.packageName) { 12740 return false; 12741 } 12742 } 12743 return true; 12744 } 12745 12746 @Override 12747 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 12748 return new PackageParser.ProviderIntentInfo[size]; 12749 } 12750 12751 @Override 12752 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 12753 if (!sUserManager.exists(userId)) 12754 return true; 12755 PackageParser.Package p = filter.provider.owner; 12756 if (p != null) { 12757 PackageSetting ps = (PackageSetting) p.mExtras; 12758 if (ps != null) { 12759 // System apps are never considered stopped for purposes of 12760 // filtering, because there may be no way for the user to 12761 // actually re-launch them. 12762 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 12763 && ps.getStopped(userId); 12764 } 12765 } 12766 return false; 12767 } 12768 12769 @Override 12770 protected boolean isPackageForFilter(String packageName, 12771 PackageParser.ProviderIntentInfo info) { 12772 return packageName.equals(info.provider.owner.packageName); 12773 } 12774 12775 @Override 12776 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 12777 int match, int userId) { 12778 if (!sUserManager.exists(userId)) 12779 return null; 12780 final PackageParser.ProviderIntentInfo info = filter; 12781 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 12782 return null; 12783 } 12784 final PackageParser.Provider provider = info.provider; 12785 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 12786 if (ps == null) { 12787 return null; 12788 } 12789 final PackageUserState userState = ps.readUserState(userId); 12790 final boolean matchVisibleToInstantApp = 12791 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 12792 final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 12793 // throw out filters that aren't visible to instant applications 12794 if (matchVisibleToInstantApp 12795 && !(info.isVisibleToInstantApp() || userState.instantApp)) { 12796 return null; 12797 } 12798 // throw out instant application filters if we're not explicitly requesting them 12799 if (!isInstantApp && userState.instantApp) { 12800 return null; 12801 } 12802 // throw out instant application filters if updates are available; will trigger 12803 // instant application resolution 12804 if (userState.instantApp && ps.isUpdateAvailable()) { 12805 return null; 12806 } 12807 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 12808 userState, userId); 12809 if (pi == null) { 12810 return null; 12811 } 12812 final ResolveInfo res = new ResolveInfo(); 12813 res.providerInfo = pi; 12814 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 12815 res.filter = filter; 12816 } 12817 res.priority = info.getPriority(); 12818 res.preferredOrder = provider.owner.mPreferredOrder; 12819 res.match = match; 12820 res.isDefault = info.hasDefault; 12821 res.labelRes = info.labelRes; 12822 res.nonLocalizedLabel = info.nonLocalizedLabel; 12823 res.icon = info.icon; 12824 res.system = res.providerInfo.applicationInfo.isSystemApp(); 12825 return res; 12826 } 12827 12828 @Override 12829 protected void sortResults(List<ResolveInfo> results) { 12830 Collections.sort(results, mResolvePrioritySorter); 12831 } 12832 12833 @Override 12834 protected void dumpFilter(PrintWriter out, String prefix, 12835 PackageParser.ProviderIntentInfo filter) { 12836 out.print(prefix); 12837 out.print( 12838 Integer.toHexString(System.identityHashCode(filter.provider))); 12839 out.print(' '); 12840 filter.provider.printComponentShortName(out); 12841 out.print(" filter "); 12842 out.println(Integer.toHexString(System.identityHashCode(filter))); 12843 } 12844 12845 @Override 12846 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 12847 return filter.provider; 12848 } 12849 12850 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12851 PackageParser.Provider provider = (PackageParser.Provider)label; 12852 out.print(prefix); out.print( 12853 Integer.toHexString(System.identityHashCode(provider))); 12854 out.print(' '); 12855 provider.printComponentShortName(out); 12856 if (count > 1) { 12857 out.print(" ("); out.print(count); out.print(" filters)"); 12858 } 12859 out.println(); 12860 } 12861 12862 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 12863 = new ArrayMap<ComponentName, PackageParser.Provider>(); 12864 private int mFlags; 12865 } 12866 12867 static final class EphemeralIntentResolver 12868 extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> { 12869 /** 12870 * The result that has the highest defined order. Ordering applies on a 12871 * per-package basis. Mapping is from package name to Pair of order and 12872 * EphemeralResolveInfo. 12873 * <p> 12874 * NOTE: This is implemented as a field variable for convenience and efficiency. 12875 * By having a field variable, we're able to track filter ordering as soon as 12876 * a non-zero order is defined. Otherwise, multiple loops across the result set 12877 * would be needed to apply ordering. If the intent resolver becomes re-entrant, 12878 * this needs to be contained entirely within {@link #filterResults}. 12879 */ 12880 final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>(); 12881 12882 @Override 12883 protected AuxiliaryResolveInfo[] newArray(int size) { 12884 return new AuxiliaryResolveInfo[size]; 12885 } 12886 12887 @Override 12888 protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) { 12889 return true; 12890 } 12891 12892 @Override 12893 protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match, 12894 int userId) { 12895 if (!sUserManager.exists(userId)) { 12896 return null; 12897 } 12898 final String packageName = responseObj.resolveInfo.getPackageName(); 12899 final Integer order = responseObj.getOrder(); 12900 final Pair<Integer, InstantAppResolveInfo> lastOrderResult = 12901 mOrderResult.get(packageName); 12902 // ordering is enabled and this item's order isn't high enough 12903 if (lastOrderResult != null && lastOrderResult.first >= order) { 12904 return null; 12905 } 12906 final InstantAppResolveInfo res = responseObj.resolveInfo; 12907 if (order > 0) { 12908 // non-zero order, enable ordering 12909 mOrderResult.put(packageName, new Pair<>(order, res)); 12910 } 12911 return responseObj; 12912 } 12913 12914 @Override 12915 protected void filterResults(List<AuxiliaryResolveInfo> results) { 12916 // only do work if ordering is enabled [most of the time it won't be] 12917 if (mOrderResult.size() == 0) { 12918 return; 12919 } 12920 int resultSize = results.size(); 12921 for (int i = 0; i < resultSize; i++) { 12922 final InstantAppResolveInfo info = results.get(i).resolveInfo; 12923 final String packageName = info.getPackageName(); 12924 final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName); 12925 if (savedInfo == null) { 12926 // package doesn't having ordering 12927 continue; 12928 } 12929 if (savedInfo.second == info) { 12930 // circled back to the highest ordered item; remove from order list 12931 mOrderResult.remove(packageName); 12932 if (mOrderResult.size() == 0) { 12933 // no more ordered items 12934 break; 12935 } 12936 continue; 12937 } 12938 // item has a worse order, remove it from the result list 12939 results.remove(i); 12940 resultSize--; 12941 i--; 12942 } 12943 } 12944 } 12945 12946 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 12947 new Comparator<ResolveInfo>() { 12948 public int compare(ResolveInfo r1, ResolveInfo r2) { 12949 int v1 = r1.priority; 12950 int v2 = r2.priority; 12951 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 12952 if (v1 != v2) { 12953 return (v1 > v2) ? -1 : 1; 12954 } 12955 v1 = r1.preferredOrder; 12956 v2 = r2.preferredOrder; 12957 if (v1 != v2) { 12958 return (v1 > v2) ? -1 : 1; 12959 } 12960 if (r1.isDefault != r2.isDefault) { 12961 return r1.isDefault ? -1 : 1; 12962 } 12963 v1 = r1.match; 12964 v2 = r2.match; 12965 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 12966 if (v1 != v2) { 12967 return (v1 > v2) ? -1 : 1; 12968 } 12969 if (r1.system != r2.system) { 12970 return r1.system ? -1 : 1; 12971 } 12972 if (r1.activityInfo != null) { 12973 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 12974 } 12975 if (r1.serviceInfo != null) { 12976 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 12977 } 12978 if (r1.providerInfo != null) { 12979 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 12980 } 12981 return 0; 12982 } 12983 }; 12984 12985 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 12986 new Comparator<ProviderInfo>() { 12987 public int compare(ProviderInfo p1, ProviderInfo p2) { 12988 final int v1 = p1.initOrder; 12989 final int v2 = p2.initOrder; 12990 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 12991 } 12992 }; 12993 12994 public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 12995 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 12996 final int[] userIds) { 12997 mHandler.post(new Runnable() { 12998 @Override 12999 public void run() { 13000 try { 13001 final IActivityManager am = ActivityManager.getService(); 13002 if (am == null) return; 13003 final int[] resolvedUserIds; 13004 if (userIds == null) { 13005 resolvedUserIds = am.getRunningUserIds(); 13006 } else { 13007 resolvedUserIds = userIds; 13008 } 13009 for (int id : resolvedUserIds) { 13010 final Intent intent = new Intent(action, 13011 pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null); 13012 if (extras != null) { 13013 intent.putExtras(extras); 13014 } 13015 if (targetPkg != null) { 13016 intent.setPackage(targetPkg); 13017 } 13018 // Modify the UID when posting to other users 13019 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 13020 if (uid > 0 && UserHandle.getUserId(uid) != id) { 13021 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 13022 intent.putExtra(Intent.EXTRA_UID, uid); 13023 } 13024 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 13025 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 13026 if (DEBUG_BROADCASTS) { 13027 RuntimeException here = new RuntimeException("here"); 13028 here.fillInStackTrace(); 13029 Slog.d(TAG, "Sending to user " + id + ": " 13030 + intent.toShortString(false, true, false, false) 13031 + " " + intent.getExtras(), here); 13032 } 13033 am.broadcastIntent(null, intent, null, finishedReceiver, 13034 0, null, null, null, android.app.AppOpsManager.OP_NONE, 13035 null, finishedReceiver != null, false, id); 13036 } 13037 } catch (RemoteException ex) { 13038 } 13039 } 13040 }); 13041 } 13042 13043 /** 13044 * Check if the external storage media is available. This is true if there 13045 * is a mounted external storage medium or if the external storage is 13046 * emulated. 13047 */ 13048 private boolean isExternalMediaAvailable() { 13049 return mMediaMounted || Environment.isExternalStorageEmulated(); 13050 } 13051 13052 @Override 13053 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 13054 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 13055 return null; 13056 } 13057 // writer 13058 synchronized (mPackages) { 13059 if (!isExternalMediaAvailable()) { 13060 // If the external storage is no longer mounted at this point, 13061 // the caller may not have been able to delete all of this 13062 // packages files and can not delete any more. Bail. 13063 return null; 13064 } 13065 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 13066 if (lastPackage != null) { 13067 pkgs.remove(lastPackage); 13068 } 13069 if (pkgs.size() > 0) { 13070 return pkgs.get(0); 13071 } 13072 } 13073 return null; 13074 } 13075 13076 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 13077 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 13078 userId, andCode ? 1 : 0, packageName); 13079 if (mSystemReady) { 13080 msg.sendToTarget(); 13081 } else { 13082 if (mPostSystemReadyMessages == null) { 13083 mPostSystemReadyMessages = new ArrayList<>(); 13084 } 13085 mPostSystemReadyMessages.add(msg); 13086 } 13087 } 13088 13089 void startCleaningPackages() { 13090 // reader 13091 if (!isExternalMediaAvailable()) { 13092 return; 13093 } 13094 synchronized (mPackages) { 13095 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 13096 return; 13097 } 13098 } 13099 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 13100 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 13101 IActivityManager am = ActivityManager.getService(); 13102 if (am != null) { 13103 int dcsUid = -1; 13104 synchronized (mPackages) { 13105 if (!mDefaultContainerWhitelisted) { 13106 mDefaultContainerWhitelisted = true; 13107 PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE); 13108 dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId); 13109 } 13110 } 13111 try { 13112 if (dcsUid > 0) { 13113 am.backgroundWhitelistUid(dcsUid); 13114 } 13115 am.startService(null, intent, null, false, mContext.getOpPackageName(), 13116 UserHandle.USER_SYSTEM); 13117 } catch (RemoteException e) { 13118 } 13119 } 13120 } 13121 13122 @Override 13123 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 13124 int installFlags, String installerPackageName, int userId) { 13125 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 13126 13127 final int callingUid = Binder.getCallingUid(); 13128 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 13129 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 13130 13131 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 13132 try { 13133 if (observer != null) { 13134 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 13135 } 13136 } catch (RemoteException re) { 13137 } 13138 return; 13139 } 13140 13141 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 13142 installFlags |= PackageManager.INSTALL_FROM_ADB; 13143 13144 } else { 13145 // Caller holds INSTALL_PACKAGES permission, so we're less strict 13146 // about installerPackageName. 13147 13148 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 13149 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 13150 } 13151 13152 UserHandle user; 13153 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 13154 user = UserHandle.ALL; 13155 } else { 13156 user = new UserHandle(userId); 13157 } 13158 13159 // Only system components can circumvent runtime permissions when installing. 13160 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 13161 && mContext.checkCallingOrSelfPermission(Manifest.permission 13162 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 13163 throw new SecurityException("You need the " 13164 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 13165 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 13166 } 13167 13168 if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0 13169 || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 13170 throw new IllegalArgumentException( 13171 "New installs into ASEC containers no longer supported"); 13172 } 13173 13174 final File originFile = new File(originPath); 13175 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 13176 13177 final Message msg = mHandler.obtainMessage(INIT_COPY); 13178 final VerificationInfo verificationInfo = new VerificationInfo( 13179 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 13180 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 13181 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 13182 null /*packageAbiOverride*/, null /*grantedPermissions*/, 13183 null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN); 13184 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 13185 msg.obj = params; 13186 13187 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 13188 System.identityHashCode(msg.obj)); 13189 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 13190 System.identityHashCode(msg.obj)); 13191 13192 mHandler.sendMessage(msg); 13193 } 13194 13195 13196 /** 13197 * Ensure that the install reason matches what we know about the package installer (e.g. whether 13198 * it is acting on behalf on an enterprise or the user). 13199 * 13200 * Note that the ordering of the conditionals in this method is important. The checks we perform 13201 * are as follows, in this order: 13202 * 13203 * 1) If the install is being performed by a system app, we can trust the app to have set the 13204 * install reason correctly. Thus, we pass through the install reason unchanged, no matter 13205 * what it is. 13206 * 2) If the install is being performed by a device or profile owner app, the install reason 13207 * should be enterprise policy. However, we cannot be sure that the device or profile owner 13208 * set the install reason correctly. If the app targets an older SDK version where install 13209 * reasons did not exist yet, or if the app author simply forgot, the install reason may be 13210 * unset or wrong. Thus, we force the install reason to be enterprise policy. 13211 * 3) In all other cases, the install is being performed by a regular app that is neither part 13212 * of the system nor a device or profile owner. We have no reason to believe that this app is 13213 * acting on behalf of the enterprise admin. Thus, we check whether the install reason was 13214 * set to enterprise policy and if so, change it to unknown instead. 13215 */ 13216 private int fixUpInstallReason(String installerPackageName, int installerUid, 13217 int installReason) { 13218 if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid) 13219 == PERMISSION_GRANTED) { 13220 // If the install is being performed by a system app, we trust that app to have set the 13221 // install reason correctly. 13222 return installReason; 13223 } 13224 13225 final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 13226 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 13227 if (dpm != null) { 13228 ComponentName owner = null; 13229 try { 13230 owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */); 13231 if (owner == null) { 13232 owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid)); 13233 } 13234 } catch (RemoteException e) { 13235 } 13236 if (owner != null && owner.getPackageName().equals(installerPackageName)) { 13237 // If the install is being performed by a device or profile owner, the install 13238 // reason should be enterprise policy. 13239 return PackageManager.INSTALL_REASON_POLICY; 13240 } 13241 } 13242 13243 if (installReason == PackageManager.INSTALL_REASON_POLICY) { 13244 // If the install is being performed by a regular app (i.e. neither system app nor 13245 // device or profile owner), we have no reason to believe that the app is acting on 13246 // behalf of an enterprise. If the app set the install reason to enterprise policy, 13247 // change it to unknown instead. 13248 return PackageManager.INSTALL_REASON_UNKNOWN; 13249 } 13250 13251 // If the install is being performed by a regular app and the install reason was set to any 13252 // value but enterprise policy, leave the install reason unchanged. 13253 return installReason; 13254 } 13255 13256 void installStage(String packageName, File stagedDir, 13257 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 13258 String installerPackageName, int installerUid, UserHandle user, 13259 Certificate[][] certificates) { 13260 if (DEBUG_EPHEMERAL) { 13261 if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) { 13262 Slog.d(TAG, "Ephemeral install of " + packageName); 13263 } 13264 } 13265 final VerificationInfo verificationInfo = new VerificationInfo( 13266 sessionParams.originatingUri, sessionParams.referrerUri, 13267 sessionParams.originatingUid, installerUid); 13268 13269 final OriginInfo origin = OriginInfo.fromStagedFile(stagedDir); 13270 13271 final Message msg = mHandler.obtainMessage(INIT_COPY); 13272 final int installReason = fixUpInstallReason(installerPackageName, installerUid, 13273 sessionParams.installReason); 13274 final InstallParams params = new InstallParams(origin, null, observer, 13275 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 13276 verificationInfo, user, sessionParams.abiOverride, 13277 sessionParams.grantedRuntimePermissions, certificates, installReason); 13278 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 13279 msg.obj = params; 13280 13281 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 13282 System.identityHashCode(msg.obj)); 13283 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 13284 System.identityHashCode(msg.obj)); 13285 13286 mHandler.sendMessage(msg); 13287 } 13288 13289 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 13290 int userId) { 13291 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 13292 sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/, 13293 false /*startReceiver*/, pkgSetting.appId, userId); 13294 13295 // Send a session commit broadcast 13296 final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo(); 13297 info.installReason = pkgSetting.getInstallReason(userId); 13298 info.appPackageName = packageName; 13299 sendSessionCommitBroadcast(info, userId); 13300 } 13301 13302 public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted, 13303 boolean includeStopped, int appId, int... userIds) { 13304 if (ArrayUtils.isEmpty(userIds)) { 13305 return; 13306 } 13307 Bundle extras = new Bundle(1); 13308 // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast 13309 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId)); 13310 13311 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 13312 packageName, extras, 0, null, null, userIds); 13313 if (sendBootCompleted) { 13314 mHandler.post(() -> { 13315 for (int userId : userIds) { 13316 sendBootCompletedBroadcastToSystemApp( 13317 packageName, includeStopped, userId); 13318 } 13319 } 13320 ); 13321 } 13322 } 13323 13324 /** 13325 * The just-installed/enabled app is bundled on the system, so presumed to be able to run 13326 * automatically without needing an explicit launch. 13327 * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones. 13328 */ 13329 private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped, 13330 int userId) { 13331 // If user is not running, the app didn't miss any broadcast 13332 if (!mUserManagerInternal.isUserRunning(userId)) { 13333 return; 13334 } 13335 final IActivityManager am = ActivityManager.getService(); 13336 try { 13337 // Deliver LOCKED_BOOT_COMPLETED first 13338 Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED) 13339 .setPackage(packageName); 13340 if (includeStopped) { 13341 lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); 13342 } 13343 final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED}; 13344 am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions, 13345 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 13346 13347 // Deliver BOOT_COMPLETED only if user is unlocked 13348 if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) { 13349 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName); 13350 if (includeStopped) { 13351 bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); 13352 } 13353 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions, 13354 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 13355 } 13356 } catch (RemoteException e) { 13357 throw e.rethrowFromSystemServer(); 13358 } 13359 } 13360 13361 @Override 13362 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 13363 int userId) { 13364 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13365 PackageSetting pkgSetting; 13366 final int callingUid = Binder.getCallingUid(); 13367 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 13368 true /* requireFullPermission */, true /* checkShell */, 13369 "setApplicationHiddenSetting for user " + userId); 13370 13371 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 13372 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 13373 return false; 13374 } 13375 13376 long callingId = Binder.clearCallingIdentity(); 13377 try { 13378 boolean sendAdded = false; 13379 boolean sendRemoved = false; 13380 // writer 13381 synchronized (mPackages) { 13382 pkgSetting = mSettings.mPackages.get(packageName); 13383 if (pkgSetting == null) { 13384 return false; 13385 } 13386 if (filterAppAccessLPr(pkgSetting, callingUid, userId)) { 13387 return false; 13388 } 13389 // Do not allow "android" is being disabled 13390 if ("android".equals(packageName)) { 13391 Slog.w(TAG, "Cannot hide package: android"); 13392 return false; 13393 } 13394 // Cannot hide static shared libs as they are considered 13395 // a part of the using app (emulating static linking). Also 13396 // static libs are installed always on internal storage. 13397 PackageParser.Package pkg = mPackages.get(packageName); 13398 if (pkg != null && pkg.staticSharedLibName != null) { 13399 Slog.w(TAG, "Cannot hide package: " + packageName 13400 + " providing static shared library: " 13401 + pkg.staticSharedLibName); 13402 return false; 13403 } 13404 // Only allow protected packages to hide themselves. 13405 if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId) 13406 && mProtectedPackages.isPackageStateProtected(userId, packageName)) { 13407 Slog.w(TAG, "Not hiding protected package: " + packageName); 13408 return false; 13409 } 13410 13411 if (pkgSetting.getHidden(userId) != hidden) { 13412 pkgSetting.setHidden(hidden, userId); 13413 mSettings.writePackageRestrictionsLPr(userId); 13414 if (hidden) { 13415 sendRemoved = true; 13416 } else { 13417 sendAdded = true; 13418 } 13419 } 13420 } 13421 if (sendAdded) { 13422 sendPackageAddedForUser(packageName, pkgSetting, userId); 13423 return true; 13424 } 13425 if (sendRemoved) { 13426 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 13427 "hiding pkg"); 13428 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 13429 return true; 13430 } 13431 } finally { 13432 Binder.restoreCallingIdentity(callingId); 13433 } 13434 return false; 13435 } 13436 13437 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 13438 int userId) { 13439 final PackageRemovedInfo info = new PackageRemovedInfo(this); 13440 info.removedPackage = packageName; 13441 info.installerPackageName = pkgSetting.installerPackageName; 13442 info.removedUsers = new int[] {userId}; 13443 info.broadcastUsers = new int[] {userId}; 13444 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 13445 info.sendPackageRemovedBroadcasts(true /*killApp*/); 13446 } 13447 13448 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 13449 if (pkgList.length > 0) { 13450 Bundle extras = new Bundle(1); 13451 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 13452 13453 sendPackageBroadcast( 13454 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 13455 : Intent.ACTION_PACKAGES_UNSUSPENDED, 13456 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 13457 new int[] {userId}); 13458 } 13459 } 13460 13461 /** 13462 * Returns true if application is not found or there was an error. Otherwise it returns 13463 * the hidden state of the package for the given user. 13464 */ 13465 @Override 13466 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 13467 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13468 final int callingUid = Binder.getCallingUid(); 13469 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 13470 true /* requireFullPermission */, false /* checkShell */, 13471 "getApplicationHidden for user " + userId); 13472 PackageSetting ps; 13473 long callingId = Binder.clearCallingIdentity(); 13474 try { 13475 // writer 13476 synchronized (mPackages) { 13477 ps = mSettings.mPackages.get(packageName); 13478 if (ps == null) { 13479 return true; 13480 } 13481 if (filterAppAccessLPr(ps, callingUid, userId)) { 13482 return true; 13483 } 13484 return ps.getHidden(userId); 13485 } 13486 } finally { 13487 Binder.restoreCallingIdentity(callingId); 13488 } 13489 } 13490 13491 /** 13492 * @hide 13493 */ 13494 @Override 13495 public int installExistingPackageAsUser(String packageName, int userId, int installFlags, 13496 int installReason) { 13497 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 13498 null); 13499 PackageSetting pkgSetting; 13500 final int callingUid = Binder.getCallingUid(); 13501 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 13502 true /* requireFullPermission */, true /* checkShell */, 13503 "installExistingPackage for user " + userId); 13504 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 13505 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 13506 } 13507 13508 long callingId = Binder.clearCallingIdentity(); 13509 try { 13510 boolean installed = false; 13511 final boolean instantApp = 13512 (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 13513 final boolean fullApp = 13514 (installFlags & PackageManager.INSTALL_FULL_APP) != 0; 13515 13516 // writer 13517 synchronized (mPackages) { 13518 pkgSetting = mSettings.mPackages.get(packageName); 13519 if (pkgSetting == null) { 13520 return PackageManager.INSTALL_FAILED_INVALID_URI; 13521 } 13522 if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) { 13523 // only allow the existing package to be used if it's installed as a full 13524 // application for at least one user 13525 boolean installAllowed = false; 13526 for (int checkUserId : sUserManager.getUserIds()) { 13527 installAllowed = !pkgSetting.getInstantApp(checkUserId); 13528 if (installAllowed) { 13529 break; 13530 } 13531 } 13532 if (!installAllowed) { 13533 return PackageManager.INSTALL_FAILED_INVALID_URI; 13534 } 13535 } 13536 if (!pkgSetting.getInstalled(userId)) { 13537 pkgSetting.setInstalled(true, userId); 13538 pkgSetting.setHidden(false, userId); 13539 pkgSetting.setInstallReason(installReason, userId); 13540 mSettings.writePackageRestrictionsLPr(userId); 13541 mSettings.writeKernelMappingLPr(pkgSetting); 13542 installed = true; 13543 } else if (fullApp && pkgSetting.getInstantApp(userId)) { 13544 // upgrade app from instant to full; we don't allow app downgrade 13545 installed = true; 13546 } 13547 setInstantAppForUser(pkgSetting, userId, instantApp, fullApp); 13548 } 13549 13550 if (installed) { 13551 if (pkgSetting.pkg != null) { 13552 synchronized (mInstallLock) { 13553 // We don't need to freeze for a brand new install 13554 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 13555 } 13556 } 13557 sendPackageAddedForUser(packageName, pkgSetting, userId); 13558 synchronized (mPackages) { 13559 updateSequenceNumberLP(pkgSetting, new int[]{ userId }); 13560 } 13561 } 13562 } finally { 13563 Binder.restoreCallingIdentity(callingId); 13564 } 13565 13566 return PackageManager.INSTALL_SUCCEEDED; 13567 } 13568 13569 void setInstantAppForUser(PackageSetting pkgSetting, int userId, 13570 boolean instantApp, boolean fullApp) { 13571 // no state specified; do nothing 13572 if (!instantApp && !fullApp) { 13573 return; 13574 } 13575 if (userId != UserHandle.USER_ALL) { 13576 if (instantApp && !pkgSetting.getInstantApp(userId)) { 13577 pkgSetting.setInstantApp(true /*instantApp*/, userId); 13578 } else if (fullApp && pkgSetting.getInstantApp(userId)) { 13579 pkgSetting.setInstantApp(false /*instantApp*/, userId); 13580 } 13581 } else { 13582 for (int currentUserId : sUserManager.getUserIds()) { 13583 if (instantApp && !pkgSetting.getInstantApp(currentUserId)) { 13584 pkgSetting.setInstantApp(true /*instantApp*/, currentUserId); 13585 } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) { 13586 pkgSetting.setInstantApp(false /*instantApp*/, currentUserId); 13587 } 13588 } 13589 } 13590 } 13591 13592 boolean isUserRestricted(int userId, String restrictionKey) { 13593 Bundle restrictions = sUserManager.getUserRestrictions(userId); 13594 if (restrictions.getBoolean(restrictionKey, false)) { 13595 Log.w(TAG, "User is restricted: " + restrictionKey); 13596 return true; 13597 } 13598 return false; 13599 } 13600 13601 @Override 13602 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 13603 int userId) { 13604 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13605 final int callingUid = Binder.getCallingUid(); 13606 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 13607 true /* requireFullPermission */, true /* checkShell */, 13608 "setPackagesSuspended for user " + userId); 13609 13610 if (ArrayUtils.isEmpty(packageNames)) { 13611 return packageNames; 13612 } 13613 13614 // List of package names for whom the suspended state has changed. 13615 List<String> changedPackages = new ArrayList<>(packageNames.length); 13616 // List of package names for whom the suspended state is not set as requested in this 13617 // method. 13618 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 13619 long callingId = Binder.clearCallingIdentity(); 13620 try { 13621 for (int i = 0; i < packageNames.length; i++) { 13622 String packageName = packageNames[i]; 13623 boolean changed = false; 13624 final int appId; 13625 synchronized (mPackages) { 13626 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 13627 if (pkgSetting == null 13628 || filterAppAccessLPr(pkgSetting, callingUid, userId)) { 13629 Slog.w(TAG, "Could not find package setting for package \"" + packageName 13630 + "\". Skipping suspending/un-suspending."); 13631 unactionedPackages.add(packageName); 13632 continue; 13633 } 13634 appId = pkgSetting.appId; 13635 if (pkgSetting.getSuspended(userId) != suspended) { 13636 if (!canSuspendPackageForUserLocked(packageName, userId)) { 13637 unactionedPackages.add(packageName); 13638 continue; 13639 } 13640 pkgSetting.setSuspended(suspended, userId); 13641 mSettings.writePackageRestrictionsLPr(userId); 13642 changed = true; 13643 changedPackages.add(packageName); 13644 } 13645 } 13646 13647 if (changed && suspended) { 13648 killApplication(packageName, UserHandle.getUid(userId, appId), 13649 "suspending package"); 13650 } 13651 } 13652 } finally { 13653 Binder.restoreCallingIdentity(callingId); 13654 } 13655 13656 if (!changedPackages.isEmpty()) { 13657 sendPackagesSuspendedForUser(changedPackages.toArray( 13658 new String[changedPackages.size()]), userId, suspended); 13659 } 13660 13661 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 13662 } 13663 13664 @Override 13665 public boolean isPackageSuspendedForUser(String packageName, int userId) { 13666 final int callingUid = Binder.getCallingUid(); 13667 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 13668 true /* requireFullPermission */, false /* checkShell */, 13669 "isPackageSuspendedForUser for user " + userId); 13670 synchronized (mPackages) { 13671 final PackageSetting ps = mSettings.mPackages.get(packageName); 13672 if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) { 13673 throw new IllegalArgumentException("Unknown target package: " + packageName); 13674 } 13675 return ps.getSuspended(userId); 13676 } 13677 } 13678 13679 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 13680 if (isPackageDeviceAdmin(packageName, userId)) { 13681 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13682 + "\": has an active device admin"); 13683 return false; 13684 } 13685 13686 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 13687 if (packageName.equals(activeLauncherPackageName)) { 13688 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13689 + "\": contains the active launcher"); 13690 return false; 13691 } 13692 13693 if (packageName.equals(mRequiredInstallerPackage)) { 13694 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13695 + "\": required for package installation"); 13696 return false; 13697 } 13698 13699 if (packageName.equals(mRequiredUninstallerPackage)) { 13700 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13701 + "\": required for package uninstallation"); 13702 return false; 13703 } 13704 13705 if (packageName.equals(mRequiredVerifierPackage)) { 13706 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13707 + "\": required for package verification"); 13708 return false; 13709 } 13710 13711 if (packageName.equals(getDefaultDialerPackageName(userId))) { 13712 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13713 + "\": is the default dialer"); 13714 return false; 13715 } 13716 13717 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 13718 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13719 + "\": protected package"); 13720 return false; 13721 } 13722 13723 // Cannot suspend static shared libs as they are considered 13724 // a part of the using app (emulating static linking). Also 13725 // static libs are installed always on internal storage. 13726 PackageParser.Package pkg = mPackages.get(packageName); 13727 if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) { 13728 Slog.w(TAG, "Cannot suspend package: " + packageName 13729 + " providing static shared library: " 13730 + pkg.staticSharedLibName); 13731 return false; 13732 } 13733 13734 return true; 13735 } 13736 13737 private String getActiveLauncherPackageName(int userId) { 13738 Intent intent = new Intent(Intent.ACTION_MAIN); 13739 intent.addCategory(Intent.CATEGORY_HOME); 13740 ResolveInfo resolveInfo = resolveIntent( 13741 intent, 13742 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 13743 PackageManager.MATCH_DEFAULT_ONLY, 13744 userId); 13745 13746 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 13747 } 13748 13749 private String getDefaultDialerPackageName(int userId) { 13750 synchronized (mPackages) { 13751 return mSettings.getDefaultDialerPackageNameLPw(userId); 13752 } 13753 } 13754 13755 @Override 13756 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 13757 mContext.enforceCallingOrSelfPermission( 13758 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13759 "Only package verification agents can verify applications"); 13760 13761 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 13762 final PackageVerificationResponse response = new PackageVerificationResponse( 13763 verificationCode, Binder.getCallingUid()); 13764 msg.arg1 = id; 13765 msg.obj = response; 13766 mHandler.sendMessage(msg); 13767 } 13768 13769 @Override 13770 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 13771 long millisecondsToDelay) { 13772 mContext.enforceCallingOrSelfPermission( 13773 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13774 "Only package verification agents can extend verification timeouts"); 13775 13776 final PackageVerificationState state = mPendingVerification.get(id); 13777 final PackageVerificationResponse response = new PackageVerificationResponse( 13778 verificationCodeAtTimeout, Binder.getCallingUid()); 13779 13780 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 13781 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 13782 } 13783 if (millisecondsToDelay < 0) { 13784 millisecondsToDelay = 0; 13785 } 13786 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 13787 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 13788 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 13789 } 13790 13791 if ((state != null) && !state.timeoutExtended()) { 13792 state.extendTimeout(); 13793 13794 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 13795 msg.arg1 = id; 13796 msg.obj = response; 13797 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 13798 } 13799 } 13800 13801 private void broadcastPackageVerified(int verificationId, Uri packageUri, 13802 int verificationCode, UserHandle user) { 13803 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 13804 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 13805 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 13806 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 13807 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 13808 13809 mContext.sendBroadcastAsUser(intent, user, 13810 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 13811 } 13812 13813 private ComponentName matchComponentForVerifier(String packageName, 13814 List<ResolveInfo> receivers) { 13815 ActivityInfo targetReceiver = null; 13816 13817 final int NR = receivers.size(); 13818 for (int i = 0; i < NR; i++) { 13819 final ResolveInfo info = receivers.get(i); 13820 if (info.activityInfo == null) { 13821 continue; 13822 } 13823 13824 if (packageName.equals(info.activityInfo.packageName)) { 13825 targetReceiver = info.activityInfo; 13826 break; 13827 } 13828 } 13829 13830 if (targetReceiver == null) { 13831 return null; 13832 } 13833 13834 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 13835 } 13836 13837 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 13838 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 13839 if (pkgInfo.verifiers.length == 0) { 13840 return null; 13841 } 13842 13843 final int N = pkgInfo.verifiers.length; 13844 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 13845 for (int i = 0; i < N; i++) { 13846 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 13847 13848 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 13849 receivers); 13850 if (comp == null) { 13851 continue; 13852 } 13853 13854 final int verifierUid = getUidForVerifier(verifierInfo); 13855 if (verifierUid == -1) { 13856 continue; 13857 } 13858 13859 if (DEBUG_VERIFY) { 13860 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 13861 + " with the correct signature"); 13862 } 13863 sufficientVerifiers.add(comp); 13864 verificationState.addSufficientVerifier(verifierUid); 13865 } 13866 13867 return sufficientVerifiers; 13868 } 13869 13870 private int getUidForVerifier(VerifierInfo verifierInfo) { 13871 synchronized (mPackages) { 13872 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 13873 if (pkg == null) { 13874 return -1; 13875 } else if (pkg.mSignatures.length != 1) { 13876 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 13877 + " has more than one signature; ignoring"); 13878 return -1; 13879 } 13880 13881 /* 13882 * If the public key of the package's signature does not match 13883 * our expected public key, then this is a different package and 13884 * we should skip. 13885 */ 13886 13887 final byte[] expectedPublicKey; 13888 try { 13889 final Signature verifierSig = pkg.mSignatures[0]; 13890 final PublicKey publicKey = verifierSig.getPublicKey(); 13891 expectedPublicKey = publicKey.getEncoded(); 13892 } catch (CertificateException e) { 13893 return -1; 13894 } 13895 13896 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 13897 13898 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 13899 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 13900 + " does not have the expected public key; ignoring"); 13901 return -1; 13902 } 13903 13904 return pkg.applicationInfo.uid; 13905 } 13906 } 13907 13908 @Override 13909 public void finishPackageInstall(int token, boolean didLaunch) { 13910 enforceSystemOrRoot("Only the system is allowed to finish installs"); 13911 13912 if (DEBUG_INSTALL) { 13913 Slog.v(TAG, "BM finishing package install for " + token); 13914 } 13915 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 13916 13917 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 13918 mHandler.sendMessage(msg); 13919 } 13920 13921 /** 13922 * Get the verification agent timeout. Used for both the APK verifier and the 13923 * intent filter verifier. 13924 * 13925 * @return verification timeout in milliseconds 13926 */ 13927 private long getVerificationTimeout() { 13928 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 13929 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 13930 DEFAULT_VERIFICATION_TIMEOUT); 13931 } 13932 13933 /** 13934 * Get the default verification agent response code. 13935 * 13936 * @return default verification response code 13937 */ 13938 private int getDefaultVerificationResponse(UserHandle user) { 13939 if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) { 13940 return PackageManager.VERIFICATION_REJECT; 13941 } 13942 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13943 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 13944 DEFAULT_VERIFICATION_RESPONSE); 13945 } 13946 13947 /** 13948 * Check whether or not package verification has been enabled. 13949 * 13950 * @return true if verification should be performed 13951 */ 13952 private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) { 13953 if (!DEFAULT_VERIFY_ENABLE) { 13954 return false; 13955 } 13956 13957 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 13958 13959 // Check if installing from ADB 13960 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 13961 // Do not run verification in a test harness environment 13962 if (ActivityManager.isRunningInTestHarness()) { 13963 return false; 13964 } 13965 if (ensureVerifyAppsEnabled) { 13966 return true; 13967 } 13968 // Check if the developer does not want package verification for ADB installs 13969 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13970 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 13971 return false; 13972 } 13973 } else { 13974 // only when not installed from ADB, skip verification for instant apps when 13975 // the installer and verifier are the same. 13976 if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) { 13977 if (mInstantAppInstallerActivity != null 13978 && mInstantAppInstallerActivity.packageName.equals( 13979 mRequiredVerifierPackage)) { 13980 try { 13981 mContext.getSystemService(AppOpsManager.class) 13982 .checkPackage(installerUid, mRequiredVerifierPackage); 13983 if (DEBUG_VERIFY) { 13984 Slog.i(TAG, "disable verification for instant app"); 13985 } 13986 return false; 13987 } catch (SecurityException ignore) { } 13988 } 13989 } 13990 } 13991 13992 if (ensureVerifyAppsEnabled) { 13993 return true; 13994 } 13995 13996 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13997 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 13998 } 13999 14000 @Override 14001 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 14002 throws RemoteException { 14003 mContext.enforceCallingOrSelfPermission( 14004 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 14005 "Only intentfilter verification agents can verify applications"); 14006 14007 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 14008 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 14009 Binder.getCallingUid(), verificationCode, failedDomains); 14010 msg.arg1 = id; 14011 msg.obj = response; 14012 mHandler.sendMessage(msg); 14013 } 14014 14015 @Override 14016 public int getIntentVerificationStatus(String packageName, int userId) { 14017 final int callingUid = Binder.getCallingUid(); 14018 if (UserHandle.getUserId(callingUid) != userId) { 14019 mContext.enforceCallingOrSelfPermission( 14020 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 14021 "getIntentVerificationStatus" + userId); 14022 } 14023 if (getInstantAppPackageName(callingUid) != null) { 14024 return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 14025 } 14026 synchronized (mPackages) { 14027 final PackageSetting ps = mSettings.mPackages.get(packageName); 14028 if (ps == null 14029 || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 14030 return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 14031 } 14032 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 14033 } 14034 } 14035 14036 @Override 14037 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 14038 mContext.enforceCallingOrSelfPermission( 14039 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14040 14041 boolean result = false; 14042 synchronized (mPackages) { 14043 final PackageSetting ps = mSettings.mPackages.get(packageName); 14044 if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) { 14045 return false; 14046 } 14047 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 14048 } 14049 if (result) { 14050 scheduleWritePackageRestrictionsLocked(userId); 14051 } 14052 return result; 14053 } 14054 14055 @Override 14056 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 14057 String packageName) { 14058 final int callingUid = Binder.getCallingUid(); 14059 if (getInstantAppPackageName(callingUid) != null) { 14060 return ParceledListSlice.emptyList(); 14061 } 14062 synchronized (mPackages) { 14063 final PackageSetting ps = mSettings.mPackages.get(packageName); 14064 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 14065 return ParceledListSlice.emptyList(); 14066 } 14067 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 14068 } 14069 } 14070 14071 @Override 14072 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 14073 if (TextUtils.isEmpty(packageName)) { 14074 return ParceledListSlice.emptyList(); 14075 } 14076 final int callingUid = Binder.getCallingUid(); 14077 final int callingUserId = UserHandle.getUserId(callingUid); 14078 synchronized (mPackages) { 14079 PackageParser.Package pkg = mPackages.get(packageName); 14080 if (pkg == null || pkg.activities == null) { 14081 return ParceledListSlice.emptyList(); 14082 } 14083 if (pkg.mExtras == null) { 14084 return ParceledListSlice.emptyList(); 14085 } 14086 final PackageSetting ps = (PackageSetting) pkg.mExtras; 14087 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 14088 return ParceledListSlice.emptyList(); 14089 } 14090 final int count = pkg.activities.size(); 14091 ArrayList<IntentFilter> result = new ArrayList<>(); 14092 for (int n=0; n<count; n++) { 14093 PackageParser.Activity activity = pkg.activities.get(n); 14094 if (activity.intents != null && activity.intents.size() > 0) { 14095 result.addAll(activity.intents); 14096 } 14097 } 14098 return new ParceledListSlice<>(result); 14099 } 14100 } 14101 14102 @Override 14103 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 14104 mContext.enforceCallingOrSelfPermission( 14105 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14106 if (UserHandle.getCallingUserId() != userId) { 14107 mContext.enforceCallingOrSelfPermission( 14108 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14109 } 14110 14111 synchronized (mPackages) { 14112 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 14113 if (packageName != null) { 14114 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowser( 14115 packageName, userId); 14116 } 14117 return result; 14118 } 14119 } 14120 14121 @Override 14122 public String getDefaultBrowserPackageName(int userId) { 14123 if (UserHandle.getCallingUserId() != userId) { 14124 mContext.enforceCallingOrSelfPermission( 14125 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14126 } 14127 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 14128 return null; 14129 } 14130 synchronized (mPackages) { 14131 return mSettings.getDefaultBrowserPackageNameLPw(userId); 14132 } 14133 } 14134 14135 /** 14136 * Get the "allow unknown sources" setting. 14137 * 14138 * @return the current "allow unknown sources" setting 14139 */ 14140 private int getUnknownSourcesSettings() { 14141 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 14142 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 14143 -1); 14144 } 14145 14146 @Override 14147 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 14148 final int callingUid = Binder.getCallingUid(); 14149 if (getInstantAppPackageName(callingUid) != null) { 14150 return; 14151 } 14152 // writer 14153 synchronized (mPackages) { 14154 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 14155 if (targetPackageSetting == null 14156 || filterAppAccessLPr( 14157 targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) { 14158 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 14159 } 14160 14161 PackageSetting installerPackageSetting; 14162 if (installerPackageName != null) { 14163 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 14164 if (installerPackageSetting == null) { 14165 throw new IllegalArgumentException("Unknown installer package: " 14166 + installerPackageName); 14167 } 14168 } else { 14169 installerPackageSetting = null; 14170 } 14171 14172 Signature[] callerSignature; 14173 Object obj = mSettings.getUserIdLPr(callingUid); 14174 if (obj != null) { 14175 if (obj instanceof SharedUserSetting) { 14176 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 14177 } else if (obj instanceof PackageSetting) { 14178 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 14179 } else { 14180 throw new SecurityException("Bad object " + obj + " for uid " + callingUid); 14181 } 14182 } else { 14183 throw new SecurityException("Unknown calling UID: " + callingUid); 14184 } 14185 14186 // Verify: can't set installerPackageName to a package that is 14187 // not signed with the same cert as the caller. 14188 if (installerPackageSetting != null) { 14189 if (compareSignatures(callerSignature, 14190 installerPackageSetting.signatures.mSignatures) 14191 != PackageManager.SIGNATURE_MATCH) { 14192 throw new SecurityException( 14193 "Caller does not have same cert as new installer package " 14194 + installerPackageName); 14195 } 14196 } 14197 14198 // Verify: if target already has an installer package, it must 14199 // be signed with the same cert as the caller. 14200 if (targetPackageSetting.installerPackageName != null) { 14201 PackageSetting setting = mSettings.mPackages.get( 14202 targetPackageSetting.installerPackageName); 14203 // If the currently set package isn't valid, then it's always 14204 // okay to change it. 14205 if (setting != null) { 14206 if (compareSignatures(callerSignature, 14207 setting.signatures.mSignatures) 14208 != PackageManager.SIGNATURE_MATCH) { 14209 throw new SecurityException( 14210 "Caller does not have same cert as old installer package " 14211 + targetPackageSetting.installerPackageName); 14212 } 14213 } 14214 } 14215 14216 // Okay! 14217 targetPackageSetting.installerPackageName = installerPackageName; 14218 if (installerPackageName != null) { 14219 mSettings.mInstallerPackages.add(installerPackageName); 14220 } 14221 scheduleWriteSettingsLocked(); 14222 } 14223 } 14224 14225 @Override 14226 public void setApplicationCategoryHint(String packageName, int categoryHint, 14227 String callerPackageName) { 14228 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 14229 throw new SecurityException("Instant applications don't have access to this method"); 14230 } 14231 mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(), 14232 callerPackageName); 14233 synchronized (mPackages) { 14234 PackageSetting ps = mSettings.mPackages.get(packageName); 14235 if (ps == null) { 14236 throw new IllegalArgumentException("Unknown target package " + packageName); 14237 } 14238 if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) { 14239 throw new IllegalArgumentException("Unknown target package " + packageName); 14240 } 14241 if (!Objects.equals(callerPackageName, ps.installerPackageName)) { 14242 throw new IllegalArgumentException("Calling package " + callerPackageName 14243 + " is not installer for " + packageName); 14244 } 14245 14246 if (ps.categoryHint != categoryHint) { 14247 ps.categoryHint = categoryHint; 14248 scheduleWriteSettingsLocked(); 14249 } 14250 } 14251 } 14252 14253 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 14254 // Queue up an async operation since the package installation may take a little while. 14255 mHandler.post(new Runnable() { 14256 public void run() { 14257 mHandler.removeCallbacks(this); 14258 // Result object to be returned 14259 PackageInstalledInfo res = new PackageInstalledInfo(); 14260 res.setReturnCode(currentStatus); 14261 res.uid = -1; 14262 res.pkg = null; 14263 res.removedInfo = null; 14264 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14265 args.doPreInstall(res.returnCode); 14266 synchronized (mInstallLock) { 14267 installPackageTracedLI(args, res); 14268 } 14269 args.doPostInstall(res.returnCode, res.uid); 14270 } 14271 14272 // A restore should be performed at this point if (a) the install 14273 // succeeded, (b) the operation is not an update, and (c) the new 14274 // package has not opted out of backup participation. 14275 final boolean update = res.removedInfo != null 14276 && res.removedInfo.removedPackage != null; 14277 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 14278 boolean doRestore = !update 14279 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 14280 14281 // Set up the post-install work request bookkeeping. This will be used 14282 // and cleaned up by the post-install event handling regardless of whether 14283 // there's a restore pass performed. Token values are >= 1. 14284 int token; 14285 if (mNextInstallToken < 0) mNextInstallToken = 1; 14286 token = mNextInstallToken++; 14287 14288 PostInstallData data = new PostInstallData(args, res); 14289 mRunningInstalls.put(token, data); 14290 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 14291 14292 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 14293 // Pass responsibility to the Backup Manager. It will perform a 14294 // restore if appropriate, then pass responsibility back to the 14295 // Package Manager to run the post-install observer callbacks 14296 // and broadcasts. 14297 IBackupManager bm = IBackupManager.Stub.asInterface( 14298 ServiceManager.getService(Context.BACKUP_SERVICE)); 14299 if (bm != null) { 14300 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 14301 + " to BM for possible restore"); 14302 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 14303 try { 14304 // TODO: http://b/22388012 14305 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 14306 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 14307 } else { 14308 doRestore = false; 14309 } 14310 } catch (RemoteException e) { 14311 // can't happen; the backup manager is local 14312 } catch (Exception e) { 14313 Slog.e(TAG, "Exception trying to enqueue restore", e); 14314 doRestore = false; 14315 } 14316 } else { 14317 Slog.e(TAG, "Backup Manager not found!"); 14318 doRestore = false; 14319 } 14320 } 14321 14322 if (!doRestore) { 14323 // No restore possible, or the Backup Manager was mysteriously not 14324 // available -- just fire the post-install work request directly. 14325 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 14326 14327 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 14328 14329 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 14330 mHandler.sendMessage(msg); 14331 } 14332 } 14333 }); 14334 } 14335 14336 /** 14337 * Callback from PackageSettings whenever an app is first transitioned out of the 14338 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 14339 * the app was "launched" for a restoreAtInstall operation. Therefore we check 14340 * here whether the app is the target of an ongoing install, and only send the 14341 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 14342 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 14343 * handling. 14344 */ 14345 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 14346 // Serialize this with the rest of the install-process message chain. In the 14347 // restore-at-install case, this Runnable will necessarily run before the 14348 // POST_INSTALL message is processed, so the contents of mRunningInstalls 14349 // are coherent. In the non-restore case, the app has already completed install 14350 // and been launched through some other means, so it is not in a problematic 14351 // state for observers to see the FIRST_LAUNCH signal. 14352 mHandler.post(new Runnable() { 14353 @Override 14354 public void run() { 14355 for (int i = 0; i < mRunningInstalls.size(); i++) { 14356 final PostInstallData data = mRunningInstalls.valueAt(i); 14357 if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14358 continue; 14359 } 14360 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 14361 // right package; but is it for the right user? 14362 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 14363 if (userId == data.res.newUsers[uIndex]) { 14364 if (DEBUG_BACKUP) { 14365 Slog.i(TAG, "Package " + pkgName 14366 + " being restored so deferring FIRST_LAUNCH"); 14367 } 14368 return; 14369 } 14370 } 14371 } 14372 } 14373 // didn't find it, so not being restored 14374 if (DEBUG_BACKUP) { 14375 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 14376 } 14377 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 14378 } 14379 }); 14380 } 14381 14382 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 14383 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 14384 installerPkg, null, userIds); 14385 } 14386 14387 private abstract class HandlerParams { 14388 private static final int MAX_RETRIES = 4; 14389 14390 /** 14391 * Number of times startCopy() has been attempted and had a non-fatal 14392 * error. 14393 */ 14394 private int mRetries = 0; 14395 14396 /** User handle for the user requesting the information or installation. */ 14397 private final UserHandle mUser; 14398 String traceMethod; 14399 int traceCookie; 14400 14401 HandlerParams(UserHandle user) { 14402 mUser = user; 14403 } 14404 14405 UserHandle getUser() { 14406 return mUser; 14407 } 14408 14409 HandlerParams setTraceMethod(String traceMethod) { 14410 this.traceMethod = traceMethod; 14411 return this; 14412 } 14413 14414 HandlerParams setTraceCookie(int traceCookie) { 14415 this.traceCookie = traceCookie; 14416 return this; 14417 } 14418 14419 final boolean startCopy() { 14420 boolean res; 14421 try { 14422 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 14423 14424 if (++mRetries > MAX_RETRIES) { 14425 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 14426 mHandler.sendEmptyMessage(MCS_GIVE_UP); 14427 handleServiceError(); 14428 return false; 14429 } else { 14430 handleStartCopy(); 14431 res = true; 14432 } 14433 } catch (RemoteException e) { 14434 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 14435 mHandler.sendEmptyMessage(MCS_RECONNECT); 14436 res = false; 14437 } 14438 handleReturnCode(); 14439 return res; 14440 } 14441 14442 final void serviceError() { 14443 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 14444 handleServiceError(); 14445 handleReturnCode(); 14446 } 14447 14448 abstract void handleStartCopy() throws RemoteException; 14449 abstract void handleServiceError(); 14450 abstract void handleReturnCode(); 14451 } 14452 14453 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 14454 for (File path : paths) { 14455 try { 14456 mcs.clearDirectory(path.getAbsolutePath()); 14457 } catch (RemoteException e) { 14458 } 14459 } 14460 } 14461 14462 static class OriginInfo { 14463 /** 14464 * Location where install is coming from, before it has been 14465 * copied/renamed into place. This could be a single monolithic APK 14466 * file, or a cluster directory. This location may be untrusted. 14467 */ 14468 final File file; 14469 14470 /** 14471 * Flag indicating that {@link #file} or {@link #cid} has already been 14472 * staged, meaning downstream users don't need to defensively copy the 14473 * contents. 14474 */ 14475 final boolean staged; 14476 14477 /** 14478 * Flag indicating that {@link #file} or {@link #cid} is an already 14479 * installed app that is being moved. 14480 */ 14481 final boolean existing; 14482 14483 final String resolvedPath; 14484 final File resolvedFile; 14485 14486 static OriginInfo fromNothing() { 14487 return new OriginInfo(null, false, false); 14488 } 14489 14490 static OriginInfo fromUntrustedFile(File file) { 14491 return new OriginInfo(file, false, false); 14492 } 14493 14494 static OriginInfo fromExistingFile(File file) { 14495 return new OriginInfo(file, false, true); 14496 } 14497 14498 static OriginInfo fromStagedFile(File file) { 14499 return new OriginInfo(file, true, false); 14500 } 14501 14502 private OriginInfo(File file, boolean staged, boolean existing) { 14503 this.file = file; 14504 this.staged = staged; 14505 this.existing = existing; 14506 14507 if (file != null) { 14508 resolvedPath = file.getAbsolutePath(); 14509 resolvedFile = file; 14510 } else { 14511 resolvedPath = null; 14512 resolvedFile = null; 14513 } 14514 } 14515 } 14516 14517 static class MoveInfo { 14518 final int moveId; 14519 final String fromUuid; 14520 final String toUuid; 14521 final String packageName; 14522 final String dataAppName; 14523 final int appId; 14524 final String seinfo; 14525 final int targetSdkVersion; 14526 14527 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 14528 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 14529 this.moveId = moveId; 14530 this.fromUuid = fromUuid; 14531 this.toUuid = toUuid; 14532 this.packageName = packageName; 14533 this.dataAppName = dataAppName; 14534 this.appId = appId; 14535 this.seinfo = seinfo; 14536 this.targetSdkVersion = targetSdkVersion; 14537 } 14538 } 14539 14540 static class VerificationInfo { 14541 /** A constant used to indicate that a uid value is not present. */ 14542 public static final int NO_UID = -1; 14543 14544 /** URI referencing where the package was downloaded from. */ 14545 final Uri originatingUri; 14546 14547 /** HTTP referrer URI associated with the originatingURI. */ 14548 final Uri referrer; 14549 14550 /** UID of the application that the install request originated from. */ 14551 final int originatingUid; 14552 14553 /** UID of application requesting the install */ 14554 final int installerUid; 14555 14556 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 14557 this.originatingUri = originatingUri; 14558 this.referrer = referrer; 14559 this.originatingUid = originatingUid; 14560 this.installerUid = installerUid; 14561 } 14562 } 14563 14564 class InstallParams extends HandlerParams { 14565 final OriginInfo origin; 14566 final MoveInfo move; 14567 final IPackageInstallObserver2 observer; 14568 int installFlags; 14569 final String installerPackageName; 14570 final String volumeUuid; 14571 private InstallArgs mArgs; 14572 private int mRet; 14573 final String packageAbiOverride; 14574 final String[] grantedRuntimePermissions; 14575 final VerificationInfo verificationInfo; 14576 final Certificate[][] certificates; 14577 final int installReason; 14578 14579 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 14580 int installFlags, String installerPackageName, String volumeUuid, 14581 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 14582 String[] grantedPermissions, Certificate[][] certificates, int installReason) { 14583 super(user); 14584 this.origin = origin; 14585 this.move = move; 14586 this.observer = observer; 14587 this.installFlags = installFlags; 14588 this.installerPackageName = installerPackageName; 14589 this.volumeUuid = volumeUuid; 14590 this.verificationInfo = verificationInfo; 14591 this.packageAbiOverride = packageAbiOverride; 14592 this.grantedRuntimePermissions = grantedPermissions; 14593 this.certificates = certificates; 14594 this.installReason = installReason; 14595 } 14596 14597 @Override 14598 public String toString() { 14599 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 14600 + " file=" + origin.file + "}"; 14601 } 14602 14603 private int installLocationPolicy(PackageInfoLite pkgLite) { 14604 String packageName = pkgLite.packageName; 14605 int installLocation = pkgLite.installLocation; 14606 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14607 // reader 14608 synchronized (mPackages) { 14609 // Currently installed package which the new package is attempting to replace or 14610 // null if no such package is installed. 14611 PackageParser.Package installedPkg = mPackages.get(packageName); 14612 // Package which currently owns the data which the new package will own if installed. 14613 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 14614 // will be null whereas dataOwnerPkg will contain information about the package 14615 // which was uninstalled while keeping its data. 14616 PackageParser.Package dataOwnerPkg = installedPkg; 14617 if (dataOwnerPkg == null) { 14618 PackageSetting ps = mSettings.mPackages.get(packageName); 14619 if (ps != null) { 14620 dataOwnerPkg = ps.pkg; 14621 } 14622 } 14623 14624 if (dataOwnerPkg != null) { 14625 // If installed, the package will get access to data left on the device by its 14626 // predecessor. As a security measure, this is permited only if this is not a 14627 // version downgrade or if the predecessor package is marked as debuggable and 14628 // a downgrade is explicitly requested. 14629 // 14630 // On debuggable platform builds, downgrades are permitted even for 14631 // non-debuggable packages to make testing easier. Debuggable platform builds do 14632 // not offer security guarantees and thus it's OK to disable some security 14633 // mechanisms to make debugging/testing easier on those builds. However, even on 14634 // debuggable builds downgrades of packages are permitted only if requested via 14635 // installFlags. This is because we aim to keep the behavior of debuggable 14636 // platform builds as close as possible to the behavior of non-debuggable 14637 // platform builds. 14638 final boolean downgradeRequested = 14639 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 14640 final boolean packageDebuggable = 14641 (dataOwnerPkg.applicationInfo.flags 14642 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 14643 final boolean downgradePermitted = 14644 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 14645 if (!downgradePermitted) { 14646 try { 14647 checkDowngrade(dataOwnerPkg, pkgLite); 14648 } catch (PackageManagerException e) { 14649 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 14650 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 14651 } 14652 } 14653 } 14654 14655 if (installedPkg != null) { 14656 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14657 // Check for updated system application. 14658 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 14659 if (onSd) { 14660 Slog.w(TAG, "Cannot install update to system app on sdcard"); 14661 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 14662 } 14663 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14664 } else { 14665 if (onSd) { 14666 // Install flag overrides everything. 14667 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14668 } 14669 // If current upgrade specifies particular preference 14670 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 14671 // Application explicitly specified internal. 14672 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14673 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 14674 // App explictly prefers external. Let policy decide 14675 } else { 14676 // Prefer previous location 14677 if (isExternal(installedPkg)) { 14678 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14679 } 14680 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14681 } 14682 } 14683 } else { 14684 // Invalid install. Return error code 14685 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 14686 } 14687 } 14688 } 14689 // All the special cases have been taken care of. 14690 // Return result based on recommended install location. 14691 if (onSd) { 14692 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14693 } 14694 return pkgLite.recommendedInstallLocation; 14695 } 14696 14697 /* 14698 * Invoke remote method to get package information and install 14699 * location values. Override install location based on default 14700 * policy if needed and then create install arguments based 14701 * on the install location. 14702 */ 14703 public void handleStartCopy() throws RemoteException { 14704 int ret = PackageManager.INSTALL_SUCCEEDED; 14705 14706 // If we're already staged, we've firmly committed to an install location 14707 if (origin.staged) { 14708 if (origin.file != null) { 14709 installFlags |= PackageManager.INSTALL_INTERNAL; 14710 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 14711 } else { 14712 throw new IllegalStateException("Invalid stage location"); 14713 } 14714 } 14715 14716 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14717 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 14718 final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 14719 PackageInfoLite pkgLite = null; 14720 14721 if (onInt && onSd) { 14722 // Check if both bits are set. 14723 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 14724 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14725 } else if (onSd && ephemeral) { 14726 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 14727 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14728 } else { 14729 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 14730 packageAbiOverride); 14731 14732 if (DEBUG_EPHEMERAL && ephemeral) { 14733 Slog.v(TAG, "pkgLite for install: " + pkgLite); 14734 } 14735 14736 /* 14737 * If we have too little free space, try to free cache 14738 * before giving up. 14739 */ 14740 if (!origin.staged && pkgLite.recommendedInstallLocation 14741 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 14742 // TODO: focus freeing disk space on the target device 14743 final StorageManager storage = StorageManager.from(mContext); 14744 final long lowThreshold = storage.getStorageLowBytes( 14745 Environment.getDataDirectory()); 14746 14747 final long sizeBytes = mContainerService.calculateInstalledSize( 14748 origin.resolvedPath, packageAbiOverride); 14749 14750 try { 14751 mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0); 14752 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 14753 installFlags, packageAbiOverride); 14754 } catch (InstallerException e) { 14755 Slog.w(TAG, "Failed to free cache", e); 14756 } 14757 14758 /* 14759 * The cache free must have deleted the file we 14760 * downloaded to install. 14761 * 14762 * TODO: fix the "freeCache" call to not delete 14763 * the file we care about. 14764 */ 14765 if (pkgLite.recommendedInstallLocation 14766 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 14767 pkgLite.recommendedInstallLocation 14768 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 14769 } 14770 } 14771 } 14772 14773 if (ret == PackageManager.INSTALL_SUCCEEDED) { 14774 int loc = pkgLite.recommendedInstallLocation; 14775 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 14776 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14777 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 14778 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 14779 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 14780 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 14781 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 14782 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 14783 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 14784 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 14785 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 14786 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 14787 } else { 14788 // Override with defaults if needed. 14789 loc = installLocationPolicy(pkgLite); 14790 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 14791 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 14792 } else if (!onSd && !onInt) { 14793 // Override install location with flags 14794 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 14795 // Set the flag to install on external media. 14796 installFlags |= PackageManager.INSTALL_EXTERNAL; 14797 installFlags &= ~PackageManager.INSTALL_INTERNAL; 14798 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 14799 if (DEBUG_EPHEMERAL) { 14800 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 14801 } 14802 installFlags |= PackageManager.INSTALL_INSTANT_APP; 14803 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 14804 |PackageManager.INSTALL_INTERNAL); 14805 } else { 14806 // Make sure the flag for installing on external 14807 // media is unset 14808 installFlags |= PackageManager.INSTALL_INTERNAL; 14809 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 14810 } 14811 } 14812 } 14813 } 14814 14815 final InstallArgs args = createInstallArgs(this); 14816 mArgs = args; 14817 14818 if (ret == PackageManager.INSTALL_SUCCEEDED) { 14819 // TODO: http://b/22976637 14820 // Apps installed for "all" users use the device owner to verify the app 14821 UserHandle verifierUser = getUser(); 14822 if (verifierUser == UserHandle.ALL) { 14823 verifierUser = UserHandle.SYSTEM; 14824 } 14825 14826 /* 14827 * Determine if we have any installed package verifiers. If we 14828 * do, then we'll defer to them to verify the packages. 14829 */ 14830 final int requiredUid = mRequiredVerifierPackage == null ? -1 14831 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 14832 verifierUser.getIdentifier()); 14833 final int installerUid = 14834 verificationInfo == null ? -1 : verificationInfo.installerUid; 14835 if (!origin.existing && requiredUid != -1 14836 && isVerificationEnabled( 14837 verifierUser.getIdentifier(), installFlags, installerUid)) { 14838 final Intent verification = new Intent( 14839 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 14840 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 14841 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 14842 PACKAGE_MIME_TYPE); 14843 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 14844 14845 // Query all live verifiers based on current user state 14846 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 14847 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(), 14848 false /*allowDynamicSplits*/); 14849 14850 if (DEBUG_VERIFY) { 14851 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 14852 + verification.toString() + " with " + pkgLite.verifiers.length 14853 + " optional verifiers"); 14854 } 14855 14856 final int verificationId = mPendingVerificationToken++; 14857 14858 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 14859 14860 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 14861 installerPackageName); 14862 14863 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 14864 installFlags); 14865 14866 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 14867 pkgLite.packageName); 14868 14869 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 14870 pkgLite.versionCode); 14871 14872 if (verificationInfo != null) { 14873 if (verificationInfo.originatingUri != null) { 14874 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 14875 verificationInfo.originatingUri); 14876 } 14877 if (verificationInfo.referrer != null) { 14878 verification.putExtra(Intent.EXTRA_REFERRER, 14879 verificationInfo.referrer); 14880 } 14881 if (verificationInfo.originatingUid >= 0) { 14882 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 14883 verificationInfo.originatingUid); 14884 } 14885 if (verificationInfo.installerUid >= 0) { 14886 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 14887 verificationInfo.installerUid); 14888 } 14889 } 14890 14891 final PackageVerificationState verificationState = new PackageVerificationState( 14892 requiredUid, args); 14893 14894 mPendingVerification.append(verificationId, verificationState); 14895 14896 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 14897 receivers, verificationState); 14898 14899 DeviceIdleController.LocalService idleController = getDeviceIdleController(); 14900 final long idleDuration = getVerificationTimeout(); 14901 14902 /* 14903 * If any sufficient verifiers were listed in the package 14904 * manifest, attempt to ask them. 14905 */ 14906 if (sufficientVerifiers != null) { 14907 final int N = sufficientVerifiers.size(); 14908 if (N == 0) { 14909 Slog.i(TAG, "Additional verifiers required, but none installed."); 14910 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 14911 } else { 14912 for (int i = 0; i < N; i++) { 14913 final ComponentName verifierComponent = sufficientVerifiers.get(i); 14914 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 14915 verifierComponent.getPackageName(), idleDuration, 14916 verifierUser.getIdentifier(), false, "package verifier"); 14917 14918 final Intent sufficientIntent = new Intent(verification); 14919 sufficientIntent.setComponent(verifierComponent); 14920 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 14921 } 14922 } 14923 } 14924 14925 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 14926 mRequiredVerifierPackage, receivers); 14927 if (ret == PackageManager.INSTALL_SUCCEEDED 14928 && mRequiredVerifierPackage != null) { 14929 Trace.asyncTraceBegin( 14930 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 14931 /* 14932 * Send the intent to the required verification agent, 14933 * but only start the verification timeout after the 14934 * target BroadcastReceivers have run. 14935 */ 14936 verification.setComponent(requiredVerifierComponent); 14937 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 14938 mRequiredVerifierPackage, idleDuration, 14939 verifierUser.getIdentifier(), false, "package verifier"); 14940 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 14941 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 14942 new BroadcastReceiver() { 14943 @Override 14944 public void onReceive(Context context, Intent intent) { 14945 final Message msg = mHandler 14946 .obtainMessage(CHECK_PENDING_VERIFICATION); 14947 msg.arg1 = verificationId; 14948 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 14949 } 14950 }, null, 0, null, null); 14951 14952 /* 14953 * We don't want the copy to proceed until verification 14954 * succeeds, so null out this field. 14955 */ 14956 mArgs = null; 14957 } 14958 } else { 14959 /* 14960 * No package verification is enabled, so immediately start 14961 * the remote call to initiate copy using temporary file. 14962 */ 14963 ret = args.copyApk(mContainerService, true); 14964 } 14965 } 14966 14967 mRet = ret; 14968 } 14969 14970 @Override 14971 void handleReturnCode() { 14972 // If mArgs is null, then MCS couldn't be reached. When it 14973 // reconnects, it will try again to install. At that point, this 14974 // will succeed. 14975 if (mArgs != null) { 14976 processPendingInstall(mArgs, mRet); 14977 } 14978 } 14979 14980 @Override 14981 void handleServiceError() { 14982 mArgs = createInstallArgs(this); 14983 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 14984 } 14985 } 14986 14987 private InstallArgs createInstallArgs(InstallParams params) { 14988 if (params.move != null) { 14989 return new MoveInstallArgs(params); 14990 } else { 14991 return new FileInstallArgs(params); 14992 } 14993 } 14994 14995 /** 14996 * Create args that describe an existing installed package. Typically used 14997 * when cleaning up old installs, or used as a move source. 14998 */ 14999 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 15000 String resourcePath, String[] instructionSets) { 15001 return new FileInstallArgs(codePath, resourcePath, instructionSets); 15002 } 15003 15004 static abstract class InstallArgs { 15005 /** @see InstallParams#origin */ 15006 final OriginInfo origin; 15007 /** @see InstallParams#move */ 15008 final MoveInfo move; 15009 15010 final IPackageInstallObserver2 observer; 15011 // Always refers to PackageManager flags only 15012 final int installFlags; 15013 final String installerPackageName; 15014 final String volumeUuid; 15015 final UserHandle user; 15016 final String abiOverride; 15017 final String[] installGrantPermissions; 15018 /** If non-null, drop an async trace when the install completes */ 15019 final String traceMethod; 15020 final int traceCookie; 15021 final Certificate[][] certificates; 15022 final int installReason; 15023 15024 // The list of instruction sets supported by this app. This is currently 15025 // only used during the rmdex() phase to clean up resources. We can get rid of this 15026 // if we move dex files under the common app path. 15027 /* nullable */ String[] instructionSets; 15028 15029 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 15030 int installFlags, String installerPackageName, String volumeUuid, 15031 UserHandle user, String[] instructionSets, 15032 String abiOverride, String[] installGrantPermissions, 15033 String traceMethod, int traceCookie, Certificate[][] certificates, 15034 int installReason) { 15035 this.origin = origin; 15036 this.move = move; 15037 this.installFlags = installFlags; 15038 this.observer = observer; 15039 this.installerPackageName = installerPackageName; 15040 this.volumeUuid = volumeUuid; 15041 this.user = user; 15042 this.instructionSets = instructionSets; 15043 this.abiOverride = abiOverride; 15044 this.installGrantPermissions = installGrantPermissions; 15045 this.traceMethod = traceMethod; 15046 this.traceCookie = traceCookie; 15047 this.certificates = certificates; 15048 this.installReason = installReason; 15049 } 15050 15051 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 15052 abstract int doPreInstall(int status); 15053 15054 /** 15055 * Rename package into final resting place. All paths on the given 15056 * scanned package should be updated to reflect the rename. 15057 */ 15058 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 15059 abstract int doPostInstall(int status, int uid); 15060 15061 /** @see PackageSettingBase#codePathString */ 15062 abstract String getCodePath(); 15063 /** @see PackageSettingBase#resourcePathString */ 15064 abstract String getResourcePath(); 15065 15066 // Need installer lock especially for dex file removal. 15067 abstract void cleanUpResourcesLI(); 15068 abstract boolean doPostDeleteLI(boolean delete); 15069 15070 /** 15071 * Called before the source arguments are copied. This is used mostly 15072 * for MoveParams when it needs to read the source file to put it in the 15073 * destination. 15074 */ 15075 int doPreCopy() { 15076 return PackageManager.INSTALL_SUCCEEDED; 15077 } 15078 15079 /** 15080 * Called after the source arguments are copied. This is used mostly for 15081 * MoveParams when it needs to read the source file to put it in the 15082 * destination. 15083 */ 15084 int doPostCopy(int uid) { 15085 return PackageManager.INSTALL_SUCCEEDED; 15086 } 15087 15088 protected boolean isFwdLocked() { 15089 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 15090 } 15091 15092 protected boolean isExternalAsec() { 15093 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 15094 } 15095 15096 protected boolean isEphemeral() { 15097 return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 15098 } 15099 15100 UserHandle getUser() { 15101 return user; 15102 } 15103 } 15104 15105 void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 15106 if (!allCodePaths.isEmpty()) { 15107 if (instructionSets == null) { 15108 throw new IllegalStateException("instructionSet == null"); 15109 } 15110 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 15111 for (String codePath : allCodePaths) { 15112 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 15113 try { 15114 mInstaller.rmdex(codePath, dexCodeInstructionSet); 15115 } catch (InstallerException ignored) { 15116 } 15117 } 15118 } 15119 } 15120 } 15121 15122 /** 15123 * Logic to handle installation of non-ASEC applications, including copying 15124 * and renaming logic. 15125 */ 15126 class FileInstallArgs extends InstallArgs { 15127 private File codeFile; 15128 private File resourceFile; 15129 15130 // Example topology: 15131 // /data/app/com.example/base.apk 15132 // /data/app/com.example/split_foo.apk 15133 // /data/app/com.example/lib/arm/libfoo.so 15134 // /data/app/com.example/lib/arm64/libfoo.so 15135 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 15136 15137 /** New install */ 15138 FileInstallArgs(InstallParams params) { 15139 super(params.origin, params.move, params.observer, params.installFlags, 15140 params.installerPackageName, params.volumeUuid, 15141 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 15142 params.grantedRuntimePermissions, 15143 params.traceMethod, params.traceCookie, params.certificates, 15144 params.installReason); 15145 if (isFwdLocked()) { 15146 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 15147 } 15148 } 15149 15150 /** Existing install */ 15151 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 15152 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 15153 null, null, null, 0, null /*certificates*/, 15154 PackageManager.INSTALL_REASON_UNKNOWN); 15155 this.codeFile = (codePath != null) ? new File(codePath) : null; 15156 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 15157 } 15158 15159 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 15160 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 15161 try { 15162 return doCopyApk(imcs, temp); 15163 } finally { 15164 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15165 } 15166 } 15167 15168 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 15169 if (origin.staged) { 15170 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 15171 codeFile = origin.file; 15172 resourceFile = origin.file; 15173 return PackageManager.INSTALL_SUCCEEDED; 15174 } 15175 15176 try { 15177 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 15178 final File tempDir = 15179 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 15180 codeFile = tempDir; 15181 resourceFile = tempDir; 15182 } catch (IOException e) { 15183 Slog.w(TAG, "Failed to create copy file: " + e); 15184 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 15185 } 15186 15187 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 15188 @Override 15189 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 15190 if (!FileUtils.isValidExtFilename(name)) { 15191 throw new IllegalArgumentException("Invalid filename: " + name); 15192 } 15193 try { 15194 final File file = new File(codeFile, name); 15195 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 15196 O_RDWR | O_CREAT, 0644); 15197 Os.chmod(file.getAbsolutePath(), 0644); 15198 return new ParcelFileDescriptor(fd); 15199 } catch (ErrnoException e) { 15200 throw new RemoteException("Failed to open: " + e.getMessage()); 15201 } 15202 } 15203 }; 15204 15205 int ret = PackageManager.INSTALL_SUCCEEDED; 15206 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 15207 if (ret != PackageManager.INSTALL_SUCCEEDED) { 15208 Slog.e(TAG, "Failed to copy package"); 15209 return ret; 15210 } 15211 15212 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 15213 NativeLibraryHelper.Handle handle = null; 15214 try { 15215 handle = NativeLibraryHelper.Handle.create(codeFile); 15216 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 15217 abiOverride); 15218 } catch (IOException e) { 15219 Slog.e(TAG, "Copying native libraries failed", e); 15220 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15221 } finally { 15222 IoUtils.closeQuietly(handle); 15223 } 15224 15225 return ret; 15226 } 15227 15228 int doPreInstall(int status) { 15229 if (status != PackageManager.INSTALL_SUCCEEDED) { 15230 cleanUp(); 15231 } 15232 return status; 15233 } 15234 15235 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15236 if (status != PackageManager.INSTALL_SUCCEEDED) { 15237 cleanUp(); 15238 return false; 15239 } 15240 15241 final File targetDir = codeFile.getParentFile(); 15242 final File beforeCodeFile = codeFile; 15243 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 15244 15245 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 15246 try { 15247 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 15248 } catch (ErrnoException e) { 15249 Slog.w(TAG, "Failed to rename", e); 15250 return false; 15251 } 15252 15253 if (!SELinux.restoreconRecursive(afterCodeFile)) { 15254 Slog.w(TAG, "Failed to restorecon"); 15255 return false; 15256 } 15257 15258 // Reflect the rename internally 15259 codeFile = afterCodeFile; 15260 resourceFile = afterCodeFile; 15261 15262 // Reflect the rename in scanned details 15263 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 15264 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 15265 afterCodeFile, pkg.baseCodePath)); 15266 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 15267 afterCodeFile, pkg.splitCodePaths)); 15268 15269 // Reflect the rename in app info 15270 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15271 pkg.setApplicationInfoCodePath(pkg.codePath); 15272 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15273 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15274 pkg.setApplicationInfoResourcePath(pkg.codePath); 15275 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15276 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15277 15278 return true; 15279 } 15280 15281 int doPostInstall(int status, int uid) { 15282 if (status != PackageManager.INSTALL_SUCCEEDED) { 15283 cleanUp(); 15284 } 15285 return status; 15286 } 15287 15288 @Override 15289 String getCodePath() { 15290 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 15291 } 15292 15293 @Override 15294 String getResourcePath() { 15295 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 15296 } 15297 15298 private boolean cleanUp() { 15299 if (codeFile == null || !codeFile.exists()) { 15300 return false; 15301 } 15302 15303 removeCodePathLI(codeFile); 15304 15305 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 15306 resourceFile.delete(); 15307 } 15308 15309 return true; 15310 } 15311 15312 void cleanUpResourcesLI() { 15313 // Try enumerating all code paths before deleting 15314 List<String> allCodePaths = Collections.EMPTY_LIST; 15315 if (codeFile != null && codeFile.exists()) { 15316 try { 15317 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 15318 allCodePaths = pkg.getAllCodePaths(); 15319 } catch (PackageParserException e) { 15320 // Ignored; we tried our best 15321 } 15322 } 15323 15324 cleanUp(); 15325 removeDexFiles(allCodePaths, instructionSets); 15326 } 15327 15328 boolean doPostDeleteLI(boolean delete) { 15329 // XXX err, shouldn't we respect the delete flag? 15330 cleanUpResourcesLI(); 15331 return true; 15332 } 15333 } 15334 15335 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 15336 PackageManagerException { 15337 if (copyRet < 0) { 15338 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 15339 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 15340 throw new PackageManagerException(copyRet, message); 15341 } 15342 } 15343 } 15344 15345 /** 15346 * Extract the StorageManagerService "container ID" from the full code path of an 15347 * .apk. 15348 */ 15349 static String cidFromCodePath(String fullCodePath) { 15350 int eidx = fullCodePath.lastIndexOf("/"); 15351 String subStr1 = fullCodePath.substring(0, eidx); 15352 int sidx = subStr1.lastIndexOf("/"); 15353 return subStr1.substring(sidx+1, eidx); 15354 } 15355 15356 /** 15357 * Logic to handle movement of existing installed applications. 15358 */ 15359 class MoveInstallArgs extends InstallArgs { 15360 private File codeFile; 15361 private File resourceFile; 15362 15363 /** New install */ 15364 MoveInstallArgs(InstallParams params) { 15365 super(params.origin, params.move, params.observer, params.installFlags, 15366 params.installerPackageName, params.volumeUuid, 15367 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 15368 params.grantedRuntimePermissions, 15369 params.traceMethod, params.traceCookie, params.certificates, 15370 params.installReason); 15371 } 15372 15373 int copyApk(IMediaContainerService imcs, boolean temp) { 15374 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 15375 + move.fromUuid + " to " + move.toUuid); 15376 synchronized (mInstaller) { 15377 try { 15378 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 15379 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 15380 } catch (InstallerException e) { 15381 Slog.w(TAG, "Failed to move app", e); 15382 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15383 } 15384 } 15385 15386 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 15387 resourceFile = codeFile; 15388 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 15389 15390 return PackageManager.INSTALL_SUCCEEDED; 15391 } 15392 15393 int doPreInstall(int status) { 15394 if (status != PackageManager.INSTALL_SUCCEEDED) { 15395 cleanUp(move.toUuid); 15396 } 15397 return status; 15398 } 15399 15400 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15401 if (status != PackageManager.INSTALL_SUCCEEDED) { 15402 cleanUp(move.toUuid); 15403 return false; 15404 } 15405 15406 // Reflect the move in app info 15407 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15408 pkg.setApplicationInfoCodePath(pkg.codePath); 15409 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15410 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15411 pkg.setApplicationInfoResourcePath(pkg.codePath); 15412 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15413 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15414 15415 return true; 15416 } 15417 15418 int doPostInstall(int status, int uid) { 15419 if (status == PackageManager.INSTALL_SUCCEEDED) { 15420 cleanUp(move.fromUuid); 15421 } else { 15422 cleanUp(move.toUuid); 15423 } 15424 return status; 15425 } 15426 15427 @Override 15428 String getCodePath() { 15429 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 15430 } 15431 15432 @Override 15433 String getResourcePath() { 15434 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 15435 } 15436 15437 private boolean cleanUp(String volumeUuid) { 15438 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 15439 move.dataAppName); 15440 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 15441 final int[] userIds = sUserManager.getUserIds(); 15442 synchronized (mInstallLock) { 15443 // Clean up both app data and code 15444 // All package moves are frozen until finished 15445 for (int userId : userIds) { 15446 try { 15447 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 15448 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 15449 } catch (InstallerException e) { 15450 Slog.w(TAG, String.valueOf(e)); 15451 } 15452 } 15453 removeCodePathLI(codeFile); 15454 } 15455 return true; 15456 } 15457 15458 void cleanUpResourcesLI() { 15459 throw new UnsupportedOperationException(); 15460 } 15461 15462 boolean doPostDeleteLI(boolean delete) { 15463 throw new UnsupportedOperationException(); 15464 } 15465 } 15466 15467 static String getAsecPackageName(String packageCid) { 15468 int idx = packageCid.lastIndexOf("-"); 15469 if (idx == -1) { 15470 return packageCid; 15471 } 15472 return packageCid.substring(0, idx); 15473 } 15474 15475 // Utility method used to create code paths based on package name and available index. 15476 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 15477 String idxStr = ""; 15478 int idx = 1; 15479 // Fall back to default value of idx=1 if prefix is not 15480 // part of oldCodePath 15481 if (oldCodePath != null) { 15482 String subStr = oldCodePath; 15483 // Drop the suffix right away 15484 if (suffix != null && subStr.endsWith(suffix)) { 15485 subStr = subStr.substring(0, subStr.length() - suffix.length()); 15486 } 15487 // If oldCodePath already contains prefix find out the 15488 // ending index to either increment or decrement. 15489 int sidx = subStr.lastIndexOf(prefix); 15490 if (sidx != -1) { 15491 subStr = subStr.substring(sidx + prefix.length()); 15492 if (subStr != null) { 15493 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 15494 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 15495 } 15496 try { 15497 idx = Integer.parseInt(subStr); 15498 if (idx <= 1) { 15499 idx++; 15500 } else { 15501 idx--; 15502 } 15503 } catch(NumberFormatException e) { 15504 } 15505 } 15506 } 15507 } 15508 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 15509 return prefix + idxStr; 15510 } 15511 15512 private File getNextCodePath(File targetDir, String packageName) { 15513 File result; 15514 SecureRandom random = new SecureRandom(); 15515 byte[] bytes = new byte[16]; 15516 do { 15517 random.nextBytes(bytes); 15518 String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP); 15519 result = new File(targetDir, packageName + "-" + suffix); 15520 } while (result.exists()); 15521 return result; 15522 } 15523 15524 // Utility method that returns the relative package path with respect 15525 // to the installation directory. Like say for /data/data/com.test-1.apk 15526 // string com.test-1 is returned. 15527 static String deriveCodePathName(String codePath) { 15528 if (codePath == null) { 15529 return null; 15530 } 15531 final File codeFile = new File(codePath); 15532 final String name = codeFile.getName(); 15533 if (codeFile.isDirectory()) { 15534 return name; 15535 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 15536 final int lastDot = name.lastIndexOf('.'); 15537 return name.substring(0, lastDot); 15538 } else { 15539 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 15540 return null; 15541 } 15542 } 15543 15544 static class PackageInstalledInfo { 15545 String name; 15546 int uid; 15547 // The set of users that originally had this package installed. 15548 int[] origUsers; 15549 // The set of users that now have this package installed. 15550 int[] newUsers; 15551 PackageParser.Package pkg; 15552 int returnCode; 15553 String returnMsg; 15554 String installerPackageName; 15555 PackageRemovedInfo removedInfo; 15556 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 15557 15558 public void setError(int code, String msg) { 15559 setReturnCode(code); 15560 setReturnMessage(msg); 15561 Slog.w(TAG, msg); 15562 } 15563 15564 public void setError(String msg, PackageParserException e) { 15565 setReturnCode(e.error); 15566 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 15567 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15568 for (int i = 0; i < childCount; i++) { 15569 addedChildPackages.valueAt(i).setError(msg, e); 15570 } 15571 Slog.w(TAG, msg, e); 15572 } 15573 15574 public void setError(String msg, PackageManagerException e) { 15575 returnCode = e.error; 15576 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 15577 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15578 for (int i = 0; i < childCount; i++) { 15579 addedChildPackages.valueAt(i).setError(msg, e); 15580 } 15581 Slog.w(TAG, msg, e); 15582 } 15583 15584 public void setReturnCode(int returnCode) { 15585 this.returnCode = returnCode; 15586 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15587 for (int i = 0; i < childCount; i++) { 15588 addedChildPackages.valueAt(i).returnCode = returnCode; 15589 } 15590 } 15591 15592 private void setReturnMessage(String returnMsg) { 15593 this.returnMsg = returnMsg; 15594 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15595 for (int i = 0; i < childCount; i++) { 15596 addedChildPackages.valueAt(i).returnMsg = returnMsg; 15597 } 15598 } 15599 15600 // In some error cases we want to convey more info back to the observer 15601 String origPackage; 15602 String origPermission; 15603 } 15604 15605 /* 15606 * Install a non-existing package. 15607 */ 15608 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 15609 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 15610 PackageInstalledInfo res, int installReason) { 15611 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 15612 15613 // Remember this for later, in case we need to rollback this install 15614 String pkgName = pkg.packageName; 15615 15616 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 15617 15618 synchronized(mPackages) { 15619 final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName); 15620 if (renamedPackage != null) { 15621 // A package with the same name is already installed, though 15622 // it has been renamed to an older name. The package we 15623 // are trying to install should be installed as an update to 15624 // the existing one, but that has not been requested, so bail. 15625 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 15626 + " without first uninstalling package running as " 15627 + renamedPackage); 15628 return; 15629 } 15630 if (mPackages.containsKey(pkgName)) { 15631 // Don't allow installation over an existing package with the same name. 15632 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 15633 + " without first uninstalling."); 15634 return; 15635 } 15636 } 15637 15638 try { 15639 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 15640 System.currentTimeMillis(), user); 15641 15642 updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason); 15643 15644 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 15645 prepareAppDataAfterInstallLIF(newPackage); 15646 15647 } else { 15648 // Remove package from internal structures, but keep around any 15649 // data that might have already existed 15650 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 15651 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 15652 } 15653 } catch (PackageManagerException e) { 15654 res.setError("Package couldn't be installed in " + pkg.codePath, e); 15655 } 15656 15657 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15658 } 15659 15660 private boolean shouldCheckUpgradeKeySetLP(PackageSettingBase oldPs, int scanFlags) { 15661 // Can't rotate keys during boot or if sharedUser. 15662 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.isSharedUser() 15663 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 15664 return false; 15665 } 15666 // app is using upgradeKeySets; make sure all are valid 15667 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15668 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 15669 for (int i = 0; i < upgradeKeySets.length; i++) { 15670 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 15671 Slog.wtf(TAG, "Package " 15672 + (oldPs.name != null ? oldPs.name : "<null>") 15673 + " contains upgrade-key-set reference to unknown key-set: " 15674 + upgradeKeySets[i] 15675 + " reverting to signatures check."); 15676 return false; 15677 } 15678 } 15679 return true; 15680 } 15681 15682 private boolean checkUpgradeKeySetLP(PackageSettingBase oldPS, PackageParser.Package newPkg) { 15683 // Upgrade keysets are being used. Determine if new package has a superset of the 15684 // required keys. 15685 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 15686 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15687 for (int i = 0; i < upgradeKeySets.length; i++) { 15688 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 15689 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 15690 return true; 15691 } 15692 } 15693 return false; 15694 } 15695 15696 private static void updateDigest(MessageDigest digest, File file) throws IOException { 15697 try (DigestInputStream digestStream = 15698 new DigestInputStream(new FileInputStream(file), digest)) { 15699 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 15700 } 15701 } 15702 15703 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 15704 UserHandle user, String installerPackageName, PackageInstalledInfo res, 15705 int installReason) { 15706 final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 15707 15708 final PackageParser.Package oldPackage; 15709 final PackageSetting ps; 15710 final String pkgName = pkg.packageName; 15711 final int[] allUsers; 15712 final int[] installedUsers; 15713 15714 synchronized(mPackages) { 15715 oldPackage = mPackages.get(pkgName); 15716 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 15717 15718 // don't allow upgrade to target a release SDK from a pre-release SDK 15719 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 15720 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 15721 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 15722 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 15723 if (oldTargetsPreRelease 15724 && !newTargetsPreRelease 15725 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 15726 Slog.w(TAG, "Can't install package targeting released sdk"); 15727 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 15728 return; 15729 } 15730 15731 ps = mSettings.mPackages.get(pkgName); 15732 15733 // verify signatures are valid 15734 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 15735 if (!checkUpgradeKeySetLP(ps, pkg)) { 15736 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 15737 "New package not signed by keys specified by upgrade-keysets: " 15738 + pkgName); 15739 return; 15740 } 15741 } else { 15742 // default to original signature matching 15743 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 15744 != PackageManager.SIGNATURE_MATCH) { 15745 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 15746 "New package has a different signature: " + pkgName); 15747 return; 15748 } 15749 } 15750 15751 // don't allow a system upgrade unless the upgrade hash matches 15752 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystem()) { 15753 byte[] digestBytes = null; 15754 try { 15755 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 15756 updateDigest(digest, new File(pkg.baseCodePath)); 15757 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 15758 for (String path : pkg.splitCodePaths) { 15759 updateDigest(digest, new File(path)); 15760 } 15761 } 15762 digestBytes = digest.digest(); 15763 } catch (NoSuchAlgorithmException | IOException e) { 15764 res.setError(INSTALL_FAILED_INVALID_APK, 15765 "Could not compute hash: " + pkgName); 15766 return; 15767 } 15768 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 15769 res.setError(INSTALL_FAILED_INVALID_APK, 15770 "New package fails restrict-update check: " + pkgName); 15771 return; 15772 } 15773 // retain upgrade restriction 15774 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 15775 } 15776 15777 // Check for shared user id changes 15778 String invalidPackageName = 15779 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 15780 if (invalidPackageName != null) { 15781 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 15782 "Package " + invalidPackageName + " tried to change user " 15783 + oldPackage.mSharedUserId); 15784 return; 15785 } 15786 15787 // In case of rollback, remember per-user/profile install state 15788 allUsers = sUserManager.getUserIds(); 15789 installedUsers = ps.queryInstalledUsers(allUsers, true); 15790 15791 // don't allow an upgrade from full to ephemeral 15792 if (isInstantApp) { 15793 if (user == null || user.getIdentifier() == UserHandle.USER_ALL) { 15794 for (int currentUser : allUsers) { 15795 if (!ps.getInstantApp(currentUser)) { 15796 // can't downgrade from full to instant 15797 Slog.w(TAG, "Can't replace full app with instant app: " + pkgName 15798 + " for user: " + currentUser); 15799 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 15800 return; 15801 } 15802 } 15803 } else if (!ps.getInstantApp(user.getIdentifier())) { 15804 // can't downgrade from full to instant 15805 Slog.w(TAG, "Can't replace full app with instant app: " + pkgName 15806 + " for user: " + user.getIdentifier()); 15807 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 15808 return; 15809 } 15810 } 15811 } 15812 15813 // Update what is removed 15814 res.removedInfo = new PackageRemovedInfo(this); 15815 res.removedInfo.uid = oldPackage.applicationInfo.uid; 15816 res.removedInfo.removedPackage = oldPackage.packageName; 15817 res.removedInfo.installerPackageName = ps.installerPackageName; 15818 res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null; 15819 res.removedInfo.isUpdate = true; 15820 res.removedInfo.origUsers = installedUsers; 15821 res.removedInfo.installReasons = new SparseArray<>(installedUsers.length); 15822 for (int i = 0; i < installedUsers.length; i++) { 15823 final int userId = installedUsers[i]; 15824 res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId)); 15825 } 15826 15827 final int childCount = (oldPackage.childPackages != null) 15828 ? oldPackage.childPackages.size() : 0; 15829 for (int i = 0; i < childCount; i++) { 15830 boolean childPackageUpdated = false; 15831 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 15832 final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 15833 if (res.addedChildPackages != null) { 15834 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 15835 if (childRes != null) { 15836 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 15837 childRes.removedInfo.removedPackage = childPkg.packageName; 15838 if (childPs != null) { 15839 childRes.removedInfo.installerPackageName = childPs.installerPackageName; 15840 } 15841 childRes.removedInfo.isUpdate = true; 15842 childRes.removedInfo.installReasons = res.removedInfo.installReasons; 15843 childPackageUpdated = true; 15844 } 15845 } 15846 if (!childPackageUpdated) { 15847 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this); 15848 childRemovedRes.removedPackage = childPkg.packageName; 15849 if (childPs != null) { 15850 childRemovedRes.installerPackageName = childPs.installerPackageName; 15851 } 15852 childRemovedRes.isUpdate = false; 15853 childRemovedRes.dataRemoved = true; 15854 synchronized (mPackages) { 15855 if (childPs != null) { 15856 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 15857 } 15858 } 15859 if (res.removedInfo.removedChildPackages == null) { 15860 res.removedInfo.removedChildPackages = new ArrayMap<>(); 15861 } 15862 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 15863 } 15864 } 15865 15866 boolean sysPkg = (isSystemApp(oldPackage)); 15867 if (sysPkg) { 15868 // Set the system/privileged/oem flags as needed 15869 final boolean privileged = 15870 (oldPackage.applicationInfo.privateFlags 15871 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 15872 final boolean oem = 15873 (oldPackage.applicationInfo.privateFlags 15874 & ApplicationInfo.PRIVATE_FLAG_OEM) != 0; 15875 final int systemPolicyFlags = policyFlags 15876 | PackageParser.PARSE_IS_SYSTEM 15877 | (privileged ? PARSE_IS_PRIVILEGED : 0) 15878 | (oem ? PARSE_IS_OEM : 0); 15879 15880 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 15881 user, allUsers, installerPackageName, res, installReason); 15882 } else { 15883 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 15884 user, allUsers, installerPackageName, res, installReason); 15885 } 15886 } 15887 15888 @Override 15889 public List<String> getPreviousCodePaths(String packageName) { 15890 final int callingUid = Binder.getCallingUid(); 15891 final List<String> result = new ArrayList<>(); 15892 if (getInstantAppPackageName(callingUid) != null) { 15893 return result; 15894 } 15895 final PackageSetting ps = mSettings.mPackages.get(packageName); 15896 if (ps != null 15897 && ps.oldCodePaths != null 15898 && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 15899 result.addAll(ps.oldCodePaths); 15900 } 15901 return result; 15902 } 15903 15904 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 15905 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 15906 int[] allUsers, String installerPackageName, PackageInstalledInfo res, 15907 int installReason) { 15908 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 15909 + deletedPackage); 15910 15911 String pkgName = deletedPackage.packageName; 15912 boolean deletedPkg = true; 15913 boolean addedPkg = false; 15914 boolean updatedSettings = false; 15915 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 15916 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 15917 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 15918 15919 final long origUpdateTime = (pkg.mExtras != null) 15920 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 15921 15922 // First delete the existing package while retaining the data directory 15923 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 15924 res.removedInfo, true, pkg)) { 15925 // If the existing package wasn't successfully deleted 15926 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 15927 deletedPkg = false; 15928 } else { 15929 // Successfully deleted the old package; proceed with replace. 15930 15931 // If deleted package lived in a container, give users a chance to 15932 // relinquish resources before killing. 15933 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 15934 if (DEBUG_INSTALL) { 15935 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 15936 } 15937 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 15938 final ArrayList<String> pkgList = new ArrayList<String>(1); 15939 pkgList.add(deletedPackage.applicationInfo.packageName); 15940 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 15941 } 15942 15943 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 15944 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 15945 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 15946 15947 try { 15948 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 15949 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 15950 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 15951 installReason); 15952 15953 // Update the in-memory copy of the previous code paths. 15954 PackageSetting ps = mSettings.mPackages.get(pkgName); 15955 if (!killApp) { 15956 if (ps.oldCodePaths == null) { 15957 ps.oldCodePaths = new ArraySet<>(); 15958 } 15959 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 15960 if (deletedPackage.splitCodePaths != null) { 15961 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 15962 } 15963 } else { 15964 ps.oldCodePaths = null; 15965 } 15966 if (ps.childPackageNames != null) { 15967 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 15968 final String childPkgName = ps.childPackageNames.get(i); 15969 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 15970 childPs.oldCodePaths = ps.oldCodePaths; 15971 } 15972 } 15973 // set instant app status, but, only if it's explicitly specified 15974 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 15975 final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0; 15976 setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp); 15977 prepareAppDataAfterInstallLIF(newPackage); 15978 addedPkg = true; 15979 mDexManager.notifyPackageUpdated(newPackage.packageName, 15980 newPackage.baseCodePath, newPackage.splitCodePaths); 15981 } catch (PackageManagerException e) { 15982 res.setError("Package couldn't be installed in " + pkg.codePath, e); 15983 } 15984 } 15985 15986 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 15987 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 15988 15989 // Revert all internal state mutations and added folders for the failed install 15990 if (addedPkg) { 15991 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 15992 res.removedInfo, true, null); 15993 } 15994 15995 // Restore the old package 15996 if (deletedPkg) { 15997 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 15998 File restoreFile = new File(deletedPackage.codePath); 15999 // Parse old package 16000 boolean oldExternal = isExternal(deletedPackage); 16001 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 16002 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 16003 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 16004 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 16005 try { 16006 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 16007 null); 16008 } catch (PackageManagerException e) { 16009 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 16010 + e.getMessage()); 16011 return; 16012 } 16013 16014 synchronized (mPackages) { 16015 // Ensure the installer package name up to date 16016 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 16017 16018 // Update permissions for restored package 16019 mPermissionManager.updatePermissions( 16020 deletedPackage.packageName, deletedPackage, false, mPackages.values(), 16021 mPermissionCallback); 16022 16023 mSettings.writeLPr(); 16024 } 16025 16026 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 16027 } 16028 } else { 16029 synchronized (mPackages) { 16030 PackageSetting ps = mSettings.getPackageLPr(pkg.packageName); 16031 if (ps != null) { 16032 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 16033 if (res.removedInfo.removedChildPackages != null) { 16034 final int childCount = res.removedInfo.removedChildPackages.size(); 16035 // Iterate in reverse as we may modify the collection 16036 for (int i = childCount - 1; i >= 0; i--) { 16037 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 16038 if (res.addedChildPackages.containsKey(childPackageName)) { 16039 res.removedInfo.removedChildPackages.removeAt(i); 16040 } else { 16041 PackageRemovedInfo childInfo = res.removedInfo 16042 .removedChildPackages.valueAt(i); 16043 childInfo.removedForAllUsers = mPackages.get( 16044 childInfo.removedPackage) == null; 16045 } 16046 } 16047 } 16048 } 16049 } 16050 } 16051 } 16052 16053 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 16054 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 16055 int[] allUsers, String installerPackageName, PackageInstalledInfo res, 16056 int installReason) { 16057 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 16058 + ", old=" + deletedPackage); 16059 16060 final boolean disabledSystem; 16061 16062 // Remove existing system package 16063 removePackageLI(deletedPackage, true); 16064 16065 synchronized (mPackages) { 16066 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 16067 } 16068 if (!disabledSystem) { 16069 // We didn't need to disable the .apk as a current system package, 16070 // which means we are replacing another update that is already 16071 // installed. We need to make sure to delete the older one's .apk. 16072 res.removedInfo.args = createInstallArgsForExisting(0, 16073 deletedPackage.applicationInfo.getCodePath(), 16074 deletedPackage.applicationInfo.getResourcePath(), 16075 getAppDexInstructionSets(deletedPackage.applicationInfo)); 16076 } else { 16077 res.removedInfo.args = null; 16078 } 16079 16080 // Successfully disabled the old package. Now proceed with re-installation 16081 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 16082 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16083 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 16084 16085 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16086 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 16087 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 16088 16089 PackageParser.Package newPackage = null; 16090 try { 16091 // Add the package to the internal data structures 16092 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 16093 16094 // Set the update and install times 16095 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 16096 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 16097 System.currentTimeMillis()); 16098 16099 // Update the package dynamic state if succeeded 16100 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 16101 // Now that the install succeeded make sure we remove data 16102 // directories for any child package the update removed. 16103 final int deletedChildCount = (deletedPackage.childPackages != null) 16104 ? deletedPackage.childPackages.size() : 0; 16105 final int newChildCount = (newPackage.childPackages != null) 16106 ? newPackage.childPackages.size() : 0; 16107 for (int i = 0; i < deletedChildCount; i++) { 16108 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 16109 boolean childPackageDeleted = true; 16110 for (int j = 0; j < newChildCount; j++) { 16111 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 16112 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 16113 childPackageDeleted = false; 16114 break; 16115 } 16116 } 16117 if (childPackageDeleted) { 16118 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 16119 deletedChildPkg.packageName); 16120 if (ps != null && res.removedInfo.removedChildPackages != null) { 16121 PackageRemovedInfo removedChildRes = res.removedInfo 16122 .removedChildPackages.get(deletedChildPkg.packageName); 16123 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 16124 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 16125 } 16126 } 16127 } 16128 16129 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 16130 installReason); 16131 prepareAppDataAfterInstallLIF(newPackage); 16132 16133 mDexManager.notifyPackageUpdated(newPackage.packageName, 16134 newPackage.baseCodePath, newPackage.splitCodePaths); 16135 } 16136 } catch (PackageManagerException e) { 16137 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 16138 res.setError("Package couldn't be installed in " + pkg.codePath, e); 16139 } 16140 16141 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 16142 // Re installation failed. Restore old information 16143 // Remove new pkg information 16144 if (newPackage != null) { 16145 removeInstalledPackageLI(newPackage, true); 16146 } 16147 // Add back the old system package 16148 try { 16149 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 16150 } catch (PackageManagerException e) { 16151 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 16152 } 16153 16154 synchronized (mPackages) { 16155 if (disabledSystem) { 16156 enableSystemPackageLPw(deletedPackage); 16157 } 16158 16159 // Ensure the installer package name up to date 16160 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 16161 16162 // Update permissions for restored package 16163 mPermissionManager.updatePermissions( 16164 deletedPackage.packageName, deletedPackage, false, mPackages.values(), 16165 mPermissionCallback); 16166 16167 mSettings.writeLPr(); 16168 } 16169 16170 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 16171 + " after failed upgrade"); 16172 } 16173 } 16174 16175 /** 16176 * Checks whether the parent or any of the child packages have a change shared 16177 * user. For a package to be a valid update the shred users of the parent and 16178 * the children should match. We may later support changing child shared users. 16179 * @param oldPkg The updated package. 16180 * @param newPkg The update package. 16181 * @return The shared user that change between the versions. 16182 */ 16183 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 16184 PackageParser.Package newPkg) { 16185 // Check parent shared user 16186 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 16187 return newPkg.packageName; 16188 } 16189 // Check child shared users 16190 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 16191 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 16192 for (int i = 0; i < newChildCount; i++) { 16193 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 16194 // If this child was present, did it have the same shared user? 16195 for (int j = 0; j < oldChildCount; j++) { 16196 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 16197 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 16198 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 16199 return newChildPkg.packageName; 16200 } 16201 } 16202 } 16203 return null; 16204 } 16205 16206 private void removeNativeBinariesLI(PackageSetting ps) { 16207 // Remove the lib path for the parent package 16208 if (ps != null) { 16209 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 16210 // Remove the lib path for the child packages 16211 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 16212 for (int i = 0; i < childCount; i++) { 16213 PackageSetting childPs = null; 16214 synchronized (mPackages) { 16215 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 16216 } 16217 if (childPs != null) { 16218 NativeLibraryHelper.removeNativeBinariesLI(childPs 16219 .legacyNativeLibraryPathString); 16220 } 16221 } 16222 } 16223 } 16224 16225 private void enableSystemPackageLPw(PackageParser.Package pkg) { 16226 // Enable the parent package 16227 mSettings.enableSystemPackageLPw(pkg.packageName); 16228 // Enable the child packages 16229 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16230 for (int i = 0; i < childCount; i++) { 16231 PackageParser.Package childPkg = pkg.childPackages.get(i); 16232 mSettings.enableSystemPackageLPw(childPkg.packageName); 16233 } 16234 } 16235 16236 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 16237 PackageParser.Package newPkg) { 16238 // Disable the parent package (parent always replaced) 16239 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 16240 // Disable the child packages 16241 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 16242 for (int i = 0; i < childCount; i++) { 16243 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 16244 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 16245 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 16246 } 16247 return disabled; 16248 } 16249 16250 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 16251 String installerPackageName) { 16252 // Enable the parent package 16253 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 16254 // Enable the child packages 16255 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16256 for (int i = 0; i < childCount; i++) { 16257 PackageParser.Package childPkg = pkg.childPackages.get(i); 16258 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 16259 } 16260 } 16261 16262 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 16263 int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) { 16264 // Update the parent package setting 16265 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 16266 res, user, installReason); 16267 // Update the child packages setting 16268 final int childCount = (newPackage.childPackages != null) 16269 ? newPackage.childPackages.size() : 0; 16270 for (int i = 0; i < childCount; i++) { 16271 PackageParser.Package childPackage = newPackage.childPackages.get(i); 16272 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 16273 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 16274 childRes.origUsers, childRes, user, installReason); 16275 } 16276 } 16277 16278 private void updateSettingsInternalLI(PackageParser.Package pkg, 16279 String installerPackageName, int[] allUsers, int[] installedForUsers, 16280 PackageInstalledInfo res, UserHandle user, int installReason) { 16281 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 16282 16283 String pkgName = pkg.packageName; 16284 synchronized (mPackages) { 16285 //write settings. the installStatus will be incomplete at this stage. 16286 //note that the new package setting would have already been 16287 //added to mPackages. It hasn't been persisted yet. 16288 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 16289 // TODO: Remove this write? It's also written at the end of this method 16290 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 16291 mSettings.writeLPr(); 16292 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16293 } 16294 16295 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + pkg.codePath); 16296 synchronized (mPackages) { 16297// NOTE: This changes slightly to include UPDATE_PERMISSIONS_ALL regardless of the size of pkg.permissions 16298 mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(), 16299 mPermissionCallback); 16300 // For system-bundled packages, we assume that installing an upgraded version 16301 // of the package implies that the user actually wants to run that new code, 16302 // so we enable the package. 16303 PackageSetting ps = mSettings.mPackages.get(pkgName); 16304 final int userId = user.getIdentifier(); 16305 if (ps != null) { 16306 if (isSystemApp(pkg)) { 16307 if (DEBUG_INSTALL) { 16308 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 16309 } 16310 // Enable system package for requested users 16311 if (res.origUsers != null) { 16312 for (int origUserId : res.origUsers) { 16313 if (userId == UserHandle.USER_ALL || userId == origUserId) { 16314 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 16315 origUserId, installerPackageName); 16316 } 16317 } 16318 } 16319 // Also convey the prior install/uninstall state 16320 if (allUsers != null && installedForUsers != null) { 16321 for (int currentUserId : allUsers) { 16322 final boolean installed = ArrayUtils.contains( 16323 installedForUsers, currentUserId); 16324 if (DEBUG_INSTALL) { 16325 Slog.d(TAG, " user " + currentUserId + " => " + installed); 16326 } 16327 ps.setInstalled(installed, currentUserId); 16328 } 16329 // these install state changes will be persisted in the 16330 // upcoming call to mSettings.writeLPr(). 16331 } 16332 } 16333 // It's implied that when a user requests installation, they want the app to be 16334 // installed and enabled. 16335 if (userId != UserHandle.USER_ALL) { 16336 ps.setInstalled(true, userId); 16337 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 16338 } 16339 16340 // When replacing an existing package, preserve the original install reason for all 16341 // users that had the package installed before. 16342 final Set<Integer> previousUserIds = new ArraySet<>(); 16343 if (res.removedInfo != null && res.removedInfo.installReasons != null) { 16344 final int installReasonCount = res.removedInfo.installReasons.size(); 16345 for (int i = 0; i < installReasonCount; i++) { 16346 final int previousUserId = res.removedInfo.installReasons.keyAt(i); 16347 final int previousInstallReason = res.removedInfo.installReasons.valueAt(i); 16348 ps.setInstallReason(previousInstallReason, previousUserId); 16349 previousUserIds.add(previousUserId); 16350 } 16351 } 16352 16353 // Set install reason for users that are having the package newly installed. 16354 if (userId == UserHandle.USER_ALL) { 16355 for (int currentUserId : sUserManager.getUserIds()) { 16356 if (!previousUserIds.contains(currentUserId)) { 16357 ps.setInstallReason(installReason, currentUserId); 16358 } 16359 } 16360 } else if (!previousUserIds.contains(userId)) { 16361 ps.setInstallReason(installReason, userId); 16362 } 16363 mSettings.writeKernelMappingLPr(ps); 16364 } 16365 res.name = pkgName; 16366 res.uid = pkg.applicationInfo.uid; 16367 res.pkg = pkg; 16368 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 16369 mSettings.setInstallerPackageName(pkgName, installerPackageName); 16370 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16371 //to update install status 16372 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 16373 mSettings.writeLPr(); 16374 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16375 } 16376 16377 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16378 } 16379 16380 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 16381 try { 16382 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 16383 installPackageLI(args, res); 16384 } finally { 16385 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16386 } 16387 } 16388 16389 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 16390 final int installFlags = args.installFlags; 16391 final String installerPackageName = args.installerPackageName; 16392 final String volumeUuid = args.volumeUuid; 16393 final File tmpPackageFile = new File(args.getCodePath()); 16394 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 16395 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 16396 || (args.volumeUuid != null)); 16397 final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0); 16398 final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0); 16399 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 16400 final boolean virtualPreload = 16401 ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0); 16402 boolean replace = false; 16403 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 16404 if (args.move != null) { 16405 // moving a complete application; perform an initial scan on the new install location 16406 scanFlags |= SCAN_INITIAL; 16407 } 16408 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 16409 scanFlags |= SCAN_DONT_KILL_APP; 16410 } 16411 if (instantApp) { 16412 scanFlags |= SCAN_AS_INSTANT_APP; 16413 } 16414 if (fullApp) { 16415 scanFlags |= SCAN_AS_FULL_APP; 16416 } 16417 if (virtualPreload) { 16418 scanFlags |= SCAN_AS_VIRTUAL_PRELOAD; 16419 } 16420 16421 // Result object to be returned 16422 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16423 res.installerPackageName = installerPackageName; 16424 16425 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 16426 16427 // Sanity check 16428 if (instantApp && (forwardLocked || onExternal)) { 16429 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 16430 + " external=" + onExternal); 16431 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 16432 return; 16433 } 16434 16435 // Retrieve PackageSettings and parse package 16436 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 16437 | PackageParser.PARSE_ENFORCE_CODE 16438 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 16439 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 16440 | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0) 16441 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 16442 PackageParser pp = new PackageParser(); 16443 pp.setSeparateProcesses(mSeparateProcesses); 16444 pp.setDisplayMetrics(mMetrics); 16445 pp.setCallback(mPackageParserCallback); 16446 16447 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 16448 final PackageParser.Package pkg; 16449 try { 16450 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 16451 } catch (PackageParserException e) { 16452 res.setError("Failed parse during installPackageLI", e); 16453 return; 16454 } finally { 16455 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16456 } 16457 16458 // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2 16459 if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) { 16460 Slog.w(TAG, "Instant app package " + pkg.packageName + " does not target O"); 16461 res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE, 16462 "Instant app package must target O"); 16463 return; 16464 } 16465 if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) { 16466 Slog.w(TAG, "Instant app package " + pkg.packageName 16467 + " does not target targetSandboxVersion 2"); 16468 res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE, 16469 "Instant app package must use targetSanboxVersion 2"); 16470 return; 16471 } 16472 16473 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16474 // Static shared libraries have synthetic package names 16475 renameStaticSharedLibraryPackage(pkg); 16476 16477 // No static shared libs on external storage 16478 if (onExternal) { 16479 Slog.i(TAG, "Static shared libs can only be installed on internal storage."); 16480 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 16481 "Packages declaring static-shared libs cannot be updated"); 16482 return; 16483 } 16484 } 16485 16486 // If we are installing a clustered package add results for the children 16487 if (pkg.childPackages != null) { 16488 synchronized (mPackages) { 16489 final int childCount = pkg.childPackages.size(); 16490 for (int i = 0; i < childCount; i++) { 16491 PackageParser.Package childPkg = pkg.childPackages.get(i); 16492 PackageInstalledInfo childRes = new PackageInstalledInfo(); 16493 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16494 childRes.pkg = childPkg; 16495 childRes.name = childPkg.packageName; 16496 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 16497 if (childPs != null) { 16498 childRes.origUsers = childPs.queryInstalledUsers( 16499 sUserManager.getUserIds(), true); 16500 } 16501 if ((mPackages.containsKey(childPkg.packageName))) { 16502 childRes.removedInfo = new PackageRemovedInfo(this); 16503 childRes.removedInfo.removedPackage = childPkg.packageName; 16504 childRes.removedInfo.installerPackageName = childPs.installerPackageName; 16505 } 16506 if (res.addedChildPackages == null) { 16507 res.addedChildPackages = new ArrayMap<>(); 16508 } 16509 res.addedChildPackages.put(childPkg.packageName, childRes); 16510 } 16511 } 16512 } 16513 16514 // If package doesn't declare API override, mark that we have an install 16515 // time CPU ABI override. 16516 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 16517 pkg.cpuAbiOverride = args.abiOverride; 16518 } 16519 16520 String pkgName = res.name = pkg.packageName; 16521 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 16522 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 16523 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 16524 return; 16525 } 16526 } 16527 16528 try { 16529 // either use what we've been given or parse directly from the APK 16530 if (args.certificates != null) { 16531 try { 16532 PackageParser.populateCertificates(pkg, args.certificates); 16533 } catch (PackageParserException e) { 16534 // there was something wrong with the certificates we were given; 16535 // try to pull them from the APK 16536 PackageParser.collectCertificates(pkg, parseFlags); 16537 } 16538 } else { 16539 PackageParser.collectCertificates(pkg, parseFlags); 16540 } 16541 } catch (PackageParserException e) { 16542 res.setError("Failed collect during installPackageLI", e); 16543 return; 16544 } 16545 16546 // Get rid of all references to package scan path via parser. 16547 pp = null; 16548 String oldCodePath = null; 16549 boolean systemApp = false; 16550 synchronized (mPackages) { 16551 // Check if installing already existing package 16552 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 16553 String oldName = mSettings.getRenamedPackageLPr(pkgName); 16554 if (pkg.mOriginalPackages != null 16555 && pkg.mOriginalPackages.contains(oldName) 16556 && mPackages.containsKey(oldName)) { 16557 // This package is derived from an original package, 16558 // and this device has been updating from that original 16559 // name. We must continue using the original name, so 16560 // rename the new package here. 16561 pkg.setPackageName(oldName); 16562 pkgName = pkg.packageName; 16563 replace = true; 16564 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 16565 + oldName + " pkgName=" + pkgName); 16566 } else if (mPackages.containsKey(pkgName)) { 16567 // This package, under its official name, already exists 16568 // on the device; we should replace it. 16569 replace = true; 16570 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 16571 } 16572 16573 // Child packages are installed through the parent package 16574 if (pkg.parentPackage != null) { 16575 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 16576 "Package " + pkg.packageName + " is child of package " 16577 + pkg.parentPackage.parentPackage + ". Child packages " 16578 + "can be updated only through the parent package."); 16579 return; 16580 } 16581 16582 if (replace) { 16583 // Prevent apps opting out from runtime permissions 16584 PackageParser.Package oldPackage = mPackages.get(pkgName); 16585 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 16586 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 16587 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 16588 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 16589 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 16590 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 16591 + " doesn't support runtime permissions but the old" 16592 + " target SDK " + oldTargetSdk + " does."); 16593 return; 16594 } 16595 // Prevent apps from downgrading their targetSandbox. 16596 final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion; 16597 final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion; 16598 if (oldTargetSandbox == 2 && newTargetSandbox != 2) { 16599 res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE, 16600 "Package " + pkg.packageName + " new target sandbox " 16601 + newTargetSandbox + " is incompatible with the previous value of" 16602 + oldTargetSandbox + "."); 16603 return; 16604 } 16605 16606 // Prevent installing of child packages 16607 if (oldPackage.parentPackage != null) { 16608 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 16609 "Package " + pkg.packageName + " is child of package " 16610 + oldPackage.parentPackage + ". Child packages " 16611 + "can be updated only through the parent package."); 16612 return; 16613 } 16614 } 16615 } 16616 16617 PackageSetting ps = mSettings.mPackages.get(pkgName); 16618 if (ps != null) { 16619 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 16620 16621 // Static shared libs have same package with different versions where 16622 // we internally use a synthetic package name to allow multiple versions 16623 // of the same package, therefore we need to compare signatures against 16624 // the package setting for the latest library version. 16625 PackageSetting signatureCheckPs = ps; 16626 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16627 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg); 16628 if (libraryEntry != null) { 16629 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk); 16630 } 16631 } 16632 16633 // Quick sanity check that we're signed correctly if updating; 16634 // we'll check this again later when scanning, but we want to 16635 // bail early here before tripping over redefined permissions. 16636 if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) { 16637 if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) { 16638 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 16639 + pkg.packageName + " upgrade keys do not match the " 16640 + "previously installed version"); 16641 return; 16642 } 16643 } else { 16644 try { 16645 verifySignaturesLP(signatureCheckPs, pkg); 16646 } catch (PackageManagerException e) { 16647 res.setError(e.error, e.getMessage()); 16648 return; 16649 } 16650 } 16651 16652 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 16653 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 16654 systemApp = (ps.pkg.applicationInfo.flags & 16655 ApplicationInfo.FLAG_SYSTEM) != 0; 16656 } 16657 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 16658 } 16659 16660 int N = pkg.permissions.size(); 16661 for (int i = N-1; i >= 0; i--) { 16662 final PackageParser.Permission perm = pkg.permissions.get(i); 16663 final BasePermission bp = 16664 (BasePermission) mPermissionManager.getPermissionTEMP(perm.info.name); 16665 16666 // Don't allow anyone but the system to define ephemeral permissions. 16667 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0 16668 && !systemApp) { 16669 Slog.w(TAG, "Non-System package " + pkg.packageName 16670 + " attempting to delcare ephemeral permission " 16671 + perm.info.name + "; Removing ephemeral."); 16672 perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTANT; 16673 } 16674 16675 // Check whether the newly-scanned package wants to define an already-defined perm 16676 if (bp != null) { 16677 // If the defining package is signed with our cert, it's okay. This 16678 // also includes the "updating the same package" case, of course. 16679 // "updating same package" could also involve key-rotation. 16680 final boolean sigsOk; 16681 final String sourcePackageName = bp.getSourcePackageName(); 16682 final PackageSettingBase sourcePackageSetting = bp.getSourcePackageSetting(); 16683 if (sourcePackageName.equals(pkg.packageName) 16684 && (shouldCheckUpgradeKeySetLP(sourcePackageSetting, 16685 scanFlags))) { 16686 sigsOk = checkUpgradeKeySetLP(sourcePackageSetting, pkg); 16687 } else { 16688 sigsOk = compareSignatures(sourcePackageSetting.signatures.mSignatures, 16689 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 16690 } 16691 if (!sigsOk) { 16692 // If the owning package is the system itself, we log but allow 16693 // install to proceed; we fail the install on all other permission 16694 // redefinitions. 16695 if (!sourcePackageName.equals("android")) { 16696 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 16697 + pkg.packageName + " attempting to redeclare permission " 16698 + perm.info.name + " already owned by " + sourcePackageName); 16699 res.origPermission = perm.info.name; 16700 res.origPackage = sourcePackageName; 16701 return; 16702 } else { 16703 Slog.w(TAG, "Package " + pkg.packageName 16704 + " attempting to redeclare system permission " 16705 + perm.info.name + "; ignoring new declaration"); 16706 pkg.permissions.remove(i); 16707 } 16708 } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) { 16709 // Prevent apps to change protection level to dangerous from any other 16710 // type as this would allow a privilege escalation where an app adds a 16711 // normal/signature permission in other app's group and later redefines 16712 // it as dangerous leading to the group auto-grant. 16713 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE) 16714 == PermissionInfo.PROTECTION_DANGEROUS) { 16715 if (bp != null && !bp.isRuntime()) { 16716 Slog.w(TAG, "Package " + pkg.packageName + " trying to change a " 16717 + "non-runtime permission " + perm.info.name 16718 + " to runtime; keeping old protection level"); 16719 perm.info.protectionLevel = bp.getProtectionLevel(); 16720 } 16721 } 16722 } 16723 } 16724 } 16725 } 16726 16727 if (systemApp) { 16728 if (onExternal) { 16729 // Abort update; system app can't be replaced with app on sdcard 16730 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 16731 "Cannot install updates to system apps on sdcard"); 16732 return; 16733 } else if (instantApp) { 16734 // Abort update; system app can't be replaced with an instant app 16735 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID, 16736 "Cannot update a system app with an instant app"); 16737 return; 16738 } 16739 } 16740 16741 if (args.move != null) { 16742 // We did an in-place move, so dex is ready to roll 16743 scanFlags |= SCAN_NO_DEX; 16744 scanFlags |= SCAN_MOVE; 16745 16746 synchronized (mPackages) { 16747 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16748 if (ps == null) { 16749 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 16750 "Missing settings for moved package " + pkgName); 16751 } 16752 16753 // We moved the entire application as-is, so bring over the 16754 // previously derived ABI information. 16755 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 16756 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 16757 } 16758 16759 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 16760 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 16761 scanFlags |= SCAN_NO_DEX; 16762 16763 try { 16764 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 16765 args.abiOverride : pkg.cpuAbiOverride); 16766 final boolean extractNativeLibs = !pkg.isLibrary(); 16767 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 16768 extractNativeLibs, mAppLib32InstallDir); 16769 } catch (PackageManagerException pme) { 16770 Slog.e(TAG, "Error deriving application ABI", pme); 16771 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 16772 return; 16773 } 16774 16775 // Shared libraries for the package need to be updated. 16776 synchronized (mPackages) { 16777 try { 16778 updateSharedLibrariesLPr(pkg, null); 16779 } catch (PackageManagerException e) { 16780 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 16781 } 16782 } 16783 } 16784 16785 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 16786 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 16787 return; 16788 } 16789 16790 // Verify if we need to dexopt the app. 16791 // 16792 // NOTE: it is *important* to call dexopt after doRename which will sync the 16793 // package data from PackageParser.Package and its corresponding ApplicationInfo. 16794 // 16795 // We only need to dexopt if the package meets ALL of the following conditions: 16796 // 1) it is not forward locked. 16797 // 2) it is not on on an external ASEC container. 16798 // 3) it is not an instant app or if it is then dexopt is enabled via gservices. 16799 // 16800 // Note that we do not dexopt instant apps by default. dexopt can take some time to 16801 // complete, so we skip this step during installation. Instead, we'll take extra time 16802 // the first time the instant app starts. It's preferred to do it this way to provide 16803 // continuous progress to the useur instead of mysteriously blocking somewhere in the 16804 // middle of running an instant app. The default behaviour can be overridden 16805 // via gservices. 16806 final boolean performDexopt = !forwardLocked 16807 && !pkg.applicationInfo.isExternalAsec() 16808 && (!instantApp || Global.getInt(mContext.getContentResolver(), 16809 Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0); 16810 16811 if (performDexopt) { 16812 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 16813 // Do not run PackageDexOptimizer through the local performDexOpt 16814 // method because `pkg` may not be in `mPackages` yet. 16815 // 16816 // Also, don't fail application installs if the dexopt step fails. 16817 DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName, 16818 REASON_INSTALL, 16819 DexoptOptions.DEXOPT_BOOT_COMPLETE); 16820 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 16821 null /* instructionSets */, 16822 getOrCreateCompilerPackageStats(pkg), 16823 mDexManager.getPackageUseInfoOrDefault(pkg.packageName), 16824 dexoptOptions); 16825 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16826 } 16827 16828 // Notify BackgroundDexOptService that the package has been changed. 16829 // If this is an update of a package which used to fail to compile, 16830 // BackgroundDexOptService will remove it from its blacklist. 16831 // TODO: Layering violation 16832 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 16833 16834 if (!instantApp) { 16835 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 16836 } else { 16837 if (DEBUG_DOMAIN_VERIFICATION) { 16838 Slog.d(TAG, "Not verifying instant app install for app links: " + pkgName); 16839 } 16840 } 16841 16842 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 16843 "installPackageLI")) { 16844 if (replace) { 16845 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16846 // Static libs have a synthetic package name containing the version 16847 // and cannot be updated as an update would get a new package name, 16848 // unless this is the exact same version code which is useful for 16849 // development. 16850 PackageParser.Package existingPkg = mPackages.get(pkg.packageName); 16851 if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) { 16852 res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring " 16853 + "static-shared libs cannot be updated"); 16854 return; 16855 } 16856 } 16857 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 16858 installerPackageName, res, args.installReason); 16859 } else { 16860 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 16861 args.user, installerPackageName, volumeUuid, res, args.installReason); 16862 } 16863 } 16864 16865 synchronized (mPackages) { 16866 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16867 if (ps != null) { 16868 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 16869 ps.setUpdateAvailable(false /*updateAvailable*/); 16870 } 16871 16872 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16873 for (int i = 0; i < childCount; i++) { 16874 PackageParser.Package childPkg = pkg.childPackages.get(i); 16875 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 16876 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 16877 if (childPs != null) { 16878 childRes.newUsers = childPs.queryInstalledUsers( 16879 sUserManager.getUserIds(), true); 16880 } 16881 } 16882 16883 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 16884 updateSequenceNumberLP(ps, res.newUsers); 16885 updateInstantAppInstallerLocked(pkgName); 16886 } 16887 } 16888 } 16889 16890 private void startIntentFilterVerifications(int userId, boolean replacing, 16891 PackageParser.Package pkg) { 16892 if (mIntentFilterVerifierComponent == null) { 16893 Slog.w(TAG, "No IntentFilter verification will not be done as " 16894 + "there is no IntentFilterVerifier available!"); 16895 return; 16896 } 16897 16898 final int verifierUid = getPackageUid( 16899 mIntentFilterVerifierComponent.getPackageName(), 16900 MATCH_DEBUG_TRIAGED_MISSING, 16901 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 16902 16903 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 16904 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 16905 mHandler.sendMessage(msg); 16906 16907 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16908 for (int i = 0; i < childCount; i++) { 16909 PackageParser.Package childPkg = pkg.childPackages.get(i); 16910 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 16911 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 16912 mHandler.sendMessage(msg); 16913 } 16914 } 16915 16916 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 16917 PackageParser.Package pkg) { 16918 int size = pkg.activities.size(); 16919 if (size == 0) { 16920 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 16921 "No activity, so no need to verify any IntentFilter!"); 16922 return; 16923 } 16924 16925 final boolean hasDomainURLs = hasDomainURLs(pkg); 16926 if (!hasDomainURLs) { 16927 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 16928 "No domain URLs, so no need to verify any IntentFilter!"); 16929 return; 16930 } 16931 16932 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 16933 + " if any IntentFilter from the " + size 16934 + " Activities needs verification ..."); 16935 16936 int count = 0; 16937 final String packageName = pkg.packageName; 16938 16939 synchronized (mPackages) { 16940 // If this is a new install and we see that we've already run verification for this 16941 // package, we have nothing to do: it means the state was restored from backup. 16942 if (!replacing) { 16943 IntentFilterVerificationInfo ivi = 16944 mSettings.getIntentFilterVerificationLPr(packageName); 16945 if (ivi != null) { 16946 if (DEBUG_DOMAIN_VERIFICATION) { 16947 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 16948 + ivi.getStatusString()); 16949 } 16950 return; 16951 } 16952 } 16953 16954 // If any filters need to be verified, then all need to be. 16955 boolean needToVerify = false; 16956 for (PackageParser.Activity a : pkg.activities) { 16957 for (ActivityIntentInfo filter : a.intents) { 16958 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 16959 if (DEBUG_DOMAIN_VERIFICATION) { 16960 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 16961 } 16962 needToVerify = true; 16963 break; 16964 } 16965 } 16966 } 16967 16968 if (needToVerify) { 16969 final int verificationId = mIntentFilterVerificationToken++; 16970 for (PackageParser.Activity a : pkg.activities) { 16971 for (ActivityIntentInfo filter : a.intents) { 16972 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 16973 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 16974 "Verification needed for IntentFilter:" + filter.toString()); 16975 mIntentFilterVerifier.addOneIntentFilterVerification( 16976 verifierUid, userId, verificationId, filter, packageName); 16977 count++; 16978 } 16979 } 16980 } 16981 } 16982 } 16983 16984 if (count > 0) { 16985 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 16986 + " IntentFilter verification" + (count > 1 ? "s" : "") 16987 + " for userId:" + userId); 16988 mIntentFilterVerifier.startVerifications(userId); 16989 } else { 16990 if (DEBUG_DOMAIN_VERIFICATION) { 16991 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 16992 } 16993 } 16994 } 16995 16996 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 16997 final ComponentName cn = filter.activity.getComponentName(); 16998 final String packageName = cn.getPackageName(); 16999 17000 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 17001 packageName); 17002 if (ivi == null) { 17003 return true; 17004 } 17005 int status = ivi.getStatus(); 17006 switch (status) { 17007 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 17008 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 17009 return true; 17010 17011 default: 17012 // Nothing to do 17013 return false; 17014 } 17015 } 17016 17017 private static boolean isMultiArch(ApplicationInfo info) { 17018 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 17019 } 17020 17021 private static boolean isExternal(PackageParser.Package pkg) { 17022 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 17023 } 17024 17025 private static boolean isExternal(PackageSetting ps) { 17026 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 17027 } 17028 17029 private static boolean isSystemApp(PackageParser.Package pkg) { 17030 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 17031 } 17032 17033 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 17034 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 17035 } 17036 17037 private static boolean isOemApp(PackageParser.Package pkg) { 17038 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0; 17039 } 17040 17041 private static boolean hasDomainURLs(PackageParser.Package pkg) { 17042 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 17043 } 17044 17045 private static boolean isSystemApp(PackageSetting ps) { 17046 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 17047 } 17048 17049 private static boolean isUpdatedSystemApp(PackageSetting ps) { 17050 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 17051 } 17052 17053 private int packageFlagsToInstallFlags(PackageSetting ps) { 17054 int installFlags = 0; 17055 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 17056 // This existing package was an external ASEC install when we have 17057 // the external flag without a UUID 17058 installFlags |= PackageManager.INSTALL_EXTERNAL; 17059 } 17060 if (ps.isForwardLocked()) { 17061 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 17062 } 17063 return installFlags; 17064 } 17065 17066 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 17067 if (isExternal(pkg)) { 17068 if (TextUtils.isEmpty(pkg.volumeUuid)) { 17069 return mSettings.getExternalVersion(); 17070 } else { 17071 return mSettings.findOrCreateVersion(pkg.volumeUuid); 17072 } 17073 } else { 17074 return mSettings.getInternalVersion(); 17075 } 17076 } 17077 17078 private void deleteTempPackageFiles() { 17079 final FilenameFilter filter = new FilenameFilter() { 17080 public boolean accept(File dir, String name) { 17081 return name.startsWith("vmdl") && name.endsWith(".tmp"); 17082 } 17083 }; 17084 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 17085 file.delete(); 17086 } 17087 } 17088 17089 @Override 17090 public void deletePackageAsUser(String packageName, int versionCode, 17091 IPackageDeleteObserver observer, int userId, int flags) { 17092 deletePackageVersioned(new VersionedPackage(packageName, versionCode), 17093 new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags); 17094 } 17095 17096 @Override 17097 public void deletePackageVersioned(VersionedPackage versionedPackage, 17098 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 17099 final int callingUid = Binder.getCallingUid(); 17100 mContext.enforceCallingOrSelfPermission( 17101 android.Manifest.permission.DELETE_PACKAGES, null); 17102 final boolean canViewInstantApps = canViewInstantApps(callingUid, userId); 17103 Preconditions.checkNotNull(versionedPackage); 17104 Preconditions.checkNotNull(observer); 17105 Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(), 17106 PackageManager.VERSION_CODE_HIGHEST, 17107 Integer.MAX_VALUE, "versionCode must be >= -1"); 17108 17109 final String packageName = versionedPackage.getPackageName(); 17110 final int versionCode = versionedPackage.getVersionCode(); 17111 final String internalPackageName; 17112 synchronized (mPackages) { 17113 // Normalize package name to handle renamed packages and static libs 17114 internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(), 17115 versionedPackage.getVersionCode()); 17116 } 17117 17118 final int uid = Binder.getCallingUid(); 17119 if (!isOrphaned(internalPackageName) 17120 && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) { 17121 try { 17122 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 17123 intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null)); 17124 intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder()); 17125 observer.onUserActionRequired(intent); 17126 } catch (RemoteException re) { 17127 } 17128 return; 17129 } 17130 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 17131 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 17132 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 17133 mContext.enforceCallingOrSelfPermission( 17134 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 17135 "deletePackage for user " + userId); 17136 } 17137 17138 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 17139 try { 17140 observer.onPackageDeleted(packageName, 17141 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 17142 } catch (RemoteException re) { 17143 } 17144 return; 17145 } 17146 17147 if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) { 17148 try { 17149 observer.onPackageDeleted(packageName, 17150 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 17151 } catch (RemoteException re) { 17152 } 17153 return; 17154 } 17155 17156 if (DEBUG_REMOVE) { 17157 Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId 17158 + " deleteAllUsers: " + deleteAllUsers + " version=" 17159 + (versionCode == PackageManager.VERSION_CODE_HIGHEST 17160 ? "VERSION_CODE_HIGHEST" : versionCode)); 17161 } 17162 // Queue up an async operation since the package deletion may take a little while. 17163 mHandler.post(new Runnable() { 17164 public void run() { 17165 mHandler.removeCallbacks(this); 17166 int returnCode; 17167 final PackageSetting ps = mSettings.mPackages.get(internalPackageName); 17168 boolean doDeletePackage = true; 17169 if (ps != null) { 17170 final boolean targetIsInstantApp = 17171 ps.getInstantApp(UserHandle.getUserId(callingUid)); 17172 doDeletePackage = !targetIsInstantApp 17173 || canViewInstantApps; 17174 } 17175 if (doDeletePackage) { 17176 if (!deleteAllUsers) { 17177 returnCode = deletePackageX(internalPackageName, versionCode, 17178 userId, deleteFlags); 17179 } else { 17180 int[] blockUninstallUserIds = getBlockUninstallForUsers( 17181 internalPackageName, users); 17182 // If nobody is blocking uninstall, proceed with delete for all users 17183 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 17184 returnCode = deletePackageX(internalPackageName, versionCode, 17185 userId, deleteFlags); 17186 } else { 17187 // Otherwise uninstall individually for users with blockUninstalls=false 17188 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 17189 for (int userId : users) { 17190 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 17191 returnCode = deletePackageX(internalPackageName, versionCode, 17192 userId, userFlags); 17193 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 17194 Slog.w(TAG, "Package delete failed for user " + userId 17195 + ", returnCode " + returnCode); 17196 } 17197 } 17198 } 17199 // The app has only been marked uninstalled for certain users. 17200 // We still need to report that delete was blocked 17201 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 17202 } 17203 } 17204 } else { 17205 returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17206 } 17207 try { 17208 observer.onPackageDeleted(packageName, returnCode, null); 17209 } catch (RemoteException e) { 17210 Log.i(TAG, "Observer no longer exists."); 17211 } //end catch 17212 } //end run 17213 }); 17214 } 17215 17216 private String resolveExternalPackageNameLPr(PackageParser.Package pkg) { 17217 if (pkg.staticSharedLibName != null) { 17218 return pkg.manifestPackageName; 17219 } 17220 return pkg.packageName; 17221 } 17222 17223 private String resolveInternalPackageNameLPr(String packageName, int versionCode) { 17224 // Handle renamed packages 17225 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 17226 packageName = normalizedPackageName != null ? normalizedPackageName : packageName; 17227 17228 // Is this a static library? 17229 SparseArray<SharedLibraryEntry> versionedLib = 17230 mStaticLibsByDeclaringPackage.get(packageName); 17231 if (versionedLib == null || versionedLib.size() <= 0) { 17232 return packageName; 17233 } 17234 17235 // Figure out which lib versions the caller can see 17236 SparseIntArray versionsCallerCanSee = null; 17237 final int callingAppId = UserHandle.getAppId(Binder.getCallingUid()); 17238 if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID 17239 && callingAppId != Process.ROOT_UID) { 17240 versionsCallerCanSee = new SparseIntArray(); 17241 String libName = versionedLib.valueAt(0).info.getName(); 17242 String[] uidPackages = getPackagesForUid(Binder.getCallingUid()); 17243 if (uidPackages != null) { 17244 for (String uidPackage : uidPackages) { 17245 PackageSetting ps = mSettings.getPackageLPr(uidPackage); 17246 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 17247 if (libIdx >= 0) { 17248 final int libVersion = ps.usesStaticLibrariesVersions[libIdx]; 17249 versionsCallerCanSee.append(libVersion, libVersion); 17250 } 17251 } 17252 } 17253 } 17254 17255 // Caller can see nothing - done 17256 if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) { 17257 return packageName; 17258 } 17259 17260 // Find the version the caller can see and the app version code 17261 SharedLibraryEntry highestVersion = null; 17262 final int versionCount = versionedLib.size(); 17263 for (int i = 0; i < versionCount; i++) { 17264 SharedLibraryEntry libEntry = versionedLib.valueAt(i); 17265 if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey( 17266 libEntry.info.getVersion()) < 0) { 17267 continue; 17268 } 17269 final int libVersionCode = libEntry.info.getDeclaringPackage().getVersionCode(); 17270 if (versionCode != PackageManager.VERSION_CODE_HIGHEST) { 17271 if (libVersionCode == versionCode) { 17272 return libEntry.apk; 17273 } 17274 } else if (highestVersion == null) { 17275 highestVersion = libEntry; 17276 } else if (libVersionCode > highestVersion.info 17277 .getDeclaringPackage().getVersionCode()) { 17278 highestVersion = libEntry; 17279 } 17280 } 17281 17282 if (highestVersion != null) { 17283 return highestVersion.apk; 17284 } 17285 17286 return packageName; 17287 } 17288 17289 boolean isCallerVerifier(int callingUid) { 17290 final int callingUserId = UserHandle.getUserId(callingUid); 17291 return mRequiredVerifierPackage != null && 17292 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId); 17293 } 17294 17295 private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) { 17296 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID 17297 || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 17298 return true; 17299 } 17300 final int callingUserId = UserHandle.getUserId(callingUid); 17301 // If the caller installed the pkgName, then allow it to silently uninstall. 17302 if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) { 17303 return true; 17304 } 17305 17306 // Allow package verifier to silently uninstall. 17307 if (mRequiredVerifierPackage != null && 17308 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) { 17309 return true; 17310 } 17311 17312 // Allow package uninstaller to silently uninstall. 17313 if (mRequiredUninstallerPackage != null && 17314 callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) { 17315 return true; 17316 } 17317 17318 // Allow storage manager to silently uninstall. 17319 if (mStorageManagerPackage != null && 17320 callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) { 17321 return true; 17322 } 17323 17324 // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently 17325 // uninstall for device owner provisioning. 17326 if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid) 17327 == PERMISSION_GRANTED) { 17328 return true; 17329 } 17330 17331 return false; 17332 } 17333 17334 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 17335 int[] result = EMPTY_INT_ARRAY; 17336 for (int userId : userIds) { 17337 if (getBlockUninstallForUser(packageName, userId)) { 17338 result = ArrayUtils.appendInt(result, userId); 17339 } 17340 } 17341 return result; 17342 } 17343 17344 @Override 17345 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 17346 final int callingUid = Binder.getCallingUid(); 17347 if (getInstantAppPackageName(callingUid) != null 17348 && !isCallerSameApp(packageName, callingUid)) { 17349 return false; 17350 } 17351 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 17352 } 17353 17354 private boolean isPackageDeviceAdmin(String packageName, int userId) { 17355 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 17356 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 17357 try { 17358 if (dpm != null) { 17359 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 17360 /* callingUserOnly =*/ false); 17361 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 17362 : deviceOwnerComponentName.getPackageName(); 17363 // Does the package contains the device owner? 17364 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 17365 // this check is probably not needed, since DO should be registered as a device 17366 // admin on some user too. (Original bug for this: b/17657954) 17367 if (packageName.equals(deviceOwnerPackageName)) { 17368 return true; 17369 } 17370 // Does it contain a device admin for any user? 17371 int[] users; 17372 if (userId == UserHandle.USER_ALL) { 17373 users = sUserManager.getUserIds(); 17374 } else { 17375 users = new int[]{userId}; 17376 } 17377 for (int i = 0; i < users.length; ++i) { 17378 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 17379 return true; 17380 } 17381 } 17382 } 17383 } catch (RemoteException e) { 17384 } 17385 return false; 17386 } 17387 17388 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 17389 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 17390 } 17391 17392 /** 17393 * This method is an internal method that could be get invoked either 17394 * to delete an installed package or to clean up a failed installation. 17395 * After deleting an installed package, a broadcast is sent to notify any 17396 * listeners that the package has been removed. For cleaning up a failed 17397 * installation, the broadcast is not necessary since the package's 17398 * installation wouldn't have sent the initial broadcast either 17399 * The key steps in deleting a package are 17400 * deleting the package information in internal structures like mPackages, 17401 * deleting the packages base directories through installd 17402 * updating mSettings to reflect current status 17403 * persisting settings for later use 17404 * sending a broadcast if necessary 17405 */ 17406 int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) { 17407 final PackageRemovedInfo info = new PackageRemovedInfo(this); 17408 final boolean res; 17409 17410 final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 17411 ? UserHandle.USER_ALL : userId; 17412 17413 if (isPackageDeviceAdmin(packageName, removeUser)) { 17414 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 17415 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 17416 } 17417 17418 PackageSetting uninstalledPs = null; 17419 PackageParser.Package pkg = null; 17420 17421 // for the uninstall-updates case and restricted profiles, remember the per- 17422 // user handle installed state 17423 int[] allUsers; 17424 synchronized (mPackages) { 17425 uninstalledPs = mSettings.mPackages.get(packageName); 17426 if (uninstalledPs == null) { 17427 Slog.w(TAG, "Not removing non-existent package " + packageName); 17428 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17429 } 17430 17431 if (versionCode != PackageManager.VERSION_CODE_HIGHEST 17432 && uninstalledPs.versionCode != versionCode) { 17433 Slog.w(TAG, "Not removing package " + packageName + " with versionCode " 17434 + uninstalledPs.versionCode + " != " + versionCode); 17435 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17436 } 17437 17438 // Static shared libs can be declared by any package, so let us not 17439 // allow removing a package if it provides a lib others depend on. 17440 pkg = mPackages.get(packageName); 17441 17442 allUsers = sUserManager.getUserIds(); 17443 17444 if (pkg != null && pkg.staticSharedLibName != null) { 17445 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName, 17446 pkg.staticSharedLibVersion); 17447 if (libEntry != null) { 17448 for (int currUserId : allUsers) { 17449 if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) { 17450 continue; 17451 } 17452 List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr( 17453 libEntry.info, 0, currUserId); 17454 if (!ArrayUtils.isEmpty(libClientPackages)) { 17455 Slog.w(TAG, "Not removing package " + pkg.manifestPackageName 17456 + " hosting lib " + libEntry.info.getName() + " version " 17457 + libEntry.info.getVersion() + " used by " + libClientPackages 17458 + " for user " + currUserId); 17459 return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY; 17460 } 17461 } 17462 } 17463 } 17464 17465 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 17466 } 17467 17468 final int freezeUser; 17469 if (isUpdatedSystemApp(uninstalledPs) 17470 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) { 17471 // We're downgrading a system app, which will apply to all users, so 17472 // freeze them all during the downgrade 17473 freezeUser = UserHandle.USER_ALL; 17474 } else { 17475 freezeUser = removeUser; 17476 } 17477 17478 synchronized (mInstallLock) { 17479 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 17480 try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser, 17481 deleteFlags, "deletePackageX")) { 17482 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers, 17483 deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null); 17484 } 17485 synchronized (mPackages) { 17486 if (res) { 17487 if (pkg != null) { 17488 mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers); 17489 } 17490 updateSequenceNumberLP(uninstalledPs, info.removedUsers); 17491 updateInstantAppInstallerLocked(packageName); 17492 } 17493 } 17494 } 17495 17496 if (res) { 17497 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 17498 info.sendPackageRemovedBroadcasts(killApp); 17499 info.sendSystemPackageUpdatedBroadcasts(); 17500 info.sendSystemPackageAppearedBroadcasts(); 17501 } 17502 // Force a gc here. 17503 Runtime.getRuntime().gc(); 17504 // Delete the resources here after sending the broadcast to let 17505 // other processes clean up before deleting resources. 17506 if (info.args != null) { 17507 synchronized (mInstallLock) { 17508 info.args.doPostDeleteLI(true); 17509 } 17510 } 17511 17512 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17513 } 17514 17515 static class PackageRemovedInfo { 17516 final PackageSender packageSender; 17517 String removedPackage; 17518 String installerPackageName; 17519 int uid = -1; 17520 int removedAppId = -1; 17521 int[] origUsers; 17522 int[] removedUsers = null; 17523 int[] broadcastUsers = null; 17524 SparseArray<Integer> installReasons; 17525 boolean isRemovedPackageSystemUpdate = false; 17526 boolean isUpdate; 17527 boolean dataRemoved; 17528 boolean removedForAllUsers; 17529 boolean isStaticSharedLib; 17530 // Clean up resources deleted packages. 17531 InstallArgs args = null; 17532 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 17533 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 17534 17535 PackageRemovedInfo(PackageSender packageSender) { 17536 this.packageSender = packageSender; 17537 } 17538 17539 void sendPackageRemovedBroadcasts(boolean killApp) { 17540 sendPackageRemovedBroadcastInternal(killApp); 17541 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 17542 for (int i = 0; i < childCount; i++) { 17543 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 17544 childInfo.sendPackageRemovedBroadcastInternal(killApp); 17545 } 17546 } 17547 17548 void sendSystemPackageUpdatedBroadcasts() { 17549 if (isRemovedPackageSystemUpdate) { 17550 sendSystemPackageUpdatedBroadcastsInternal(); 17551 final int childCount = (removedChildPackages != null) 17552 ? removedChildPackages.size() : 0; 17553 for (int i = 0; i < childCount; i++) { 17554 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 17555 if (childInfo.isRemovedPackageSystemUpdate) { 17556 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 17557 } 17558 } 17559 } 17560 } 17561 17562 void sendSystemPackageAppearedBroadcasts() { 17563 final int packageCount = (appearedChildPackages != null) 17564 ? appearedChildPackages.size() : 0; 17565 for (int i = 0; i < packageCount; i++) { 17566 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 17567 packageSender.sendPackageAddedForNewUsers(installedInfo.name, 17568 true /*sendBootCompleted*/, false /*startReceiver*/, 17569 UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers); 17570 } 17571 } 17572 17573 private void sendSystemPackageUpdatedBroadcastsInternal() { 17574 Bundle extras = new Bundle(2); 17575 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 17576 extras.putBoolean(Intent.EXTRA_REPLACING, true); 17577 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 17578 removedPackage, extras, 0, null /*targetPackage*/, null, null); 17579 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 17580 removedPackage, extras, 0, null /*targetPackage*/, null, null); 17581 packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 17582 null, null, 0, removedPackage, null, null); 17583 if (installerPackageName != null) { 17584 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 17585 removedPackage, extras, 0 /*flags*/, 17586 installerPackageName, null, null); 17587 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 17588 removedPackage, extras, 0 /*flags*/, 17589 installerPackageName, null, null); 17590 } 17591 } 17592 17593 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 17594 // Don't send static shared library removal broadcasts as these 17595 // libs are visible only the the apps that depend on them an one 17596 // cannot remove the library if it has a dependency. 17597 if (isStaticSharedLib) { 17598 return; 17599 } 17600 Bundle extras = new Bundle(2); 17601 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 17602 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 17603 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 17604 if (isUpdate || isRemovedPackageSystemUpdate) { 17605 extras.putBoolean(Intent.EXTRA_REPLACING, true); 17606 } 17607 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 17608 if (removedPackage != null) { 17609 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, 17610 removedPackage, extras, 0, null /*targetPackage*/, null, broadcastUsers); 17611 if (installerPackageName != null) { 17612 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, 17613 removedPackage, extras, 0 /*flags*/, 17614 installerPackageName, null, broadcastUsers); 17615 } 17616 if (dataRemoved && !isRemovedPackageSystemUpdate) { 17617 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 17618 removedPackage, extras, 17619 Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, 17620 null, null, broadcastUsers); 17621 } 17622 } 17623 if (removedAppId >= 0) { 17624 packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED, 17625 null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, 17626 null, null, broadcastUsers); 17627 } 17628 } 17629 17630 void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) { 17631 removedUsers = userIds; 17632 if (removedUsers == null) { 17633 broadcastUsers = null; 17634 return; 17635 } 17636 17637 broadcastUsers = EMPTY_INT_ARRAY; 17638 for (int i = userIds.length - 1; i >= 0; --i) { 17639 final int userId = userIds[i]; 17640 if (deletedPackageSetting.getInstantApp(userId)) { 17641 continue; 17642 } 17643 broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId); 17644 } 17645 } 17646 } 17647 17648 /* 17649 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 17650 * flag is not set, the data directory is removed as well. 17651 * make sure this flag is set for partially installed apps. If not its meaningless to 17652 * delete a partially installed application. 17653 */ 17654 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 17655 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 17656 String packageName = ps.name; 17657 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 17658 // Retrieve object to delete permissions for shared user later on 17659 final PackageParser.Package deletedPkg; 17660 final PackageSetting deletedPs; 17661 // reader 17662 synchronized (mPackages) { 17663 deletedPkg = mPackages.get(packageName); 17664 deletedPs = mSettings.mPackages.get(packageName); 17665 if (outInfo != null) { 17666 outInfo.removedPackage = packageName; 17667 outInfo.installerPackageName = ps.installerPackageName; 17668 outInfo.isStaticSharedLib = deletedPkg != null 17669 && deletedPkg.staticSharedLibName != null; 17670 outInfo.populateUsers(deletedPs == null ? null 17671 : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs); 17672 } 17673 } 17674 17675 removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0); 17676 17677 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 17678 final PackageParser.Package resolvedPkg; 17679 if (deletedPkg != null) { 17680 resolvedPkg = deletedPkg; 17681 } else { 17682 // We don't have a parsed package when it lives on an ejected 17683 // adopted storage device, so fake something together 17684 resolvedPkg = new PackageParser.Package(ps.name); 17685 resolvedPkg.setVolumeUuid(ps.volumeUuid); 17686 } 17687 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 17688 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 17689 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 17690 if (outInfo != null) { 17691 outInfo.dataRemoved = true; 17692 } 17693 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 17694 } 17695 17696 int removedAppId = -1; 17697 17698 // writer 17699 synchronized (mPackages) { 17700 boolean installedStateChanged = false; 17701 if (deletedPs != null) { 17702 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 17703 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 17704 clearDefaultBrowserIfNeeded(packageName); 17705 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 17706 removedAppId = mSettings.removePackageLPw(packageName); 17707 if (outInfo != null) { 17708 outInfo.removedAppId = removedAppId; 17709 } 17710 mPermissionManager.updatePermissions( 17711 deletedPs.name, null, false, mPackages.values(), mPermissionCallback); 17712 if (deletedPs.sharedUser != null) { 17713 // Remove permissions associated with package. Since runtime 17714 // permissions are per user we have to kill the removed package 17715 // or packages running under the shared user of the removed 17716 // package if revoking the permissions requested only by the removed 17717 // package is successful and this causes a change in gids. 17718 for (int userId : UserManagerService.getInstance().getUserIds()) { 17719 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 17720 userId); 17721 if (userIdToKill == UserHandle.USER_ALL 17722 || userIdToKill >= UserHandle.USER_SYSTEM) { 17723 // If gids changed for this user, kill all affected packages. 17724 mHandler.post(new Runnable() { 17725 @Override 17726 public void run() { 17727 // This has to happen with no lock held. 17728 killApplication(deletedPs.name, deletedPs.appId, 17729 KILL_APP_REASON_GIDS_CHANGED); 17730 } 17731 }); 17732 break; 17733 } 17734 } 17735 } 17736 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 17737 } 17738 // make sure to preserve per-user disabled state if this removal was just 17739 // a downgrade of a system app to the factory package 17740 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 17741 if (DEBUG_REMOVE) { 17742 Slog.d(TAG, "Propagating install state across downgrade"); 17743 } 17744 for (int userId : allUserHandles) { 17745 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 17746 if (DEBUG_REMOVE) { 17747 Slog.d(TAG, " user " + userId + " => " + installed); 17748 } 17749 if (installed != ps.getInstalled(userId)) { 17750 installedStateChanged = true; 17751 } 17752 ps.setInstalled(installed, userId); 17753 } 17754 } 17755 } 17756 // can downgrade to reader 17757 if (writeSettings) { 17758 // Save settings now 17759 mSettings.writeLPr(); 17760 } 17761 if (installedStateChanged) { 17762 mSettings.writeKernelMappingLPr(ps); 17763 } 17764 } 17765 if (removedAppId != -1) { 17766 // A user ID was deleted here. Go through all users and remove it 17767 // from KeyStore. 17768 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId); 17769 } 17770 } 17771 17772 static boolean locationIsPrivileged(File path) { 17773 try { 17774 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 17775 .getCanonicalPath(); 17776 return path.getCanonicalPath().startsWith(privilegedAppDir); 17777 } catch (IOException e) { 17778 Slog.e(TAG, "Unable to access code path " + path); 17779 } 17780 return false; 17781 } 17782 17783 static boolean locationIsOem(File path) { 17784 try { 17785 return path.getCanonicalPath().startsWith( 17786 Environment.getOemDirectory().getCanonicalPath()); 17787 } catch (IOException e) { 17788 Slog.e(TAG, "Unable to access code path " + path); 17789 } 17790 return false; 17791 } 17792 17793 /* 17794 * Tries to delete system package. 17795 */ 17796 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 17797 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 17798 boolean writeSettings) { 17799 if (deletedPs.parentPackageName != null) { 17800 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 17801 return false; 17802 } 17803 17804 final boolean applyUserRestrictions 17805 = (allUserHandles != null) && (outInfo.origUsers != null); 17806 final PackageSetting disabledPs; 17807 // Confirm if the system package has been updated 17808 // An updated system app can be deleted. This will also have to restore 17809 // the system pkg from system partition 17810 // reader 17811 synchronized (mPackages) { 17812 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 17813 } 17814 17815 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 17816 + " disabledPs=" + disabledPs); 17817 17818 if (disabledPs == null) { 17819 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 17820 return false; 17821 } else if (DEBUG_REMOVE) { 17822 Slog.d(TAG, "Deleting system pkg from data partition"); 17823 } 17824 17825 if (DEBUG_REMOVE) { 17826 if (applyUserRestrictions) { 17827 Slog.d(TAG, "Remembering install states:"); 17828 for (int userId : allUserHandles) { 17829 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 17830 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 17831 } 17832 } 17833 } 17834 17835 // Delete the updated package 17836 outInfo.isRemovedPackageSystemUpdate = true; 17837 if (outInfo.removedChildPackages != null) { 17838 final int childCount = (deletedPs.childPackageNames != null) 17839 ? deletedPs.childPackageNames.size() : 0; 17840 for (int i = 0; i < childCount; i++) { 17841 String childPackageName = deletedPs.childPackageNames.get(i); 17842 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 17843 .contains(childPackageName)) { 17844 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 17845 childPackageName); 17846 if (childInfo != null) { 17847 childInfo.isRemovedPackageSystemUpdate = true; 17848 } 17849 } 17850 } 17851 } 17852 17853 if (disabledPs.versionCode < deletedPs.versionCode) { 17854 // Delete data for downgrades 17855 flags &= ~PackageManager.DELETE_KEEP_DATA; 17856 } else { 17857 // Preserve data by setting flag 17858 flags |= PackageManager.DELETE_KEEP_DATA; 17859 } 17860 17861 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 17862 outInfo, writeSettings, disabledPs.pkg); 17863 if (!ret) { 17864 return false; 17865 } 17866 17867 // writer 17868 synchronized (mPackages) { 17869 // NOTE: The system package always needs to be enabled; even if it's for 17870 // a compressed stub. If we don't, installing the system package fails 17871 // during scan [scanning checks the disabled packages]. We will reverse 17872 // this later, after we've "installed" the stub. 17873 // Reinstate the old system package 17874 enableSystemPackageLPw(disabledPs.pkg); 17875 // Remove any native libraries from the upgraded package. 17876 removeNativeBinariesLI(deletedPs); 17877 } 17878 17879 // Install the system package 17880 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 17881 try { 17882 installPackageFromSystemLIF(disabledPs.codePath, false /*isPrivileged*/, allUserHandles, 17883 outInfo.origUsers, deletedPs.getPermissionsState(), writeSettings); 17884 } catch (PackageManagerException e) { 17885 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 17886 + e.getMessage()); 17887 return false; 17888 } finally { 17889 if (disabledPs.pkg.isStub) { 17890 mSettings.disableSystemPackageLPw(disabledPs.name, true /*replaced*/); 17891 } 17892 } 17893 return true; 17894 } 17895 17896 /** 17897 * Installs a package that's already on the system partition. 17898 */ 17899 private PackageParser.Package installPackageFromSystemLIF(@NonNull File codePath, 17900 boolean isPrivileged, @Nullable int[] allUserHandles, @Nullable int[] origUserHandles, 17901 @Nullable PermissionsState origPermissionState, boolean writeSettings) 17902 throws PackageManagerException { 17903 int parseFlags = mDefParseFlags 17904 | PackageParser.PARSE_MUST_BE_APK 17905 | PackageParser.PARSE_IS_SYSTEM 17906 | PackageParser.PARSE_IS_SYSTEM_DIR; 17907 if (isPrivileged || locationIsPrivileged(codePath)) { 17908 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 17909 } 17910 if (locationIsOem(codePath)) { 17911 parseFlags |= PackageParser.PARSE_IS_OEM; 17912 } 17913 17914 final PackageParser.Package pkg = 17915 scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/, 0 /*currentTime*/, null); 17916 17917 try { 17918 // update shared libraries for the newly re-installed system package 17919 updateSharedLibrariesLPr(pkg, null); 17920 } catch (PackageManagerException e) { 17921 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 17922 } 17923 17924 prepareAppDataAfterInstallLIF(pkg); 17925 17926 // writer 17927 synchronized (mPackages) { 17928 PackageSetting ps = mSettings.mPackages.get(pkg.packageName); 17929 17930 // Propagate the permissions state as we do not want to drop on the floor 17931 // runtime permissions. The update permissions method below will take 17932 // care of removing obsolete permissions and grant install permissions. 17933 if (origPermissionState != null) { 17934 ps.getPermissionsState().copyFrom(origPermissionState); 17935 } 17936 mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(), 17937 mPermissionCallback); 17938 17939 final boolean applyUserRestrictions 17940 = (allUserHandles != null) && (origUserHandles != null); 17941 if (applyUserRestrictions) { 17942 boolean installedStateChanged = false; 17943 if (DEBUG_REMOVE) { 17944 Slog.d(TAG, "Propagating install state across reinstall"); 17945 } 17946 for (int userId : allUserHandles) { 17947 final boolean installed = ArrayUtils.contains(origUserHandles, userId); 17948 if (DEBUG_REMOVE) { 17949 Slog.d(TAG, " user " + userId + " => " + installed); 17950 } 17951 if (installed != ps.getInstalled(userId)) { 17952 installedStateChanged = true; 17953 } 17954 ps.setInstalled(installed, userId); 17955 17956 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 17957 } 17958 // Regardless of writeSettings we need to ensure that this restriction 17959 // state propagation is persisted 17960 mSettings.writeAllUsersPackageRestrictionsLPr(); 17961 if (installedStateChanged) { 17962 mSettings.writeKernelMappingLPr(ps); 17963 } 17964 } 17965 // can downgrade to reader here 17966 if (writeSettings) { 17967 mSettings.writeLPr(); 17968 } 17969 } 17970 return pkg; 17971 } 17972 17973 private boolean deleteInstalledPackageLIF(PackageSetting ps, 17974 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 17975 PackageRemovedInfo outInfo, boolean writeSettings, 17976 PackageParser.Package replacingPackage) { 17977 synchronized (mPackages) { 17978 if (outInfo != null) { 17979 outInfo.uid = ps.appId; 17980 } 17981 17982 if (outInfo != null && outInfo.removedChildPackages != null) { 17983 final int childCount = (ps.childPackageNames != null) 17984 ? ps.childPackageNames.size() : 0; 17985 for (int i = 0; i < childCount; i++) { 17986 String childPackageName = ps.childPackageNames.get(i); 17987 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 17988 if (childPs == null) { 17989 return false; 17990 } 17991 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 17992 childPackageName); 17993 if (childInfo != null) { 17994 childInfo.uid = childPs.appId; 17995 } 17996 } 17997 } 17998 } 17999 18000 // Delete package data from internal structures and also remove data if flag is set 18001 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 18002 18003 // Delete the child packages data 18004 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 18005 for (int i = 0; i < childCount; i++) { 18006 PackageSetting childPs; 18007 synchronized (mPackages) { 18008 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 18009 } 18010 if (childPs != null) { 18011 PackageRemovedInfo childOutInfo = (outInfo != null 18012 && outInfo.removedChildPackages != null) 18013 ? outInfo.removedChildPackages.get(childPs.name) : null; 18014 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 18015 && (replacingPackage != null 18016 && !replacingPackage.hasChildPackage(childPs.name)) 18017 ? flags & ~DELETE_KEEP_DATA : flags; 18018 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 18019 deleteFlags, writeSettings); 18020 } 18021 } 18022 18023 // Delete application code and resources only for parent packages 18024 if (ps.parentPackageName == null) { 18025 if (deleteCodeAndResources && (outInfo != null)) { 18026 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 18027 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 18028 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 18029 } 18030 } 18031 18032 return true; 18033 } 18034 18035 @Override 18036 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 18037 int userId) { 18038 mContext.enforceCallingOrSelfPermission( 18039 android.Manifest.permission.DELETE_PACKAGES, null); 18040 synchronized (mPackages) { 18041 // Cannot block uninstall of static shared libs as they are 18042 // considered a part of the using app (emulating static linking). 18043 // Also static libs are installed always on internal storage. 18044 PackageParser.Package pkg = mPackages.get(packageName); 18045 if (pkg != null && pkg.staticSharedLibName != null) { 18046 Slog.w(TAG, "Cannot block uninstall of package: " + packageName 18047 + " providing static shared library: " + pkg.staticSharedLibName); 18048 return false; 18049 } 18050 mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall); 18051 mSettings.writePackageRestrictionsLPr(userId); 18052 } 18053 return true; 18054 } 18055 18056 @Override 18057 public boolean getBlockUninstallForUser(String packageName, int userId) { 18058 synchronized (mPackages) { 18059 final PackageSetting ps = mSettings.mPackages.get(packageName); 18060 if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) { 18061 return false; 18062 } 18063 return mSettings.getBlockUninstallLPr(userId, packageName); 18064 } 18065 } 18066 18067 @Override 18068 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 18069 enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root"); 18070 synchronized (mPackages) { 18071 PackageSetting ps = mSettings.mPackages.get(packageName); 18072 if (ps == null) { 18073 Log.w(TAG, "Package doesn't exist: " + packageName); 18074 return false; 18075 } 18076 if (systemUserApp) { 18077 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 18078 } else { 18079 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 18080 } 18081 mSettings.writeLPr(); 18082 } 18083 return true; 18084 } 18085 18086 /* 18087 * This method handles package deletion in general 18088 */ 18089 private boolean deletePackageLIF(String packageName, UserHandle user, 18090 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 18091 PackageRemovedInfo outInfo, boolean writeSettings, 18092 PackageParser.Package replacingPackage) { 18093 if (packageName == null) { 18094 Slog.w(TAG, "Attempt to delete null packageName."); 18095 return false; 18096 } 18097 18098 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 18099 18100 PackageSetting ps; 18101 synchronized (mPackages) { 18102 ps = mSettings.mPackages.get(packageName); 18103 if (ps == null) { 18104 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 18105 return false; 18106 } 18107 18108 if (ps.parentPackageName != null && (!isSystemApp(ps) 18109 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 18110 if (DEBUG_REMOVE) { 18111 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 18112 + ((user == null) ? UserHandle.USER_ALL : user)); 18113 } 18114 final int removedUserId = (user != null) ? user.getIdentifier() 18115 : UserHandle.USER_ALL; 18116 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 18117 return false; 18118 } 18119 markPackageUninstalledForUserLPw(ps, user); 18120 scheduleWritePackageRestrictionsLocked(user); 18121 return true; 18122 } 18123 } 18124 18125 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 18126 && user.getIdentifier() != UserHandle.USER_ALL)) { 18127 // The caller is asking that the package only be deleted for a single 18128 // user. To do this, we just mark its uninstalled state and delete 18129 // its data. If this is a system app, we only allow this to happen if 18130 // they have set the special DELETE_SYSTEM_APP which requests different 18131 // semantics than normal for uninstalling system apps. 18132 markPackageUninstalledForUserLPw(ps, user); 18133 18134 if (!isSystemApp(ps)) { 18135 // Do not uninstall the APK if an app should be cached 18136 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 18137 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 18138 // Other user still have this package installed, so all 18139 // we need to do is clear this user's data and save that 18140 // it is uninstalled. 18141 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 18142 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 18143 return false; 18144 } 18145 scheduleWritePackageRestrictionsLocked(user); 18146 return true; 18147 } else { 18148 // We need to set it back to 'installed' so the uninstall 18149 // broadcasts will be sent correctly. 18150 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 18151 ps.setInstalled(true, user.getIdentifier()); 18152 mSettings.writeKernelMappingLPr(ps); 18153 } 18154 } else { 18155 // This is a system app, so we assume that the 18156 // other users still have this package installed, so all 18157 // we need to do is clear this user's data and save that 18158 // it is uninstalled. 18159 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 18160 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 18161 return false; 18162 } 18163 scheduleWritePackageRestrictionsLocked(user); 18164 return true; 18165 } 18166 } 18167 18168 // If we are deleting a composite package for all users, keep track 18169 // of result for each child. 18170 if (ps.childPackageNames != null && outInfo != null) { 18171 synchronized (mPackages) { 18172 final int childCount = ps.childPackageNames.size(); 18173 outInfo.removedChildPackages = new ArrayMap<>(childCount); 18174 for (int i = 0; i < childCount; i++) { 18175 String childPackageName = ps.childPackageNames.get(i); 18176 PackageRemovedInfo childInfo = new PackageRemovedInfo(this); 18177 childInfo.removedPackage = childPackageName; 18178 childInfo.installerPackageName = ps.installerPackageName; 18179 outInfo.removedChildPackages.put(childPackageName, childInfo); 18180 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 18181 if (childPs != null) { 18182 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 18183 } 18184 } 18185 } 18186 } 18187 18188 boolean ret = false; 18189 if (isSystemApp(ps)) { 18190 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 18191 // When an updated system application is deleted we delete the existing resources 18192 // as well and fall back to existing code in system partition 18193 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 18194 } else { 18195 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 18196 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 18197 outInfo, writeSettings, replacingPackage); 18198 } 18199 18200 // Take a note whether we deleted the package for all users 18201 if (outInfo != null) { 18202 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 18203 if (outInfo.removedChildPackages != null) { 18204 synchronized (mPackages) { 18205 final int childCount = outInfo.removedChildPackages.size(); 18206 for (int i = 0; i < childCount; i++) { 18207 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 18208 if (childInfo != null) { 18209 childInfo.removedForAllUsers = mPackages.get( 18210 childInfo.removedPackage) == null; 18211 } 18212 } 18213 } 18214 } 18215 // If we uninstalled an update to a system app there may be some 18216 // child packages that appeared as they are declared in the system 18217 // app but were not declared in the update. 18218 if (isSystemApp(ps)) { 18219 synchronized (mPackages) { 18220 PackageSetting updatedPs = mSettings.getPackageLPr(ps.name); 18221 final int childCount = (updatedPs.childPackageNames != null) 18222 ? updatedPs.childPackageNames.size() : 0; 18223 for (int i = 0; i < childCount; i++) { 18224 String childPackageName = updatedPs.childPackageNames.get(i); 18225 if (outInfo.removedChildPackages == null 18226 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 18227 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 18228 if (childPs == null) { 18229 continue; 18230 } 18231 PackageInstalledInfo installRes = new PackageInstalledInfo(); 18232 installRes.name = childPackageName; 18233 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 18234 installRes.pkg = mPackages.get(childPackageName); 18235 installRes.uid = childPs.pkg.applicationInfo.uid; 18236 if (outInfo.appearedChildPackages == null) { 18237 outInfo.appearedChildPackages = new ArrayMap<>(); 18238 } 18239 outInfo.appearedChildPackages.put(childPackageName, installRes); 18240 } 18241 } 18242 } 18243 } 18244 } 18245 18246 return ret; 18247 } 18248 18249 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 18250 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 18251 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 18252 for (int nextUserId : userIds) { 18253 if (DEBUG_REMOVE) { 18254 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 18255 } 18256 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 18257 false /*installed*/, 18258 true /*stopped*/, 18259 true /*notLaunched*/, 18260 false /*hidden*/, 18261 false /*suspended*/, 18262 false /*instantApp*/, 18263 false /*virtualPreload*/, 18264 null /*lastDisableAppCaller*/, 18265 null /*enabledComponents*/, 18266 null /*disabledComponents*/, 18267 ps.readUserState(nextUserId).domainVerificationStatus, 18268 0, PackageManager.INSTALL_REASON_UNKNOWN); 18269 } 18270 mSettings.writeKernelMappingLPr(ps); 18271 } 18272 18273 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 18274 PackageRemovedInfo outInfo) { 18275 final PackageParser.Package pkg; 18276 synchronized (mPackages) { 18277 pkg = mPackages.get(ps.name); 18278 } 18279 18280 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 18281 : new int[] {userId}; 18282 for (int nextUserId : userIds) { 18283 if (DEBUG_REMOVE) { 18284 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 18285 + nextUserId); 18286 } 18287 18288 destroyAppDataLIF(pkg, userId, 18289 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18290 destroyAppProfilesLIF(pkg, userId); 18291 clearDefaultBrowserIfNeededForUser(ps.name, userId); 18292 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 18293 schedulePackageCleaning(ps.name, nextUserId, false); 18294 synchronized (mPackages) { 18295 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 18296 scheduleWritePackageRestrictionsLocked(nextUserId); 18297 } 18298 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 18299 } 18300 } 18301 18302 if (outInfo != null) { 18303 outInfo.removedPackage = ps.name; 18304 outInfo.installerPackageName = ps.installerPackageName; 18305 outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null; 18306 outInfo.removedAppId = ps.appId; 18307 outInfo.removedUsers = userIds; 18308 outInfo.broadcastUsers = userIds; 18309 } 18310 18311 return true; 18312 } 18313 18314 private final class ClearStorageConnection implements ServiceConnection { 18315 IMediaContainerService mContainerService; 18316 18317 @Override 18318 public void onServiceConnected(ComponentName name, IBinder service) { 18319 synchronized (this) { 18320 mContainerService = IMediaContainerService.Stub 18321 .asInterface(Binder.allowBlocking(service)); 18322 notifyAll(); 18323 } 18324 } 18325 18326 @Override 18327 public void onServiceDisconnected(ComponentName name) { 18328 } 18329 } 18330 18331 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 18332 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 18333 18334 final boolean mounted; 18335 if (Environment.isExternalStorageEmulated()) { 18336 mounted = true; 18337 } else { 18338 final String status = Environment.getExternalStorageState(); 18339 18340 mounted = status.equals(Environment.MEDIA_MOUNTED) 18341 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 18342 } 18343 18344 if (!mounted) { 18345 return; 18346 } 18347 18348 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 18349 int[] users; 18350 if (userId == UserHandle.USER_ALL) { 18351 users = sUserManager.getUserIds(); 18352 } else { 18353 users = new int[] { userId }; 18354 } 18355 final ClearStorageConnection conn = new ClearStorageConnection(); 18356 if (mContext.bindServiceAsUser( 18357 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 18358 try { 18359 for (int curUser : users) { 18360 long timeout = SystemClock.uptimeMillis() + 5000; 18361 synchronized (conn) { 18362 long now; 18363 while (conn.mContainerService == null && 18364 (now = SystemClock.uptimeMillis()) < timeout) { 18365 try { 18366 conn.wait(timeout - now); 18367 } catch (InterruptedException e) { 18368 } 18369 } 18370 } 18371 if (conn.mContainerService == null) { 18372 return; 18373 } 18374 18375 final UserEnvironment userEnv = new UserEnvironment(curUser); 18376 clearDirectory(conn.mContainerService, 18377 userEnv.buildExternalStorageAppCacheDirs(packageName)); 18378 if (allData) { 18379 clearDirectory(conn.mContainerService, 18380 userEnv.buildExternalStorageAppDataDirs(packageName)); 18381 clearDirectory(conn.mContainerService, 18382 userEnv.buildExternalStorageAppMediaDirs(packageName)); 18383 } 18384 } 18385 } finally { 18386 mContext.unbindService(conn); 18387 } 18388 } 18389 } 18390 18391 @Override 18392 public void clearApplicationProfileData(String packageName) { 18393 enforceSystemOrRoot("Only the system can clear all profile data"); 18394 18395 final PackageParser.Package pkg; 18396 synchronized (mPackages) { 18397 pkg = mPackages.get(packageName); 18398 } 18399 18400 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 18401 synchronized (mInstallLock) { 18402 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 18403 } 18404 } 18405 } 18406 18407 @Override 18408 public void clearApplicationUserData(final String packageName, 18409 final IPackageDataObserver observer, final int userId) { 18410 mContext.enforceCallingOrSelfPermission( 18411 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 18412 18413 final int callingUid = Binder.getCallingUid(); 18414 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 18415 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 18416 18417 final PackageSetting ps = mSettings.getPackageLPr(packageName); 18418 final boolean filterApp = (ps != null && filterAppAccessLPr(ps, callingUid, userId)); 18419 if (!filterApp && mProtectedPackages.isPackageDataProtected(userId, packageName)) { 18420 throw new SecurityException("Cannot clear data for a protected package: " 18421 + packageName); 18422 } 18423 // Queue up an async operation since the package deletion may take a little while. 18424 mHandler.post(new Runnable() { 18425 public void run() { 18426 mHandler.removeCallbacks(this); 18427 final boolean succeeded; 18428 if (!filterApp) { 18429 try (PackageFreezer freezer = freezePackage(packageName, 18430 "clearApplicationUserData")) { 18431 synchronized (mInstallLock) { 18432 succeeded = clearApplicationUserDataLIF(packageName, userId); 18433 } 18434 clearExternalStorageDataSync(packageName, userId, true); 18435 synchronized (mPackages) { 18436 mInstantAppRegistry.deleteInstantApplicationMetadataLPw( 18437 packageName, userId); 18438 } 18439 } 18440 if (succeeded) { 18441 // invoke DeviceStorageMonitor's update method to clear any notifications 18442 DeviceStorageMonitorInternal dsm = LocalServices 18443 .getService(DeviceStorageMonitorInternal.class); 18444 if (dsm != null) { 18445 dsm.checkMemory(); 18446 } 18447 } 18448 } else { 18449 succeeded = false; 18450 } 18451 if (observer != null) { 18452 try { 18453 observer.onRemoveCompleted(packageName, succeeded); 18454 } catch (RemoteException e) { 18455 Log.i(TAG, "Observer no longer exists."); 18456 } 18457 } //end if observer 18458 } //end run 18459 }); 18460 } 18461 18462 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 18463 if (packageName == null) { 18464 Slog.w(TAG, "Attempt to delete null packageName."); 18465 return false; 18466 } 18467 18468 // Try finding details about the requested package 18469 PackageParser.Package pkg; 18470 synchronized (mPackages) { 18471 pkg = mPackages.get(packageName); 18472 if (pkg == null) { 18473 final PackageSetting ps = mSettings.mPackages.get(packageName); 18474 if (ps != null) { 18475 pkg = ps.pkg; 18476 } 18477 } 18478 18479 if (pkg == null) { 18480 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 18481 return false; 18482 } 18483 18484 PackageSetting ps = (PackageSetting) pkg.mExtras; 18485 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 18486 } 18487 18488 clearAppDataLIF(pkg, userId, 18489 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18490 18491 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 18492 removeKeystoreDataIfNeeded(userId, appId); 18493 18494 UserManagerInternal umInternal = getUserManagerInternal(); 18495 final int flags; 18496 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 18497 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18498 } else if (umInternal.isUserRunning(userId)) { 18499 flags = StorageManager.FLAG_STORAGE_DE; 18500 } else { 18501 flags = 0; 18502 } 18503 prepareAppDataContentsLIF(pkg, userId, flags); 18504 18505 return true; 18506 } 18507 18508 /** 18509 * Reverts user permission state changes (permissions and flags) in 18510 * all packages for a given user. 18511 * 18512 * @param userId The device user for which to do a reset. 18513 */ 18514 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 18515 final int packageCount = mPackages.size(); 18516 for (int i = 0; i < packageCount; i++) { 18517 PackageParser.Package pkg = mPackages.valueAt(i); 18518 PackageSetting ps = (PackageSetting) pkg.mExtras; 18519 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 18520 } 18521 } 18522 18523 private void resetNetworkPolicies(int userId) { 18524 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 18525 } 18526 18527 /** 18528 * Reverts user permission state changes (permissions and flags). 18529 * 18530 * @param ps The package for which to reset. 18531 * @param userId The device user for which to do a reset. 18532 */ 18533 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 18534 final PackageSetting ps, final int userId) { 18535 if (ps.pkg == null) { 18536 return; 18537 } 18538 18539 // These are flags that can change base on user actions. 18540 final int userSettableMask = FLAG_PERMISSION_USER_SET 18541 | FLAG_PERMISSION_USER_FIXED 18542 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 18543 | FLAG_PERMISSION_REVIEW_REQUIRED; 18544 18545 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 18546 | FLAG_PERMISSION_POLICY_FIXED; 18547 18548 boolean writeInstallPermissions = false; 18549 boolean writeRuntimePermissions = false; 18550 18551 final int permissionCount = ps.pkg.requestedPermissions.size(); 18552 for (int i = 0; i < permissionCount; i++) { 18553 final String permName = ps.pkg.requestedPermissions.get(i); 18554 final BasePermission bp = 18555 (BasePermission) mPermissionManager.getPermissionTEMP(permName); 18556 if (bp == null) { 18557 continue; 18558 } 18559 18560 // If shared user we just reset the state to which only this app contributed. 18561 if (ps.sharedUser != null) { 18562 boolean used = false; 18563 final int packageCount = ps.sharedUser.packages.size(); 18564 for (int j = 0; j < packageCount; j++) { 18565 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 18566 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 18567 && pkg.pkg.requestedPermissions.contains(permName)) { 18568 used = true; 18569 break; 18570 } 18571 } 18572 if (used) { 18573 continue; 18574 } 18575 } 18576 18577 final PermissionsState permissionsState = ps.getPermissionsState(); 18578 18579 final int oldFlags = permissionsState.getPermissionFlags(permName, userId); 18580 18581 // Always clear the user settable flags. 18582 final boolean hasInstallState = 18583 permissionsState.getInstallPermissionState(permName) != null; 18584 // If permission review is enabled and this is a legacy app, mark the 18585 // permission as requiring a review as this is the initial state. 18586 int flags = 0; 18587 if (mSettings.mPermissions.mPermissionReviewRequired 18588 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 18589 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 18590 } 18591 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 18592 if (hasInstallState) { 18593 writeInstallPermissions = true; 18594 } else { 18595 writeRuntimePermissions = true; 18596 } 18597 } 18598 18599 // Below is only runtime permission handling. 18600 if (!bp.isRuntime()) { 18601 continue; 18602 } 18603 18604 // Never clobber system or policy. 18605 if ((oldFlags & policyOrSystemFlags) != 0) { 18606 continue; 18607 } 18608 18609 // If this permission was granted by default, make sure it is. 18610 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 18611 if (permissionsState.grantRuntimePermission(bp, userId) 18612 != PERMISSION_OPERATION_FAILURE) { 18613 writeRuntimePermissions = true; 18614 } 18615 // If permission review is enabled the permissions for a legacy apps 18616 // are represented as constantly granted runtime ones, so don't revoke. 18617 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 18618 // Otherwise, reset the permission. 18619 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 18620 switch (revokeResult) { 18621 case PERMISSION_OPERATION_SUCCESS: 18622 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 18623 writeRuntimePermissions = true; 18624 final int appId = ps.appId; 18625 mHandler.post(new Runnable() { 18626 @Override 18627 public void run() { 18628 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 18629 } 18630 }); 18631 } break; 18632 } 18633 } 18634 } 18635 18636 // Synchronously write as we are taking permissions away. 18637 if (writeRuntimePermissions) { 18638 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 18639 } 18640 18641 // Synchronously write as we are taking permissions away. 18642 if (writeInstallPermissions) { 18643 mSettings.writeLPr(); 18644 } 18645 } 18646 18647 /** 18648 * Remove entries from the keystore daemon. Will only remove it if the 18649 * {@code appId} is valid. 18650 */ 18651 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 18652 if (appId < 0) { 18653 return; 18654 } 18655 18656 final KeyStore keyStore = KeyStore.getInstance(); 18657 if (keyStore != null) { 18658 if (userId == UserHandle.USER_ALL) { 18659 for (final int individual : sUserManager.getUserIds()) { 18660 keyStore.clearUid(UserHandle.getUid(individual, appId)); 18661 } 18662 } else { 18663 keyStore.clearUid(UserHandle.getUid(userId, appId)); 18664 } 18665 } else { 18666 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 18667 } 18668 } 18669 18670 @Override 18671 public void deleteApplicationCacheFiles(final String packageName, 18672 final IPackageDataObserver observer) { 18673 final int userId = UserHandle.getCallingUserId(); 18674 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 18675 } 18676 18677 @Override 18678 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 18679 final IPackageDataObserver observer) { 18680 final int callingUid = Binder.getCallingUid(); 18681 mContext.enforceCallingOrSelfPermission( 18682 android.Manifest.permission.DELETE_CACHE_FILES, null); 18683 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 18684 /* requireFullPermission= */ true, /* checkShell= */ false, 18685 "delete application cache files"); 18686 final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission( 18687 android.Manifest.permission.ACCESS_INSTANT_APPS); 18688 18689 final PackageParser.Package pkg; 18690 synchronized (mPackages) { 18691 pkg = mPackages.get(packageName); 18692 } 18693 18694 // Queue up an async operation since the package deletion may take a little while. 18695 mHandler.post(new Runnable() { 18696 public void run() { 18697 final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras; 18698 boolean doClearData = true; 18699 if (ps != null) { 18700 final boolean targetIsInstantApp = 18701 ps.getInstantApp(UserHandle.getUserId(callingUid)); 18702 doClearData = !targetIsInstantApp 18703 || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED; 18704 } 18705 if (doClearData) { 18706 synchronized (mInstallLock) { 18707 final int flags = StorageManager.FLAG_STORAGE_DE 18708 | StorageManager.FLAG_STORAGE_CE; 18709 // We're only clearing cache files, so we don't care if the 18710 // app is unfrozen and still able to run 18711 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 18712 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 18713 } 18714 clearExternalStorageDataSync(packageName, userId, false); 18715 } 18716 if (observer != null) { 18717 try { 18718 observer.onRemoveCompleted(packageName, true); 18719 } catch (RemoteException e) { 18720 Log.i(TAG, "Observer no longer exists."); 18721 } 18722 } 18723 } 18724 }); 18725 } 18726 18727 @Override 18728 public void getPackageSizeInfo(final String packageName, int userHandle, 18729 final IPackageStatsObserver observer) { 18730 throw new UnsupportedOperationException( 18731 "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!"); 18732 } 18733 18734 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 18735 final PackageSetting ps; 18736 synchronized (mPackages) { 18737 ps = mSettings.mPackages.get(packageName); 18738 if (ps == null) { 18739 Slog.w(TAG, "Failed to find settings for " + packageName); 18740 return false; 18741 } 18742 } 18743 18744 final String[] packageNames = { packageName }; 18745 final long[] ceDataInodes = { ps.getCeDataInode(userId) }; 18746 final String[] codePaths = { ps.codePathString }; 18747 18748 try { 18749 mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0, 18750 ps.appId, ceDataInodes, codePaths, stats); 18751 18752 // For now, ignore code size of packages on system partition 18753 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 18754 stats.codeSize = 0; 18755 } 18756 18757 // External clients expect these to be tracked separately 18758 stats.dataSize -= stats.cacheSize; 18759 18760 } catch (InstallerException e) { 18761 Slog.w(TAG, String.valueOf(e)); 18762 return false; 18763 } 18764 18765 return true; 18766 } 18767 18768 private int getUidTargetSdkVersionLockedLPr(int uid) { 18769 Object obj = mSettings.getUserIdLPr(uid); 18770 if (obj instanceof SharedUserSetting) { 18771 final SharedUserSetting sus = (SharedUserSetting) obj; 18772 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 18773 final Iterator<PackageSetting> it = sus.packages.iterator(); 18774 while (it.hasNext()) { 18775 final PackageSetting ps = it.next(); 18776 if (ps.pkg != null) { 18777 int v = ps.pkg.applicationInfo.targetSdkVersion; 18778 if (v < vers) vers = v; 18779 } 18780 } 18781 return vers; 18782 } else if (obj instanceof PackageSetting) { 18783 final PackageSetting ps = (PackageSetting) obj; 18784 if (ps.pkg != null) { 18785 return ps.pkg.applicationInfo.targetSdkVersion; 18786 } 18787 } 18788 return Build.VERSION_CODES.CUR_DEVELOPMENT; 18789 } 18790 18791 @Override 18792 public void addPreferredActivity(IntentFilter filter, int match, 18793 ComponentName[] set, ComponentName activity, int userId) { 18794 addPreferredActivityInternal(filter, match, set, activity, true, userId, 18795 "Adding preferred"); 18796 } 18797 18798 private void addPreferredActivityInternal(IntentFilter filter, int match, 18799 ComponentName[] set, ComponentName activity, boolean always, int userId, 18800 String opname) { 18801 // writer 18802 int callingUid = Binder.getCallingUid(); 18803 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 18804 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 18805 if (filter.countActions() == 0) { 18806 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 18807 return; 18808 } 18809 synchronized (mPackages) { 18810 if (mContext.checkCallingOrSelfPermission( 18811 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 18812 != PackageManager.PERMISSION_GRANTED) { 18813 if (getUidTargetSdkVersionLockedLPr(callingUid) 18814 < Build.VERSION_CODES.FROYO) { 18815 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 18816 + callingUid); 18817 return; 18818 } 18819 mContext.enforceCallingOrSelfPermission( 18820 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 18821 } 18822 18823 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 18824 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 18825 + userId + ":"); 18826 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18827 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 18828 scheduleWritePackageRestrictionsLocked(userId); 18829 postPreferredActivityChangedBroadcast(userId); 18830 } 18831 } 18832 18833 private void postPreferredActivityChangedBroadcast(int userId) { 18834 mHandler.post(() -> { 18835 final IActivityManager am = ActivityManager.getService(); 18836 if (am == null) { 18837 return; 18838 } 18839 18840 final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED); 18841 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 18842 try { 18843 am.broadcastIntent(null, intent, null, null, 18844 0, null, null, null, android.app.AppOpsManager.OP_NONE, 18845 null, false, false, userId); 18846 } catch (RemoteException e) { 18847 } 18848 }); 18849 } 18850 18851 @Override 18852 public void replacePreferredActivity(IntentFilter filter, int match, 18853 ComponentName[] set, ComponentName activity, int userId) { 18854 if (filter.countActions() != 1) { 18855 throw new IllegalArgumentException( 18856 "replacePreferredActivity expects filter to have only 1 action."); 18857 } 18858 if (filter.countDataAuthorities() != 0 18859 || filter.countDataPaths() != 0 18860 || filter.countDataSchemes() > 1 18861 || filter.countDataTypes() != 0) { 18862 throw new IllegalArgumentException( 18863 "replacePreferredActivity expects filter to have no data authorities, " + 18864 "paths, or types; and at most one scheme."); 18865 } 18866 18867 final int callingUid = Binder.getCallingUid(); 18868 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 18869 true /* requireFullPermission */, false /* checkShell */, 18870 "replace preferred activity"); 18871 synchronized (mPackages) { 18872 if (mContext.checkCallingOrSelfPermission( 18873 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 18874 != PackageManager.PERMISSION_GRANTED) { 18875 if (getUidTargetSdkVersionLockedLPr(callingUid) 18876 < Build.VERSION_CODES.FROYO) { 18877 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 18878 + Binder.getCallingUid()); 18879 return; 18880 } 18881 mContext.enforceCallingOrSelfPermission( 18882 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 18883 } 18884 18885 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 18886 if (pir != null) { 18887 // Get all of the existing entries that exactly match this filter. 18888 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 18889 if (existing != null && existing.size() == 1) { 18890 PreferredActivity cur = existing.get(0); 18891 if (DEBUG_PREFERRED) { 18892 Slog.i(TAG, "Checking replace of preferred:"); 18893 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18894 if (!cur.mPref.mAlways) { 18895 Slog.i(TAG, " -- CUR; not mAlways!"); 18896 } else { 18897 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 18898 Slog.i(TAG, " -- CUR: mSet=" 18899 + Arrays.toString(cur.mPref.mSetComponents)); 18900 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 18901 Slog.i(TAG, " -- NEW: mMatch=" 18902 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 18903 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 18904 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 18905 } 18906 } 18907 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 18908 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 18909 && cur.mPref.sameSet(set)) { 18910 // Setting the preferred activity to what it happens to be already 18911 if (DEBUG_PREFERRED) { 18912 Slog.i(TAG, "Replacing with same preferred activity " 18913 + cur.mPref.mShortComponent + " for user " 18914 + userId + ":"); 18915 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18916 } 18917 return; 18918 } 18919 } 18920 18921 if (existing != null) { 18922 if (DEBUG_PREFERRED) { 18923 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 18924 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18925 } 18926 for (int i = 0; i < existing.size(); i++) { 18927 PreferredActivity pa = existing.get(i); 18928 if (DEBUG_PREFERRED) { 18929 Slog.i(TAG, "Removing existing preferred activity " 18930 + pa.mPref.mComponent + ":"); 18931 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 18932 } 18933 pir.removeFilter(pa); 18934 } 18935 } 18936 } 18937 addPreferredActivityInternal(filter, match, set, activity, true, userId, 18938 "Replacing preferred"); 18939 } 18940 } 18941 18942 @Override 18943 public void clearPackagePreferredActivities(String packageName) { 18944 final int callingUid = Binder.getCallingUid(); 18945 if (getInstantAppPackageName(callingUid) != null) { 18946 return; 18947 } 18948 // writer 18949 synchronized (mPackages) { 18950 PackageParser.Package pkg = mPackages.get(packageName); 18951 if (pkg == null || pkg.applicationInfo.uid != callingUid) { 18952 if (mContext.checkCallingOrSelfPermission( 18953 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 18954 != PackageManager.PERMISSION_GRANTED) { 18955 if (getUidTargetSdkVersionLockedLPr(callingUid) 18956 < Build.VERSION_CODES.FROYO) { 18957 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 18958 + callingUid); 18959 return; 18960 } 18961 mContext.enforceCallingOrSelfPermission( 18962 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 18963 } 18964 } 18965 final PackageSetting ps = mSettings.getPackageLPr(packageName); 18966 if (ps != null 18967 && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 18968 return; 18969 } 18970 int user = UserHandle.getCallingUserId(); 18971 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 18972 scheduleWritePackageRestrictionsLocked(user); 18973 } 18974 } 18975 } 18976 18977 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 18978 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 18979 ArrayList<PreferredActivity> removed = null; 18980 boolean changed = false; 18981 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18982 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 18983 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18984 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 18985 continue; 18986 } 18987 Iterator<PreferredActivity> it = pir.filterIterator(); 18988 while (it.hasNext()) { 18989 PreferredActivity pa = it.next(); 18990 // Mark entry for removal only if it matches the package name 18991 // and the entry is of type "always". 18992 if (packageName == null || 18993 (pa.mPref.mComponent.getPackageName().equals(packageName) 18994 && pa.mPref.mAlways)) { 18995 if (removed == null) { 18996 removed = new ArrayList<PreferredActivity>(); 18997 } 18998 removed.add(pa); 18999 } 19000 } 19001 if (removed != null) { 19002 for (int j=0; j<removed.size(); j++) { 19003 PreferredActivity pa = removed.get(j); 19004 pir.removeFilter(pa); 19005 } 19006 changed = true; 19007 } 19008 } 19009 if (changed) { 19010 postPreferredActivityChangedBroadcast(userId); 19011 } 19012 return changed; 19013 } 19014 19015 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 19016 private void clearIntentFilterVerificationsLPw(int userId) { 19017 final int packageCount = mPackages.size(); 19018 for (int i = 0; i < packageCount; i++) { 19019 PackageParser.Package pkg = mPackages.valueAt(i); 19020 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 19021 } 19022 } 19023 19024 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 19025 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 19026 if (userId == UserHandle.USER_ALL) { 19027 if (mSettings.removeIntentFilterVerificationLPw(packageName, 19028 sUserManager.getUserIds())) { 19029 for (int oneUserId : sUserManager.getUserIds()) { 19030 scheduleWritePackageRestrictionsLocked(oneUserId); 19031 } 19032 } 19033 } else { 19034 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 19035 scheduleWritePackageRestrictionsLocked(userId); 19036 } 19037 } 19038 } 19039 19040 /** Clears state for all users, and touches intent filter verification policy */ 19041 void clearDefaultBrowserIfNeeded(String packageName) { 19042 for (int oneUserId : sUserManager.getUserIds()) { 19043 clearDefaultBrowserIfNeededForUser(packageName, oneUserId); 19044 } 19045 } 19046 19047 private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) { 19048 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 19049 if (!TextUtils.isEmpty(defaultBrowserPackageName)) { 19050 if (packageName.equals(defaultBrowserPackageName)) { 19051 setDefaultBrowserPackageName(null, userId); 19052 } 19053 } 19054 } 19055 19056 @Override 19057 public void resetApplicationPreferences(int userId) { 19058 mContext.enforceCallingOrSelfPermission( 19059 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 19060 final long identity = Binder.clearCallingIdentity(); 19061 // writer 19062 try { 19063 synchronized (mPackages) { 19064 clearPackagePreferredActivitiesLPw(null, userId); 19065 mSettings.applyDefaultPreferredAppsLPw(this, userId); 19066 // TODO: We have to reset the default SMS and Phone. This requires 19067 // significant refactoring to keep all default apps in the package 19068 // manager (cleaner but more work) or have the services provide 19069 // callbacks to the package manager to request a default app reset. 19070 applyFactoryDefaultBrowserLPw(userId); 19071 clearIntentFilterVerificationsLPw(userId); 19072 primeDomainVerificationsLPw(userId); 19073 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 19074 scheduleWritePackageRestrictionsLocked(userId); 19075 } 19076 resetNetworkPolicies(userId); 19077 } finally { 19078 Binder.restoreCallingIdentity(identity); 19079 } 19080 } 19081 19082 @Override 19083 public int getPreferredActivities(List<IntentFilter> outFilters, 19084 List<ComponentName> outActivities, String packageName) { 19085 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 19086 return 0; 19087 } 19088 int num = 0; 19089 final int userId = UserHandle.getCallingUserId(); 19090 // reader 19091 synchronized (mPackages) { 19092 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 19093 if (pir != null) { 19094 final Iterator<PreferredActivity> it = pir.filterIterator(); 19095 while (it.hasNext()) { 19096 final PreferredActivity pa = it.next(); 19097 if (packageName == null 19098 || (pa.mPref.mComponent.getPackageName().equals(packageName) 19099 && pa.mPref.mAlways)) { 19100 if (outFilters != null) { 19101 outFilters.add(new IntentFilter(pa)); 19102 } 19103 if (outActivities != null) { 19104 outActivities.add(pa.mPref.mComponent); 19105 } 19106 } 19107 } 19108 } 19109 } 19110 19111 return num; 19112 } 19113 19114 @Override 19115 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 19116 int userId) { 19117 int callingUid = Binder.getCallingUid(); 19118 if (callingUid != Process.SYSTEM_UID) { 19119 throw new SecurityException( 19120 "addPersistentPreferredActivity can only be run by the system"); 19121 } 19122 if (filter.countActions() == 0) { 19123 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 19124 return; 19125 } 19126 synchronized (mPackages) { 19127 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 19128 ":"); 19129 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19130 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 19131 new PersistentPreferredActivity(filter, activity)); 19132 scheduleWritePackageRestrictionsLocked(userId); 19133 postPreferredActivityChangedBroadcast(userId); 19134 } 19135 } 19136 19137 @Override 19138 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 19139 int callingUid = Binder.getCallingUid(); 19140 if (callingUid != Process.SYSTEM_UID) { 19141 throw new SecurityException( 19142 "clearPackagePersistentPreferredActivities can only be run by the system"); 19143 } 19144 ArrayList<PersistentPreferredActivity> removed = null; 19145 boolean changed = false; 19146 synchronized (mPackages) { 19147 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 19148 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 19149 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 19150 .valueAt(i); 19151 if (userId != thisUserId) { 19152 continue; 19153 } 19154 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 19155 while (it.hasNext()) { 19156 PersistentPreferredActivity ppa = it.next(); 19157 // Mark entry for removal only if it matches the package name. 19158 if (ppa.mComponent.getPackageName().equals(packageName)) { 19159 if (removed == null) { 19160 removed = new ArrayList<PersistentPreferredActivity>(); 19161 } 19162 removed.add(ppa); 19163 } 19164 } 19165 if (removed != null) { 19166 for (int j=0; j<removed.size(); j++) { 19167 PersistentPreferredActivity ppa = removed.get(j); 19168 ppir.removeFilter(ppa); 19169 } 19170 changed = true; 19171 } 19172 } 19173 19174 if (changed) { 19175 scheduleWritePackageRestrictionsLocked(userId); 19176 postPreferredActivityChangedBroadcast(userId); 19177 } 19178 } 19179 } 19180 19181 /** 19182 * Common machinery for picking apart a restored XML blob and passing 19183 * it to a caller-supplied functor to be applied to the running system. 19184 */ 19185 private void restoreFromXml(XmlPullParser parser, int userId, 19186 String expectedStartTag, BlobXmlRestorer functor) 19187 throws IOException, XmlPullParserException { 19188 int type; 19189 while ((type = parser.next()) != XmlPullParser.START_TAG 19190 && type != XmlPullParser.END_DOCUMENT) { 19191 } 19192 if (type != XmlPullParser.START_TAG) { 19193 // oops didn't find a start tag?! 19194 if (DEBUG_BACKUP) { 19195 Slog.e(TAG, "Didn't find start tag during restore"); 19196 } 19197 return; 19198 } 19199Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 19200 // this is supposed to be TAG_PREFERRED_BACKUP 19201 if (!expectedStartTag.equals(parser.getName())) { 19202 if (DEBUG_BACKUP) { 19203 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 19204 } 19205 return; 19206 } 19207 19208 // skip interfering stuff, then we're aligned with the backing implementation 19209 while ((type = parser.next()) == XmlPullParser.TEXT) { } 19210Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 19211 functor.apply(parser, userId); 19212 } 19213 19214 private interface BlobXmlRestorer { 19215 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 19216 } 19217 19218 /** 19219 * Non-Binder method, support for the backup/restore mechanism: write the 19220 * full set of preferred activities in its canonical XML format. Returns the 19221 * XML output as a byte array, or null if there is none. 19222 */ 19223 @Override 19224 public byte[] getPreferredActivityBackup(int userId) { 19225 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19226 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 19227 } 19228 19229 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19230 try { 19231 final XmlSerializer serializer = new FastXmlSerializer(); 19232 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19233 serializer.startDocument(null, true); 19234 serializer.startTag(null, TAG_PREFERRED_BACKUP); 19235 19236 synchronized (mPackages) { 19237 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 19238 } 19239 19240 serializer.endTag(null, TAG_PREFERRED_BACKUP); 19241 serializer.endDocument(); 19242 serializer.flush(); 19243 } catch (Exception e) { 19244 if (DEBUG_BACKUP) { 19245 Slog.e(TAG, "Unable to write preferred activities for backup", e); 19246 } 19247 return null; 19248 } 19249 19250 return dataStream.toByteArray(); 19251 } 19252 19253 @Override 19254 public void restorePreferredActivities(byte[] backup, int userId) { 19255 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19256 throw new SecurityException("Only the system may call restorePreferredActivities()"); 19257 } 19258 19259 try { 19260 final XmlPullParser parser = Xml.newPullParser(); 19261 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19262 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 19263 new BlobXmlRestorer() { 19264 @Override 19265 public void apply(XmlPullParser parser, int userId) 19266 throws XmlPullParserException, IOException { 19267 synchronized (mPackages) { 19268 mSettings.readPreferredActivitiesLPw(parser, userId); 19269 } 19270 } 19271 } ); 19272 } catch (Exception e) { 19273 if (DEBUG_BACKUP) { 19274 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19275 } 19276 } 19277 } 19278 19279 /** 19280 * Non-Binder method, support for the backup/restore mechanism: write the 19281 * default browser (etc) settings in its canonical XML format. Returns the default 19282 * browser XML representation as a byte array, or null if there is none. 19283 */ 19284 @Override 19285 public byte[] getDefaultAppsBackup(int userId) { 19286 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19287 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 19288 } 19289 19290 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19291 try { 19292 final XmlSerializer serializer = new FastXmlSerializer(); 19293 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19294 serializer.startDocument(null, true); 19295 serializer.startTag(null, TAG_DEFAULT_APPS); 19296 19297 synchronized (mPackages) { 19298 mSettings.writeDefaultAppsLPr(serializer, userId); 19299 } 19300 19301 serializer.endTag(null, TAG_DEFAULT_APPS); 19302 serializer.endDocument(); 19303 serializer.flush(); 19304 } catch (Exception e) { 19305 if (DEBUG_BACKUP) { 19306 Slog.e(TAG, "Unable to write default apps for backup", e); 19307 } 19308 return null; 19309 } 19310 19311 return dataStream.toByteArray(); 19312 } 19313 19314 @Override 19315 public void restoreDefaultApps(byte[] backup, int userId) { 19316 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19317 throw new SecurityException("Only the system may call restoreDefaultApps()"); 19318 } 19319 19320 try { 19321 final XmlPullParser parser = Xml.newPullParser(); 19322 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19323 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 19324 new BlobXmlRestorer() { 19325 @Override 19326 public void apply(XmlPullParser parser, int userId) 19327 throws XmlPullParserException, IOException { 19328 synchronized (mPackages) { 19329 mSettings.readDefaultAppsLPw(parser, userId); 19330 } 19331 } 19332 } ); 19333 } catch (Exception e) { 19334 if (DEBUG_BACKUP) { 19335 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 19336 } 19337 } 19338 } 19339 19340 @Override 19341 public byte[] getIntentFilterVerificationBackup(int userId) { 19342 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19343 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 19344 } 19345 19346 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19347 try { 19348 final XmlSerializer serializer = new FastXmlSerializer(); 19349 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19350 serializer.startDocument(null, true); 19351 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 19352 19353 synchronized (mPackages) { 19354 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 19355 } 19356 19357 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 19358 serializer.endDocument(); 19359 serializer.flush(); 19360 } catch (Exception e) { 19361 if (DEBUG_BACKUP) { 19362 Slog.e(TAG, "Unable to write default apps for backup", e); 19363 } 19364 return null; 19365 } 19366 19367 return dataStream.toByteArray(); 19368 } 19369 19370 @Override 19371 public void restoreIntentFilterVerification(byte[] backup, int userId) { 19372 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19373 throw new SecurityException("Only the system may call restorePreferredActivities()"); 19374 } 19375 19376 try { 19377 final XmlPullParser parser = Xml.newPullParser(); 19378 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19379 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 19380 new BlobXmlRestorer() { 19381 @Override 19382 public void apply(XmlPullParser parser, int userId) 19383 throws XmlPullParserException, IOException { 19384 synchronized (mPackages) { 19385 mSettings.readAllDomainVerificationsLPr(parser, userId); 19386 mSettings.writeLPr(); 19387 } 19388 } 19389 } ); 19390 } catch (Exception e) { 19391 if (DEBUG_BACKUP) { 19392 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19393 } 19394 } 19395 } 19396 19397 @Override 19398 public byte[] getPermissionGrantBackup(int userId) { 19399 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19400 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 19401 } 19402 19403 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19404 try { 19405 final XmlSerializer serializer = new FastXmlSerializer(); 19406 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19407 serializer.startDocument(null, true); 19408 serializer.startTag(null, TAG_PERMISSION_BACKUP); 19409 19410 synchronized (mPackages) { 19411 serializeRuntimePermissionGrantsLPr(serializer, userId); 19412 } 19413 19414 serializer.endTag(null, TAG_PERMISSION_BACKUP); 19415 serializer.endDocument(); 19416 serializer.flush(); 19417 } catch (Exception e) { 19418 if (DEBUG_BACKUP) { 19419 Slog.e(TAG, "Unable to write default apps for backup", e); 19420 } 19421 return null; 19422 } 19423 19424 return dataStream.toByteArray(); 19425 } 19426 19427 @Override 19428 public void restorePermissionGrants(byte[] backup, int userId) { 19429 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19430 throw new SecurityException("Only the system may call restorePermissionGrants()"); 19431 } 19432 19433 try { 19434 final XmlPullParser parser = Xml.newPullParser(); 19435 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19436 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 19437 new BlobXmlRestorer() { 19438 @Override 19439 public void apply(XmlPullParser parser, int userId) 19440 throws XmlPullParserException, IOException { 19441 synchronized (mPackages) { 19442 processRestoredPermissionGrantsLPr(parser, userId); 19443 } 19444 } 19445 } ); 19446 } catch (Exception e) { 19447 if (DEBUG_BACKUP) { 19448 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19449 } 19450 } 19451 } 19452 19453 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 19454 throws IOException { 19455 serializer.startTag(null, TAG_ALL_GRANTS); 19456 19457 final int N = mSettings.mPackages.size(); 19458 for (int i = 0; i < N; i++) { 19459 final PackageSetting ps = mSettings.mPackages.valueAt(i); 19460 boolean pkgGrantsKnown = false; 19461 19462 PermissionsState packagePerms = ps.getPermissionsState(); 19463 19464 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 19465 final int grantFlags = state.getFlags(); 19466 // only look at grants that are not system/policy fixed 19467 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 19468 final boolean isGranted = state.isGranted(); 19469 // And only back up the user-twiddled state bits 19470 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 19471 final String packageName = mSettings.mPackages.keyAt(i); 19472 if (!pkgGrantsKnown) { 19473 serializer.startTag(null, TAG_GRANT); 19474 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 19475 pkgGrantsKnown = true; 19476 } 19477 19478 final boolean userSet = 19479 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 19480 final boolean userFixed = 19481 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 19482 final boolean revoke = 19483 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 19484 19485 serializer.startTag(null, TAG_PERMISSION); 19486 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 19487 if (isGranted) { 19488 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 19489 } 19490 if (userSet) { 19491 serializer.attribute(null, ATTR_USER_SET, "true"); 19492 } 19493 if (userFixed) { 19494 serializer.attribute(null, ATTR_USER_FIXED, "true"); 19495 } 19496 if (revoke) { 19497 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 19498 } 19499 serializer.endTag(null, TAG_PERMISSION); 19500 } 19501 } 19502 } 19503 19504 if (pkgGrantsKnown) { 19505 serializer.endTag(null, TAG_GRANT); 19506 } 19507 } 19508 19509 serializer.endTag(null, TAG_ALL_GRANTS); 19510 } 19511 19512 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 19513 throws XmlPullParserException, IOException { 19514 String pkgName = null; 19515 int outerDepth = parser.getDepth(); 19516 int type; 19517 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 19518 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 19519 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 19520 continue; 19521 } 19522 19523 final String tagName = parser.getName(); 19524 if (tagName.equals(TAG_GRANT)) { 19525 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 19526 if (DEBUG_BACKUP) { 19527 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 19528 } 19529 } else if (tagName.equals(TAG_PERMISSION)) { 19530 19531 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 19532 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 19533 19534 int newFlagSet = 0; 19535 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 19536 newFlagSet |= FLAG_PERMISSION_USER_SET; 19537 } 19538 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 19539 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 19540 } 19541 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 19542 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 19543 } 19544 if (DEBUG_BACKUP) { 19545 Slog.v(TAG, " + Restoring grant:" 19546 + " pkg=" + pkgName 19547 + " perm=" + permName 19548 + " granted=" + isGranted 19549 + " bits=0x" + Integer.toHexString(newFlagSet)); 19550 } 19551 final PackageSetting ps = mSettings.mPackages.get(pkgName); 19552 if (ps != null) { 19553 // Already installed so we apply the grant immediately 19554 if (DEBUG_BACKUP) { 19555 Slog.v(TAG, " + already installed; applying"); 19556 } 19557 PermissionsState perms = ps.getPermissionsState(); 19558 BasePermission bp = 19559 (BasePermission) mPermissionManager.getPermissionTEMP(permName); 19560 if (bp != null) { 19561 if (isGranted) { 19562 perms.grantRuntimePermission(bp, userId); 19563 } 19564 if (newFlagSet != 0) { 19565 perms.updatePermissionFlags( 19566 bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 19567 } 19568 } 19569 } else { 19570 // Need to wait for post-restore install to apply the grant 19571 if (DEBUG_BACKUP) { 19572 Slog.v(TAG, " - not yet installed; saving for later"); 19573 } 19574 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 19575 isGranted, newFlagSet, userId); 19576 } 19577 } else { 19578 PackageManagerService.reportSettingsProblem(Log.WARN, 19579 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 19580 XmlUtils.skipCurrentTag(parser); 19581 } 19582 } 19583 19584 scheduleWriteSettingsLocked(); 19585 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 19586 } 19587 19588 @Override 19589 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 19590 int sourceUserId, int targetUserId, int flags) { 19591 mContext.enforceCallingOrSelfPermission( 19592 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 19593 int callingUid = Binder.getCallingUid(); 19594 enforceOwnerRights(ownerPackage, callingUid); 19595 PackageManagerServiceUtils.enforceShellRestriction( 19596 UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 19597 if (intentFilter.countActions() == 0) { 19598 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 19599 return; 19600 } 19601 synchronized (mPackages) { 19602 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 19603 ownerPackage, targetUserId, flags); 19604 CrossProfileIntentResolver resolver = 19605 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 19606 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 19607 // We have all those whose filter is equal. Now checking if the rest is equal as well. 19608 if (existing != null) { 19609 int size = existing.size(); 19610 for (int i = 0; i < size; i++) { 19611 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 19612 return; 19613 } 19614 } 19615 } 19616 resolver.addFilter(newFilter); 19617 scheduleWritePackageRestrictionsLocked(sourceUserId); 19618 } 19619 } 19620 19621 @Override 19622 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 19623 mContext.enforceCallingOrSelfPermission( 19624 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 19625 final int callingUid = Binder.getCallingUid(); 19626 enforceOwnerRights(ownerPackage, callingUid); 19627 PackageManagerServiceUtils.enforceShellRestriction( 19628 UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 19629 synchronized (mPackages) { 19630 CrossProfileIntentResolver resolver = 19631 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 19632 ArraySet<CrossProfileIntentFilter> set = 19633 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 19634 for (CrossProfileIntentFilter filter : set) { 19635 if (filter.getOwnerPackage().equals(ownerPackage)) { 19636 resolver.removeFilter(filter); 19637 } 19638 } 19639 scheduleWritePackageRestrictionsLocked(sourceUserId); 19640 } 19641 } 19642 19643 // Enforcing that callingUid is owning pkg on userId 19644 private void enforceOwnerRights(String pkg, int callingUid) { 19645 // The system owns everything. 19646 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 19647 return; 19648 } 19649 final int callingUserId = UserHandle.getUserId(callingUid); 19650 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 19651 if (pi == null) { 19652 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 19653 + callingUserId); 19654 } 19655 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 19656 throw new SecurityException("Calling uid " + callingUid 19657 + " does not own package " + pkg); 19658 } 19659 } 19660 19661 @Override 19662 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 19663 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 19664 return null; 19665 } 19666 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 19667 } 19668 19669 public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) { 19670 UserManagerService ums = UserManagerService.getInstance(); 19671 if (ums != null) { 19672 final UserInfo parent = ums.getProfileParent(userId); 19673 final int launcherUid = (parent != null) ? parent.id : userId; 19674 final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid); 19675 if (launcherComponent != null) { 19676 Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED) 19677 .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo) 19678 .putExtra(Intent.EXTRA_USER, UserHandle.of(userId)) 19679 .setPackage(launcherComponent.getPackageName()); 19680 mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid)); 19681 } 19682 } 19683 } 19684 19685 /** 19686 * Report the 'Home' activity which is currently set as "always use this one". If non is set 19687 * then reports the most likely home activity or null if there are more than one. 19688 */ 19689 private ComponentName getDefaultHomeActivity(int userId) { 19690 List<ResolveInfo> allHomeCandidates = new ArrayList<>(); 19691 ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId); 19692 if (cn != null) { 19693 return cn; 19694 } 19695 19696 // Find the launcher with the highest priority and return that component if there are no 19697 // other home activity with the same priority. 19698 int lastPriority = Integer.MIN_VALUE; 19699 ComponentName lastComponent = null; 19700 final int size = allHomeCandidates.size(); 19701 for (int i = 0; i < size; i++) { 19702 final ResolveInfo ri = allHomeCandidates.get(i); 19703 if (ri.priority > lastPriority) { 19704 lastComponent = ri.activityInfo.getComponentName(); 19705 lastPriority = ri.priority; 19706 } else if (ri.priority == lastPriority) { 19707 // Two components found with same priority. 19708 lastComponent = null; 19709 } 19710 } 19711 return lastComponent; 19712 } 19713 19714 private Intent getHomeIntent() { 19715 Intent intent = new Intent(Intent.ACTION_MAIN); 19716 intent.addCategory(Intent.CATEGORY_HOME); 19717 intent.addCategory(Intent.CATEGORY_DEFAULT); 19718 return intent; 19719 } 19720 19721 private IntentFilter getHomeFilter() { 19722 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 19723 filter.addCategory(Intent.CATEGORY_HOME); 19724 filter.addCategory(Intent.CATEGORY_DEFAULT); 19725 return filter; 19726 } 19727 19728 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 19729 int userId) { 19730 Intent intent = getHomeIntent(); 19731 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 19732 PackageManager.GET_META_DATA, userId); 19733 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 19734 true, false, false, userId); 19735 19736 allHomeCandidates.clear(); 19737 if (list != null) { 19738 for (ResolveInfo ri : list) { 19739 allHomeCandidates.add(ri); 19740 } 19741 } 19742 return (preferred == null || preferred.activityInfo == null) 19743 ? null 19744 : new ComponentName(preferred.activityInfo.packageName, 19745 preferred.activityInfo.name); 19746 } 19747 19748 @Override 19749 public void setHomeActivity(ComponentName comp, int userId) { 19750 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 19751 return; 19752 } 19753 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 19754 getHomeActivitiesAsUser(homeActivities, userId); 19755 19756 boolean found = false; 19757 19758 final int size = homeActivities.size(); 19759 final ComponentName[] set = new ComponentName[size]; 19760 for (int i = 0; i < size; i++) { 19761 final ResolveInfo candidate = homeActivities.get(i); 19762 final ActivityInfo info = candidate.activityInfo; 19763 final ComponentName activityName = new ComponentName(info.packageName, info.name); 19764 set[i] = activityName; 19765 if (!found && activityName.equals(comp)) { 19766 found = true; 19767 } 19768 } 19769 if (!found) { 19770 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 19771 + userId); 19772 } 19773 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 19774 set, comp, userId); 19775 } 19776 19777 private @Nullable String getSetupWizardPackageName() { 19778 final Intent intent = new Intent(Intent.ACTION_MAIN); 19779 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 19780 19781 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 19782 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 19783 | MATCH_DISABLED_COMPONENTS, 19784 UserHandle.myUserId()); 19785 if (matches.size() == 1) { 19786 return matches.get(0).getComponentInfo().packageName; 19787 } else { 19788 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 19789 + ": matches=" + matches); 19790 return null; 19791 } 19792 } 19793 19794 private @Nullable String getStorageManagerPackageName() { 19795 final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE); 19796 19797 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 19798 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 19799 | MATCH_DISABLED_COMPONENTS, 19800 UserHandle.myUserId()); 19801 if (matches.size() == 1) { 19802 return matches.get(0).getComponentInfo().packageName; 19803 } else { 19804 Slog.e(TAG, "There should probably be exactly one storage manager; found " 19805 + matches.size() + ": matches=" + matches); 19806 return null; 19807 } 19808 } 19809 19810 @Override 19811 public void setApplicationEnabledSetting(String appPackageName, 19812 int newState, int flags, int userId, String callingPackage) { 19813 if (!sUserManager.exists(userId)) return; 19814 if (callingPackage == null) { 19815 callingPackage = Integer.toString(Binder.getCallingUid()); 19816 } 19817 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 19818 } 19819 19820 @Override 19821 public void setUpdateAvailable(String packageName, boolean updateAvailable) { 19822 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 19823 synchronized (mPackages) { 19824 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 19825 if (pkgSetting != null) { 19826 pkgSetting.setUpdateAvailable(updateAvailable); 19827 } 19828 } 19829 } 19830 19831 @Override 19832 public void setComponentEnabledSetting(ComponentName componentName, 19833 int newState, int flags, int userId) { 19834 if (!sUserManager.exists(userId)) return; 19835 setEnabledSetting(componentName.getPackageName(), 19836 componentName.getClassName(), newState, flags, userId, null); 19837 } 19838 19839 private void setEnabledSetting(final String packageName, String className, int newState, 19840 final int flags, int userId, String callingPackage) { 19841 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 19842 || newState == COMPONENT_ENABLED_STATE_ENABLED 19843 || newState == COMPONENT_ENABLED_STATE_DISABLED 19844 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 19845 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 19846 throw new IllegalArgumentException("Invalid new component state: " 19847 + newState); 19848 } 19849 PackageSetting pkgSetting; 19850 final int callingUid = Binder.getCallingUid(); 19851 final int permission; 19852 if (callingUid == Process.SYSTEM_UID) { 19853 permission = PackageManager.PERMISSION_GRANTED; 19854 } else { 19855 permission = mContext.checkCallingOrSelfPermission( 19856 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 19857 } 19858 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 19859 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 19860 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 19861 boolean sendNow = false; 19862 boolean isApp = (className == null); 19863 final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null); 19864 String componentName = isApp ? packageName : className; 19865 int packageUid = -1; 19866 ArrayList<String> components; 19867 19868 // reader 19869 synchronized (mPackages) { 19870 pkgSetting = mSettings.mPackages.get(packageName); 19871 if (pkgSetting == null) { 19872 if (!isCallerInstantApp) { 19873 if (className == null) { 19874 throw new IllegalArgumentException("Unknown package: " + packageName); 19875 } 19876 throw new IllegalArgumentException( 19877 "Unknown component: " + packageName + "/" + className); 19878 } else { 19879 // throw SecurityException to prevent leaking package information 19880 throw new SecurityException( 19881 "Attempt to change component state; " 19882 + "pid=" + Binder.getCallingPid() 19883 + ", uid=" + callingUid 19884 + (className == null 19885 ? ", package=" + packageName 19886 : ", component=" + packageName + "/" + className)); 19887 } 19888 } 19889 } 19890 19891 // Limit who can change which apps 19892 if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) { 19893 // Don't allow apps that don't have permission to modify other apps 19894 if (!allowedByPermission 19895 || filterAppAccessLPr(pkgSetting, callingUid, userId)) { 19896 throw new SecurityException( 19897 "Attempt to change component state; " 19898 + "pid=" + Binder.getCallingPid() 19899 + ", uid=" + callingUid 19900 + (className == null 19901 ? ", package=" + packageName 19902 : ", component=" + packageName + "/" + className)); 19903 } 19904 // Don't allow changing protected packages. 19905 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 19906 throw new SecurityException("Cannot disable a protected package: " + packageName); 19907 } 19908 } 19909 19910 synchronized (mPackages) { 19911 if (callingUid == Process.SHELL_UID 19912 && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) { 19913 // Shell can only change whole packages between ENABLED and DISABLED_USER states 19914 // unless it is a test package. 19915 int oldState = pkgSetting.getEnabled(userId); 19916 if (className == null 19917 && 19918 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 19919 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 19920 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 19921 && 19922 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 19923 || newState == COMPONENT_ENABLED_STATE_DEFAULT 19924 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 19925 // ok 19926 } else { 19927 throw new SecurityException( 19928 "Shell cannot change component state for " + packageName + "/" 19929 + className + " to " + newState); 19930 } 19931 } 19932 } 19933 if (className == null) { 19934 // We're dealing with an application/package level state change 19935 synchronized (mPackages) { 19936 if (pkgSetting.getEnabled(userId) == newState) { 19937 // Nothing to do 19938 return; 19939 } 19940 } 19941 // If we're enabling a system stub, there's a little more work to do. 19942 // Prior to enabling the package, we need to decompress the APK(s) to the 19943 // data partition and then replace the version on the system partition. 19944 final PackageParser.Package deletedPkg = pkgSetting.pkg; 19945 final boolean isSystemStub = deletedPkg.isStub 19946 && deletedPkg.isSystem(); 19947 if (isSystemStub 19948 && (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 19949 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)) { 19950 final File codePath = decompressPackage(deletedPkg); 19951 if (codePath == null) { 19952 Slog.e(TAG, "couldn't decompress pkg: " + pkgSetting.name); 19953 return; 19954 } 19955 // TODO remove direct parsing of the package object during internal cleanup 19956 // of scan package 19957 // We need to call parse directly here for no other reason than we need 19958 // the new package in order to disable the old one [we use the information 19959 // for some internal optimization to optionally create a new package setting 19960 // object on replace]. However, we can't get the package from the scan 19961 // because the scan modifies live structures and we need to remove the 19962 // old [system] package from the system before a scan can be attempted. 19963 // Once scan is indempotent we can remove this parse and use the package 19964 // object we scanned, prior to adding it to package settings. 19965 final PackageParser pp = new PackageParser(); 19966 pp.setSeparateProcesses(mSeparateProcesses); 19967 pp.setDisplayMetrics(mMetrics); 19968 pp.setCallback(mPackageParserCallback); 19969 final PackageParser.Package tmpPkg; 19970 try { 19971 final int parseFlags = mDefParseFlags 19972 | PackageParser.PARSE_MUST_BE_APK 19973 | PackageParser.PARSE_IS_SYSTEM 19974 | PackageParser.PARSE_IS_SYSTEM_DIR; 19975 tmpPkg = pp.parsePackage(codePath, parseFlags); 19976 } catch (PackageParserException e) { 19977 Slog.w(TAG, "Failed to parse compressed system package:" + pkgSetting.name, e); 19978 return; 19979 } 19980 synchronized (mInstallLock) { 19981 // Disable the stub and remove any package entries 19982 removePackageLI(deletedPkg, true); 19983 synchronized (mPackages) { 19984 disableSystemPackageLPw(deletedPkg, tmpPkg); 19985 } 19986 final PackageParser.Package pkg; 19987 try (PackageFreezer freezer = 19988 freezePackage(deletedPkg.packageName, "setEnabledSetting")) { 19989 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 19990 | PackageParser.PARSE_ENFORCE_CODE; 19991 pkg = scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/, 19992 0 /*currentTime*/, null /*user*/); 19993 prepareAppDataAfterInstallLIF(pkg); 19994 synchronized (mPackages) { 19995 try { 19996 updateSharedLibrariesLPr(pkg, null); 19997 } catch (PackageManagerException e) { 19998 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: ", e); 19999 } 20000 mPermissionManager.updatePermissions( 20001 pkg.packageName, pkg, true, mPackages.values(), 20002 mPermissionCallback); 20003 mSettings.writeLPr(); 20004 } 20005 } catch (PackageManagerException e) { 20006 // Whoops! Something went wrong; try to roll back to the stub 20007 Slog.w(TAG, "Failed to install compressed system package:" 20008 + pkgSetting.name, e); 20009 // Remove the failed install 20010 removeCodePathLI(codePath); 20011 20012 // Install the system package 20013 try (PackageFreezer freezer = 20014 freezePackage(deletedPkg.packageName, "setEnabledSetting")) { 20015 synchronized (mPackages) { 20016 // NOTE: The system package always needs to be enabled; even 20017 // if it's for a compressed stub. If we don't, installing the 20018 // system package fails during scan [scanning checks the disabled 20019 // packages]. We will reverse this later, after we've "installed" 20020 // the stub. 20021 // This leaves us in a fragile state; the stub should never be 20022 // enabled, so, cross your fingers and hope nothing goes wrong 20023 // until we can disable the package later. 20024 enableSystemPackageLPw(deletedPkg); 20025 } 20026 installPackageFromSystemLIF(new File(deletedPkg.codePath), 20027 false /*isPrivileged*/, null /*allUserHandles*/, 20028 null /*origUserHandles*/, null /*origPermissionsState*/, 20029 true /*writeSettings*/); 20030 } catch (PackageManagerException pme) { 20031 Slog.w(TAG, "Failed to restore system package:" 20032 + deletedPkg.packageName, pme); 20033 } finally { 20034 synchronized (mPackages) { 20035 mSettings.disableSystemPackageLPw( 20036 deletedPkg.packageName, true /*replaced*/); 20037 mSettings.writeLPr(); 20038 } 20039 } 20040 return; 20041 } 20042 clearAppDataLIF(pkg, UserHandle.USER_ALL, FLAG_STORAGE_DE 20043 | FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 20044 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 20045 mDexManager.notifyPackageUpdated(pkg.packageName, 20046 pkg.baseCodePath, pkg.splitCodePaths); 20047 } 20048 } 20049 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 20050 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 20051 // Don't care about who enables an app. 20052 callingPackage = null; 20053 } 20054 synchronized (mPackages) { 20055 pkgSetting.setEnabled(newState, userId, callingPackage); 20056 } 20057 } else { 20058 synchronized (mPackages) { 20059 // We're dealing with a component level state change 20060 // First, verify that this is a valid class name. 20061 PackageParser.Package pkg = pkgSetting.pkg; 20062 if (pkg == null || !pkg.hasComponentClassName(className)) { 20063 if (pkg != null && 20064 pkg.applicationInfo.targetSdkVersion >= 20065 Build.VERSION_CODES.JELLY_BEAN) { 20066 throw new IllegalArgumentException("Component class " + className 20067 + " does not exist in " + packageName); 20068 } else { 20069 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 20070 + className + " does not exist in " + packageName); 20071 } 20072 } 20073 switch (newState) { 20074 case COMPONENT_ENABLED_STATE_ENABLED: 20075 if (!pkgSetting.enableComponentLPw(className, userId)) { 20076 return; 20077 } 20078 break; 20079 case COMPONENT_ENABLED_STATE_DISABLED: 20080 if (!pkgSetting.disableComponentLPw(className, userId)) { 20081 return; 20082 } 20083 break; 20084 case COMPONENT_ENABLED_STATE_DEFAULT: 20085 if (!pkgSetting.restoreComponentLPw(className, userId)) { 20086 return; 20087 } 20088 break; 20089 default: 20090 Slog.e(TAG, "Invalid new component state: " + newState); 20091 return; 20092 } 20093 } 20094 } 20095 synchronized (mPackages) { 20096 scheduleWritePackageRestrictionsLocked(userId); 20097 updateSequenceNumberLP(pkgSetting, new int[] { userId }); 20098 final long callingId = Binder.clearCallingIdentity(); 20099 try { 20100 updateInstantAppInstallerLocked(packageName); 20101 } finally { 20102 Binder.restoreCallingIdentity(callingId); 20103 } 20104 components = mPendingBroadcasts.get(userId, packageName); 20105 final boolean newPackage = components == null; 20106 if (newPackage) { 20107 components = new ArrayList<String>(); 20108 } 20109 if (!components.contains(componentName)) { 20110 components.add(componentName); 20111 } 20112 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 20113 sendNow = true; 20114 // Purge entry from pending broadcast list if another one exists already 20115 // since we are sending one right away. 20116 mPendingBroadcasts.remove(userId, packageName); 20117 } else { 20118 if (newPackage) { 20119 mPendingBroadcasts.put(userId, packageName, components); 20120 } 20121 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 20122 // Schedule a message 20123 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 20124 } 20125 } 20126 } 20127 20128 long callingId = Binder.clearCallingIdentity(); 20129 try { 20130 if (sendNow) { 20131 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 20132 sendPackageChangedBroadcast(packageName, 20133 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 20134 } 20135 } finally { 20136 Binder.restoreCallingIdentity(callingId); 20137 } 20138 } 20139 20140 @Override 20141 public void flushPackageRestrictionsAsUser(int userId) { 20142 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 20143 return; 20144 } 20145 if (!sUserManager.exists(userId)) { 20146 return; 20147 } 20148 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 20149 false /* checkShell */, "flushPackageRestrictions"); 20150 synchronized (mPackages) { 20151 mSettings.writePackageRestrictionsLPr(userId); 20152 mDirtyUsers.remove(userId); 20153 if (mDirtyUsers.isEmpty()) { 20154 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 20155 } 20156 } 20157 } 20158 20159 private void sendPackageChangedBroadcast(String packageName, 20160 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 20161 if (DEBUG_INSTALL) 20162 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 20163 + componentNames); 20164 Bundle extras = new Bundle(4); 20165 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 20166 String nameList[] = new String[componentNames.size()]; 20167 componentNames.toArray(nameList); 20168 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 20169 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 20170 extras.putInt(Intent.EXTRA_UID, packageUid); 20171 // If this is not reporting a change of the overall package, then only send it 20172 // to registered receivers. We don't want to launch a swath of apps for every 20173 // little component state change. 20174 final int flags = !componentNames.contains(packageName) 20175 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 20176 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 20177 new int[] {UserHandle.getUserId(packageUid)}); 20178 } 20179 20180 @Override 20181 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 20182 if (!sUserManager.exists(userId)) return; 20183 final int callingUid = Binder.getCallingUid(); 20184 if (getInstantAppPackageName(callingUid) != null) { 20185 return; 20186 } 20187 final int permission = mContext.checkCallingOrSelfPermission( 20188 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 20189 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 20190 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 20191 true /* requireFullPermission */, true /* checkShell */, "stop package"); 20192 // writer 20193 synchronized (mPackages) { 20194 final PackageSetting ps = mSettings.mPackages.get(packageName); 20195 if (!filterAppAccessLPr(ps, callingUid, userId) 20196 && mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 20197 allowedByPermission, callingUid, userId)) { 20198 scheduleWritePackageRestrictionsLocked(userId); 20199 } 20200 } 20201 } 20202 20203 @Override 20204 public String getInstallerPackageName(String packageName) { 20205 final int callingUid = Binder.getCallingUid(); 20206 if (getInstantAppPackageName(callingUid) != null) { 20207 return null; 20208 } 20209 // reader 20210 synchronized (mPackages) { 20211 final PackageSetting ps = mSettings.mPackages.get(packageName); 20212 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 20213 return null; 20214 } 20215 return mSettings.getInstallerPackageNameLPr(packageName); 20216 } 20217 } 20218 20219 public boolean isOrphaned(String packageName) { 20220 // reader 20221 synchronized (mPackages) { 20222 return mSettings.isOrphaned(packageName); 20223 } 20224 } 20225 20226 @Override 20227 public int getApplicationEnabledSetting(String packageName, int userId) { 20228 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 20229 int callingUid = Binder.getCallingUid(); 20230 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 20231 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 20232 // reader 20233 synchronized (mPackages) { 20234 if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) { 20235 return COMPONENT_ENABLED_STATE_DISABLED; 20236 } 20237 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 20238 } 20239 } 20240 20241 @Override 20242 public int getComponentEnabledSetting(ComponentName component, int userId) { 20243 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 20244 int callingUid = Binder.getCallingUid(); 20245 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 20246 false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled"); 20247 synchronized (mPackages) { 20248 if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid, 20249 component, TYPE_UNKNOWN, userId)) { 20250 return COMPONENT_ENABLED_STATE_DISABLED; 20251 } 20252 return mSettings.getComponentEnabledSettingLPr(component, userId); 20253 } 20254 } 20255 20256 @Override 20257 public void enterSafeMode() { 20258 enforceSystemOrRoot("Only the system can request entering safe mode"); 20259 20260 if (!mSystemReady) { 20261 mSafeMode = true; 20262 } 20263 } 20264 20265 @Override 20266 public void systemReady() { 20267 enforceSystemOrRoot("Only the system can claim the system is ready"); 20268 20269 mSystemReady = true; 20270 final ContentResolver resolver = mContext.getContentResolver(); 20271 ContentObserver co = new ContentObserver(mHandler) { 20272 @Override 20273 public void onChange(boolean selfChange) { 20274 mEphemeralAppsDisabled = 20275 (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) || 20276 (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0); 20277 } 20278 }; 20279 mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global 20280 .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE), 20281 false, co, UserHandle.USER_SYSTEM); 20282 mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global 20283 .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM); 20284 co.onChange(true); 20285 20286 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 20287 // disabled after already being started. 20288 CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this, 20289 mContext.getContentResolver(), UserHandle.USER_SYSTEM); 20290 20291 // Read the compatibilty setting when the system is ready. 20292 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 20293 mContext.getContentResolver(), 20294 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 20295 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 20296 if (DEBUG_SETTINGS) { 20297 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 20298 } 20299 20300 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 20301 20302 synchronized (mPackages) { 20303 // Verify that all of the preferred activity components actually 20304 // exist. It is possible for applications to be updated and at 20305 // that point remove a previously declared activity component that 20306 // had been set as a preferred activity. We try to clean this up 20307 // the next time we encounter that preferred activity, but it is 20308 // possible for the user flow to never be able to return to that 20309 // situation so here we do a sanity check to make sure we haven't 20310 // left any junk around. 20311 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 20312 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 20313 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 20314 removed.clear(); 20315 for (PreferredActivity pa : pir.filterSet()) { 20316 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 20317 removed.add(pa); 20318 } 20319 } 20320 if (removed.size() > 0) { 20321 for (int r=0; r<removed.size(); r++) { 20322 PreferredActivity pa = removed.get(r); 20323 Slog.w(TAG, "Removing dangling preferred activity: " 20324 + pa.mPref.mComponent); 20325 pir.removeFilter(pa); 20326 } 20327 mSettings.writePackageRestrictionsLPr( 20328 mSettings.mPreferredActivities.keyAt(i)); 20329 } 20330 } 20331 20332 for (int userId : UserManagerService.getInstance().getUserIds()) { 20333 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 20334 grantPermissionsUserIds = ArrayUtils.appendInt( 20335 grantPermissionsUserIds, userId); 20336 } 20337 } 20338 } 20339 sUserManager.systemReady(); 20340 20341 // If we upgraded grant all default permissions before kicking off. 20342 for (int userId : grantPermissionsUserIds) { 20343 mDefaultPermissionPolicy.grantDefaultPermissions(mPackages.values(), userId); 20344 } 20345 20346 if (grantPermissionsUserIds == EMPTY_INT_ARRAY) { 20347 // If we did not grant default permissions, we preload from this the 20348 // default permission exceptions lazily to ensure we don't hit the 20349 // disk on a new user creation. 20350 mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions(); 20351 } 20352 20353 // Now that we've scanned all packages, and granted any default 20354 // permissions, ensure permissions are updated. Beware of dragons if you 20355 // try optimizing this. 20356 synchronized (mPackages) { 20357 mPermissionManager.updateAllPermissions( 20358 StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(), 20359 mPermissionCallback); 20360 } 20361 20362 // Kick off any messages waiting for system ready 20363 if (mPostSystemReadyMessages != null) { 20364 for (Message msg : mPostSystemReadyMessages) { 20365 msg.sendToTarget(); 20366 } 20367 mPostSystemReadyMessages = null; 20368 } 20369 20370 // Watch for external volumes that come and go over time 20371 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20372 storage.registerListener(mStorageListener); 20373 20374 mInstallerService.systemReady(); 20375 mPackageDexOptimizer.systemReady(); 20376 20377 StorageManagerInternal StorageManagerInternal = LocalServices.getService( 20378 StorageManagerInternal.class); 20379 StorageManagerInternal.addExternalStoragePolicy( 20380 new StorageManagerInternal.ExternalStorageMountPolicy() { 20381 @Override 20382 public int getMountMode(int uid, String packageName) { 20383 if (Process.isIsolated(uid)) { 20384 return Zygote.MOUNT_EXTERNAL_NONE; 20385 } 20386 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 20387 return Zygote.MOUNT_EXTERNAL_DEFAULT; 20388 } 20389 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 20390 return Zygote.MOUNT_EXTERNAL_DEFAULT; 20391 } 20392 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 20393 return Zygote.MOUNT_EXTERNAL_READ; 20394 } 20395 return Zygote.MOUNT_EXTERNAL_WRITE; 20396 } 20397 20398 @Override 20399 public boolean hasExternalStorage(int uid, String packageName) { 20400 return true; 20401 } 20402 }); 20403 20404 // Now that we're mostly running, clean up stale users and apps 20405 sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 20406 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 20407 20408 mPermissionManager.systemReady(); 20409 } 20410 20411 public void waitForAppDataPrepared() { 20412 if (mPrepareAppDataFuture == null) { 20413 return; 20414 } 20415 ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData"); 20416 mPrepareAppDataFuture = null; 20417 } 20418 20419 @Override 20420 public boolean isSafeMode() { 20421 // allow instant applications 20422 return mSafeMode; 20423 } 20424 20425 @Override 20426 public boolean hasSystemUidErrors() { 20427 // allow instant applications 20428 return mHasSystemUidErrors; 20429 } 20430 20431 static String arrayToString(int[] array) { 20432 StringBuffer buf = new StringBuffer(128); 20433 buf.append('['); 20434 if (array != null) { 20435 for (int i=0; i<array.length; i++) { 20436 if (i > 0) buf.append(", "); 20437 buf.append(array[i]); 20438 } 20439 } 20440 buf.append(']'); 20441 return buf.toString(); 20442 } 20443 20444 @Override 20445 public void onShellCommand(FileDescriptor in, FileDescriptor out, 20446 FileDescriptor err, String[] args, ShellCallback callback, 20447 ResultReceiver resultReceiver) { 20448 (new PackageManagerShellCommand(this)).exec( 20449 this, in, out, err, args, callback, resultReceiver); 20450 } 20451 20452 @Override 20453 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 20454 if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return; 20455 20456 DumpState dumpState = new DumpState(); 20457 boolean fullPreferred = false; 20458 boolean checkin = false; 20459 20460 String packageName = null; 20461 ArraySet<String> permissionNames = null; 20462 20463 int opti = 0; 20464 while (opti < args.length) { 20465 String opt = args[opti]; 20466 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 20467 break; 20468 } 20469 opti++; 20470 20471 if ("-a".equals(opt)) { 20472 // Right now we only know how to print all. 20473 } else if ("-h".equals(opt)) { 20474 pw.println("Package manager dump options:"); 20475 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 20476 pw.println(" --checkin: dump for a checkin"); 20477 pw.println(" -f: print details of intent filters"); 20478 pw.println(" -h: print this help"); 20479 pw.println(" cmd may be one of:"); 20480 pw.println(" l[ibraries]: list known shared libraries"); 20481 pw.println(" f[eatures]: list device features"); 20482 pw.println(" k[eysets]: print known keysets"); 20483 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 20484 pw.println(" perm[issions]: dump permissions"); 20485 pw.println(" permission [name ...]: dump declaration and use of given permission"); 20486 pw.println(" pref[erred]: print preferred package settings"); 20487 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 20488 pw.println(" prov[iders]: dump content providers"); 20489 pw.println(" p[ackages]: dump installed packages"); 20490 pw.println(" s[hared-users]: dump shared user IDs"); 20491 pw.println(" m[essages]: print collected runtime messages"); 20492 pw.println(" v[erifiers]: print package verifier info"); 20493 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 20494 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 20495 pw.println(" version: print database version info"); 20496 pw.println(" write: write current settings now"); 20497 pw.println(" installs: details about install sessions"); 20498 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 20499 pw.println(" dexopt: dump dexopt state"); 20500 pw.println(" compiler-stats: dump compiler statistics"); 20501 pw.println(" enabled-overlays: dump list of enabled overlay packages"); 20502 pw.println(" <package.name>: info about given package"); 20503 return; 20504 } else if ("--checkin".equals(opt)) { 20505 checkin = true; 20506 } else if ("-f".equals(opt)) { 20507 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 20508 } else if ("--proto".equals(opt)) { 20509 dumpProto(fd); 20510 return; 20511 } else { 20512 pw.println("Unknown argument: " + opt + "; use -h for help"); 20513 } 20514 } 20515 20516 // Is the caller requesting to dump a particular piece of data? 20517 if (opti < args.length) { 20518 String cmd = args[opti]; 20519 opti++; 20520 // Is this a package name? 20521 if ("android".equals(cmd) || cmd.contains(".")) { 20522 packageName = cmd; 20523 // When dumping a single package, we always dump all of its 20524 // filter information since the amount of data will be reasonable. 20525 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 20526 } else if ("check-permission".equals(cmd)) { 20527 if (opti >= args.length) { 20528 pw.println("Error: check-permission missing permission argument"); 20529 return; 20530 } 20531 String perm = args[opti]; 20532 opti++; 20533 if (opti >= args.length) { 20534 pw.println("Error: check-permission missing package argument"); 20535 return; 20536 } 20537 20538 String pkg = args[opti]; 20539 opti++; 20540 int user = UserHandle.getUserId(Binder.getCallingUid()); 20541 if (opti < args.length) { 20542 try { 20543 user = Integer.parseInt(args[opti]); 20544 } catch (NumberFormatException e) { 20545 pw.println("Error: check-permission user argument is not a number: " 20546 + args[opti]); 20547 return; 20548 } 20549 } 20550 20551 // Normalize package name to handle renamed packages and static libs 20552 pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST); 20553 20554 pw.println(checkPermission(perm, pkg, user)); 20555 return; 20556 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 20557 dumpState.setDump(DumpState.DUMP_LIBS); 20558 } else if ("f".equals(cmd) || "features".equals(cmd)) { 20559 dumpState.setDump(DumpState.DUMP_FEATURES); 20560 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 20561 if (opti >= args.length) { 20562 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 20563 | DumpState.DUMP_SERVICE_RESOLVERS 20564 | DumpState.DUMP_RECEIVER_RESOLVERS 20565 | DumpState.DUMP_CONTENT_RESOLVERS); 20566 } else { 20567 while (opti < args.length) { 20568 String name = args[opti]; 20569 if ("a".equals(name) || "activity".equals(name)) { 20570 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 20571 } else if ("s".equals(name) || "service".equals(name)) { 20572 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 20573 } else if ("r".equals(name) || "receiver".equals(name)) { 20574 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 20575 } else if ("c".equals(name) || "content".equals(name)) { 20576 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 20577 } else { 20578 pw.println("Error: unknown resolver table type: " + name); 20579 return; 20580 } 20581 opti++; 20582 } 20583 } 20584 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 20585 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 20586 } else if ("permission".equals(cmd)) { 20587 if (opti >= args.length) { 20588 pw.println("Error: permission requires permission name"); 20589 return; 20590 } 20591 permissionNames = new ArraySet<>(); 20592 while (opti < args.length) { 20593 permissionNames.add(args[opti]); 20594 opti++; 20595 } 20596 dumpState.setDump(DumpState.DUMP_PERMISSIONS 20597 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 20598 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 20599 dumpState.setDump(DumpState.DUMP_PREFERRED); 20600 } else if ("preferred-xml".equals(cmd)) { 20601 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 20602 if (opti < args.length && "--full".equals(args[opti])) { 20603 fullPreferred = true; 20604 opti++; 20605 } 20606 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 20607 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 20608 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 20609 dumpState.setDump(DumpState.DUMP_PACKAGES); 20610 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 20611 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 20612 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 20613 dumpState.setDump(DumpState.DUMP_PROVIDERS); 20614 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 20615 dumpState.setDump(DumpState.DUMP_MESSAGES); 20616 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 20617 dumpState.setDump(DumpState.DUMP_VERIFIERS); 20618 } else if ("i".equals(cmd) || "ifv".equals(cmd) 20619 || "intent-filter-verifiers".equals(cmd)) { 20620 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 20621 } else if ("version".equals(cmd)) { 20622 dumpState.setDump(DumpState.DUMP_VERSION); 20623 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 20624 dumpState.setDump(DumpState.DUMP_KEYSETS); 20625 } else if ("installs".equals(cmd)) { 20626 dumpState.setDump(DumpState.DUMP_INSTALLS); 20627 } else if ("frozen".equals(cmd)) { 20628 dumpState.setDump(DumpState.DUMP_FROZEN); 20629 } else if ("volumes".equals(cmd)) { 20630 dumpState.setDump(DumpState.DUMP_VOLUMES); 20631 } else if ("dexopt".equals(cmd)) { 20632 dumpState.setDump(DumpState.DUMP_DEXOPT); 20633 } else if ("compiler-stats".equals(cmd)) { 20634 dumpState.setDump(DumpState.DUMP_COMPILER_STATS); 20635 } else if ("changes".equals(cmd)) { 20636 dumpState.setDump(DumpState.DUMP_CHANGES); 20637 } else if ("write".equals(cmd)) { 20638 synchronized (mPackages) { 20639 mSettings.writeLPr(); 20640 pw.println("Settings written."); 20641 return; 20642 } 20643 } 20644 } 20645 20646 if (checkin) { 20647 pw.println("vers,1"); 20648 } 20649 20650 // reader 20651 synchronized (mPackages) { 20652 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 20653 if (!checkin) { 20654 if (dumpState.onTitlePrinted()) 20655 pw.println(); 20656 pw.println("Database versions:"); 20657 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 20658 } 20659 } 20660 20661 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 20662 if (!checkin) { 20663 if (dumpState.onTitlePrinted()) 20664 pw.println(); 20665 pw.println("Verifiers:"); 20666 pw.print(" Required: "); 20667 pw.print(mRequiredVerifierPackage); 20668 pw.print(" (uid="); 20669 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 20670 UserHandle.USER_SYSTEM)); 20671 pw.println(")"); 20672 } else if (mRequiredVerifierPackage != null) { 20673 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 20674 pw.print(","); 20675 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 20676 UserHandle.USER_SYSTEM)); 20677 } 20678 } 20679 20680 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 20681 packageName == null) { 20682 if (mIntentFilterVerifierComponent != null) { 20683 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 20684 if (!checkin) { 20685 if (dumpState.onTitlePrinted()) 20686 pw.println(); 20687 pw.println("Intent Filter Verifier:"); 20688 pw.print(" Using: "); 20689 pw.print(verifierPackageName); 20690 pw.print(" (uid="); 20691 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 20692 UserHandle.USER_SYSTEM)); 20693 pw.println(")"); 20694 } else if (verifierPackageName != null) { 20695 pw.print("ifv,"); pw.print(verifierPackageName); 20696 pw.print(","); 20697 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 20698 UserHandle.USER_SYSTEM)); 20699 } 20700 } else { 20701 pw.println(); 20702 pw.println("No Intent Filter Verifier available!"); 20703 } 20704 } 20705 20706 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 20707 boolean printedHeader = false; 20708 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 20709 while (it.hasNext()) { 20710 String libName = it.next(); 20711 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName); 20712 if (versionedLib == null) { 20713 continue; 20714 } 20715 final int versionCount = versionedLib.size(); 20716 for (int i = 0; i < versionCount; i++) { 20717 SharedLibraryEntry libEntry = versionedLib.valueAt(i); 20718 if (!checkin) { 20719 if (!printedHeader) { 20720 if (dumpState.onTitlePrinted()) 20721 pw.println(); 20722 pw.println("Libraries:"); 20723 printedHeader = true; 20724 } 20725 pw.print(" "); 20726 } else { 20727 pw.print("lib,"); 20728 } 20729 pw.print(libEntry.info.getName()); 20730 if (libEntry.info.isStatic()) { 20731 pw.print(" version=" + libEntry.info.getVersion()); 20732 } 20733 if (!checkin) { 20734 pw.print(" -> "); 20735 } 20736 if (libEntry.path != null) { 20737 pw.print(" (jar) "); 20738 pw.print(libEntry.path); 20739 } else { 20740 pw.print(" (apk) "); 20741 pw.print(libEntry.apk); 20742 } 20743 pw.println(); 20744 } 20745 } 20746 } 20747 20748 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 20749 if (dumpState.onTitlePrinted()) 20750 pw.println(); 20751 if (!checkin) { 20752 pw.println("Features:"); 20753 } 20754 20755 synchronized (mAvailableFeatures) { 20756 for (FeatureInfo feat : mAvailableFeatures.values()) { 20757 if (checkin) { 20758 pw.print("feat,"); 20759 pw.print(feat.name); 20760 pw.print(","); 20761 pw.println(feat.version); 20762 } else { 20763 pw.print(" "); 20764 pw.print(feat.name); 20765 if (feat.version > 0) { 20766 pw.print(" version="); 20767 pw.print(feat.version); 20768 } 20769 pw.println(); 20770 } 20771 } 20772 } 20773 } 20774 20775 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 20776 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 20777 : "Activity Resolver Table:", " ", packageName, 20778 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20779 dumpState.setTitlePrinted(true); 20780 } 20781 } 20782 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 20783 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 20784 : "Receiver Resolver Table:", " ", packageName, 20785 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20786 dumpState.setTitlePrinted(true); 20787 } 20788 } 20789 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 20790 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 20791 : "Service Resolver Table:", " ", packageName, 20792 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20793 dumpState.setTitlePrinted(true); 20794 } 20795 } 20796 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 20797 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 20798 : "Provider Resolver Table:", " ", packageName, 20799 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20800 dumpState.setTitlePrinted(true); 20801 } 20802 } 20803 20804 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 20805 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 20806 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 20807 int user = mSettings.mPreferredActivities.keyAt(i); 20808 if (pir.dump(pw, 20809 dumpState.getTitlePrinted() 20810 ? "\nPreferred Activities User " + user + ":" 20811 : "Preferred Activities User " + user + ":", " ", 20812 packageName, true, false)) { 20813 dumpState.setTitlePrinted(true); 20814 } 20815 } 20816 } 20817 20818 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 20819 pw.flush(); 20820 FileOutputStream fout = new FileOutputStream(fd); 20821 BufferedOutputStream str = new BufferedOutputStream(fout); 20822 XmlSerializer serializer = new FastXmlSerializer(); 20823 try { 20824 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 20825 serializer.startDocument(null, true); 20826 serializer.setFeature( 20827 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 20828 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 20829 serializer.endDocument(); 20830 serializer.flush(); 20831 } catch (IllegalArgumentException e) { 20832 pw.println("Failed writing: " + e); 20833 } catch (IllegalStateException e) { 20834 pw.println("Failed writing: " + e); 20835 } catch (IOException e) { 20836 pw.println("Failed writing: " + e); 20837 } 20838 } 20839 20840 if (!checkin 20841 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 20842 && packageName == null) { 20843 pw.println(); 20844 int count = mSettings.mPackages.size(); 20845 if (count == 0) { 20846 pw.println("No applications!"); 20847 pw.println(); 20848 } else { 20849 final String prefix = " "; 20850 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 20851 if (allPackageSettings.size() == 0) { 20852 pw.println("No domain preferred apps!"); 20853 pw.println(); 20854 } else { 20855 pw.println("App verification status:"); 20856 pw.println(); 20857 count = 0; 20858 for (PackageSetting ps : allPackageSettings) { 20859 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 20860 if (ivi == null || ivi.getPackageName() == null) continue; 20861 pw.println(prefix + "Package: " + ivi.getPackageName()); 20862 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 20863 pw.println(prefix + "Status: " + ivi.getStatusString()); 20864 pw.println(); 20865 count++; 20866 } 20867 if (count == 0) { 20868 pw.println(prefix + "No app verification established."); 20869 pw.println(); 20870 } 20871 for (int userId : sUserManager.getUserIds()) { 20872 pw.println("App linkages for user " + userId + ":"); 20873 pw.println(); 20874 count = 0; 20875 for (PackageSetting ps : allPackageSettings) { 20876 final long status = ps.getDomainVerificationStatusForUser(userId); 20877 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 20878 && !DEBUG_DOMAIN_VERIFICATION) { 20879 continue; 20880 } 20881 pw.println(prefix + "Package: " + ps.name); 20882 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 20883 String statusStr = IntentFilterVerificationInfo. 20884 getStatusStringFromValue(status); 20885 pw.println(prefix + "Status: " + statusStr); 20886 pw.println(); 20887 count++; 20888 } 20889 if (count == 0) { 20890 pw.println(prefix + "No configured app linkages."); 20891 pw.println(); 20892 } 20893 } 20894 } 20895 } 20896 } 20897 20898 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 20899 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 20900 } 20901 20902 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 20903 boolean printedSomething = false; 20904 for (PackageParser.Provider p : mProviders.mProviders.values()) { 20905 if (packageName != null && !packageName.equals(p.info.packageName)) { 20906 continue; 20907 } 20908 if (!printedSomething) { 20909 if (dumpState.onTitlePrinted()) 20910 pw.println(); 20911 pw.println("Registered ContentProviders:"); 20912 printedSomething = true; 20913 } 20914 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 20915 pw.print(" "); pw.println(p.toString()); 20916 } 20917 printedSomething = false; 20918 for (Map.Entry<String, PackageParser.Provider> entry : 20919 mProvidersByAuthority.entrySet()) { 20920 PackageParser.Provider p = entry.getValue(); 20921 if (packageName != null && !packageName.equals(p.info.packageName)) { 20922 continue; 20923 } 20924 if (!printedSomething) { 20925 if (dumpState.onTitlePrinted()) 20926 pw.println(); 20927 pw.println("ContentProvider Authorities:"); 20928 printedSomething = true; 20929 } 20930 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 20931 pw.print(" "); pw.println(p.toString()); 20932 if (p.info != null && p.info.applicationInfo != null) { 20933 final String appInfo = p.info.applicationInfo.toString(); 20934 pw.print(" applicationInfo="); pw.println(appInfo); 20935 } 20936 } 20937 } 20938 20939 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 20940 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 20941 } 20942 20943 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 20944 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 20945 } 20946 20947 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 20948 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 20949 } 20950 20951 if (dumpState.isDumping(DumpState.DUMP_CHANGES)) { 20952 if (dumpState.onTitlePrinted()) pw.println(); 20953 pw.println("Package Changes:"); 20954 pw.print(" Sequence number="); pw.println(mChangedPackagesSequenceNumber); 20955 final int K = mChangedPackages.size(); 20956 for (int i = 0; i < K; i++) { 20957 final SparseArray<String> changes = mChangedPackages.valueAt(i); 20958 pw.print(" User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":"); 20959 final int N = changes.size(); 20960 if (N == 0) { 20961 pw.print(" "); pw.println("No packages changed"); 20962 } else { 20963 for (int j = 0; j < N; j++) { 20964 final String pkgName = changes.valueAt(j); 20965 final int sequenceNumber = changes.keyAt(j); 20966 pw.print(" "); 20967 pw.print("seq="); 20968 pw.print(sequenceNumber); 20969 pw.print(", package="); 20970 pw.println(pkgName); 20971 } 20972 } 20973 } 20974 } 20975 20976 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 20977 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 20978 } 20979 20980 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 20981 // XXX should handle packageName != null by dumping only install data that 20982 // the given package is involved with. 20983 if (dumpState.onTitlePrinted()) pw.println(); 20984 20985 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 20986 ipw.println(); 20987 ipw.println("Frozen packages:"); 20988 ipw.increaseIndent(); 20989 if (mFrozenPackages.size() == 0) { 20990 ipw.println("(none)"); 20991 } else { 20992 for (int i = 0; i < mFrozenPackages.size(); i++) { 20993 ipw.println(mFrozenPackages.valueAt(i)); 20994 } 20995 } 20996 ipw.decreaseIndent(); 20997 } 20998 20999 if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) { 21000 if (dumpState.onTitlePrinted()) pw.println(); 21001 21002 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 21003 ipw.println(); 21004 ipw.println("Loaded volumes:"); 21005 ipw.increaseIndent(); 21006 if (mLoadedVolumes.size() == 0) { 21007 ipw.println("(none)"); 21008 } else { 21009 for (int i = 0; i < mLoadedVolumes.size(); i++) { 21010 ipw.println(mLoadedVolumes.valueAt(i)); 21011 } 21012 } 21013 ipw.decreaseIndent(); 21014 } 21015 21016 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 21017 if (dumpState.onTitlePrinted()) pw.println(); 21018 dumpDexoptStateLPr(pw, packageName); 21019 } 21020 21021 if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) { 21022 if (dumpState.onTitlePrinted()) pw.println(); 21023 dumpCompilerStatsLPr(pw, packageName); 21024 } 21025 21026 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 21027 if (dumpState.onTitlePrinted()) pw.println(); 21028 mSettings.dumpReadMessagesLPr(pw, dumpState); 21029 21030 pw.println(); 21031 pw.println("Package warning messages:"); 21032 BufferedReader in = null; 21033 String line = null; 21034 try { 21035 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 21036 while ((line = in.readLine()) != null) { 21037 if (line.contains("ignored: updated version")) continue; 21038 pw.println(line); 21039 } 21040 } catch (IOException ignored) { 21041 } finally { 21042 IoUtils.closeQuietly(in); 21043 } 21044 } 21045 21046 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 21047 BufferedReader in = null; 21048 String line = null; 21049 try { 21050 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 21051 while ((line = in.readLine()) != null) { 21052 if (line.contains("ignored: updated version")) continue; 21053 pw.print("msg,"); 21054 pw.println(line); 21055 } 21056 } catch (IOException ignored) { 21057 } finally { 21058 IoUtils.closeQuietly(in); 21059 } 21060 } 21061 } 21062 21063 // PackageInstaller should be called outside of mPackages lock 21064 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 21065 // XXX should handle packageName != null by dumping only install data that 21066 // the given package is involved with. 21067 if (dumpState.onTitlePrinted()) pw.println(); 21068 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 21069 } 21070 } 21071 21072 private void dumpProto(FileDescriptor fd) { 21073 final ProtoOutputStream proto = new ProtoOutputStream(fd); 21074 21075 synchronized (mPackages) { 21076 final long requiredVerifierPackageToken = 21077 proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE); 21078 proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage); 21079 proto.write( 21080 PackageServiceDumpProto.PackageShortProto.UID, 21081 getPackageUid( 21082 mRequiredVerifierPackage, 21083 MATCH_DEBUG_TRIAGED_MISSING, 21084 UserHandle.USER_SYSTEM)); 21085 proto.end(requiredVerifierPackageToken); 21086 21087 if (mIntentFilterVerifierComponent != null) { 21088 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 21089 final long verifierPackageToken = 21090 proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE); 21091 proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName); 21092 proto.write( 21093 PackageServiceDumpProto.PackageShortProto.UID, 21094 getPackageUid( 21095 verifierPackageName, 21096 MATCH_DEBUG_TRIAGED_MISSING, 21097 UserHandle.USER_SYSTEM)); 21098 proto.end(verifierPackageToken); 21099 } 21100 21101 dumpSharedLibrariesProto(proto); 21102 dumpFeaturesProto(proto); 21103 mSettings.dumpPackagesProto(proto); 21104 mSettings.dumpSharedUsersProto(proto); 21105 dumpMessagesProto(proto); 21106 } 21107 proto.flush(); 21108 } 21109 21110 private void dumpMessagesProto(ProtoOutputStream proto) { 21111 BufferedReader in = null; 21112 String line = null; 21113 try { 21114 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 21115 while ((line = in.readLine()) != null) { 21116 if (line.contains("ignored: updated version")) continue; 21117 proto.write(PackageServiceDumpProto.MESSAGES, line); 21118 } 21119 } catch (IOException ignored) { 21120 } finally { 21121 IoUtils.closeQuietly(in); 21122 } 21123 } 21124 21125 private void dumpFeaturesProto(ProtoOutputStream proto) { 21126 synchronized (mAvailableFeatures) { 21127 final int count = mAvailableFeatures.size(); 21128 for (int i = 0; i < count; i++) { 21129 mAvailableFeatures.valueAt(i).writeToProto(proto, PackageServiceDumpProto.FEATURES); 21130 } 21131 } 21132 } 21133 21134 private void dumpSharedLibrariesProto(ProtoOutputStream proto) { 21135 final int count = mSharedLibraries.size(); 21136 for (int i = 0; i < count; i++) { 21137 final String libName = mSharedLibraries.keyAt(i); 21138 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName); 21139 if (versionedLib == null) { 21140 continue; 21141 } 21142 final int versionCount = versionedLib.size(); 21143 for (int j = 0; j < versionCount; j++) { 21144 final SharedLibraryEntry libEntry = versionedLib.valueAt(j); 21145 final long sharedLibraryToken = 21146 proto.start(PackageServiceDumpProto.SHARED_LIBRARIES); 21147 proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName()); 21148 final boolean isJar = (libEntry.path != null); 21149 proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar); 21150 if (isJar) { 21151 proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path); 21152 } else { 21153 proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk); 21154 } 21155 proto.end(sharedLibraryToken); 21156 } 21157 } 21158 } 21159 21160 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 21161 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " "); 21162 ipw.println(); 21163 ipw.println("Dexopt state:"); 21164 ipw.increaseIndent(); 21165 Collection<PackageParser.Package> packages = null; 21166 if (packageName != null) { 21167 PackageParser.Package targetPackage = mPackages.get(packageName); 21168 if (targetPackage != null) { 21169 packages = Collections.singletonList(targetPackage); 21170 } else { 21171 ipw.println("Unable to find package: " + packageName); 21172 return; 21173 } 21174 } else { 21175 packages = mPackages.values(); 21176 } 21177 21178 for (PackageParser.Package pkg : packages) { 21179 ipw.println("[" + pkg.packageName + "]"); 21180 ipw.increaseIndent(); 21181 mPackageDexOptimizer.dumpDexoptState(ipw, pkg, 21182 mDexManager.getPackageUseInfoOrDefault(pkg.packageName)); 21183 ipw.decreaseIndent(); 21184 } 21185 } 21186 21187 private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) { 21188 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " "); 21189 ipw.println(); 21190 ipw.println("Compiler stats:"); 21191 ipw.increaseIndent(); 21192 Collection<PackageParser.Package> packages = null; 21193 if (packageName != null) { 21194 PackageParser.Package targetPackage = mPackages.get(packageName); 21195 if (targetPackage != null) { 21196 packages = Collections.singletonList(targetPackage); 21197 } else { 21198 ipw.println("Unable to find package: " + packageName); 21199 return; 21200 } 21201 } else { 21202 packages = mPackages.values(); 21203 } 21204 21205 for (PackageParser.Package pkg : packages) { 21206 ipw.println("[" + pkg.packageName + "]"); 21207 ipw.increaseIndent(); 21208 21209 CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName); 21210 if (stats == null) { 21211 ipw.println("(No recorded stats)"); 21212 } else { 21213 stats.dump(ipw); 21214 } 21215 ipw.decreaseIndent(); 21216 } 21217 } 21218 21219 private String dumpDomainString(String packageName) { 21220 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 21221 .getList(); 21222 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 21223 21224 ArraySet<String> result = new ArraySet<>(); 21225 if (iviList.size() > 0) { 21226 for (IntentFilterVerificationInfo ivi : iviList) { 21227 for (String host : ivi.getDomains()) { 21228 result.add(host); 21229 } 21230 } 21231 } 21232 if (filters != null && filters.size() > 0) { 21233 for (IntentFilter filter : filters) { 21234 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 21235 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 21236 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 21237 result.addAll(filter.getHostsList()); 21238 } 21239 } 21240 } 21241 21242 StringBuilder sb = new StringBuilder(result.size() * 16); 21243 for (String domain : result) { 21244 if (sb.length() > 0) sb.append(" "); 21245 sb.append(domain); 21246 } 21247 return sb.toString(); 21248 } 21249 21250 // ------- apps on sdcard specific code ------- 21251 static final boolean DEBUG_SD_INSTALL = false; 21252 21253 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 21254 21255 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 21256 21257 private boolean mMediaMounted = false; 21258 21259 static String getEncryptKey() { 21260 try { 21261 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 21262 SD_ENCRYPTION_KEYSTORE_NAME); 21263 if (sdEncKey == null) { 21264 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 21265 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 21266 if (sdEncKey == null) { 21267 Slog.e(TAG, "Failed to create encryption keys"); 21268 return null; 21269 } 21270 } 21271 return sdEncKey; 21272 } catch (NoSuchAlgorithmException nsae) { 21273 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 21274 return null; 21275 } catch (IOException ioe) { 21276 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 21277 return null; 21278 } 21279 } 21280 21281 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21282 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 21283 final int size = infos.size(); 21284 final String[] packageNames = new String[size]; 21285 final int[] packageUids = new int[size]; 21286 for (int i = 0; i < size; i++) { 21287 final ApplicationInfo info = infos.get(i); 21288 packageNames[i] = info.packageName; 21289 packageUids[i] = info.uid; 21290 } 21291 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 21292 finishedReceiver); 21293 } 21294 21295 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21296 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 21297 sendResourcesChangedBroadcast(mediaStatus, replacing, 21298 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 21299 } 21300 21301 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21302 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 21303 int size = pkgList.length; 21304 if (size > 0) { 21305 // Send broadcasts here 21306 Bundle extras = new Bundle(); 21307 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 21308 if (uidArr != null) { 21309 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 21310 } 21311 if (replacing) { 21312 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 21313 } 21314 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 21315 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 21316 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 21317 } 21318 } 21319 21320 private void loadPrivatePackages(final VolumeInfo vol) { 21321 mHandler.post(new Runnable() { 21322 @Override 21323 public void run() { 21324 loadPrivatePackagesInner(vol); 21325 } 21326 }); 21327 } 21328 21329 private void loadPrivatePackagesInner(VolumeInfo vol) { 21330 final String volumeUuid = vol.fsUuid; 21331 if (TextUtils.isEmpty(volumeUuid)) { 21332 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 21333 return; 21334 } 21335 21336 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 21337 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 21338 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 21339 21340 final VersionInfo ver; 21341 final List<PackageSetting> packages; 21342 synchronized (mPackages) { 21343 ver = mSettings.findOrCreateVersion(volumeUuid); 21344 packages = mSettings.getVolumePackagesLPr(volumeUuid); 21345 } 21346 21347 for (PackageSetting ps : packages) { 21348 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 21349 synchronized (mInstallLock) { 21350 final PackageParser.Package pkg; 21351 try { 21352 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 21353 loaded.add(pkg.applicationInfo); 21354 21355 } catch (PackageManagerException e) { 21356 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 21357 } 21358 21359 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 21360 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 21361 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 21362 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 21363 } 21364 } 21365 } 21366 21367 // Reconcile app data for all started/unlocked users 21368 final StorageManager sm = mContext.getSystemService(StorageManager.class); 21369 final UserManager um = mContext.getSystemService(UserManager.class); 21370 UserManagerInternal umInternal = getUserManagerInternal(); 21371 for (UserInfo user : um.getUsers()) { 21372 final int flags; 21373 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 21374 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 21375 } else if (umInternal.isUserRunning(user.id)) { 21376 flags = StorageManager.FLAG_STORAGE_DE; 21377 } else { 21378 continue; 21379 } 21380 21381 try { 21382 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 21383 synchronized (mInstallLock) { 21384 reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */); 21385 } 21386 } catch (IllegalStateException e) { 21387 // Device was probably ejected, and we'll process that event momentarily 21388 Slog.w(TAG, "Failed to prepare storage: " + e); 21389 } 21390 } 21391 21392 synchronized (mPackages) { 21393 final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion); 21394 if (sdkUpdated) { 21395 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 21396 + mSdkVersion + "; regranting permissions for " + volumeUuid); 21397 } 21398 mPermissionManager.updateAllPermissions(volumeUuid, sdkUpdated, mPackages.values(), 21399 mPermissionCallback); 21400 21401 // Yay, everything is now upgraded 21402 ver.forceCurrent(); 21403 21404 mSettings.writeLPr(); 21405 } 21406 21407 for (PackageFreezer freezer : freezers) { 21408 freezer.close(); 21409 } 21410 21411 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 21412 sendResourcesChangedBroadcast(true, false, loaded, null); 21413 mLoadedVolumes.add(vol.getId()); 21414 } 21415 21416 private void unloadPrivatePackages(final VolumeInfo vol) { 21417 mHandler.post(new Runnable() { 21418 @Override 21419 public void run() { 21420 unloadPrivatePackagesInner(vol); 21421 } 21422 }); 21423 } 21424 21425 private void unloadPrivatePackagesInner(VolumeInfo vol) { 21426 final String volumeUuid = vol.fsUuid; 21427 if (TextUtils.isEmpty(volumeUuid)) { 21428 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 21429 return; 21430 } 21431 21432 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 21433 synchronized (mInstallLock) { 21434 synchronized (mPackages) { 21435 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 21436 for (PackageSetting ps : packages) { 21437 if (ps.pkg == null) continue; 21438 21439 final ApplicationInfo info = ps.pkg.applicationInfo; 21440 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 21441 final PackageRemovedInfo outInfo = new PackageRemovedInfo(this); 21442 21443 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 21444 "unloadPrivatePackagesInner")) { 21445 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 21446 false, null)) { 21447 unloaded.add(info); 21448 } else { 21449 Slog.w(TAG, "Failed to unload " + ps.codePath); 21450 } 21451 } 21452 21453 // Try very hard to release any references to this package 21454 // so we don't risk the system server being killed due to 21455 // open FDs 21456 AttributeCache.instance().removePackage(ps.name); 21457 } 21458 21459 mSettings.writeLPr(); 21460 } 21461 } 21462 21463 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 21464 sendResourcesChangedBroadcast(false, false, unloaded, null); 21465 mLoadedVolumes.remove(vol.getId()); 21466 21467 // Try very hard to release any references to this path so we don't risk 21468 // the system server being killed due to open FDs 21469 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 21470 21471 for (int i = 0; i < 3; i++) { 21472 System.gc(); 21473 System.runFinalization(); 21474 } 21475 } 21476 21477 private void assertPackageKnown(String volumeUuid, String packageName) 21478 throws PackageManagerException { 21479 synchronized (mPackages) { 21480 // Normalize package name to handle renamed packages 21481 packageName = normalizePackageNameLPr(packageName); 21482 21483 final PackageSetting ps = mSettings.mPackages.get(packageName); 21484 if (ps == null) { 21485 throw new PackageManagerException("Package " + packageName + " is unknown"); 21486 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 21487 throw new PackageManagerException( 21488 "Package " + packageName + " found on unknown volume " + volumeUuid 21489 + "; expected volume " + ps.volumeUuid); 21490 } 21491 } 21492 } 21493 21494 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 21495 throws PackageManagerException { 21496 synchronized (mPackages) { 21497 // Normalize package name to handle renamed packages 21498 packageName = normalizePackageNameLPr(packageName); 21499 21500 final PackageSetting ps = mSettings.mPackages.get(packageName); 21501 if (ps == null) { 21502 throw new PackageManagerException("Package " + packageName + " is unknown"); 21503 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 21504 throw new PackageManagerException( 21505 "Package " + packageName + " found on unknown volume " + volumeUuid 21506 + "; expected volume " + ps.volumeUuid); 21507 } else if (!ps.getInstalled(userId)) { 21508 throw new PackageManagerException( 21509 "Package " + packageName + " not installed for user " + userId); 21510 } 21511 } 21512 } 21513 21514 private List<String> collectAbsoluteCodePaths() { 21515 synchronized (mPackages) { 21516 List<String> codePaths = new ArrayList<>(); 21517 final int packageCount = mSettings.mPackages.size(); 21518 for (int i = 0; i < packageCount; i++) { 21519 final PackageSetting ps = mSettings.mPackages.valueAt(i); 21520 codePaths.add(ps.codePath.getAbsolutePath()); 21521 } 21522 return codePaths; 21523 } 21524 } 21525 21526 /** 21527 * Examine all apps present on given mounted volume, and destroy apps that 21528 * aren't expected, either due to uninstallation or reinstallation on 21529 * another volume. 21530 */ 21531 private void reconcileApps(String volumeUuid) { 21532 List<String> absoluteCodePaths = collectAbsoluteCodePaths(); 21533 List<File> filesToDelete = null; 21534 21535 final File[] files = FileUtils.listFilesOrEmpty( 21536 Environment.getDataAppDirectory(volumeUuid)); 21537 for (File file : files) { 21538 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 21539 && !PackageInstallerService.isStageName(file.getName()); 21540 if (!isPackage) { 21541 // Ignore entries which are not packages 21542 continue; 21543 } 21544 21545 String absolutePath = file.getAbsolutePath(); 21546 21547 boolean pathValid = false; 21548 final int absoluteCodePathCount = absoluteCodePaths.size(); 21549 for (int i = 0; i < absoluteCodePathCount; i++) { 21550 String absoluteCodePath = absoluteCodePaths.get(i); 21551 if (absolutePath.startsWith(absoluteCodePath)) { 21552 pathValid = true; 21553 break; 21554 } 21555 } 21556 21557 if (!pathValid) { 21558 if (filesToDelete == null) { 21559 filesToDelete = new ArrayList<>(); 21560 } 21561 filesToDelete.add(file); 21562 } 21563 } 21564 21565 if (filesToDelete != null) { 21566 final int fileToDeleteCount = filesToDelete.size(); 21567 for (int i = 0; i < fileToDeleteCount; i++) { 21568 File fileToDelete = filesToDelete.get(i); 21569 logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete); 21570 synchronized (mInstallLock) { 21571 removeCodePathLI(fileToDelete); 21572 } 21573 } 21574 } 21575 } 21576 21577 /** 21578 * Reconcile all app data for the given user. 21579 * <p> 21580 * Verifies that directories exist and that ownership and labeling is 21581 * correct for all installed apps on all mounted volumes. 21582 */ 21583 void reconcileAppsData(int userId, int flags, boolean migrateAppsData) { 21584 final StorageManager storage = mContext.getSystemService(StorageManager.class); 21585 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 21586 final String volumeUuid = vol.getFsUuid(); 21587 synchronized (mInstallLock) { 21588 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData); 21589 } 21590 } 21591 } 21592 21593 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags, 21594 boolean migrateAppData) { 21595 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */); 21596 } 21597 21598 /** 21599 * Reconcile all app data on given mounted volume. 21600 * <p> 21601 * Destroys app data that isn't expected, either due to uninstallation or 21602 * reinstallation on another volume. 21603 * <p> 21604 * Verifies that directories exist and that ownership and labeling is 21605 * correct for all installed apps. 21606 * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true) 21607 */ 21608 private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags, 21609 boolean migrateAppData, boolean onlyCoreApps) { 21610 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 21611 + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData); 21612 List<String> result = onlyCoreApps ? new ArrayList<>() : null; 21613 21614 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 21615 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 21616 21617 // First look for stale data that doesn't belong, and check if things 21618 // have changed since we did our last restorecon 21619 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 21620 if (StorageManager.isFileEncryptedNativeOrEmulated() 21621 && !StorageManager.isUserKeyUnlocked(userId)) { 21622 throw new RuntimeException( 21623 "Yikes, someone asked us to reconcile CE storage while " + userId 21624 + " was still locked; this would have caused massive data loss!"); 21625 } 21626 21627 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 21628 for (File file : files) { 21629 final String packageName = file.getName(); 21630 try { 21631 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 21632 } catch (PackageManagerException e) { 21633 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 21634 try { 21635 mInstaller.destroyAppData(volumeUuid, packageName, userId, 21636 StorageManager.FLAG_STORAGE_CE, 0); 21637 } catch (InstallerException e2) { 21638 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 21639 } 21640 } 21641 } 21642 } 21643 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 21644 final File[] files = FileUtils.listFilesOrEmpty(deDir); 21645 for (File file : files) { 21646 final String packageName = file.getName(); 21647 try { 21648 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 21649 } catch (PackageManagerException e) { 21650 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 21651 try { 21652 mInstaller.destroyAppData(volumeUuid, packageName, userId, 21653 StorageManager.FLAG_STORAGE_DE, 0); 21654 } catch (InstallerException e2) { 21655 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 21656 } 21657 } 21658 } 21659 } 21660 21661 // Ensure that data directories are ready to roll for all packages 21662 // installed for this volume and user 21663 final List<PackageSetting> packages; 21664 synchronized (mPackages) { 21665 packages = mSettings.getVolumePackagesLPr(volumeUuid); 21666 } 21667 int preparedCount = 0; 21668 for (PackageSetting ps : packages) { 21669 final String packageName = ps.name; 21670 if (ps.pkg == null) { 21671 Slog.w(TAG, "Odd, missing scanned package " + packageName); 21672 // TODO: might be due to legacy ASEC apps; we should circle back 21673 // and reconcile again once they're scanned 21674 continue; 21675 } 21676 // Skip non-core apps if requested 21677 if (onlyCoreApps && !ps.pkg.coreApp) { 21678 result.add(packageName); 21679 continue; 21680 } 21681 21682 if (ps.getInstalled(userId)) { 21683 prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData); 21684 preparedCount++; 21685 } 21686 } 21687 21688 Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages"); 21689 return result; 21690 } 21691 21692 /** 21693 * Prepare app data for the given app just after it was installed or 21694 * upgraded. This method carefully only touches users that it's installed 21695 * for, and it forces a restorecon to handle any seinfo changes. 21696 * <p> 21697 * Verifies that directories exist and that ownership and labeling is 21698 * correct for all installed apps. If there is an ownership mismatch, it 21699 * will try recovering system apps by wiping data; third-party app data is 21700 * left intact. 21701 * <p> 21702 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 21703 */ 21704 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 21705 final PackageSetting ps; 21706 synchronized (mPackages) { 21707 ps = mSettings.mPackages.get(pkg.packageName); 21708 mSettings.writeKernelMappingLPr(ps); 21709 } 21710 21711 final UserManager um = mContext.getSystemService(UserManager.class); 21712 UserManagerInternal umInternal = getUserManagerInternal(); 21713 for (UserInfo user : um.getUsers()) { 21714 final int flags; 21715 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 21716 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 21717 } else if (umInternal.isUserRunning(user.id)) { 21718 flags = StorageManager.FLAG_STORAGE_DE; 21719 } else { 21720 continue; 21721 } 21722 21723 if (ps.getInstalled(user.id)) { 21724 // TODO: when user data is locked, mark that we're still dirty 21725 prepareAppDataLIF(pkg, user.id, flags); 21726 } 21727 } 21728 } 21729 21730 /** 21731 * Prepare app data for the given app. 21732 * <p> 21733 * Verifies that directories exist and that ownership and labeling is 21734 * correct for all installed apps. If there is an ownership mismatch, this 21735 * will try recovering system apps by wiping data; third-party app data is 21736 * left intact. 21737 */ 21738 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 21739 if (pkg == null) { 21740 Slog.wtf(TAG, "Package was null!", new Throwable()); 21741 return; 21742 } 21743 prepareAppDataLeafLIF(pkg, userId, flags); 21744 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 21745 for (int i = 0; i < childCount; i++) { 21746 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 21747 } 21748 } 21749 21750 private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags, 21751 boolean maybeMigrateAppData) { 21752 prepareAppDataLIF(pkg, userId, flags); 21753 21754 if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) { 21755 // We may have just shuffled around app data directories, so 21756 // prepare them one more time 21757 prepareAppDataLIF(pkg, userId, flags); 21758 } 21759 } 21760 21761 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 21762 if (DEBUG_APP_DATA) { 21763 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 21764 + Integer.toHexString(flags)); 21765 } 21766 21767 final String volumeUuid = pkg.volumeUuid; 21768 final String packageName = pkg.packageName; 21769 final ApplicationInfo app = pkg.applicationInfo; 21770 final int appId = UserHandle.getAppId(app.uid); 21771 21772 Preconditions.checkNotNull(app.seInfo); 21773 21774 long ceDataInode = -1; 21775 try { 21776 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 21777 appId, app.seInfo, app.targetSdkVersion); 21778 } catch (InstallerException e) { 21779 if (app.isSystemApp()) { 21780 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 21781 + ", but trying to recover: " + e); 21782 destroyAppDataLeafLIF(pkg, userId, flags); 21783 try { 21784 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 21785 appId, app.seInfo, app.targetSdkVersion); 21786 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 21787 } catch (InstallerException e2) { 21788 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 21789 } 21790 } else { 21791 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 21792 } 21793 } 21794 21795 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) { 21796 // TODO: mark this structure as dirty so we persist it! 21797 synchronized (mPackages) { 21798 final PackageSetting ps = mSettings.mPackages.get(packageName); 21799 if (ps != null) { 21800 ps.setCeDataInode(ceDataInode, userId); 21801 } 21802 } 21803 } 21804 21805 prepareAppDataContentsLeafLIF(pkg, userId, flags); 21806 } 21807 21808 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 21809 if (pkg == null) { 21810 Slog.wtf(TAG, "Package was null!", new Throwable()); 21811 return; 21812 } 21813 prepareAppDataContentsLeafLIF(pkg, userId, flags); 21814 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 21815 for (int i = 0; i < childCount; i++) { 21816 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 21817 } 21818 } 21819 21820 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 21821 final String volumeUuid = pkg.volumeUuid; 21822 final String packageName = pkg.packageName; 21823 final ApplicationInfo app = pkg.applicationInfo; 21824 21825 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 21826 // Create a native library symlink only if we have native libraries 21827 // and if the native libraries are 32 bit libraries. We do not provide 21828 // this symlink for 64 bit libraries. 21829 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 21830 final String nativeLibPath = app.nativeLibraryDir; 21831 try { 21832 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 21833 nativeLibPath, userId); 21834 } catch (InstallerException e) { 21835 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 21836 } 21837 } 21838 } 21839 } 21840 21841 /** 21842 * For system apps on non-FBE devices, this method migrates any existing 21843 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 21844 * requested by the app. 21845 */ 21846 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 21847 if (pkg.isSystem() && !StorageManager.isFileEncryptedNativeOrEmulated() 21848 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 21849 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 21850 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 21851 try { 21852 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 21853 storageTarget); 21854 } catch (InstallerException e) { 21855 logCriticalInfo(Log.WARN, 21856 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 21857 } 21858 return true; 21859 } else { 21860 return false; 21861 } 21862 } 21863 21864 public PackageFreezer freezePackage(String packageName, String killReason) { 21865 return freezePackage(packageName, UserHandle.USER_ALL, killReason); 21866 } 21867 21868 public PackageFreezer freezePackage(String packageName, int userId, String killReason) { 21869 return new PackageFreezer(packageName, userId, killReason); 21870 } 21871 21872 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 21873 String killReason) { 21874 return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason); 21875 } 21876 21877 public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags, 21878 String killReason) { 21879 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 21880 return new PackageFreezer(); 21881 } else { 21882 return freezePackage(packageName, userId, killReason); 21883 } 21884 } 21885 21886 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 21887 String killReason) { 21888 return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason); 21889 } 21890 21891 public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags, 21892 String killReason) { 21893 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 21894 return new PackageFreezer(); 21895 } else { 21896 return freezePackage(packageName, userId, killReason); 21897 } 21898 } 21899 21900 /** 21901 * Class that freezes and kills the given package upon creation, and 21902 * unfreezes it upon closing. This is typically used when doing surgery on 21903 * app code/data to prevent the app from running while you're working. 21904 */ 21905 private class PackageFreezer implements AutoCloseable { 21906 private final String mPackageName; 21907 private final PackageFreezer[] mChildren; 21908 21909 private final boolean mWeFroze; 21910 21911 private final AtomicBoolean mClosed = new AtomicBoolean(); 21912 private final CloseGuard mCloseGuard = CloseGuard.get(); 21913 21914 /** 21915 * Create and return a stub freezer that doesn't actually do anything, 21916 * typically used when someone requested 21917 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 21918 * {@link PackageManager#DELETE_DONT_KILL_APP}. 21919 */ 21920 public PackageFreezer() { 21921 mPackageName = null; 21922 mChildren = null; 21923 mWeFroze = false; 21924 mCloseGuard.open("close"); 21925 } 21926 21927 public PackageFreezer(String packageName, int userId, String killReason) { 21928 synchronized (mPackages) { 21929 mPackageName = packageName; 21930 mWeFroze = mFrozenPackages.add(mPackageName); 21931 21932 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 21933 if (ps != null) { 21934 killApplication(ps.name, ps.appId, userId, killReason); 21935 } 21936 21937 final PackageParser.Package p = mPackages.get(packageName); 21938 if (p != null && p.childPackages != null) { 21939 final int N = p.childPackages.size(); 21940 mChildren = new PackageFreezer[N]; 21941 for (int i = 0; i < N; i++) { 21942 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 21943 userId, killReason); 21944 } 21945 } else { 21946 mChildren = null; 21947 } 21948 } 21949 mCloseGuard.open("close"); 21950 } 21951 21952 @Override 21953 protected void finalize() throws Throwable { 21954 try { 21955 if (mCloseGuard != null) { 21956 mCloseGuard.warnIfOpen(); 21957 } 21958 21959 close(); 21960 } finally { 21961 super.finalize(); 21962 } 21963 } 21964 21965 @Override 21966 public void close() { 21967 mCloseGuard.close(); 21968 if (mClosed.compareAndSet(false, true)) { 21969 synchronized (mPackages) { 21970 if (mWeFroze) { 21971 mFrozenPackages.remove(mPackageName); 21972 } 21973 21974 if (mChildren != null) { 21975 for (PackageFreezer freezer : mChildren) { 21976 freezer.close(); 21977 } 21978 } 21979 } 21980 } 21981 } 21982 } 21983 21984 /** 21985 * Verify that given package is currently frozen. 21986 */ 21987 private void checkPackageFrozen(String packageName) { 21988 synchronized (mPackages) { 21989 if (!mFrozenPackages.contains(packageName)) { 21990 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 21991 } 21992 } 21993 } 21994 21995 @Override 21996 public int movePackage(final String packageName, final String volumeUuid) { 21997 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 21998 21999 final int callingUid = Binder.getCallingUid(); 22000 final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid)); 22001 final int moveId = mNextMoveId.getAndIncrement(); 22002 mHandler.post(new Runnable() { 22003 @Override 22004 public void run() { 22005 try { 22006 movePackageInternal(packageName, volumeUuid, moveId, callingUid, user); 22007 } catch (PackageManagerException e) { 22008 Slog.w(TAG, "Failed to move " + packageName, e); 22009 mMoveCallbacks.notifyStatusChanged(moveId, e.error); 22010 } 22011 } 22012 }); 22013 return moveId; 22014 } 22015 22016 private void movePackageInternal(final String packageName, final String volumeUuid, 22017 final int moveId, final int callingUid, UserHandle user) 22018 throws PackageManagerException { 22019 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22020 final PackageManager pm = mContext.getPackageManager(); 22021 22022 final boolean currentAsec; 22023 final String currentVolumeUuid; 22024 final File codeFile; 22025 final String installerPackageName; 22026 final String packageAbiOverride; 22027 final int appId; 22028 final String seinfo; 22029 final String label; 22030 final int targetSdkVersion; 22031 final PackageFreezer freezer; 22032 final int[] installedUserIds; 22033 22034 // reader 22035 synchronized (mPackages) { 22036 final PackageParser.Package pkg = mPackages.get(packageName); 22037 final PackageSetting ps = mSettings.mPackages.get(packageName); 22038 if (pkg == null 22039 || ps == null 22040 || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) { 22041 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 22042 } 22043 if (pkg.applicationInfo.isSystemApp()) { 22044 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 22045 "Cannot move system application"); 22046 } 22047 22048 final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid); 22049 final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean( 22050 com.android.internal.R.bool.config_allow3rdPartyAppOnInternal); 22051 if (isInternalStorage && !allow3rdPartyOnInternal) { 22052 throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL, 22053 "3rd party apps are not allowed on internal storage"); 22054 } 22055 22056 if (pkg.applicationInfo.isExternalAsec()) { 22057 currentAsec = true; 22058 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 22059 } else if (pkg.applicationInfo.isForwardLocked()) { 22060 currentAsec = true; 22061 currentVolumeUuid = "forward_locked"; 22062 } else { 22063 currentAsec = false; 22064 currentVolumeUuid = ps.volumeUuid; 22065 22066 final File probe = new File(pkg.codePath); 22067 final File probeOat = new File(probe, "oat"); 22068 if (!probe.isDirectory() || !probeOat.isDirectory()) { 22069 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22070 "Move only supported for modern cluster style installs"); 22071 } 22072 } 22073 22074 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 22075 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22076 "Package already moved to " + volumeUuid); 22077 } 22078 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 22079 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 22080 "Device admin cannot be moved"); 22081 } 22082 22083 if (mFrozenPackages.contains(packageName)) { 22084 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 22085 "Failed to move already frozen package"); 22086 } 22087 22088 codeFile = new File(pkg.codePath); 22089 installerPackageName = ps.installerPackageName; 22090 packageAbiOverride = ps.cpuAbiOverrideString; 22091 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 22092 seinfo = pkg.applicationInfo.seInfo; 22093 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 22094 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 22095 freezer = freezePackage(packageName, "movePackageInternal"); 22096 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 22097 } 22098 22099 final Bundle extras = new Bundle(); 22100 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 22101 extras.putString(Intent.EXTRA_TITLE, label); 22102 mMoveCallbacks.notifyCreated(moveId, extras); 22103 22104 int installFlags; 22105 final boolean moveCompleteApp; 22106 final File measurePath; 22107 22108 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 22109 installFlags = INSTALL_INTERNAL; 22110 moveCompleteApp = !currentAsec; 22111 measurePath = Environment.getDataAppDirectory(volumeUuid); 22112 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 22113 installFlags = INSTALL_EXTERNAL; 22114 moveCompleteApp = false; 22115 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 22116 } else { 22117 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 22118 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 22119 || !volume.isMountedWritable()) { 22120 freezer.close(); 22121 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22122 "Move location not mounted private volume"); 22123 } 22124 22125 Preconditions.checkState(!currentAsec); 22126 22127 installFlags = INSTALL_INTERNAL; 22128 moveCompleteApp = true; 22129 measurePath = Environment.getDataAppDirectory(volumeUuid); 22130 } 22131 22132 // If we're moving app data around, we need all the users unlocked 22133 if (moveCompleteApp) { 22134 for (int userId : installedUserIds) { 22135 if (StorageManager.isFileEncryptedNativeOrEmulated() 22136 && !StorageManager.isUserKeyUnlocked(userId)) { 22137 throw new PackageManagerException(MOVE_FAILED_LOCKED_USER, 22138 "User " + userId + " must be unlocked"); 22139 } 22140 } 22141 } 22142 22143 final PackageStats stats = new PackageStats(null, -1); 22144 synchronized (mInstaller) { 22145 for (int userId : installedUserIds) { 22146 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 22147 freezer.close(); 22148 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22149 "Failed to measure package size"); 22150 } 22151 } 22152 } 22153 22154 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 22155 + stats.dataSize); 22156 22157 final long startFreeBytes = measurePath.getUsableSpace(); 22158 final long sizeBytes; 22159 if (moveCompleteApp) { 22160 sizeBytes = stats.codeSize + stats.dataSize; 22161 } else { 22162 sizeBytes = stats.codeSize; 22163 } 22164 22165 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 22166 freezer.close(); 22167 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22168 "Not enough free space to move"); 22169 } 22170 22171 mMoveCallbacks.notifyStatusChanged(moveId, 10); 22172 22173 final CountDownLatch installedLatch = new CountDownLatch(1); 22174 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 22175 @Override 22176 public void onUserActionRequired(Intent intent) throws RemoteException { 22177 throw new IllegalStateException(); 22178 } 22179 22180 @Override 22181 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 22182 Bundle extras) throws RemoteException { 22183 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 22184 + PackageManager.installStatusToString(returnCode, msg)); 22185 22186 installedLatch.countDown(); 22187 freezer.close(); 22188 22189 final int status = PackageManager.installStatusToPublicStatus(returnCode); 22190 switch (status) { 22191 case PackageInstaller.STATUS_SUCCESS: 22192 mMoveCallbacks.notifyStatusChanged(moveId, 22193 PackageManager.MOVE_SUCCEEDED); 22194 break; 22195 case PackageInstaller.STATUS_FAILURE_STORAGE: 22196 mMoveCallbacks.notifyStatusChanged(moveId, 22197 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 22198 break; 22199 default: 22200 mMoveCallbacks.notifyStatusChanged(moveId, 22201 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 22202 break; 22203 } 22204 } 22205 }; 22206 22207 final MoveInfo move; 22208 if (moveCompleteApp) { 22209 // Kick off a thread to report progress estimates 22210 new Thread() { 22211 @Override 22212 public void run() { 22213 while (true) { 22214 try { 22215 if (installedLatch.await(1, TimeUnit.SECONDS)) { 22216 break; 22217 } 22218 } catch (InterruptedException ignored) { 22219 } 22220 22221 final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace(); 22222 final int progress = 10 + (int) MathUtils.constrain( 22223 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 22224 mMoveCallbacks.notifyStatusChanged(moveId, progress); 22225 } 22226 } 22227 }.start(); 22228 22229 final String dataAppName = codeFile.getName(); 22230 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 22231 dataAppName, appId, seinfo, targetSdkVersion); 22232 } else { 22233 move = null; 22234 } 22235 22236 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 22237 22238 final Message msg = mHandler.obtainMessage(INIT_COPY); 22239 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 22240 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 22241 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 22242 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/, 22243 PackageManager.INSTALL_REASON_UNKNOWN); 22244 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 22245 msg.obj = params; 22246 22247 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 22248 System.identityHashCode(msg.obj)); 22249 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 22250 System.identityHashCode(msg.obj)); 22251 22252 mHandler.sendMessage(msg); 22253 } 22254 22255 @Override 22256 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 22257 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 22258 22259 final int realMoveId = mNextMoveId.getAndIncrement(); 22260 final Bundle extras = new Bundle(); 22261 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 22262 mMoveCallbacks.notifyCreated(realMoveId, extras); 22263 22264 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 22265 @Override 22266 public void onCreated(int moveId, Bundle extras) { 22267 // Ignored 22268 } 22269 22270 @Override 22271 public void onStatusChanged(int moveId, int status, long estMillis) { 22272 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 22273 } 22274 }; 22275 22276 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22277 storage.setPrimaryStorageUuid(volumeUuid, callback); 22278 return realMoveId; 22279 } 22280 22281 @Override 22282 public int getMoveStatus(int moveId) { 22283 mContext.enforceCallingOrSelfPermission( 22284 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22285 return mMoveCallbacks.mLastStatus.get(moveId); 22286 } 22287 22288 @Override 22289 public void registerMoveCallback(IPackageMoveObserver callback) { 22290 mContext.enforceCallingOrSelfPermission( 22291 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22292 mMoveCallbacks.register(callback); 22293 } 22294 22295 @Override 22296 public void unregisterMoveCallback(IPackageMoveObserver callback) { 22297 mContext.enforceCallingOrSelfPermission( 22298 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22299 mMoveCallbacks.unregister(callback); 22300 } 22301 22302 @Override 22303 public boolean setInstallLocation(int loc) { 22304 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 22305 null); 22306 if (getInstallLocation() == loc) { 22307 return true; 22308 } 22309 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 22310 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 22311 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 22312 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 22313 return true; 22314 } 22315 return false; 22316 } 22317 22318 @Override 22319 public int getInstallLocation() { 22320 // allow instant app access 22321 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 22322 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 22323 PackageHelper.APP_INSTALL_AUTO); 22324 } 22325 22326 /** Called by UserManagerService */ 22327 void cleanUpUser(UserManagerService userManager, int userHandle) { 22328 synchronized (mPackages) { 22329 mDirtyUsers.remove(userHandle); 22330 mUserNeedsBadging.delete(userHandle); 22331 mSettings.removeUserLPw(userHandle); 22332 mPendingBroadcasts.remove(userHandle); 22333 mInstantAppRegistry.onUserRemovedLPw(userHandle); 22334 removeUnusedPackagesLPw(userManager, userHandle); 22335 } 22336 } 22337 22338 /** 22339 * We're removing userHandle and would like to remove any downloaded packages 22340 * that are no longer in use by any other user. 22341 * @param userHandle the user being removed 22342 */ 22343 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 22344 final boolean DEBUG_CLEAN_APKS = false; 22345 int [] users = userManager.getUserIds(); 22346 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 22347 while (psit.hasNext()) { 22348 PackageSetting ps = psit.next(); 22349 if (ps.pkg == null) { 22350 continue; 22351 } 22352 final String packageName = ps.pkg.packageName; 22353 // Skip over if system app 22354 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 22355 continue; 22356 } 22357 if (DEBUG_CLEAN_APKS) { 22358 Slog.i(TAG, "Checking package " + packageName); 22359 } 22360 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 22361 if (keep) { 22362 if (DEBUG_CLEAN_APKS) { 22363 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 22364 } 22365 } else { 22366 for (int i = 0; i < users.length; i++) { 22367 if (users[i] != userHandle && ps.getInstalled(users[i])) { 22368 keep = true; 22369 if (DEBUG_CLEAN_APKS) { 22370 Slog.i(TAG, " Keeping package " + packageName + " for user " 22371 + users[i]); 22372 } 22373 break; 22374 } 22375 } 22376 } 22377 if (!keep) { 22378 if (DEBUG_CLEAN_APKS) { 22379 Slog.i(TAG, " Removing package " + packageName); 22380 } 22381 mHandler.post(new Runnable() { 22382 public void run() { 22383 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 22384 userHandle, 0); 22385 } //end run 22386 }); 22387 } 22388 } 22389 } 22390 22391 /** Called by UserManagerService */ 22392 void createNewUser(int userId, String[] disallowedPackages) { 22393 synchronized (mInstallLock) { 22394 mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages); 22395 } 22396 synchronized (mPackages) { 22397 scheduleWritePackageRestrictionsLocked(userId); 22398 scheduleWritePackageListLocked(userId); 22399 applyFactoryDefaultBrowserLPw(userId); 22400 primeDomainVerificationsLPw(userId); 22401 } 22402 } 22403 22404 void onNewUserCreated(final int userId) { 22405 synchronized(mPackages) { 22406 mDefaultPermissionPolicy.grantDefaultPermissions(mPackages.values(), userId); 22407 // If permission review for legacy apps is required, we represent 22408 // dagerous permissions for such apps as always granted runtime 22409 // permissions to keep per user flag state whether review is needed. 22410 // Hence, if a new user is added we have to propagate dangerous 22411 // permission grants for these legacy apps. 22412 if (mSettings.mPermissions.mPermissionReviewRequired) { 22413// NOTE: This adds UPDATE_PERMISSIONS_REPLACE_PKG 22414 mPermissionManager.updateAllPermissions( 22415 StorageManager.UUID_PRIVATE_INTERNAL, true, mPackages.values(), 22416 mPermissionCallback); 22417 } 22418 } 22419 } 22420 22421 @Override 22422 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 22423 mContext.enforceCallingOrSelfPermission( 22424 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 22425 "Only package verification agents can read the verifier device identity"); 22426 22427 synchronized (mPackages) { 22428 return mSettings.getVerifierDeviceIdentityLPw(); 22429 } 22430 } 22431 22432 @Override 22433 public void setPermissionEnforced(String permission, boolean enforced) { 22434 // TODO: Now that we no longer change GID for storage, this should to away. 22435 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 22436 "setPermissionEnforced"); 22437 if (READ_EXTERNAL_STORAGE.equals(permission)) { 22438 synchronized (mPackages) { 22439 if (mSettings.mReadExternalStorageEnforced == null 22440 || mSettings.mReadExternalStorageEnforced != enforced) { 22441 mSettings.mReadExternalStorageEnforced = 22442 enforced ? Boolean.TRUE : Boolean.FALSE; 22443 mSettings.writeLPr(); 22444 } 22445 } 22446 // kill any non-foreground processes so we restart them and 22447 // grant/revoke the GID. 22448 final IActivityManager am = ActivityManager.getService(); 22449 if (am != null) { 22450 final long token = Binder.clearCallingIdentity(); 22451 try { 22452 am.killProcessesBelowForeground("setPermissionEnforcement"); 22453 } catch (RemoteException e) { 22454 } finally { 22455 Binder.restoreCallingIdentity(token); 22456 } 22457 } 22458 } else { 22459 throw new IllegalArgumentException("No selective enforcement for " + permission); 22460 } 22461 } 22462 22463 @Override 22464 @Deprecated 22465 public boolean isPermissionEnforced(String permission) { 22466 // allow instant applications 22467 return true; 22468 } 22469 22470 @Override 22471 public boolean isStorageLow() { 22472 // allow instant applications 22473 final long token = Binder.clearCallingIdentity(); 22474 try { 22475 final DeviceStorageMonitorInternal 22476 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 22477 if (dsm != null) { 22478 return dsm.isMemoryLow(); 22479 } else { 22480 return false; 22481 } 22482 } finally { 22483 Binder.restoreCallingIdentity(token); 22484 } 22485 } 22486 22487 @Override 22488 public IPackageInstaller getPackageInstaller() { 22489 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 22490 return null; 22491 } 22492 return mInstallerService; 22493 } 22494 22495 private boolean userNeedsBadging(int userId) { 22496 int index = mUserNeedsBadging.indexOfKey(userId); 22497 if (index < 0) { 22498 final UserInfo userInfo; 22499 final long token = Binder.clearCallingIdentity(); 22500 try { 22501 userInfo = sUserManager.getUserInfo(userId); 22502 } finally { 22503 Binder.restoreCallingIdentity(token); 22504 } 22505 final boolean b; 22506 if (userInfo != null && userInfo.isManagedProfile()) { 22507 b = true; 22508 } else { 22509 b = false; 22510 } 22511 mUserNeedsBadging.put(userId, b); 22512 return b; 22513 } 22514 return mUserNeedsBadging.valueAt(index); 22515 } 22516 22517 @Override 22518 public KeySet getKeySetByAlias(String packageName, String alias) { 22519 if (packageName == null || alias == null) { 22520 return null; 22521 } 22522 synchronized(mPackages) { 22523 final PackageParser.Package pkg = mPackages.get(packageName); 22524 if (pkg == null) { 22525 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22526 throw new IllegalArgumentException("Unknown package: " + packageName); 22527 } 22528 final PackageSetting ps = (PackageSetting) pkg.mExtras; 22529 if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) { 22530 Slog.w(TAG, "KeySet requested for filtered package: " + packageName); 22531 throw new IllegalArgumentException("Unknown package: " + packageName); 22532 } 22533 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22534 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 22535 } 22536 } 22537 22538 @Override 22539 public KeySet getSigningKeySet(String packageName) { 22540 if (packageName == null) { 22541 return null; 22542 } 22543 synchronized(mPackages) { 22544 final int callingUid = Binder.getCallingUid(); 22545 final int callingUserId = UserHandle.getUserId(callingUid); 22546 final PackageParser.Package pkg = mPackages.get(packageName); 22547 if (pkg == null) { 22548 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22549 throw new IllegalArgumentException("Unknown package: " + packageName); 22550 } 22551 final PackageSetting ps = (PackageSetting) pkg.mExtras; 22552 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 22553 // filter and pretend the package doesn't exist 22554 Slog.w(TAG, "KeySet requested for filtered package: " + packageName 22555 + ", uid:" + callingUid); 22556 throw new IllegalArgumentException("Unknown package: " + packageName); 22557 } 22558 if (pkg.applicationInfo.uid != callingUid 22559 && Process.SYSTEM_UID != callingUid) { 22560 throw new SecurityException("May not access signing KeySet of other apps."); 22561 } 22562 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22563 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 22564 } 22565 } 22566 22567 @Override 22568 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 22569 final int callingUid = Binder.getCallingUid(); 22570 if (getInstantAppPackageName(callingUid) != null) { 22571 return false; 22572 } 22573 if (packageName == null || ks == null) { 22574 return false; 22575 } 22576 synchronized(mPackages) { 22577 final PackageParser.Package pkg = mPackages.get(packageName); 22578 if (pkg == null 22579 || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid, 22580 UserHandle.getUserId(callingUid))) { 22581 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22582 throw new IllegalArgumentException("Unknown package: " + packageName); 22583 } 22584 IBinder ksh = ks.getToken(); 22585 if (ksh instanceof KeySetHandle) { 22586 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22587 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 22588 } 22589 return false; 22590 } 22591 } 22592 22593 @Override 22594 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 22595 final int callingUid = Binder.getCallingUid(); 22596 if (getInstantAppPackageName(callingUid) != null) { 22597 return false; 22598 } 22599 if (packageName == null || ks == null) { 22600 return false; 22601 } 22602 synchronized(mPackages) { 22603 final PackageParser.Package pkg = mPackages.get(packageName); 22604 if (pkg == null 22605 || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid, 22606 UserHandle.getUserId(callingUid))) { 22607 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22608 throw new IllegalArgumentException("Unknown package: " + packageName); 22609 } 22610 IBinder ksh = ks.getToken(); 22611 if (ksh instanceof KeySetHandle) { 22612 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22613 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 22614 } 22615 return false; 22616 } 22617 } 22618 22619 private void deletePackageIfUnusedLPr(final String packageName) { 22620 PackageSetting ps = mSettings.mPackages.get(packageName); 22621 if (ps == null) { 22622 return; 22623 } 22624 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 22625 // TODO Implement atomic delete if package is unused 22626 // It is currently possible that the package will be deleted even if it is installed 22627 // after this method returns. 22628 mHandler.post(new Runnable() { 22629 public void run() { 22630 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 22631 0, PackageManager.DELETE_ALL_USERS); 22632 } 22633 }); 22634 } 22635 } 22636 22637 /** 22638 * Check and throw if the given before/after packages would be considered a 22639 * downgrade. 22640 */ 22641 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 22642 throws PackageManagerException { 22643 if (after.versionCode < before.mVersionCode) { 22644 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 22645 "Update version code " + after.versionCode + " is older than current " 22646 + before.mVersionCode); 22647 } else if (after.versionCode == before.mVersionCode) { 22648 if (after.baseRevisionCode < before.baseRevisionCode) { 22649 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 22650 "Update base revision code " + after.baseRevisionCode 22651 + " is older than current " + before.baseRevisionCode); 22652 } 22653 22654 if (!ArrayUtils.isEmpty(after.splitNames)) { 22655 for (int i = 0; i < after.splitNames.length; i++) { 22656 final String splitName = after.splitNames[i]; 22657 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 22658 if (j != -1) { 22659 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 22660 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 22661 "Update split " + splitName + " revision code " 22662 + after.splitRevisionCodes[i] + " is older than current " 22663 + before.splitRevisionCodes[j]); 22664 } 22665 } 22666 } 22667 } 22668 } 22669 } 22670 22671 private static class MoveCallbacks extends Handler { 22672 private static final int MSG_CREATED = 1; 22673 private static final int MSG_STATUS_CHANGED = 2; 22674 22675 private final RemoteCallbackList<IPackageMoveObserver> 22676 mCallbacks = new RemoteCallbackList<>(); 22677 22678 private final SparseIntArray mLastStatus = new SparseIntArray(); 22679 22680 public MoveCallbacks(Looper looper) { 22681 super(looper); 22682 } 22683 22684 public void register(IPackageMoveObserver callback) { 22685 mCallbacks.register(callback); 22686 } 22687 22688 public void unregister(IPackageMoveObserver callback) { 22689 mCallbacks.unregister(callback); 22690 } 22691 22692 @Override 22693 public void handleMessage(Message msg) { 22694 final SomeArgs args = (SomeArgs) msg.obj; 22695 final int n = mCallbacks.beginBroadcast(); 22696 for (int i = 0; i < n; i++) { 22697 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 22698 try { 22699 invokeCallback(callback, msg.what, args); 22700 } catch (RemoteException ignored) { 22701 } 22702 } 22703 mCallbacks.finishBroadcast(); 22704 args.recycle(); 22705 } 22706 22707 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 22708 throws RemoteException { 22709 switch (what) { 22710 case MSG_CREATED: { 22711 callback.onCreated(args.argi1, (Bundle) args.arg2); 22712 break; 22713 } 22714 case MSG_STATUS_CHANGED: { 22715 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 22716 break; 22717 } 22718 } 22719 } 22720 22721 private void notifyCreated(int moveId, Bundle extras) { 22722 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 22723 22724 final SomeArgs args = SomeArgs.obtain(); 22725 args.argi1 = moveId; 22726 args.arg2 = extras; 22727 obtainMessage(MSG_CREATED, args).sendToTarget(); 22728 } 22729 22730 private void notifyStatusChanged(int moveId, int status) { 22731 notifyStatusChanged(moveId, status, -1); 22732 } 22733 22734 private void notifyStatusChanged(int moveId, int status, long estMillis) { 22735 Slog.v(TAG, "Move " + moveId + " status " + status); 22736 22737 final SomeArgs args = SomeArgs.obtain(); 22738 args.argi1 = moveId; 22739 args.argi2 = status; 22740 args.arg3 = estMillis; 22741 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 22742 22743 synchronized (mLastStatus) { 22744 mLastStatus.put(moveId, status); 22745 } 22746 } 22747 } 22748 22749 private final static class OnPermissionChangeListeners extends Handler { 22750 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 22751 22752 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 22753 new RemoteCallbackList<>(); 22754 22755 public OnPermissionChangeListeners(Looper looper) { 22756 super(looper); 22757 } 22758 22759 @Override 22760 public void handleMessage(Message msg) { 22761 switch (msg.what) { 22762 case MSG_ON_PERMISSIONS_CHANGED: { 22763 final int uid = msg.arg1; 22764 handleOnPermissionsChanged(uid); 22765 } break; 22766 } 22767 } 22768 22769 public void addListenerLocked(IOnPermissionsChangeListener listener) { 22770 mPermissionListeners.register(listener); 22771 22772 } 22773 22774 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 22775 mPermissionListeners.unregister(listener); 22776 } 22777 22778 public void onPermissionsChanged(int uid) { 22779 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 22780 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 22781 } 22782 } 22783 22784 private void handleOnPermissionsChanged(int uid) { 22785 final int count = mPermissionListeners.beginBroadcast(); 22786 try { 22787 for (int i = 0; i < count; i++) { 22788 IOnPermissionsChangeListener callback = mPermissionListeners 22789 .getBroadcastItem(i); 22790 try { 22791 callback.onPermissionsChanged(uid); 22792 } catch (RemoteException e) { 22793 Log.e(TAG, "Permission listener is dead", e); 22794 } 22795 } 22796 } finally { 22797 mPermissionListeners.finishBroadcast(); 22798 } 22799 } 22800 } 22801 22802 private class PackageManagerNative extends IPackageManagerNative.Stub { 22803 @Override 22804 public String[] getNamesForUids(int[] uids) throws RemoteException { 22805 final String[] results = PackageManagerService.this.getNamesForUids(uids); 22806 // massage results so they can be parsed by the native binder 22807 for (int i = results.length - 1; i >= 0; --i) { 22808 if (results[i] == null) { 22809 results[i] = ""; 22810 } 22811 } 22812 return results; 22813 } 22814 22815 // NB: this differentiates between preloads and sideloads 22816 @Override 22817 public String getInstallerForPackage(String packageName) throws RemoteException { 22818 final String installerName = getInstallerPackageName(packageName); 22819 if (!TextUtils.isEmpty(installerName)) { 22820 return installerName; 22821 } 22822 // differentiate between preload and sideload 22823 int callingUser = UserHandle.getUserId(Binder.getCallingUid()); 22824 ApplicationInfo appInfo = getApplicationInfo(packageName, 22825 /*flags*/ 0, 22826 /*userId*/ callingUser); 22827 if (appInfo != null && (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 22828 return "preload"; 22829 } 22830 return ""; 22831 } 22832 22833 @Override 22834 public int getVersionCodeForPackage(String packageName) throws RemoteException { 22835 try { 22836 int callingUser = UserHandle.getUserId(Binder.getCallingUid()); 22837 PackageInfo pInfo = getPackageInfo(packageName, 0, callingUser); 22838 if (pInfo != null) { 22839 return pInfo.versionCode; 22840 } 22841 } catch (Exception e) { 22842 } 22843 return 0; 22844 } 22845 } 22846 22847 private class PackageManagerInternalImpl extends PackageManagerInternal { 22848 @Override 22849 public void updatePermissionFlagsTEMP(String permName, String packageName, int flagMask, 22850 int flagValues, int userId) { 22851 PackageManagerService.this.updatePermissionFlags( 22852 permName, packageName, flagMask, flagValues, userId); 22853 } 22854 22855 @Override 22856 public int getPermissionFlagsTEMP(String permName, String packageName, int userId) { 22857 return PackageManagerService.this.getPermissionFlags(permName, packageName, userId); 22858 } 22859 22860 @Override 22861 public boolean isInstantApp(String packageName, int userId) { 22862 return PackageManagerService.this.isInstantApp(packageName, userId); 22863 } 22864 22865 @Override 22866 public String getInstantAppPackageName(int uid) { 22867 return PackageManagerService.this.getInstantAppPackageName(uid); 22868 } 22869 22870 @Override 22871 public boolean filterAppAccess(PackageParser.Package pkg, int callingUid, int userId) { 22872 synchronized (mPackages) { 22873 return PackageManagerService.this.filterAppAccessLPr( 22874 (PackageSetting) pkg.mExtras, callingUid, userId); 22875 } 22876 } 22877 22878 @Override 22879 public PackageParser.Package getPackage(String packageName) { 22880 synchronized (mPackages) { 22881 packageName = resolveInternalPackageNameLPr( 22882 packageName, PackageManager.VERSION_CODE_HIGHEST); 22883 return mPackages.get(packageName); 22884 } 22885 } 22886 22887 @Override 22888 public PackageParser.Package getDisabledPackage(String packageName) { 22889 synchronized (mPackages) { 22890 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 22891 return (ps != null) ? ps.pkg : null; 22892 } 22893 } 22894 22895 @Override 22896 public String getKnownPackageName(int knownPackage, int userId) { 22897 switch(knownPackage) { 22898 case PackageManagerInternal.PACKAGE_BROWSER: 22899 return getDefaultBrowserPackageName(userId); 22900 case PackageManagerInternal.PACKAGE_INSTALLER: 22901 return mRequiredInstallerPackage; 22902 case PackageManagerInternal.PACKAGE_SETUP_WIZARD: 22903 return mSetupWizardPackage; 22904 case PackageManagerInternal.PACKAGE_SYSTEM: 22905 return "android"; 22906 case PackageManagerInternal.PACKAGE_VERIFIER: 22907 return mRequiredVerifierPackage; 22908 } 22909 return null; 22910 } 22911 22912 @Override 22913 public boolean isResolveActivityComponent(ComponentInfo component) { 22914 return mResolveActivity.packageName.equals(component.packageName) 22915 && mResolveActivity.name.equals(component.name); 22916 } 22917 22918 @Override 22919 public void setLocationPackagesProvider(PackagesProvider provider) { 22920 mDefaultPermissionPolicy.setLocationPackagesProvider(provider); 22921 } 22922 22923 @Override 22924 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 22925 mDefaultPermissionPolicy.setVoiceInteractionPackagesProvider(provider); 22926 } 22927 22928 @Override 22929 public void setSmsAppPackagesProvider(PackagesProvider provider) { 22930 mDefaultPermissionPolicy.setSmsAppPackagesProvider(provider); 22931 } 22932 22933 @Override 22934 public void setDialerAppPackagesProvider(PackagesProvider provider) { 22935 mDefaultPermissionPolicy.setDialerAppPackagesProvider(provider); 22936 } 22937 22938 @Override 22939 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 22940 mDefaultPermissionPolicy.setSimCallManagerPackagesProvider(provider); 22941 } 22942 22943 @Override 22944 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 22945 mDefaultPermissionPolicy.setSyncAdapterPackagesProvider(provider); 22946 } 22947 22948 @Override 22949 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 22950 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsApp(packageName, userId); 22951 } 22952 22953 @Override 22954 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 22955 synchronized (mPackages) { 22956 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 22957 } 22958 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerApp(packageName, userId); 22959 } 22960 22961 @Override 22962 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 22963 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManager( 22964 packageName, userId); 22965 } 22966 22967 @Override 22968 public void setKeepUninstalledPackages(final List<String> packageList) { 22969 Preconditions.checkNotNull(packageList); 22970 List<String> removedFromList = null; 22971 synchronized (mPackages) { 22972 if (mKeepUninstalledPackages != null) { 22973 final int packagesCount = mKeepUninstalledPackages.size(); 22974 for (int i = 0; i < packagesCount; i++) { 22975 String oldPackage = mKeepUninstalledPackages.get(i); 22976 if (packageList != null && packageList.contains(oldPackage)) { 22977 continue; 22978 } 22979 if (removedFromList == null) { 22980 removedFromList = new ArrayList<>(); 22981 } 22982 removedFromList.add(oldPackage); 22983 } 22984 } 22985 mKeepUninstalledPackages = new ArrayList<>(packageList); 22986 if (removedFromList != null) { 22987 final int removedCount = removedFromList.size(); 22988 for (int i = 0; i < removedCount; i++) { 22989 deletePackageIfUnusedLPr(removedFromList.get(i)); 22990 } 22991 } 22992 } 22993 } 22994 22995 @Override 22996 public boolean isPermissionsReviewRequired(String packageName, int userId) { 22997 synchronized (mPackages) { 22998 return mPermissionManager.isPermissionsReviewRequired( 22999 mPackages.get(packageName), userId); 23000 } 23001 } 23002 23003 @Override 23004 public PackageInfo getPackageInfo( 23005 String packageName, int flags, int filterCallingUid, int userId) { 23006 return PackageManagerService.this 23007 .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST, 23008 flags, filterCallingUid, userId); 23009 } 23010 23011 @Override 23012 public ApplicationInfo getApplicationInfo( 23013 String packageName, int flags, int filterCallingUid, int userId) { 23014 return PackageManagerService.this 23015 .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId); 23016 } 23017 23018 @Override 23019 public ActivityInfo getActivityInfo( 23020 ComponentName component, int flags, int filterCallingUid, int userId) { 23021 return PackageManagerService.this 23022 .getActivityInfoInternal(component, flags, filterCallingUid, userId); 23023 } 23024 23025 @Override 23026 public List<ResolveInfo> queryIntentActivities( 23027 Intent intent, int flags, int filterCallingUid, int userId) { 23028 final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver()); 23029 return PackageManagerService.this 23030 .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid, 23031 userId, false /*resolveForStart*/, true /*allowDynamicSplits*/); 23032 } 23033 23034 @Override 23035 public List<ResolveInfo> queryIntentServices( 23036 Intent intent, int flags, int callingUid, int userId) { 23037 final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver()); 23038 return PackageManagerService.this 23039 .queryIntentServicesInternal(intent, resolvedType, flags, userId, callingUid, 23040 false); 23041 } 23042 23043 @Override 23044 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 23045 int userId) { 23046 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 23047 } 23048 23049 @Override 23050 public void setDeviceAndProfileOwnerPackages( 23051 int deviceOwnerUserId, String deviceOwnerPackage, 23052 SparseArray<String> profileOwnerPackages) { 23053 mProtectedPackages.setDeviceAndProfileOwnerPackages( 23054 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages); 23055 } 23056 23057 @Override 23058 public boolean isPackageDataProtected(int userId, String packageName) { 23059 return mProtectedPackages.isPackageDataProtected(userId, packageName); 23060 } 23061 23062 @Override 23063 public boolean isPackageEphemeral(int userId, String packageName) { 23064 synchronized (mPackages) { 23065 final PackageSetting ps = mSettings.mPackages.get(packageName); 23066 return ps != null ? ps.getInstantApp(userId) : false; 23067 } 23068 } 23069 23070 @Override 23071 public boolean wasPackageEverLaunched(String packageName, int userId) { 23072 synchronized (mPackages) { 23073 return mSettings.wasPackageEverLaunchedLPr(packageName, userId); 23074 } 23075 } 23076 23077 @Override 23078 public void grantRuntimePermission(String packageName, String permName, int userId, 23079 boolean overridePolicy) { 23080 PackageManagerService.this.mPermissionManager.grantRuntimePermission( 23081 permName, packageName, overridePolicy, getCallingUid(), userId, 23082 mPermissionCallback); 23083 } 23084 23085 @Override 23086 public void revokeRuntimePermission(String packageName, String permName, int userId, 23087 boolean overridePolicy) { 23088 mPermissionManager.revokeRuntimePermission( 23089 permName, packageName, overridePolicy, getCallingUid(), userId, 23090 mPermissionCallback); 23091 } 23092 23093 @Override 23094 public String getNameForUid(int uid) { 23095 return PackageManagerService.this.getNameForUid(uid); 23096 } 23097 23098 @Override 23099 public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj, 23100 Intent origIntent, String resolvedType, String callingPackage, 23101 Bundle verificationBundle, int userId) { 23102 PackageManagerService.this.requestInstantAppResolutionPhaseTwo( 23103 responseObj, origIntent, resolvedType, callingPackage, verificationBundle, 23104 userId); 23105 } 23106 23107 @Override 23108 public void grantEphemeralAccess(int userId, Intent intent, 23109 int targetAppId, int ephemeralAppId) { 23110 synchronized (mPackages) { 23111 mInstantAppRegistry.grantInstantAccessLPw(userId, intent, 23112 targetAppId, ephemeralAppId); 23113 } 23114 } 23115 23116 @Override 23117 public boolean isInstantAppInstallerComponent(ComponentName component) { 23118 synchronized (mPackages) { 23119 return mInstantAppInstallerActivity != null 23120 && mInstantAppInstallerActivity.getComponentName().equals(component); 23121 } 23122 } 23123 23124 @Override 23125 public void pruneInstantApps() { 23126 mInstantAppRegistry.pruneInstantApps(); 23127 } 23128 23129 @Override 23130 public String getSetupWizardPackageName() { 23131 return mSetupWizardPackage; 23132 } 23133 23134 public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) { 23135 if (policy != null) { 23136 mExternalSourcesPolicy = policy; 23137 } 23138 } 23139 23140 @Override 23141 public boolean isPackagePersistent(String packageName) { 23142 synchronized (mPackages) { 23143 PackageParser.Package pkg = mPackages.get(packageName); 23144 return pkg != null 23145 ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM 23146 | ApplicationInfo.FLAG_PERSISTENT)) == 23147 (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT)) 23148 : false; 23149 } 23150 } 23151 23152 @Override 23153 public boolean isLegacySystemApp(Package pkg) { 23154 synchronized (mPackages) { 23155 final PackageSetting ps = (PackageSetting) pkg.mExtras; 23156 return mPromoteSystemApps 23157 && ps.isSystem() 23158 && mExistingSystemPackages.contains(ps.name); 23159 } 23160 } 23161 23162 @Override 23163 public List<PackageInfo> getOverlayPackages(int userId) { 23164 final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>(); 23165 synchronized (mPackages) { 23166 for (PackageParser.Package p : mPackages.values()) { 23167 if (p.mOverlayTarget != null) { 23168 PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId); 23169 if (pkg != null) { 23170 overlayPackages.add(pkg); 23171 } 23172 } 23173 } 23174 } 23175 return overlayPackages; 23176 } 23177 23178 @Override 23179 public List<String> getTargetPackageNames(int userId) { 23180 List<String> targetPackages = new ArrayList<>(); 23181 synchronized (mPackages) { 23182 for (PackageParser.Package p : mPackages.values()) { 23183 if (p.mOverlayTarget == null) { 23184 targetPackages.add(p.packageName); 23185 } 23186 } 23187 } 23188 return targetPackages; 23189 } 23190 23191 @Override 23192 public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName, 23193 @Nullable List<String> overlayPackageNames) { 23194 synchronized (mPackages) { 23195 if (targetPackageName == null || mPackages.get(targetPackageName) == null) { 23196 Slog.e(TAG, "failed to find package " + targetPackageName); 23197 return false; 23198 } 23199 ArrayList<String> overlayPaths = null; 23200 if (overlayPackageNames != null && overlayPackageNames.size() > 0) { 23201 final int N = overlayPackageNames.size(); 23202 overlayPaths = new ArrayList<>(N); 23203 for (int i = 0; i < N; i++) { 23204 final String packageName = overlayPackageNames.get(i); 23205 final PackageParser.Package pkg = mPackages.get(packageName); 23206 if (pkg == null) { 23207 Slog.e(TAG, "failed to find package " + packageName); 23208 return false; 23209 } 23210 overlayPaths.add(pkg.baseCodePath); 23211 } 23212 } 23213 23214 final PackageSetting ps = mSettings.mPackages.get(targetPackageName); 23215 ps.setOverlayPaths(overlayPaths, userId); 23216 return true; 23217 } 23218 } 23219 23220 @Override 23221 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 23222 int flags, int userId, boolean resolveForStart) { 23223 return resolveIntentInternal( 23224 intent, resolvedType, flags, userId, resolveForStart); 23225 } 23226 23227 @Override 23228 public ResolveInfo resolveService(Intent intent, String resolvedType, 23229 int flags, int userId, int callingUid) { 23230 return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid); 23231 } 23232 23233 @Override 23234 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 23235 return PackageManagerService.this.resolveContentProviderInternal( 23236 name, flags, userId); 23237 } 23238 23239 @Override 23240 public void addIsolatedUid(int isolatedUid, int ownerUid) { 23241 synchronized (mPackages) { 23242 mIsolatedOwners.put(isolatedUid, ownerUid); 23243 } 23244 } 23245 23246 @Override 23247 public void removeIsolatedUid(int isolatedUid) { 23248 synchronized (mPackages) { 23249 mIsolatedOwners.delete(isolatedUid); 23250 } 23251 } 23252 23253 @Override 23254 public int getUidTargetSdkVersion(int uid) { 23255 synchronized (mPackages) { 23256 return getUidTargetSdkVersionLockedLPr(uid); 23257 } 23258 } 23259 23260 @Override 23261 public boolean canAccessInstantApps(int callingUid, int userId) { 23262 return PackageManagerService.this.canViewInstantApps(callingUid, userId); 23263 } 23264 23265 @Override 23266 public boolean hasInstantApplicationMetadata(String packageName, int userId) { 23267 synchronized (mPackages) { 23268 return mInstantAppRegistry.hasInstantApplicationMetadataLPr(packageName, userId); 23269 } 23270 } 23271 23272 @Override 23273 public void notifyPackageUse(String packageName, int reason) { 23274 synchronized (mPackages) { 23275 PackageManagerService.this.notifyPackageUseLocked(packageName, reason); 23276 } 23277 } 23278 } 23279 23280 @Override 23281 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 23282 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 23283 synchronized (mPackages) { 23284 final long identity = Binder.clearCallingIdentity(); 23285 try { 23286 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierApps( 23287 packageNames, userId); 23288 } finally { 23289 Binder.restoreCallingIdentity(identity); 23290 } 23291 } 23292 } 23293 23294 @Override 23295 public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) { 23296 enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices"); 23297 synchronized (mPackages) { 23298 final long identity = Binder.clearCallingIdentity(); 23299 try { 23300 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServices( 23301 packageNames, userId); 23302 } finally { 23303 Binder.restoreCallingIdentity(identity); 23304 } 23305 } 23306 } 23307 23308 private static void enforceSystemOrPhoneCaller(String tag) { 23309 int callingUid = Binder.getCallingUid(); 23310 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 23311 throw new SecurityException( 23312 "Cannot call " + tag + " from UID " + callingUid); 23313 } 23314 } 23315 23316 boolean isHistoricalPackageUsageAvailable() { 23317 return mPackageUsage.isHistoricalPackageUsageAvailable(); 23318 } 23319 23320 /** 23321 * Return a <b>copy</b> of the collection of packages known to the package manager. 23322 * @return A copy of the values of mPackages. 23323 */ 23324 Collection<PackageParser.Package> getPackages() { 23325 synchronized (mPackages) { 23326 return new ArrayList<>(mPackages.values()); 23327 } 23328 } 23329 23330 /** 23331 * Logs process start information (including base APK hash) to the security log. 23332 * @hide 23333 */ 23334 @Override 23335 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 23336 String apkFile, int pid) { 23337 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 23338 return; 23339 } 23340 if (!SecurityLog.isLoggingEnabled()) { 23341 return; 23342 } 23343 Bundle data = new Bundle(); 23344 data.putLong("startTimestamp", System.currentTimeMillis()); 23345 data.putString("processName", processName); 23346 data.putInt("uid", uid); 23347 data.putString("seinfo", seinfo); 23348 data.putString("apkFile", apkFile); 23349 data.putInt("pid", pid); 23350 Message msg = mProcessLoggingHandler.obtainMessage( 23351 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 23352 msg.setData(data); 23353 mProcessLoggingHandler.sendMessage(msg); 23354 } 23355 23356 public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) { 23357 return mCompilerStats.getPackageStats(pkgName); 23358 } 23359 23360 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) { 23361 return getOrCreateCompilerPackageStats(pkg.packageName); 23362 } 23363 23364 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) { 23365 return mCompilerStats.getOrCreatePackageStats(pkgName); 23366 } 23367 23368 public void deleteCompilerPackageStats(String pkgName) { 23369 mCompilerStats.deletePackageStats(pkgName); 23370 } 23371 23372 @Override 23373 public int getInstallReason(String packageName, int userId) { 23374 final int callingUid = Binder.getCallingUid(); 23375 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 23376 true /* requireFullPermission */, false /* checkShell */, 23377 "get install reason"); 23378 synchronized (mPackages) { 23379 final PackageSetting ps = mSettings.mPackages.get(packageName); 23380 if (filterAppAccessLPr(ps, callingUid, userId)) { 23381 return PackageManager.INSTALL_REASON_UNKNOWN; 23382 } 23383 if (ps != null) { 23384 return ps.getInstallReason(userId); 23385 } 23386 } 23387 return PackageManager.INSTALL_REASON_UNKNOWN; 23388 } 23389 23390 @Override 23391 public boolean canRequestPackageInstalls(String packageName, int userId) { 23392 return canRequestPackageInstallsInternal(packageName, 0, userId, 23393 true /* throwIfPermNotDeclared*/); 23394 } 23395 23396 private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId, 23397 boolean throwIfPermNotDeclared) { 23398 int callingUid = Binder.getCallingUid(); 23399 int uid = getPackageUid(packageName, 0, userId); 23400 if (callingUid != uid && callingUid != Process.ROOT_UID 23401 && callingUid != Process.SYSTEM_UID) { 23402 throw new SecurityException( 23403 "Caller uid " + callingUid + " does not own package " + packageName); 23404 } 23405 ApplicationInfo info = getApplicationInfo(packageName, flags, userId); 23406 if (info == null) { 23407 return false; 23408 } 23409 if (info.targetSdkVersion < Build.VERSION_CODES.O) { 23410 return false; 23411 } 23412 String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES; 23413 String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission); 23414 if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) { 23415 if (throwIfPermNotDeclared) { 23416 throw new SecurityException("Need to declare " + appOpPermission 23417 + " to call this api"); 23418 } else { 23419 Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api"); 23420 return false; 23421 } 23422 } 23423 if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) { 23424 return false; 23425 } 23426 if (mExternalSourcesPolicy != null) { 23427 int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid); 23428 if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) { 23429 return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED; 23430 } 23431 } 23432 return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED; 23433 } 23434 23435 @Override 23436 public ComponentName getInstantAppResolverSettingsComponent() { 23437 return mInstantAppResolverSettingsComponent; 23438 } 23439 23440 @Override 23441 public ComponentName getInstantAppInstallerComponent() { 23442 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 23443 return null; 23444 } 23445 return mInstantAppInstallerActivity == null 23446 ? null : mInstantAppInstallerActivity.getComponentName(); 23447 } 23448 23449 @Override 23450 public String getInstantAppAndroidId(String packageName, int userId) { 23451 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS, 23452 "getInstantAppAndroidId"); 23453 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 23454 true /* requireFullPermission */, false /* checkShell */, 23455 "getInstantAppAndroidId"); 23456 // Make sure the target is an Instant App. 23457 if (!isInstantApp(packageName, userId)) { 23458 return null; 23459 } 23460 synchronized (mPackages) { 23461 return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId); 23462 } 23463 } 23464 23465 boolean canHaveOatDir(String packageName) { 23466 synchronized (mPackages) { 23467 PackageParser.Package p = mPackages.get(packageName); 23468 if (p == null) { 23469 return false; 23470 } 23471 return p.canHaveOatDir(); 23472 } 23473 } 23474 23475 private String getOatDir(PackageParser.Package pkg) { 23476 if (!pkg.canHaveOatDir()) { 23477 return null; 23478 } 23479 File codePath = new File(pkg.codePath); 23480 if (codePath.isDirectory()) { 23481 return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath(); 23482 } 23483 return null; 23484 } 23485 23486 void deleteOatArtifactsOfPackage(String packageName) { 23487 final String[] instructionSets; 23488 final List<String> codePaths; 23489 final String oatDir; 23490 final PackageParser.Package pkg; 23491 synchronized (mPackages) { 23492 pkg = mPackages.get(packageName); 23493 } 23494 instructionSets = getAppDexInstructionSets(pkg.applicationInfo); 23495 codePaths = pkg.getAllCodePaths(); 23496 oatDir = getOatDir(pkg); 23497 23498 for (String codePath : codePaths) { 23499 for (String isa : instructionSets) { 23500 try { 23501 mInstaller.deleteOdex(codePath, isa, oatDir); 23502 } catch (InstallerException e) { 23503 Log.e(TAG, "Failed deleting oat files for " + codePath, e); 23504 } 23505 } 23506 } 23507 } 23508 23509 Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) { 23510 Set<String> unusedPackages = new HashSet<>(); 23511 long currentTimeInMillis = System.currentTimeMillis(); 23512 synchronized (mPackages) { 23513 for (PackageParser.Package pkg : mPackages.values()) { 23514 PackageSetting ps = mSettings.mPackages.get(pkg.packageName); 23515 if (ps == null) { 23516 continue; 23517 } 23518 PackageDexUsage.PackageUseInfo packageUseInfo = 23519 getDexManager().getPackageUseInfoOrDefault(pkg.packageName); 23520 if (PackageManagerServiceUtils 23521 .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis, 23522 downgradeTimeThresholdMillis, packageUseInfo, 23523 pkg.getLatestPackageUseTimeInMills(), 23524 pkg.getLatestForegroundPackageUseTimeInMills())) { 23525 unusedPackages.add(pkg.packageName); 23526 } 23527 } 23528 } 23529 return unusedPackages; 23530 } 23531} 23532 23533interface PackageSender { 23534 void sendPackageBroadcast(final String action, final String pkg, 23535 final Bundle extras, final int flags, final String targetPkg, 23536 final IIntentReceiver finishedReceiver, final int[] userIds); 23537 void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted, 23538 boolean includeStopped, int appId, int... userIds); 23539} 23540