PackageManagerService.java revision d7a2c1c23bdd6547aa864e325792cd89ffde0c5e
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.READ_EXTERNAL_STORAGE; 22import static android.Manifest.permission.REQUEST_DELETE_PACKAGES; 23import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; 24import static android.Manifest.permission.WRITE_MEDIA_STORAGE; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 27import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 28import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 29import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 30import static android.content.pm.PackageManager.DELETE_KEEP_DATA; 31import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 32import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED; 33import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 34import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 35import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 36import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED; 37import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET; 38import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 39import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 40import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 41import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 42import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 43import static android.content.pm.PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID; 44import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 45import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 46import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 47import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 48import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 49import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 50import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 51import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 52import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 53import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 54import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 55import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 56import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 57import static android.content.pm.PackageManager.INSTALL_INTERNAL; 58import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK; 61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 64import static android.content.pm.PackageManager.MATCH_ALL; 65import static android.content.pm.PackageManager.MATCH_ANY_USER; 66import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 67import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE; 68import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE; 69import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS; 70import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY; 71import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES; 72import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY; 73import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES; 74import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL; 75import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN; 76import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 77import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 78import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 79import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 80import static android.content.pm.PackageManager.PERMISSION_DENIED; 81import static android.content.pm.PackageManager.PERMISSION_GRANTED; 82import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED; 83import static android.content.pm.PackageParser.isApkFile; 84import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 85import static android.system.OsConstants.O_CREAT; 86import static android.system.OsConstants.O_RDWR; 87import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 88import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 89import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 90import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 91import static com.android.internal.util.ArrayUtils.appendInt; 92import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 93import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 94import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 95import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 96import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 97import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason; 98import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter; 99import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 100import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 101import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 102import static dalvik.system.DexFile.getNonProfileGuidedCompilerFilter; 103 104import android.Manifest; 105import android.annotation.IntDef; 106import android.annotation.NonNull; 107import android.annotation.Nullable; 108import android.app.ActivityManager; 109import android.app.AppOpsManager; 110import android.app.IActivityManager; 111import android.app.ResourcesManager; 112import android.app.admin.IDevicePolicyManager; 113import android.app.admin.SecurityLog; 114import android.app.backup.IBackupManager; 115import android.content.BroadcastReceiver; 116import android.content.ComponentName; 117import android.content.ContentResolver; 118import android.content.Context; 119import android.content.IIntentReceiver; 120import android.content.Intent; 121import android.content.IntentFilter; 122import android.content.IntentSender; 123import android.content.IntentSender.SendIntentException; 124import android.content.ServiceConnection; 125import android.content.pm.ActivityInfo; 126import android.content.pm.ApplicationInfo; 127import android.content.pm.AppsQueryHelper; 128import android.content.pm.AuxiliaryResolveInfo; 129import android.content.pm.ChangedPackages; 130import android.content.pm.FallbackCategoryProvider; 131import android.content.pm.FeatureInfo; 132import android.content.pm.IOnPermissionsChangeListener; 133import android.content.pm.IPackageDataObserver; 134import android.content.pm.IPackageDeleteObserver; 135import android.content.pm.IPackageDeleteObserver2; 136import android.content.pm.IPackageInstallObserver2; 137import android.content.pm.IPackageInstaller; 138import android.content.pm.IPackageManager; 139import android.content.pm.IPackageMoveObserver; 140import android.content.pm.IPackageStatsObserver; 141import android.content.pm.InstantAppInfo; 142import android.content.pm.InstantAppRequest; 143import android.content.pm.InstantAppResolveInfo; 144import android.content.pm.InstrumentationInfo; 145import android.content.pm.IntentFilterVerificationInfo; 146import android.content.pm.KeySet; 147import android.content.pm.PackageCleanItem; 148import android.content.pm.PackageInfo; 149import android.content.pm.PackageInfoLite; 150import android.content.pm.PackageInstaller; 151import android.content.pm.PackageManager; 152import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 153import android.content.pm.PackageManagerInternal; 154import android.content.pm.PackageParser; 155import android.content.pm.PackageParser.ActivityIntentInfo; 156import android.content.pm.PackageParser.PackageLite; 157import android.content.pm.PackageParser.PackageParserException; 158import android.content.pm.PackageStats; 159import android.content.pm.PackageUserState; 160import android.content.pm.ParceledListSlice; 161import android.content.pm.PermissionGroupInfo; 162import android.content.pm.PermissionInfo; 163import android.content.pm.ProviderInfo; 164import android.content.pm.ResolveInfo; 165import android.content.pm.ServiceInfo; 166import android.content.pm.SharedLibraryInfo; 167import android.content.pm.Signature; 168import android.content.pm.UserInfo; 169import android.content.pm.VerifierDeviceIdentity; 170import android.content.pm.VerifierInfo; 171import android.content.pm.VersionedPackage; 172import android.content.res.Resources; 173import android.database.ContentObserver; 174import android.graphics.Bitmap; 175import android.hardware.display.DisplayManager; 176import android.net.Uri; 177import android.os.Binder; 178import android.os.Build; 179import android.os.Bundle; 180import android.os.Debug; 181import android.os.Environment; 182import android.os.Environment.UserEnvironment; 183import android.os.FileUtils; 184import android.os.Handler; 185import android.os.IBinder; 186import android.os.Looper; 187import android.os.Message; 188import android.os.Parcel; 189import android.os.ParcelFileDescriptor; 190import android.os.PatternMatcher; 191import android.os.Process; 192import android.os.RemoteCallbackList; 193import android.os.RemoteException; 194import android.os.ResultReceiver; 195import android.os.SELinux; 196import android.os.ServiceManager; 197import android.os.ShellCallback; 198import android.os.SystemClock; 199import android.os.SystemProperties; 200import android.os.Trace; 201import android.os.UserHandle; 202import android.os.UserManager; 203import android.os.UserManagerInternal; 204import android.os.storage.IStorageManager; 205import android.os.storage.StorageEventListener; 206import android.os.storage.StorageManager; 207import android.os.storage.StorageManagerInternal; 208import android.os.storage.VolumeInfo; 209import android.os.storage.VolumeRecord; 210import android.provider.Settings.Global; 211import android.provider.Settings.Secure; 212import android.security.KeyStore; 213import android.security.SystemKeyStore; 214import android.service.pm.PackageServiceDumpProto; 215import android.system.ErrnoException; 216import android.system.Os; 217import android.text.TextUtils; 218import android.text.format.DateUtils; 219import android.util.ArrayMap; 220import android.util.ArraySet; 221import android.util.Base64; 222import android.util.BootTimingsTraceLog; 223import android.util.DisplayMetrics; 224import android.util.EventLog; 225import android.util.ExceptionUtils; 226import android.util.Log; 227import android.util.LogPrinter; 228import android.util.MathUtils; 229import android.util.PackageUtils; 230import android.util.Pair; 231import android.util.PrintStreamPrinter; 232import android.util.Slog; 233import android.util.SparseArray; 234import android.util.SparseBooleanArray; 235import android.util.SparseIntArray; 236import android.util.Xml; 237import android.util.jar.StrictJarFile; 238import android.util.proto.ProtoOutputStream; 239import android.view.Display; 240 241import com.android.internal.R; 242import com.android.internal.annotations.GuardedBy; 243import com.android.internal.app.IMediaContainerService; 244import com.android.internal.app.ResolverActivity; 245import com.android.internal.content.NativeLibraryHelper; 246import com.android.internal.content.PackageHelper; 247import com.android.internal.logging.MetricsLogger; 248import com.android.internal.logging.nano.MetricsProto.MetricsEvent; 249import com.android.internal.os.IParcelFileDescriptorFactory; 250import com.android.internal.os.RoSystemProperties; 251import com.android.internal.os.SomeArgs; 252import com.android.internal.os.Zygote; 253import com.android.internal.telephony.CarrierAppUtils; 254import com.android.internal.util.ArrayUtils; 255import com.android.internal.util.ConcurrentUtils; 256import com.android.internal.util.DumpUtils; 257import com.android.internal.util.FastPrintWriter; 258import com.android.internal.util.FastXmlSerializer; 259import com.android.internal.util.IndentingPrintWriter; 260import com.android.internal.util.Preconditions; 261import com.android.internal.util.XmlUtils; 262import com.android.server.AttributeCache; 263import com.android.server.DeviceIdleController; 264import com.android.server.EventLogTags; 265import com.android.server.FgThread; 266import com.android.server.IntentResolver; 267import com.android.server.LocalServices; 268import com.android.server.LockGuard; 269import com.android.server.ServiceThread; 270import com.android.server.SystemConfig; 271import com.android.server.SystemServerInitThreadPool; 272import com.android.server.Watchdog; 273import com.android.server.net.NetworkPolicyManagerInternal; 274import com.android.server.pm.Installer.InstallerException; 275import com.android.server.pm.PermissionsState.PermissionState; 276import com.android.server.pm.Settings.DatabaseVersion; 277import com.android.server.pm.Settings.VersionInfo; 278import com.android.server.pm.dex.DexManager; 279import com.android.server.storage.DeviceStorageMonitorInternal; 280 281import dalvik.system.CloseGuard; 282import dalvik.system.DexFile; 283import dalvik.system.VMRuntime; 284 285import libcore.io.IoUtils; 286import libcore.util.EmptyArray; 287 288import org.xmlpull.v1.XmlPullParser; 289import org.xmlpull.v1.XmlPullParserException; 290import org.xmlpull.v1.XmlSerializer; 291 292import java.io.BufferedOutputStream; 293import java.io.BufferedReader; 294import java.io.ByteArrayInputStream; 295import java.io.ByteArrayOutputStream; 296import java.io.File; 297import java.io.FileDescriptor; 298import java.io.FileInputStream; 299import java.io.FileOutputStream; 300import java.io.FileReader; 301import java.io.FilenameFilter; 302import java.io.IOException; 303import java.io.PrintWriter; 304import java.lang.annotation.Retention; 305import java.lang.annotation.RetentionPolicy; 306import java.nio.charset.StandardCharsets; 307import java.security.DigestInputStream; 308import java.security.MessageDigest; 309import java.security.NoSuchAlgorithmException; 310import java.security.PublicKey; 311import java.security.SecureRandom; 312import java.security.cert.Certificate; 313import java.security.cert.CertificateEncodingException; 314import java.security.cert.CertificateException; 315import java.text.SimpleDateFormat; 316import java.util.ArrayList; 317import java.util.Arrays; 318import java.util.Collection; 319import java.util.Collections; 320import java.util.Comparator; 321import java.util.Date; 322import java.util.HashMap; 323import java.util.HashSet; 324import java.util.Iterator; 325import java.util.List; 326import java.util.Map; 327import java.util.Objects; 328import java.util.Set; 329import java.util.concurrent.CountDownLatch; 330import java.util.concurrent.Future; 331import java.util.concurrent.TimeUnit; 332import java.util.concurrent.atomic.AtomicBoolean; 333import java.util.concurrent.atomic.AtomicInteger; 334 335/** 336 * Keep track of all those APKs everywhere. 337 * <p> 338 * Internally there are two important locks: 339 * <ul> 340 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 341 * and other related state. It is a fine-grained lock that should only be held 342 * momentarily, as it's one of the most contended locks in the system. 343 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 344 * operations typically involve heavy lifting of application data on disk. Since 345 * {@code installd} is single-threaded, and it's operations can often be slow, 346 * this lock should never be acquired while already holding {@link #mPackages}. 347 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 348 * holding {@link #mInstallLock}. 349 * </ul> 350 * Many internal methods rely on the caller to hold the appropriate locks, and 351 * this contract is expressed through method name suffixes: 352 * <ul> 353 * <li>fooLI(): the caller must hold {@link #mInstallLock} 354 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 355 * being modified must be frozen 356 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 357 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 358 * </ul> 359 * <p> 360 * Because this class is very central to the platform's security; please run all 361 * CTS and unit tests whenever making modifications: 362 * 363 * <pre> 364 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 365 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases 366 * </pre> 367 */ 368public class PackageManagerService extends IPackageManager.Stub 369 implements PackageSender { 370 static final String TAG = "PackageManager"; 371 static final boolean DEBUG_SETTINGS = false; 372 static final boolean DEBUG_PREFERRED = false; 373 static final boolean DEBUG_UPGRADE = false; 374 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 375 private static final boolean DEBUG_BACKUP = false; 376 private static final boolean DEBUG_INSTALL = false; 377 private static final boolean DEBUG_REMOVE = false; 378 private static final boolean DEBUG_BROADCASTS = false; 379 private static final boolean DEBUG_SHOW_INFO = false; 380 private static final boolean DEBUG_PACKAGE_INFO = false; 381 private static final boolean DEBUG_INTENT_MATCHING = false; 382 private static final boolean DEBUG_PACKAGE_SCANNING = false; 383 private static final boolean DEBUG_VERIFY = false; 384 private static final boolean DEBUG_FILTERS = false; 385 private static final boolean DEBUG_PERMISSIONS = false; 386 private static final boolean DEBUG_SHARED_LIBRARIES = false; 387 388 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 389 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 390 // user, but by default initialize to this. 391 public static final boolean DEBUG_DEXOPT = false; 392 393 private static final boolean DEBUG_ABI_SELECTION = false; 394 private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE; 395 private static final boolean DEBUG_TRIAGED_MISSING = false; 396 private static final boolean DEBUG_APP_DATA = false; 397 398 /** REMOVE. According to Svet, this was only used to reset permissions during development. */ 399 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 400 401 private static final boolean HIDE_EPHEMERAL_APIS = false; 402 403 private static final boolean ENABLE_FREE_CACHE_V2 = 404 SystemProperties.getBoolean("fw.free_cache_v2", true); 405 406 private static final int RADIO_UID = Process.PHONE_UID; 407 private static final int LOG_UID = Process.LOG_UID; 408 private static final int NFC_UID = Process.NFC_UID; 409 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 410 private static final int SHELL_UID = Process.SHELL_UID; 411 412 // Cap the size of permission trees that 3rd party apps can define 413 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 414 415 // Suffix used during package installation when copying/moving 416 // package apks to install directory. 417 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 418 419 static final int SCAN_NO_DEX = 1<<1; 420 static final int SCAN_FORCE_DEX = 1<<2; 421 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 422 static final int SCAN_NEW_INSTALL = 1<<4; 423 static final int SCAN_UPDATE_TIME = 1<<5; 424 static final int SCAN_BOOTING = 1<<6; 425 static final int SCAN_TRUSTED_OVERLAY = 1<<7; 426 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8; 427 static final int SCAN_REPLACING = 1<<9; 428 static final int SCAN_REQUIRE_KNOWN = 1<<10; 429 static final int SCAN_MOVE = 1<<11; 430 static final int SCAN_INITIAL = 1<<12; 431 static final int SCAN_CHECK_ONLY = 1<<13; 432 static final int SCAN_DONT_KILL_APP = 1<<14; 433 static final int SCAN_IGNORE_FROZEN = 1<<15; 434 static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16; 435 static final int SCAN_AS_INSTANT_APP = 1<<17; 436 static final int SCAN_AS_FULL_APP = 1<<18; 437 /** Should not be with the scan flags */ 438 static final int FLAGS_REMOVE_CHATTY = 1<<31; 439 440 private static final String STATIC_SHARED_LIB_DELIMITER = "_"; 441 442 private static final int[] EMPTY_INT_ARRAY = new int[0]; 443 444 private static final int TYPE_UNKNOWN = 0; 445 private static final int TYPE_ACTIVITY = 1; 446 private static final int TYPE_RECEIVER = 2; 447 private static final int TYPE_SERVICE = 3; 448 private static final int TYPE_PROVIDER = 4; 449 @IntDef(prefix = { "TYPE_" }, value = { 450 TYPE_UNKNOWN, 451 TYPE_ACTIVITY, 452 TYPE_RECEIVER, 453 TYPE_SERVICE, 454 TYPE_PROVIDER, 455 }) 456 @Retention(RetentionPolicy.SOURCE) 457 public @interface ComponentType {} 458 459 /** 460 * Timeout (in milliseconds) after which the watchdog should declare that 461 * our handler thread is wedged. The usual default for such things is one 462 * minute but we sometimes do very lengthy I/O operations on this thread, 463 * such as installing multi-gigabyte applications, so ours needs to be longer. 464 */ 465 static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 466 467 /** 468 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 469 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 470 * settings entry if available, otherwise we use the hardcoded default. If it's been 471 * more than this long since the last fstrim, we force one during the boot sequence. 472 * 473 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 474 * one gets run at the next available charging+idle time. This final mandatory 475 * no-fstrim check kicks in only of the other scheduling criteria is never met. 476 */ 477 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 478 479 /** 480 * Whether verification is enabled by default. 481 */ 482 private static final boolean DEFAULT_VERIFY_ENABLE = true; 483 484 /** 485 * The default maximum time to wait for the verification agent to return in 486 * milliseconds. 487 */ 488 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 489 490 /** 491 * The default response for package verification timeout. 492 * 493 * This can be either PackageManager.VERIFICATION_ALLOW or 494 * PackageManager.VERIFICATION_REJECT. 495 */ 496 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 497 498 static final String PLATFORM_PACKAGE_NAME = "android"; 499 500 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 501 502 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 503 DEFAULT_CONTAINER_PACKAGE, 504 "com.android.defcontainer.DefaultContainerService"); 505 506 private static final String KILL_APP_REASON_GIDS_CHANGED = 507 "permission grant or revoke changed gids"; 508 509 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 510 "permissions revoked"; 511 512 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 513 514 private static final String PACKAGE_SCHEME = "package"; 515 516 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 517 518 /** Permission grant: not grant the permission. */ 519 private static final int GRANT_DENIED = 1; 520 521 /** Permission grant: grant the permission as an install permission. */ 522 private static final int GRANT_INSTALL = 2; 523 524 /** Permission grant: grant the permission as a runtime one. */ 525 private static final int GRANT_RUNTIME = 3; 526 527 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 528 private static final int GRANT_UPGRADE = 4; 529 530 /** Canonical intent used to identify what counts as a "web browser" app */ 531 private static final Intent sBrowserIntent; 532 static { 533 sBrowserIntent = new Intent(); 534 sBrowserIntent.setAction(Intent.ACTION_VIEW); 535 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 536 sBrowserIntent.setData(Uri.parse("http:")); 537 } 538 539 /** 540 * The set of all protected actions [i.e. those actions for which a high priority 541 * intent filter is disallowed]. 542 */ 543 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 544 static { 545 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 546 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 547 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 548 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 549 } 550 551 // Compilation reasons. 552 public static final int REASON_FIRST_BOOT = 0; 553 public static final int REASON_BOOT = 1; 554 public static final int REASON_INSTALL = 2; 555 public static final int REASON_BACKGROUND_DEXOPT = 3; 556 public static final int REASON_AB_OTA = 4; 557 558 public static final int REASON_LAST = REASON_AB_OTA; 559 560 /** All dangerous permission names in the same order as the events in MetricsEvent */ 561 private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList( 562 Manifest.permission.READ_CALENDAR, 563 Manifest.permission.WRITE_CALENDAR, 564 Manifest.permission.CAMERA, 565 Manifest.permission.READ_CONTACTS, 566 Manifest.permission.WRITE_CONTACTS, 567 Manifest.permission.GET_ACCOUNTS, 568 Manifest.permission.ACCESS_FINE_LOCATION, 569 Manifest.permission.ACCESS_COARSE_LOCATION, 570 Manifest.permission.RECORD_AUDIO, 571 Manifest.permission.READ_PHONE_STATE, 572 Manifest.permission.CALL_PHONE, 573 Manifest.permission.READ_CALL_LOG, 574 Manifest.permission.WRITE_CALL_LOG, 575 Manifest.permission.ADD_VOICEMAIL, 576 Manifest.permission.USE_SIP, 577 Manifest.permission.PROCESS_OUTGOING_CALLS, 578 Manifest.permission.READ_CELL_BROADCASTS, 579 Manifest.permission.BODY_SENSORS, 580 Manifest.permission.SEND_SMS, 581 Manifest.permission.RECEIVE_SMS, 582 Manifest.permission.READ_SMS, 583 Manifest.permission.RECEIVE_WAP_PUSH, 584 Manifest.permission.RECEIVE_MMS, 585 Manifest.permission.READ_EXTERNAL_STORAGE, 586 Manifest.permission.WRITE_EXTERNAL_STORAGE, 587 Manifest.permission.READ_PHONE_NUMBERS, 588 Manifest.permission.ANSWER_PHONE_CALLS); 589 590 591 /** 592 * Version number for the package parser cache. Increment this whenever the format or 593 * extent of cached data changes. See {@code PackageParser#setCacheDir}. 594 */ 595 private static final String PACKAGE_PARSER_CACHE_VERSION = "1"; 596 597 /** 598 * Whether the package parser cache is enabled. 599 */ 600 private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true; 601 602 final ServiceThread mHandlerThread; 603 604 final PackageHandler mHandler; 605 606 private final ProcessLoggingHandler mProcessLoggingHandler; 607 608 /** 609 * Messages for {@link #mHandler} that need to wait for system ready before 610 * being dispatched. 611 */ 612 private ArrayList<Message> mPostSystemReadyMessages; 613 614 final int mSdkVersion = Build.VERSION.SDK_INT; 615 616 final Context mContext; 617 final boolean mFactoryTest; 618 final boolean mOnlyCore; 619 final DisplayMetrics mMetrics; 620 final int mDefParseFlags; 621 final String[] mSeparateProcesses; 622 final boolean mIsUpgrade; 623 final boolean mIsPreNUpgrade; 624 final boolean mIsPreNMR1Upgrade; 625 626 // Have we told the Activity Manager to whitelist the default container service by uid yet? 627 @GuardedBy("mPackages") 628 boolean mDefaultContainerWhitelisted = false; 629 630 @GuardedBy("mPackages") 631 private boolean mDexOptDialogShown; 632 633 /** The location for ASEC container files on internal storage. */ 634 final String mAsecInternalPath; 635 636 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 637 // LOCK HELD. Can be called with mInstallLock held. 638 @GuardedBy("mInstallLock") 639 final Installer mInstaller; 640 641 /** Directory where installed third-party apps stored */ 642 final File mAppInstallDir; 643 644 /** 645 * Directory to which applications installed internally have their 646 * 32 bit native libraries copied. 647 */ 648 private File mAppLib32InstallDir; 649 650 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 651 // apps. 652 final File mDrmAppPrivateInstallDir; 653 654 // ---------------------------------------------------------------- 655 656 // Lock for state used when installing and doing other long running 657 // operations. Methods that must be called with this lock held have 658 // the suffix "LI". 659 final Object mInstallLock = new Object(); 660 661 // ---------------------------------------------------------------- 662 663 // Keys are String (package name), values are Package. This also serves 664 // as the lock for the global state. Methods that must be called with 665 // this lock held have the prefix "LP". 666 @GuardedBy("mPackages") 667 final ArrayMap<String, PackageParser.Package> mPackages = 668 new ArrayMap<String, PackageParser.Package>(); 669 670 final ArrayMap<String, Set<String>> mKnownCodebase = 671 new ArrayMap<String, Set<String>>(); 672 673 // Keys are isolated uids and values are the uid of the application 674 // that created the isolated proccess. 675 @GuardedBy("mPackages") 676 final SparseIntArray mIsolatedOwners = new SparseIntArray(); 677 678 // List of APK paths to load for each user and package. This data is never 679 // persisted by the package manager. Instead, the overlay manager will 680 // ensure the data is up-to-date in runtime. 681 @GuardedBy("mPackages") 682 final SparseArray<ArrayMap<String, ArrayList<String>>> mEnabledOverlayPaths = 683 new SparseArray<ArrayMap<String, ArrayList<String>>>(); 684 685 /** 686 * Tracks new system packages [received in an OTA] that we expect to 687 * find updated user-installed versions. Keys are package name, values 688 * are package location. 689 */ 690 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 691 /** 692 * Tracks high priority intent filters for protected actions. During boot, certain 693 * filter actions are protected and should never be allowed to have a high priority 694 * intent filter for them. However, there is one, and only one exception -- the 695 * setup wizard. It must be able to define a high priority intent filter for these 696 * actions to ensure there are no escapes from the wizard. We need to delay processing 697 * of these during boot as we need to look at all of the system packages in order 698 * to know which component is the setup wizard. 699 */ 700 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 701 /** 702 * Whether or not processing protected filters should be deferred. 703 */ 704 private boolean mDeferProtectedFilters = true; 705 706 /** 707 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 708 */ 709 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 710 /** 711 * Whether or not system app permissions should be promoted from install to runtime. 712 */ 713 boolean mPromoteSystemApps; 714 715 @GuardedBy("mPackages") 716 final Settings mSettings; 717 718 /** 719 * Set of package names that are currently "frozen", which means active 720 * surgery is being done on the code/data for that package. The platform 721 * will refuse to launch frozen packages to avoid race conditions. 722 * 723 * @see PackageFreezer 724 */ 725 @GuardedBy("mPackages") 726 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 727 728 final ProtectedPackages mProtectedPackages; 729 730 boolean mFirstBoot; 731 732 PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy; 733 734 // System configuration read by SystemConfig. 735 final int[] mGlobalGids; 736 final SparseArray<ArraySet<String>> mSystemPermissions; 737 @GuardedBy("mAvailableFeatures") 738 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 739 740 // If mac_permissions.xml was found for seinfo labeling. 741 boolean mFoundPolicyFile; 742 743 private final InstantAppRegistry mInstantAppRegistry; 744 745 @GuardedBy("mPackages") 746 int mChangedPackagesSequenceNumber; 747 /** 748 * List of changed [installed, removed or updated] packages. 749 * mapping from user id -> sequence number -> package name 750 */ 751 @GuardedBy("mPackages") 752 final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>(); 753 /** 754 * The sequence number of the last change to a package. 755 * mapping from user id -> package name -> sequence number 756 */ 757 @GuardedBy("mPackages") 758 final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>(); 759 760 class PackageParserCallback implements PackageParser.Callback { 761 @Override public final boolean hasFeature(String feature) { 762 return PackageManagerService.this.hasSystemFeature(feature, 0); 763 } 764 765 final List<PackageParser.Package> getStaticOverlayPackagesLocked( 766 Collection<PackageParser.Package> allPackages, String targetPackageName) { 767 List<PackageParser.Package> overlayPackages = null; 768 for (PackageParser.Package p : allPackages) { 769 if (targetPackageName.equals(p.mOverlayTarget) && p.mIsStaticOverlay) { 770 if (overlayPackages == null) { 771 overlayPackages = new ArrayList<PackageParser.Package>(); 772 } 773 overlayPackages.add(p); 774 } 775 } 776 if (overlayPackages != null) { 777 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 778 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 779 return p1.mOverlayPriority - p2.mOverlayPriority; 780 } 781 }; 782 Collections.sort(overlayPackages, cmp); 783 } 784 return overlayPackages; 785 } 786 787 final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages, 788 String targetPackageName, String targetPath) { 789 if ("android".equals(targetPackageName)) { 790 // Static RROs targeting to "android", ie framework-res.apk, are already applied by 791 // native AssetManager. 792 return null; 793 } 794 List<PackageParser.Package> overlayPackages = 795 getStaticOverlayPackagesLocked(allPackages, targetPackageName); 796 if (overlayPackages == null || overlayPackages.isEmpty()) { 797 return null; 798 } 799 List<String> overlayPathList = null; 800 for (PackageParser.Package overlayPackage : overlayPackages) { 801 if (targetPath == null) { 802 if (overlayPathList == null) { 803 overlayPathList = new ArrayList<String>(); 804 } 805 overlayPathList.add(overlayPackage.baseCodePath); 806 continue; 807 } 808 809 try { 810 // Creates idmaps for system to parse correctly the Android manifest of the 811 // target package. 812 // 813 // OverlayManagerService will update each of them with a correct gid from its 814 // target package app id. 815 mInstaller.idmap(targetPath, overlayPackage.baseCodePath, 816 UserHandle.getSharedAppGid( 817 UserHandle.getUserGid(UserHandle.USER_SYSTEM))); 818 if (overlayPathList == null) { 819 overlayPathList = new ArrayList<String>(); 820 } 821 overlayPathList.add(overlayPackage.baseCodePath); 822 } catch (InstallerException e) { 823 Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " + 824 overlayPackage.baseCodePath); 825 } 826 } 827 return overlayPathList == null ? null : overlayPathList.toArray(new String[0]); 828 } 829 830 String[] getStaticOverlayPaths(String targetPackageName, String targetPath) { 831 synchronized (mPackages) { 832 return getStaticOverlayPathsLocked( 833 mPackages.values(), targetPackageName, targetPath); 834 } 835 } 836 837 @Override public final String[] getOverlayApks(String targetPackageName) { 838 return getStaticOverlayPaths(targetPackageName, null); 839 } 840 841 @Override public final String[] getOverlayPaths(String targetPackageName, 842 String targetPath) { 843 return getStaticOverlayPaths(targetPackageName, targetPath); 844 } 845 }; 846 847 class ParallelPackageParserCallback extends PackageParserCallback { 848 List<PackageParser.Package> mOverlayPackages = null; 849 850 void findStaticOverlayPackages() { 851 synchronized (mPackages) { 852 for (PackageParser.Package p : mPackages.values()) { 853 if (p.mIsStaticOverlay) { 854 if (mOverlayPackages == null) { 855 mOverlayPackages = new ArrayList<PackageParser.Package>(); 856 } 857 mOverlayPackages.add(p); 858 } 859 } 860 } 861 } 862 863 @Override 864 synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) { 865 // We can trust mOverlayPackages without holding mPackages because package uninstall 866 // can't happen while running parallel parsing. 867 // Moreover holding mPackages on each parsing thread causes dead-lock. 868 return mOverlayPackages == null ? null : 869 getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath); 870 } 871 } 872 873 final PackageParser.Callback mPackageParserCallback = new PackageParserCallback(); 874 final ParallelPackageParserCallback mParallelPackageParserCallback = 875 new ParallelPackageParserCallback(); 876 877 public static final class SharedLibraryEntry { 878 public final String path; 879 public final String apk; 880 public final SharedLibraryInfo info; 881 882 SharedLibraryEntry(String _path, String _apk, String name, int version, int type, 883 String declaringPackageName, int declaringPackageVersionCode) { 884 path = _path; 885 apk = _apk; 886 info = new SharedLibraryInfo(name, version, type, new VersionedPackage( 887 declaringPackageName, declaringPackageVersionCode), null); 888 } 889 } 890 891 // Currently known shared libraries. 892 final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>(); 893 final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage = 894 new ArrayMap<>(); 895 896 // All available activities, for your resolving pleasure. 897 final ActivityIntentResolver mActivities = 898 new ActivityIntentResolver(); 899 900 // All available receivers, for your resolving pleasure. 901 final ActivityIntentResolver mReceivers = 902 new ActivityIntentResolver(); 903 904 // All available services, for your resolving pleasure. 905 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 906 907 // All available providers, for your resolving pleasure. 908 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 909 910 // Mapping from provider base names (first directory in content URI codePath) 911 // to the provider information. 912 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 913 new ArrayMap<String, PackageParser.Provider>(); 914 915 // Mapping from instrumentation class names to info about them. 916 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 917 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 918 919 // Mapping from permission names to info about them. 920 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 921 new ArrayMap<String, PackageParser.PermissionGroup>(); 922 923 // Packages whose data we have transfered into another package, thus 924 // should no longer exist. 925 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 926 927 // Broadcast actions that are only available to the system. 928 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 929 930 /** List of packages waiting for verification. */ 931 final SparseArray<PackageVerificationState> mPendingVerification 932 = new SparseArray<PackageVerificationState>(); 933 934 /** Set of packages associated with each app op permission. */ 935 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 936 937 final PackageInstallerService mInstallerService; 938 939 private final PackageDexOptimizer mPackageDexOptimizer; 940 // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package 941 // is used by other apps). 942 private final DexManager mDexManager; 943 944 private AtomicInteger mNextMoveId = new AtomicInteger(); 945 private final MoveCallbacks mMoveCallbacks; 946 947 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 948 949 // Cache of users who need badging. 950 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 951 952 /** Token for keys in mPendingVerification. */ 953 private int mPendingVerificationToken = 0; 954 955 volatile boolean mSystemReady; 956 volatile boolean mSafeMode; 957 volatile boolean mHasSystemUidErrors; 958 private volatile boolean mEphemeralAppsDisabled; 959 960 ApplicationInfo mAndroidApplication; 961 final ActivityInfo mResolveActivity = new ActivityInfo(); 962 final ResolveInfo mResolveInfo = new ResolveInfo(); 963 ComponentName mResolveComponentName; 964 PackageParser.Package mPlatformPackage; 965 ComponentName mCustomResolverComponentName; 966 967 boolean mResolverReplaced = false; 968 969 private final @Nullable ComponentName mIntentFilterVerifierComponent; 970 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 971 972 private int mIntentFilterVerificationToken = 0; 973 974 /** The service connection to the ephemeral resolver */ 975 final EphemeralResolverConnection mInstantAppResolverConnection; 976 /** Component used to show resolver settings for Instant Apps */ 977 final ComponentName mInstantAppResolverSettingsComponent; 978 979 /** Activity used to install instant applications */ 980 ActivityInfo mInstantAppInstallerActivity; 981 final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo(); 982 983 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 984 = new SparseArray<IntentFilterVerificationState>(); 985 986 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy; 987 988 // List of packages names to keep cached, even if they are uninstalled for all users 989 private List<String> mKeepUninstalledPackages; 990 991 private UserManagerInternal mUserManagerInternal; 992 993 private DeviceIdleController.LocalService mDeviceIdleController; 994 995 private File mCacheDir; 996 997 private ArraySet<String> mPrivappPermissionsViolations; 998 999 private Future<?> mPrepareAppDataFuture; 1000 1001 private static class IFVerificationParams { 1002 PackageParser.Package pkg; 1003 boolean replacing; 1004 int userId; 1005 int verifierUid; 1006 1007 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 1008 int _userId, int _verifierUid) { 1009 pkg = _pkg; 1010 replacing = _replacing; 1011 userId = _userId; 1012 replacing = _replacing; 1013 verifierUid = _verifierUid; 1014 } 1015 } 1016 1017 private interface IntentFilterVerifier<T extends IntentFilter> { 1018 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 1019 T filter, String packageName); 1020 void startVerifications(int userId); 1021 void receiveVerificationResponse(int verificationId); 1022 } 1023 1024 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 1025 private Context mContext; 1026 private ComponentName mIntentFilterVerifierComponent; 1027 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 1028 1029 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 1030 mContext = context; 1031 mIntentFilterVerifierComponent = verifierComponent; 1032 } 1033 1034 private String getDefaultScheme() { 1035 return IntentFilter.SCHEME_HTTPS; 1036 } 1037 1038 @Override 1039 public void startVerifications(int userId) { 1040 // Launch verifications requests 1041 int count = mCurrentIntentFilterVerifications.size(); 1042 for (int n=0; n<count; n++) { 1043 int verificationId = mCurrentIntentFilterVerifications.get(n); 1044 final IntentFilterVerificationState ivs = 1045 mIntentFilterVerificationStates.get(verificationId); 1046 1047 String packageName = ivs.getPackageName(); 1048 1049 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 1050 final int filterCount = filters.size(); 1051 ArraySet<String> domainsSet = new ArraySet<>(); 1052 for (int m=0; m<filterCount; m++) { 1053 PackageParser.ActivityIntentInfo filter = filters.get(m); 1054 domainsSet.addAll(filter.getHostsList()); 1055 } 1056 synchronized (mPackages) { 1057 if (mSettings.createIntentFilterVerificationIfNeededLPw( 1058 packageName, domainsSet) != null) { 1059 scheduleWriteSettingsLocked(); 1060 } 1061 } 1062 sendVerificationRequest(userId, verificationId, ivs); 1063 } 1064 mCurrentIntentFilterVerifications.clear(); 1065 } 1066 1067 private void sendVerificationRequest(int userId, int verificationId, 1068 IntentFilterVerificationState ivs) { 1069 1070 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 1071 verificationIntent.putExtra( 1072 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 1073 verificationId); 1074 verificationIntent.putExtra( 1075 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 1076 getDefaultScheme()); 1077 verificationIntent.putExtra( 1078 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 1079 ivs.getHostsString()); 1080 verificationIntent.putExtra( 1081 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 1082 ivs.getPackageName()); 1083 verificationIntent.setComponent(mIntentFilterVerifierComponent); 1084 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 1085 1086 DeviceIdleController.LocalService idleController = getDeviceIdleController(); 1087 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 1088 mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(), 1089 userId, false, "intent filter verifier"); 1090 1091 UserHandle user = new UserHandle(userId); 1092 mContext.sendBroadcastAsUser(verificationIntent, user); 1093 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1094 "Sending IntentFilter verification broadcast"); 1095 } 1096 1097 public void receiveVerificationResponse(int verificationId) { 1098 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 1099 1100 final boolean verified = ivs.isVerified(); 1101 1102 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 1103 final int count = filters.size(); 1104 if (DEBUG_DOMAIN_VERIFICATION) { 1105 Slog.i(TAG, "Received verification response " + verificationId 1106 + " for " + count + " filters, verified=" + verified); 1107 } 1108 for (int n=0; n<count; n++) { 1109 PackageParser.ActivityIntentInfo filter = filters.get(n); 1110 filter.setVerified(verified); 1111 1112 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 1113 + " verified with result:" + verified + " and hosts:" 1114 + ivs.getHostsString()); 1115 } 1116 1117 mIntentFilterVerificationStates.remove(verificationId); 1118 1119 final String packageName = ivs.getPackageName(); 1120 IntentFilterVerificationInfo ivi = null; 1121 1122 synchronized (mPackages) { 1123 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 1124 } 1125 if (ivi == null) { 1126 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 1127 + verificationId + " packageName:" + packageName); 1128 return; 1129 } 1130 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1131 "Updating IntentFilterVerificationInfo for package " + packageName 1132 +" verificationId:" + verificationId); 1133 1134 synchronized (mPackages) { 1135 if (verified) { 1136 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 1137 } else { 1138 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 1139 } 1140 scheduleWriteSettingsLocked(); 1141 1142 final int userId = ivs.getUserId(); 1143 if (userId != UserHandle.USER_ALL) { 1144 final int userStatus = 1145 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 1146 1147 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 1148 boolean needUpdate = false; 1149 1150 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 1151 // already been set by the User thru the Disambiguation dialog 1152 switch (userStatus) { 1153 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 1154 if (verified) { 1155 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 1156 } else { 1157 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 1158 } 1159 needUpdate = true; 1160 break; 1161 1162 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 1163 if (verified) { 1164 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 1165 needUpdate = true; 1166 } 1167 break; 1168 1169 default: 1170 // Nothing to do 1171 } 1172 1173 if (needUpdate) { 1174 mSettings.updateIntentFilterVerificationStatusLPw( 1175 packageName, updatedStatus, userId); 1176 scheduleWritePackageRestrictionsLocked(userId); 1177 } 1178 } 1179 } 1180 } 1181 1182 @Override 1183 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 1184 ActivityIntentInfo filter, String packageName) { 1185 if (!hasValidDomains(filter)) { 1186 return false; 1187 } 1188 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 1189 if (ivs == null) { 1190 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 1191 packageName); 1192 } 1193 if (DEBUG_DOMAIN_VERIFICATION) { 1194 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 1195 } 1196 ivs.addFilter(filter); 1197 return true; 1198 } 1199 1200 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 1201 int userId, int verificationId, String packageName) { 1202 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 1203 verifierUid, userId, packageName); 1204 ivs.setPendingState(); 1205 synchronized (mPackages) { 1206 mIntentFilterVerificationStates.append(verificationId, ivs); 1207 mCurrentIntentFilterVerifications.add(verificationId); 1208 } 1209 return ivs; 1210 } 1211 } 1212 1213 private static boolean hasValidDomains(ActivityIntentInfo filter) { 1214 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 1215 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 1216 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 1217 } 1218 1219 // Set of pending broadcasts for aggregating enable/disable of components. 1220 static class PendingPackageBroadcasts { 1221 // for each user id, a map of <package name -> components within that package> 1222 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 1223 1224 public PendingPackageBroadcasts() { 1225 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 1226 } 1227 1228 public ArrayList<String> get(int userId, String packageName) { 1229 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1230 return packages.get(packageName); 1231 } 1232 1233 public void put(int userId, String packageName, ArrayList<String> components) { 1234 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1235 packages.put(packageName, components); 1236 } 1237 1238 public void remove(int userId, String packageName) { 1239 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 1240 if (packages != null) { 1241 packages.remove(packageName); 1242 } 1243 } 1244 1245 public void remove(int userId) { 1246 mUidMap.remove(userId); 1247 } 1248 1249 public int userIdCount() { 1250 return mUidMap.size(); 1251 } 1252 1253 public int userIdAt(int n) { 1254 return mUidMap.keyAt(n); 1255 } 1256 1257 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 1258 return mUidMap.get(userId); 1259 } 1260 1261 public int size() { 1262 // total number of pending broadcast entries across all userIds 1263 int num = 0; 1264 for (int i = 0; i< mUidMap.size(); i++) { 1265 num += mUidMap.valueAt(i).size(); 1266 } 1267 return num; 1268 } 1269 1270 public void clear() { 1271 mUidMap.clear(); 1272 } 1273 1274 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1275 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1276 if (map == null) { 1277 map = new ArrayMap<String, ArrayList<String>>(); 1278 mUidMap.put(userId, map); 1279 } 1280 return map; 1281 } 1282 } 1283 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1284 1285 // Service Connection to remote media container service to copy 1286 // package uri's from external media onto secure containers 1287 // or internal storage. 1288 private IMediaContainerService mContainerService = null; 1289 1290 static final int SEND_PENDING_BROADCAST = 1; 1291 static final int MCS_BOUND = 3; 1292 static final int END_COPY = 4; 1293 static final int INIT_COPY = 5; 1294 static final int MCS_UNBIND = 6; 1295 static final int START_CLEANING_PACKAGE = 7; 1296 static final int FIND_INSTALL_LOC = 8; 1297 static final int POST_INSTALL = 9; 1298 static final int MCS_RECONNECT = 10; 1299 static final int MCS_GIVE_UP = 11; 1300 static final int UPDATED_MEDIA_STATUS = 12; 1301 static final int WRITE_SETTINGS = 13; 1302 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1303 static final int PACKAGE_VERIFIED = 15; 1304 static final int CHECK_PENDING_VERIFICATION = 16; 1305 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1306 static final int INTENT_FILTER_VERIFIED = 18; 1307 static final int WRITE_PACKAGE_LIST = 19; 1308 static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20; 1309 1310 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1311 1312 // Delay time in millisecs 1313 static final int BROADCAST_DELAY = 10 * 1000; 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 final boolean mPermissionReviewRequired; 1388 1389 private final PackageUsage mPackageUsage = new PackageUsage(); 1390 private final CompilerStats mCompilerStats = new CompilerStats(); 1391 1392 class PackageHandler extends Handler { 1393 private boolean mBound = false; 1394 final ArrayList<HandlerParams> mPendingInstalls = 1395 new ArrayList<HandlerParams>(); 1396 1397 private boolean connectToService() { 1398 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1399 " DefaultContainerService"); 1400 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1401 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1402 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1403 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1404 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1405 mBound = true; 1406 return true; 1407 } 1408 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1409 return false; 1410 } 1411 1412 private void disconnectService() { 1413 mContainerService = null; 1414 mBound = false; 1415 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1416 mContext.unbindService(mDefContainerConn); 1417 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1418 } 1419 1420 PackageHandler(Looper looper) { 1421 super(looper); 1422 } 1423 1424 public void handleMessage(Message msg) { 1425 try { 1426 doHandleMessage(msg); 1427 } finally { 1428 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1429 } 1430 } 1431 1432 void doHandleMessage(Message msg) { 1433 switch (msg.what) { 1434 case INIT_COPY: { 1435 HandlerParams params = (HandlerParams) msg.obj; 1436 int idx = mPendingInstalls.size(); 1437 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1438 // If a bind was already initiated we dont really 1439 // need to do anything. The pending install 1440 // will be processed later on. 1441 if (!mBound) { 1442 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1443 System.identityHashCode(mHandler)); 1444 // If this is the only one pending we might 1445 // have to bind to the service again. 1446 if (!connectToService()) { 1447 Slog.e(TAG, "Failed to bind to media container service"); 1448 params.serviceError(); 1449 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1450 System.identityHashCode(mHandler)); 1451 if (params.traceMethod != null) { 1452 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1453 params.traceCookie); 1454 } 1455 return; 1456 } else { 1457 // Once we bind to the service, the first 1458 // pending request will be processed. 1459 mPendingInstalls.add(idx, params); 1460 } 1461 } else { 1462 mPendingInstalls.add(idx, params); 1463 // Already bound to the service. Just make 1464 // sure we trigger off processing the first request. 1465 if (idx == 0) { 1466 mHandler.sendEmptyMessage(MCS_BOUND); 1467 } 1468 } 1469 break; 1470 } 1471 case MCS_BOUND: { 1472 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1473 if (msg.obj != null) { 1474 mContainerService = (IMediaContainerService) msg.obj; 1475 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1476 System.identityHashCode(mHandler)); 1477 } 1478 if (mContainerService == null) { 1479 if (!mBound) { 1480 // Something seriously wrong since we are not bound and we are not 1481 // waiting for connection. Bail out. 1482 Slog.e(TAG, "Cannot bind to media container service"); 1483 for (HandlerParams params : mPendingInstalls) { 1484 // Indicate service bind error 1485 params.serviceError(); 1486 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1487 System.identityHashCode(params)); 1488 if (params.traceMethod != null) { 1489 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1490 params.traceMethod, params.traceCookie); 1491 } 1492 return; 1493 } 1494 mPendingInstalls.clear(); 1495 } else { 1496 Slog.w(TAG, "Waiting to connect to media container service"); 1497 } 1498 } else if (mPendingInstalls.size() > 0) { 1499 HandlerParams params = mPendingInstalls.get(0); 1500 if (params != null) { 1501 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1502 System.identityHashCode(params)); 1503 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1504 if (params.startCopy()) { 1505 // We are done... look for more work or to 1506 // go idle. 1507 if (DEBUG_SD_INSTALL) Log.i(TAG, 1508 "Checking for more work or unbind..."); 1509 // Delete pending install 1510 if (mPendingInstalls.size() > 0) { 1511 mPendingInstalls.remove(0); 1512 } 1513 if (mPendingInstalls.size() == 0) { 1514 if (mBound) { 1515 if (DEBUG_SD_INSTALL) Log.i(TAG, 1516 "Posting delayed MCS_UNBIND"); 1517 removeMessages(MCS_UNBIND); 1518 Message ubmsg = obtainMessage(MCS_UNBIND); 1519 // Unbind after a little delay, to avoid 1520 // continual thrashing. 1521 sendMessageDelayed(ubmsg, 10000); 1522 } 1523 } else { 1524 // There are more pending requests in queue. 1525 // Just post MCS_BOUND message to trigger processing 1526 // of next pending install. 1527 if (DEBUG_SD_INSTALL) Log.i(TAG, 1528 "Posting MCS_BOUND for next work"); 1529 mHandler.sendEmptyMessage(MCS_BOUND); 1530 } 1531 } 1532 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1533 } 1534 } else { 1535 // Should never happen ideally. 1536 Slog.w(TAG, "Empty queue"); 1537 } 1538 break; 1539 } 1540 case MCS_RECONNECT: { 1541 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1542 if (mPendingInstalls.size() > 0) { 1543 if (mBound) { 1544 disconnectService(); 1545 } 1546 if (!connectToService()) { 1547 Slog.e(TAG, "Failed to bind to media container service"); 1548 for (HandlerParams params : mPendingInstalls) { 1549 // Indicate service bind error 1550 params.serviceError(); 1551 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1552 System.identityHashCode(params)); 1553 } 1554 mPendingInstalls.clear(); 1555 } 1556 } 1557 break; 1558 } 1559 case MCS_UNBIND: { 1560 // If there is no actual work left, then time to unbind. 1561 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1562 1563 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1564 if (mBound) { 1565 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1566 1567 disconnectService(); 1568 } 1569 } else if (mPendingInstalls.size() > 0) { 1570 // There are more pending requests in queue. 1571 // Just post MCS_BOUND message to trigger processing 1572 // of next pending install. 1573 mHandler.sendEmptyMessage(MCS_BOUND); 1574 } 1575 1576 break; 1577 } 1578 case MCS_GIVE_UP: { 1579 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1580 HandlerParams params = mPendingInstalls.remove(0); 1581 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1582 System.identityHashCode(params)); 1583 break; 1584 } 1585 case SEND_PENDING_BROADCAST: { 1586 String packages[]; 1587 ArrayList<String> components[]; 1588 int size = 0; 1589 int uids[]; 1590 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1591 synchronized (mPackages) { 1592 if (mPendingBroadcasts == null) { 1593 return; 1594 } 1595 size = mPendingBroadcasts.size(); 1596 if (size <= 0) { 1597 // Nothing to be done. Just return 1598 return; 1599 } 1600 packages = new String[size]; 1601 components = new ArrayList[size]; 1602 uids = new int[size]; 1603 int i = 0; // filling out the above arrays 1604 1605 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1606 int packageUserId = mPendingBroadcasts.userIdAt(n); 1607 Iterator<Map.Entry<String, ArrayList<String>>> it 1608 = mPendingBroadcasts.packagesForUserId(packageUserId) 1609 .entrySet().iterator(); 1610 while (it.hasNext() && i < size) { 1611 Map.Entry<String, ArrayList<String>> ent = it.next(); 1612 packages[i] = ent.getKey(); 1613 components[i] = ent.getValue(); 1614 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1615 uids[i] = (ps != null) 1616 ? UserHandle.getUid(packageUserId, ps.appId) 1617 : -1; 1618 i++; 1619 } 1620 } 1621 size = i; 1622 mPendingBroadcasts.clear(); 1623 } 1624 // Send broadcasts 1625 for (int i = 0; i < size; i++) { 1626 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1627 } 1628 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1629 break; 1630 } 1631 case START_CLEANING_PACKAGE: { 1632 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1633 final String packageName = (String)msg.obj; 1634 final int userId = msg.arg1; 1635 final boolean andCode = msg.arg2 != 0; 1636 synchronized (mPackages) { 1637 if (userId == UserHandle.USER_ALL) { 1638 int[] users = sUserManager.getUserIds(); 1639 for (int user : users) { 1640 mSettings.addPackageToCleanLPw( 1641 new PackageCleanItem(user, packageName, andCode)); 1642 } 1643 } else { 1644 mSettings.addPackageToCleanLPw( 1645 new PackageCleanItem(userId, packageName, andCode)); 1646 } 1647 } 1648 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1649 startCleaningPackages(); 1650 } break; 1651 case POST_INSTALL: { 1652 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1653 1654 PostInstallData data = mRunningInstalls.get(msg.arg1); 1655 final boolean didRestore = (msg.arg2 != 0); 1656 mRunningInstalls.delete(msg.arg1); 1657 1658 if (data != null) { 1659 InstallArgs args = data.args; 1660 PackageInstalledInfo parentRes = data.res; 1661 1662 final boolean grantPermissions = (args.installFlags 1663 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1664 final boolean killApp = (args.installFlags 1665 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1666 final String[] grantedPermissions = args.installGrantPermissions; 1667 1668 // Handle the parent package 1669 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1670 grantedPermissions, didRestore, args.installerPackageName, 1671 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 grantedPermissions, false, args.installerPackageName, 1680 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 UPDATED_MEDIA_STATUS: { 1695 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1696 boolean reportStatus = msg.arg1 == 1; 1697 boolean doGc = msg.arg2 == 1; 1698 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1699 if (doGc) { 1700 // Force a gc to clear up stale containers. 1701 Runtime.getRuntime().gc(); 1702 } 1703 if (msg.obj != null) { 1704 @SuppressWarnings("unchecked") 1705 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1706 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1707 // Unload containers 1708 unloadAllContainers(args); 1709 } 1710 if (reportStatus) { 1711 try { 1712 if (DEBUG_SD_INSTALL) Log.i(TAG, 1713 "Invoking StorageManagerService call back"); 1714 PackageHelper.getStorageManager().finishMediaUpdate(); 1715 } catch (RemoteException e) { 1716 Log.e(TAG, "StorageManagerService not running?"); 1717 } 1718 } 1719 } break; 1720 case WRITE_SETTINGS: { 1721 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1722 synchronized (mPackages) { 1723 removeMessages(WRITE_SETTINGS); 1724 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1725 mSettings.writeLPr(); 1726 mDirtyUsers.clear(); 1727 } 1728 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1729 } break; 1730 case WRITE_PACKAGE_RESTRICTIONS: { 1731 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1732 synchronized (mPackages) { 1733 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1734 for (int userId : mDirtyUsers) { 1735 mSettings.writePackageRestrictionsLPr(userId); 1736 } 1737 mDirtyUsers.clear(); 1738 } 1739 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1740 } break; 1741 case WRITE_PACKAGE_LIST: { 1742 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1743 synchronized (mPackages) { 1744 removeMessages(WRITE_PACKAGE_LIST); 1745 mSettings.writePackageListLPr(msg.arg1); 1746 } 1747 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1748 } break; 1749 case CHECK_PENDING_VERIFICATION: { 1750 final int verificationId = msg.arg1; 1751 final PackageVerificationState state = mPendingVerification.get(verificationId); 1752 1753 if ((state != null) && !state.timeoutExtended()) { 1754 final InstallArgs args = state.getInstallArgs(); 1755 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1756 1757 Slog.i(TAG, "Verification timed out for " + originUri); 1758 mPendingVerification.remove(verificationId); 1759 1760 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1761 1762 final UserHandle user = args.getUser(); 1763 if (getDefaultVerificationResponse(user) 1764 == PackageManager.VERIFICATION_ALLOW) { 1765 Slog.i(TAG, "Continuing with installation of " + originUri); 1766 state.setVerifierResponse(Binder.getCallingUid(), 1767 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1768 broadcastPackageVerified(verificationId, originUri, 1769 PackageManager.VERIFICATION_ALLOW, user); 1770 try { 1771 ret = args.copyApk(mContainerService, true); 1772 } catch (RemoteException e) { 1773 Slog.e(TAG, "Could not contact the ContainerService"); 1774 } 1775 } else { 1776 broadcastPackageVerified(verificationId, originUri, 1777 PackageManager.VERIFICATION_REJECT, user); 1778 } 1779 1780 Trace.asyncTraceEnd( 1781 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1782 1783 processPendingInstall(args, ret); 1784 mHandler.sendEmptyMessage(MCS_UNBIND); 1785 } 1786 break; 1787 } 1788 case PACKAGE_VERIFIED: { 1789 final int verificationId = msg.arg1; 1790 1791 final PackageVerificationState state = mPendingVerification.get(verificationId); 1792 if (state == null) { 1793 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1794 break; 1795 } 1796 1797 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1798 1799 state.setVerifierResponse(response.callerUid, response.code); 1800 1801 if (state.isVerificationComplete()) { 1802 mPendingVerification.remove(verificationId); 1803 1804 final InstallArgs args = state.getInstallArgs(); 1805 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1806 1807 int ret; 1808 if (state.isInstallAllowed()) { 1809 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1810 broadcastPackageVerified(verificationId, originUri, 1811 response.code, state.getInstallArgs().getUser()); 1812 try { 1813 ret = args.copyApk(mContainerService, true); 1814 } catch (RemoteException e) { 1815 Slog.e(TAG, "Could not contact the ContainerService"); 1816 } 1817 } else { 1818 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1819 } 1820 1821 Trace.asyncTraceEnd( 1822 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1823 1824 processPendingInstall(args, ret); 1825 mHandler.sendEmptyMessage(MCS_UNBIND); 1826 } 1827 1828 break; 1829 } 1830 case START_INTENT_FILTER_VERIFICATIONS: { 1831 IFVerificationParams params = (IFVerificationParams) msg.obj; 1832 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1833 params.replacing, params.pkg); 1834 break; 1835 } 1836 case INTENT_FILTER_VERIFIED: { 1837 final int verificationId = msg.arg1; 1838 1839 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1840 verificationId); 1841 if (state == null) { 1842 Slog.w(TAG, "Invalid IntentFilter verification token " 1843 + verificationId + " received"); 1844 break; 1845 } 1846 1847 final int userId = state.getUserId(); 1848 1849 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1850 "Processing IntentFilter verification with token:" 1851 + verificationId + " and userId:" + userId); 1852 1853 final IntentFilterVerificationResponse response = 1854 (IntentFilterVerificationResponse) msg.obj; 1855 1856 state.setVerifierResponse(response.callerUid, response.code); 1857 1858 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1859 "IntentFilter verification with token:" + verificationId 1860 + " and userId:" + userId 1861 + " is settings verifier response with response code:" 1862 + response.code); 1863 1864 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1865 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1866 + response.getFailedDomainsString()); 1867 } 1868 1869 if (state.isVerificationComplete()) { 1870 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1871 } else { 1872 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1873 "IntentFilter verification with token:" + verificationId 1874 + " was not said to be complete"); 1875 } 1876 1877 break; 1878 } 1879 case INSTANT_APP_RESOLUTION_PHASE_TWO: { 1880 InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext, 1881 mInstantAppResolverConnection, 1882 (InstantAppRequest) msg.obj, 1883 mInstantAppInstallerActivity, 1884 mHandler); 1885 } 1886 } 1887 } 1888 } 1889 1890 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1891 boolean killApp, String[] grantedPermissions, 1892 boolean launchedForRestore, String installerPackage, 1893 IPackageInstallObserver2 installObserver) { 1894 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1895 // Send the removed broadcasts 1896 if (res.removedInfo != null) { 1897 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1898 } 1899 1900 // Now that we successfully installed the package, grant runtime 1901 // permissions if requested before broadcasting the install. Also 1902 // for legacy apps in permission review mode we clear the permission 1903 // review flag which is used to emulate runtime permissions for 1904 // legacy apps. 1905 if (grantPermissions) { 1906 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1907 } 1908 1909 final boolean update = res.removedInfo != null 1910 && res.removedInfo.removedPackage != null; 1911 final String origInstallerPackageName = res.removedInfo != null 1912 ? res.removedInfo.installerPackageName : null; 1913 1914 // If this is the first time we have child packages for a disabled privileged 1915 // app that had no children, we grant requested runtime permissions to the new 1916 // children if the parent on the system image had them already granted. 1917 if (res.pkg.parentPackage != null) { 1918 synchronized (mPackages) { 1919 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1920 } 1921 } 1922 1923 synchronized (mPackages) { 1924 mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers); 1925 } 1926 1927 final String packageName = res.pkg.applicationInfo.packageName; 1928 1929 // Determine the set of users who are adding this package for 1930 // the first time vs. those who are seeing an update. 1931 int[] firstUsers = EMPTY_INT_ARRAY; 1932 int[] updateUsers = EMPTY_INT_ARRAY; 1933 final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0; 1934 final PackageSetting ps = (PackageSetting) res.pkg.mExtras; 1935 for (int newUser : res.newUsers) { 1936 if (ps.getInstantApp(newUser)) { 1937 continue; 1938 } 1939 if (allNewUsers) { 1940 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1941 continue; 1942 } 1943 boolean isNew = true; 1944 for (int origUser : res.origUsers) { 1945 if (origUser == newUser) { 1946 isNew = false; 1947 break; 1948 } 1949 } 1950 if (isNew) { 1951 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1952 } else { 1953 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1954 } 1955 } 1956 1957 // Send installed broadcasts if the package is not a static shared lib. 1958 if (res.pkg.staticSharedLibName == null) { 1959 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1960 1961 // Send added for users that see the package for the first time 1962 // sendPackageAddedForNewUsers also deals with system apps 1963 int appId = UserHandle.getAppId(res.uid); 1964 boolean isSystem = res.pkg.applicationInfo.isSystemApp(); 1965 sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers); 1966 1967 // Send added for users that don't see the package for the first time 1968 Bundle extras = new Bundle(1); 1969 extras.putInt(Intent.EXTRA_UID, res.uid); 1970 if (update) { 1971 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1972 } 1973 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1974 extras, 0 /*flags*/, 1975 null /*targetPackage*/, null /*finishedReceiver*/, updateUsers); 1976 if (origInstallerPackageName != null) { 1977 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1978 extras, 0 /*flags*/, 1979 origInstallerPackageName, null /*finishedReceiver*/, updateUsers); 1980 } 1981 1982 // Send replaced for users that don't see the package for the first time 1983 if (update) { 1984 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1985 packageName, extras, 0 /*flags*/, 1986 null /*targetPackage*/, null /*finishedReceiver*/, 1987 updateUsers); 1988 if (origInstallerPackageName != null) { 1989 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 1990 extras, 0 /*flags*/, 1991 origInstallerPackageName, null /*finishedReceiver*/, updateUsers); 1992 } 1993 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1994 null /*package*/, null /*extras*/, 0 /*flags*/, 1995 packageName /*targetPackage*/, 1996 null /*finishedReceiver*/, updateUsers); 1997 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 1998 // First-install and we did a restore, so we're responsible for the 1999 // first-launch broadcast. 2000 if (DEBUG_BACKUP) { 2001 Slog.i(TAG, "Post-restore of " + packageName 2002 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers)); 2003 } 2004 sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers); 2005 } 2006 2007 // Send broadcast package appeared if forward locked/external for all users 2008 // treat asec-hosted packages like removable media on upgrade 2009 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 2010 if (DEBUG_INSTALL) { 2011 Slog.i(TAG, "upgrading pkg " + res.pkg 2012 + " is ASEC-hosted -> AVAILABLE"); 2013 } 2014 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 2015 ArrayList<String> pkgList = new ArrayList<>(1); 2016 pkgList.add(packageName); 2017 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 2018 } 2019 } 2020 2021 // Work that needs to happen on first install within each user 2022 if (firstUsers != null && firstUsers.length > 0) { 2023 synchronized (mPackages) { 2024 for (int userId : firstUsers) { 2025 // If this app is a browser and it's newly-installed for some 2026 // users, clear any default-browser state in those users. The 2027 // app's nature doesn't depend on the user, so we can just check 2028 // its browser nature in any user and generalize. 2029 if (packageIsBrowser(packageName, userId)) { 2030 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 2031 } 2032 2033 // We may also need to apply pending (restored) runtime 2034 // permission grants within these users. 2035 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 2036 } 2037 } 2038 } 2039 2040 // Log current value of "unknown sources" setting 2041 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 2042 getUnknownSourcesSettings()); 2043 2044 // Remove the replaced package's older resources safely now 2045 // We delete after a gc for applications on sdcard. 2046 if (res.removedInfo != null && res.removedInfo.args != null) { 2047 Runtime.getRuntime().gc(); 2048 synchronized (mInstallLock) { 2049 res.removedInfo.args.doPostDeleteLI(true); 2050 } 2051 } else { 2052 // Force a gc to clear up things. Ask for a background one, it's fine to go on 2053 // and not block here. 2054 VMRuntime.getRuntime().requestConcurrentGC(); 2055 } 2056 2057 // Notify DexManager that the package was installed for new users. 2058 // The updated users should already be indexed and the package code paths 2059 // should not change. 2060 // Don't notify the manager for ephemeral apps as they are not expected to 2061 // survive long enough to benefit of background optimizations. 2062 for (int userId : firstUsers) { 2063 PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId); 2064 // There's a race currently where some install events may interleave with an uninstall. 2065 // This can lead to package info being null (b/36642664). 2066 if (info != null) { 2067 mDexManager.notifyPackageInstalled(info, userId); 2068 } 2069 } 2070 } 2071 2072 // If someone is watching installs - notify them 2073 if (installObserver != null) { 2074 try { 2075 Bundle extras = extrasForInstallResult(res); 2076 installObserver.onPackageInstalled(res.name, res.returnCode, 2077 res.returnMsg, extras); 2078 } catch (RemoteException e) { 2079 Slog.i(TAG, "Observer no longer exists."); 2080 } 2081 } 2082 } 2083 2084 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 2085 PackageParser.Package pkg) { 2086 if (pkg.parentPackage == null) { 2087 return; 2088 } 2089 if (pkg.requestedPermissions == null) { 2090 return; 2091 } 2092 final PackageSetting disabledSysParentPs = mSettings 2093 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 2094 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 2095 || !disabledSysParentPs.isPrivileged() 2096 || (disabledSysParentPs.childPackageNames != null 2097 && !disabledSysParentPs.childPackageNames.isEmpty())) { 2098 return; 2099 } 2100 final int[] allUserIds = sUserManager.getUserIds(); 2101 final int permCount = pkg.requestedPermissions.size(); 2102 for (int i = 0; i < permCount; i++) { 2103 String permission = pkg.requestedPermissions.get(i); 2104 BasePermission bp = mSettings.mPermissions.get(permission); 2105 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 2106 continue; 2107 } 2108 for (int userId : allUserIds) { 2109 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 2110 permission, userId)) { 2111 grantRuntimePermission(pkg.packageName, permission, userId); 2112 } 2113 } 2114 } 2115 } 2116 2117 private StorageEventListener mStorageListener = new StorageEventListener() { 2118 @Override 2119 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 2120 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 2121 if (vol.state == VolumeInfo.STATE_MOUNTED) { 2122 final String volumeUuid = vol.getFsUuid(); 2123 2124 // Clean up any users or apps that were removed or recreated 2125 // while this volume was missing 2126 sUserManager.reconcileUsers(volumeUuid); 2127 reconcileApps(volumeUuid); 2128 2129 // Clean up any install sessions that expired or were 2130 // cancelled while this volume was missing 2131 mInstallerService.onPrivateVolumeMounted(volumeUuid); 2132 2133 loadPrivatePackages(vol); 2134 2135 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2136 unloadPrivatePackages(vol); 2137 } 2138 } 2139 2140 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 2141 if (vol.state == VolumeInfo.STATE_MOUNTED) { 2142 updateExternalMediaStatus(true, false); 2143 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2144 updateExternalMediaStatus(false, false); 2145 } 2146 } 2147 } 2148 2149 @Override 2150 public void onVolumeForgotten(String fsUuid) { 2151 if (TextUtils.isEmpty(fsUuid)) { 2152 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 2153 return; 2154 } 2155 2156 // Remove any apps installed on the forgotten volume 2157 synchronized (mPackages) { 2158 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 2159 for (PackageSetting ps : packages) { 2160 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 2161 deletePackageVersioned(new VersionedPackage(ps.name, 2162 PackageManager.VERSION_CODE_HIGHEST), 2163 new LegacyPackageDeleteObserver(null).getBinder(), 2164 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 2165 // Try very hard to release any references to this package 2166 // so we don't risk the system server being killed due to 2167 // open FDs 2168 AttributeCache.instance().removePackage(ps.name); 2169 } 2170 2171 mSettings.onVolumeForgotten(fsUuid); 2172 mSettings.writeLPr(); 2173 } 2174 } 2175 }; 2176 2177 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 2178 String[] grantedPermissions) { 2179 for (int userId : userIds) { 2180 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 2181 } 2182 } 2183 2184 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 2185 String[] grantedPermissions) { 2186 SettingBase sb = (SettingBase) pkg.mExtras; 2187 if (sb == null) { 2188 return; 2189 } 2190 2191 PermissionsState permissionsState = sb.getPermissionsState(); 2192 2193 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 2194 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 2195 2196 final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 2197 >= Build.VERSION_CODES.M; 2198 2199 final boolean instantApp = isInstantApp(pkg.packageName, userId); 2200 2201 for (String permission : pkg.requestedPermissions) { 2202 final BasePermission bp; 2203 synchronized (mPackages) { 2204 bp = mSettings.mPermissions.get(permission); 2205 } 2206 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 2207 && (!instantApp || bp.isInstant()) 2208 && (supportsRuntimePermissions || !bp.isRuntimeOnly()) 2209 && (grantedPermissions == null 2210 || ArrayUtils.contains(grantedPermissions, permission))) { 2211 final int flags = permissionsState.getPermissionFlags(permission, userId); 2212 if (supportsRuntimePermissions) { 2213 // Installer cannot change immutable permissions. 2214 if ((flags & immutableFlags) == 0) { 2215 grantRuntimePermission(pkg.packageName, permission, userId); 2216 } 2217 } else if (mPermissionReviewRequired) { 2218 // In permission review mode we clear the review flag when we 2219 // are asked to install the app with all permissions granted. 2220 if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 2221 updatePermissionFlags(permission, pkg.packageName, 2222 PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId); 2223 } 2224 } 2225 } 2226 } 2227 } 2228 2229 Bundle extrasForInstallResult(PackageInstalledInfo res) { 2230 Bundle extras = null; 2231 switch (res.returnCode) { 2232 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 2233 extras = new Bundle(); 2234 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 2235 res.origPermission); 2236 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 2237 res.origPackage); 2238 break; 2239 } 2240 case PackageManager.INSTALL_SUCCEEDED: { 2241 extras = new Bundle(); 2242 extras.putBoolean(Intent.EXTRA_REPLACING, 2243 res.removedInfo != null && res.removedInfo.removedPackage != null); 2244 break; 2245 } 2246 } 2247 return extras; 2248 } 2249 2250 void scheduleWriteSettingsLocked() { 2251 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2252 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2253 } 2254 } 2255 2256 void scheduleWritePackageListLocked(int userId) { 2257 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) { 2258 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST); 2259 msg.arg1 = userId; 2260 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY); 2261 } 2262 } 2263 2264 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2265 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2266 scheduleWritePackageRestrictionsLocked(userId); 2267 } 2268 2269 void scheduleWritePackageRestrictionsLocked(int userId) { 2270 final int[] userIds = (userId == UserHandle.USER_ALL) 2271 ? sUserManager.getUserIds() : new int[]{userId}; 2272 for (int nextUserId : userIds) { 2273 if (!sUserManager.exists(nextUserId)) return; 2274 mDirtyUsers.add(nextUserId); 2275 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2276 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2277 } 2278 } 2279 } 2280 2281 public static PackageManagerService main(Context context, Installer installer, 2282 boolean factoryTest, boolean onlyCore) { 2283 // Self-check for initial settings. 2284 PackageManagerServiceCompilerMapping.checkProperties(); 2285 2286 PackageManagerService m = new PackageManagerService(context, installer, 2287 factoryTest, onlyCore); 2288 m.enableSystemUserPackages(); 2289 ServiceManager.addService("package", m); 2290 return m; 2291 } 2292 2293 private void enableSystemUserPackages() { 2294 if (!UserManager.isSplitSystemUser()) { 2295 return; 2296 } 2297 // For system user, enable apps based on the following conditions: 2298 // - app is whitelisted or belong to one of these groups: 2299 // -- system app which has no launcher icons 2300 // -- system app which has INTERACT_ACROSS_USERS permission 2301 // -- system IME app 2302 // - app is not in the blacklist 2303 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2304 Set<String> enableApps = new ArraySet<>(); 2305 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2306 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2307 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2308 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2309 enableApps.addAll(wlApps); 2310 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2311 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2312 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2313 enableApps.removeAll(blApps); 2314 Log.i(TAG, "Applications installed for system user: " + enableApps); 2315 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2316 UserHandle.SYSTEM); 2317 final int allAppsSize = allAps.size(); 2318 synchronized (mPackages) { 2319 for (int i = 0; i < allAppsSize; i++) { 2320 String pName = allAps.get(i); 2321 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2322 // Should not happen, but we shouldn't be failing if it does 2323 if (pkgSetting == null) { 2324 continue; 2325 } 2326 boolean install = enableApps.contains(pName); 2327 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2328 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2329 + " for system user"); 2330 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2331 } 2332 } 2333 scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM); 2334 } 2335 } 2336 2337 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2338 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2339 Context.DISPLAY_SERVICE); 2340 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2341 } 2342 2343 /** 2344 * Requests that files preopted on a secondary system partition be copied to the data partition 2345 * if possible. Note that the actual copying of the files is accomplished by init for security 2346 * reasons. This simply requests that the copy takes place and awaits confirmation of its 2347 * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy. 2348 */ 2349 private static void requestCopyPreoptedFiles() { 2350 final int WAIT_TIME_MS = 100; 2351 final String CP_PREOPT_PROPERTY = "sys.cppreopt"; 2352 if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) { 2353 SystemProperties.set(CP_PREOPT_PROPERTY, "requested"); 2354 // We will wait for up to 100 seconds. 2355 final long timeStart = SystemClock.uptimeMillis(); 2356 final long timeEnd = timeStart + 100 * 1000; 2357 long timeNow = timeStart; 2358 while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) { 2359 try { 2360 Thread.sleep(WAIT_TIME_MS); 2361 } catch (InterruptedException e) { 2362 // Do nothing 2363 } 2364 timeNow = SystemClock.uptimeMillis(); 2365 if (timeNow > timeEnd) { 2366 SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out"); 2367 Slog.wtf(TAG, "cppreopt did not finish!"); 2368 break; 2369 } 2370 } 2371 2372 Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms"); 2373 } 2374 } 2375 2376 public PackageManagerService(Context context, Installer installer, 2377 boolean factoryTest, boolean onlyCore) { 2378 LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES); 2379 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager"); 2380 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2381 SystemClock.uptimeMillis()); 2382 2383 if (mSdkVersion <= 0) { 2384 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2385 } 2386 2387 mContext = context; 2388 2389 mPermissionReviewRequired = context.getResources().getBoolean( 2390 R.bool.config_permissionReviewRequired); 2391 2392 mFactoryTest = factoryTest; 2393 mOnlyCore = onlyCore; 2394 mMetrics = new DisplayMetrics(); 2395 mSettings = new Settings(mPackages); 2396 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2397 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2398 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2399 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2400 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2401 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2402 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2403 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2404 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2405 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2406 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2407 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2408 2409 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2410 if (separateProcesses != null && separateProcesses.length() > 0) { 2411 if ("*".equals(separateProcesses)) { 2412 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2413 mSeparateProcesses = null; 2414 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2415 } else { 2416 mDefParseFlags = 0; 2417 mSeparateProcesses = separateProcesses.split(","); 2418 Slog.w(TAG, "Running with debug.separate_processes: " 2419 + separateProcesses); 2420 } 2421 } else { 2422 mDefParseFlags = 0; 2423 mSeparateProcesses = null; 2424 } 2425 2426 mInstaller = installer; 2427 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2428 "*dexopt*"); 2429 mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock); 2430 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2431 2432 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2433 FgThread.get().getLooper()); 2434 2435 getDefaultDisplayMetrics(context, mMetrics); 2436 2437 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config"); 2438 SystemConfig systemConfig = SystemConfig.getInstance(); 2439 mGlobalGids = systemConfig.getGlobalGids(); 2440 mSystemPermissions = systemConfig.getSystemPermissions(); 2441 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2442 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2443 2444 mProtectedPackages = new ProtectedPackages(mContext); 2445 2446 synchronized (mInstallLock) { 2447 // writer 2448 synchronized (mPackages) { 2449 mHandlerThread = new ServiceThread(TAG, 2450 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2451 mHandlerThread.start(); 2452 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2453 mProcessLoggingHandler = new ProcessLoggingHandler(); 2454 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2455 2456 mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this); 2457 mInstantAppRegistry = new InstantAppRegistry(this); 2458 2459 File dataDir = Environment.getDataDirectory(); 2460 mAppInstallDir = new File(dataDir, "app"); 2461 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2462 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2463 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2464 sUserManager = new UserManagerService(context, this, 2465 new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages); 2466 2467 // Propagate permission configuration in to package manager. 2468 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2469 = systemConfig.getPermissions(); 2470 for (int i=0; i<permConfig.size(); i++) { 2471 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2472 BasePermission bp = mSettings.mPermissions.get(perm.name); 2473 if (bp == null) { 2474 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2475 mSettings.mPermissions.put(perm.name, bp); 2476 } 2477 if (perm.gids != null) { 2478 bp.setGids(perm.gids, perm.perUser); 2479 } 2480 } 2481 2482 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2483 final int builtInLibCount = libConfig.size(); 2484 for (int i = 0; i < builtInLibCount; i++) { 2485 String name = libConfig.keyAt(i); 2486 String path = libConfig.valueAt(i); 2487 addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED, 2488 SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0); 2489 } 2490 2491 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2492 2493 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings"); 2494 mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false)); 2495 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2496 2497 // Clean up orphaned packages for which the code path doesn't exist 2498 // and they are an update to a system app - caused by bug/32321269 2499 final int packageSettingCount = mSettings.mPackages.size(); 2500 for (int i = packageSettingCount - 1; i >= 0; i--) { 2501 PackageSetting ps = mSettings.mPackages.valueAt(i); 2502 if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists()) 2503 && mSettings.getDisabledSystemPkgLPr(ps.name) != null) { 2504 mSettings.mPackages.removeAt(i); 2505 mSettings.enableSystemPackageLPw(ps.name); 2506 } 2507 } 2508 2509 if (mFirstBoot) { 2510 requestCopyPreoptedFiles(); 2511 } 2512 2513 String customResolverActivity = Resources.getSystem().getString( 2514 R.string.config_customResolverActivity); 2515 if (TextUtils.isEmpty(customResolverActivity)) { 2516 customResolverActivity = null; 2517 } else { 2518 mCustomResolverComponentName = ComponentName.unflattenFromString( 2519 customResolverActivity); 2520 } 2521 2522 long startTime = SystemClock.uptimeMillis(); 2523 2524 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2525 startTime); 2526 2527 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2528 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2529 2530 if (bootClassPath == null) { 2531 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2532 } 2533 2534 if (systemServerClassPath == null) { 2535 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2536 } 2537 2538 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2539 2540 final VersionInfo ver = mSettings.getInternalVersion(); 2541 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2542 if (mIsUpgrade) { 2543 logCriticalInfo(Log.INFO, 2544 "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT); 2545 } 2546 2547 // when upgrading from pre-M, promote system app permissions from install to runtime 2548 mPromoteSystemApps = 2549 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2550 2551 // When upgrading from pre-N, we need to handle package extraction like first boot, 2552 // as there is no profiling data available. 2553 mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N; 2554 2555 mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1; 2556 2557 // save off the names of pre-existing system packages prior to scanning; we don't 2558 // want to automatically grant runtime permissions for new system apps 2559 if (mPromoteSystemApps) { 2560 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2561 while (pkgSettingIter.hasNext()) { 2562 PackageSetting ps = pkgSettingIter.next(); 2563 if (isSystemApp(ps)) { 2564 mExistingSystemPackages.add(ps.name); 2565 } 2566 } 2567 } 2568 2569 mCacheDir = preparePackageParserCache(mIsUpgrade); 2570 2571 // Set flag to monitor and not change apk file paths when 2572 // scanning install directories. 2573 int scanFlags = SCAN_BOOTING | SCAN_INITIAL; 2574 2575 if (mIsUpgrade || mFirstBoot) { 2576 scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE; 2577 } 2578 2579 // Collect vendor overlay packages. (Do this before scanning any apps.) 2580 // For security and version matching reason, only consider 2581 // overlay packages if they reside in the right directory. 2582 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags 2583 | PackageParser.PARSE_IS_SYSTEM 2584 | PackageParser.PARSE_IS_SYSTEM_DIR 2585 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2586 2587 mParallelPackageParserCallback.findStaticOverlayPackages(); 2588 2589 // Find base frameworks (resource packages without code). 2590 scanDirTracedLI(frameworkDir, mDefParseFlags 2591 | PackageParser.PARSE_IS_SYSTEM 2592 | PackageParser.PARSE_IS_SYSTEM_DIR 2593 | PackageParser.PARSE_IS_PRIVILEGED, 2594 scanFlags | SCAN_NO_DEX, 0); 2595 2596 // Collected privileged system packages. 2597 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2598 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2599 | PackageParser.PARSE_IS_SYSTEM 2600 | PackageParser.PARSE_IS_SYSTEM_DIR 2601 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2602 2603 // Collect ordinary system packages. 2604 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2605 scanDirTracedLI(systemAppDir, mDefParseFlags 2606 | PackageParser.PARSE_IS_SYSTEM 2607 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2608 2609 // Collect all vendor packages. 2610 File vendorAppDir = new File("/vendor/app"); 2611 try { 2612 vendorAppDir = vendorAppDir.getCanonicalFile(); 2613 } catch (IOException e) { 2614 // failed to look up canonical path, continue with original one 2615 } 2616 scanDirTracedLI(vendorAppDir, mDefParseFlags 2617 | PackageParser.PARSE_IS_SYSTEM 2618 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2619 2620 // Collect all OEM packages. 2621 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2622 scanDirTracedLI(oemAppDir, mDefParseFlags 2623 | PackageParser.PARSE_IS_SYSTEM 2624 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2625 2626 // Prune any system packages that no longer exist. 2627 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2628 if (!mOnlyCore) { 2629 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2630 while (psit.hasNext()) { 2631 PackageSetting ps = psit.next(); 2632 2633 /* 2634 * If this is not a system app, it can't be a 2635 * disable system app. 2636 */ 2637 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2638 continue; 2639 } 2640 2641 /* 2642 * If the package is scanned, it's not erased. 2643 */ 2644 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2645 if (scannedPkg != null) { 2646 /* 2647 * If the system app is both scanned and in the 2648 * disabled packages list, then it must have been 2649 * added via OTA. Remove it from the currently 2650 * scanned package so the previously user-installed 2651 * application can be scanned. 2652 */ 2653 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2654 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2655 + ps.name + "; removing system app. Last known codePath=" 2656 + ps.codePathString + ", installStatus=" + ps.installStatus 2657 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2658 + scannedPkg.mVersionCode); 2659 removePackageLI(scannedPkg, true); 2660 mExpectingBetter.put(ps.name, ps.codePath); 2661 } 2662 2663 continue; 2664 } 2665 2666 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2667 psit.remove(); 2668 logCriticalInfo(Log.WARN, "System package " + ps.name 2669 + " no longer exists; it's data will be wiped"); 2670 // Actual deletion of code and data will be handled by later 2671 // reconciliation step 2672 } else { 2673 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2674 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2675 possiblyDeletedUpdatedSystemApps.add(ps.name); 2676 } 2677 } 2678 } 2679 } 2680 2681 //look for any incomplete package installations 2682 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2683 for (int i = 0; i < deletePkgsList.size(); i++) { 2684 // Actual deletion of code and data will be handled by later 2685 // reconciliation step 2686 final String packageName = deletePkgsList.get(i).name; 2687 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2688 synchronized (mPackages) { 2689 mSettings.removePackageLPw(packageName); 2690 } 2691 } 2692 2693 //delete tmp files 2694 deleteTempPackageFiles(); 2695 2696 // Remove any shared userIDs that have no associated packages 2697 mSettings.pruneSharedUsersLPw(); 2698 2699 if (!mOnlyCore) { 2700 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2701 SystemClock.uptimeMillis()); 2702 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2703 2704 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2705 | PackageParser.PARSE_FORWARD_LOCK, 2706 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2707 2708 /** 2709 * Remove disable package settings for any updated system 2710 * apps that were removed via an OTA. If they're not a 2711 * previously-updated app, remove them completely. 2712 * Otherwise, just revoke their system-level permissions. 2713 */ 2714 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2715 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2716 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2717 2718 String msg; 2719 if (deletedPkg == null) { 2720 msg = "Updated system package " + deletedAppName 2721 + " no longer exists; it's data will be wiped"; 2722 // Actual deletion of code and data will be handled by later 2723 // reconciliation step 2724 } else { 2725 msg = "Updated system app + " + deletedAppName 2726 + " no longer present; removing system privileges for " 2727 + deletedAppName; 2728 2729 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2730 2731 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2732 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2733 } 2734 logCriticalInfo(Log.WARN, msg); 2735 } 2736 2737 /** 2738 * Make sure all system apps that we expected to appear on 2739 * the userdata partition actually showed up. If they never 2740 * appeared, crawl back and revive the system version. 2741 */ 2742 for (int i = 0; i < mExpectingBetter.size(); i++) { 2743 final String packageName = mExpectingBetter.keyAt(i); 2744 if (!mPackages.containsKey(packageName)) { 2745 final File scanFile = mExpectingBetter.valueAt(i); 2746 2747 logCriticalInfo(Log.WARN, "Expected better " + packageName 2748 + " but never showed up; reverting to system"); 2749 2750 int reparseFlags = mDefParseFlags; 2751 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2752 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2753 | PackageParser.PARSE_IS_SYSTEM_DIR 2754 | PackageParser.PARSE_IS_PRIVILEGED; 2755 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2756 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2757 | PackageParser.PARSE_IS_SYSTEM_DIR; 2758 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2759 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2760 | PackageParser.PARSE_IS_SYSTEM_DIR; 2761 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2762 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2763 | PackageParser.PARSE_IS_SYSTEM_DIR; 2764 } else { 2765 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2766 continue; 2767 } 2768 2769 mSettings.enableSystemPackageLPw(packageName); 2770 2771 try { 2772 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2773 } catch (PackageManagerException e) { 2774 Slog.e(TAG, "Failed to parse original system package: " 2775 + e.getMessage()); 2776 } 2777 } 2778 } 2779 } 2780 mExpectingBetter.clear(); 2781 2782 // Resolve the storage manager. 2783 mStorageManagerPackage = getStorageManagerPackageName(); 2784 2785 // Resolve protected action filters. Only the setup wizard is allowed to 2786 // have a high priority filter for these actions. 2787 mSetupWizardPackage = getSetupWizardPackageName(); 2788 if (mProtectedFilters.size() > 0) { 2789 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2790 Slog.i(TAG, "No setup wizard;" 2791 + " All protected intents capped to priority 0"); 2792 } 2793 for (ActivityIntentInfo filter : mProtectedFilters) { 2794 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2795 if (DEBUG_FILTERS) { 2796 Slog.i(TAG, "Found setup wizard;" 2797 + " allow priority " + filter.getPriority() + ";" 2798 + " package: " + filter.activity.info.packageName 2799 + " activity: " + filter.activity.className 2800 + " priority: " + filter.getPriority()); 2801 } 2802 // skip setup wizard; allow it to keep the high priority filter 2803 continue; 2804 } 2805 if (DEBUG_FILTERS) { 2806 Slog.i(TAG, "Protected action; cap priority to 0;" 2807 + " package: " + filter.activity.info.packageName 2808 + " activity: " + filter.activity.className 2809 + " origPrio: " + filter.getPriority()); 2810 } 2811 filter.setPriority(0); 2812 } 2813 } 2814 mDeferProtectedFilters = false; 2815 mProtectedFilters.clear(); 2816 2817 // Now that we know all of the shared libraries, update all clients to have 2818 // the correct library paths. 2819 updateAllSharedLibrariesLPw(null); 2820 2821 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2822 // NOTE: We ignore potential failures here during a system scan (like 2823 // the rest of the commands above) because there's precious little we 2824 // can do about it. A settings error is reported, though. 2825 adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/); 2826 } 2827 2828 // Now that we know all the packages we are keeping, 2829 // read and update their last usage times. 2830 mPackageUsage.read(mPackages); 2831 mCompilerStats.read(); 2832 2833 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2834 SystemClock.uptimeMillis()); 2835 Slog.i(TAG, "Time to scan packages: " 2836 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2837 + " seconds"); 2838 2839 // If the platform SDK has changed since the last time we booted, 2840 // we need to re-grant app permission to catch any new ones that 2841 // appear. This is really a hack, and means that apps can in some 2842 // cases get permissions that the user didn't initially explicitly 2843 // allow... it would be nice to have some better way to handle 2844 // this situation. 2845 int updateFlags = UPDATE_PERMISSIONS_ALL; 2846 if (ver.sdkVersion != mSdkVersion) { 2847 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2848 + mSdkVersion + "; regranting permissions for internal storage"); 2849 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2850 } 2851 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2852 ver.sdkVersion = mSdkVersion; 2853 2854 // If this is the first boot or an update from pre-M, and it is a normal 2855 // boot, then we need to initialize the default preferred apps across 2856 // all defined users. 2857 if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) { 2858 for (UserInfo user : sUserManager.getUsers(true)) { 2859 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2860 applyFactoryDefaultBrowserLPw(user.id); 2861 primeDomainVerificationsLPw(user.id); 2862 } 2863 } 2864 2865 // Prepare storage for system user really early during boot, 2866 // since core system apps like SettingsProvider and SystemUI 2867 // can't wait for user to start 2868 final int storageFlags; 2869 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2870 storageFlags = StorageManager.FLAG_STORAGE_DE; 2871 } else { 2872 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2873 } 2874 List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, 2875 UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */, 2876 true /* onlyCoreApps */); 2877 mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> { 2878 BootTimingsTraceLog traceLog = new BootTimingsTraceLog("SystemServerTimingAsync", 2879 Trace.TRACE_TAG_PACKAGE_MANAGER); 2880 traceLog.traceBegin("AppDataFixup"); 2881 try { 2882 mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL, 2883 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 2884 } catch (InstallerException e) { 2885 Slog.w(TAG, "Trouble fixing GIDs", e); 2886 } 2887 traceLog.traceEnd(); 2888 2889 traceLog.traceBegin("AppDataPrepare"); 2890 if (deferPackages == null || deferPackages.isEmpty()) { 2891 return; 2892 } 2893 int count = 0; 2894 for (String pkgName : deferPackages) { 2895 PackageParser.Package pkg = null; 2896 synchronized (mPackages) { 2897 PackageSetting ps = mSettings.getPackageLPr(pkgName); 2898 if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) { 2899 pkg = ps.pkg; 2900 } 2901 } 2902 if (pkg != null) { 2903 synchronized (mInstallLock) { 2904 prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags, 2905 true /* maybeMigrateAppData */); 2906 } 2907 count++; 2908 } 2909 } 2910 traceLog.traceEnd(); 2911 Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages"); 2912 }, "prepareAppData"); 2913 2914 // If this is first boot after an OTA, and a normal boot, then 2915 // we need to clear code cache directories. 2916 // Note that we do *not* clear the application profiles. These remain valid 2917 // across OTAs and are used to drive profile verification (post OTA) and 2918 // profile compilation (without waiting to collect a fresh set of profiles). 2919 if (mIsUpgrade && !onlyCore) { 2920 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2921 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2922 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2923 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2924 // No apps are running this early, so no need to freeze 2925 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2926 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2927 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2928 } 2929 } 2930 ver.fingerprint = Build.FINGERPRINT; 2931 } 2932 2933 checkDefaultBrowser(); 2934 2935 // clear only after permissions and other defaults have been updated 2936 mExistingSystemPackages.clear(); 2937 mPromoteSystemApps = false; 2938 2939 // All the changes are done during package scanning. 2940 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2941 2942 // can downgrade to reader 2943 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings"); 2944 mSettings.writeLPr(); 2945 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2946 2947 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2948 SystemClock.uptimeMillis()); 2949 2950 if (!mOnlyCore) { 2951 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2952 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2953 mRequiredUninstallerPackage = getRequiredUninstallerLPr(); 2954 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2955 if (mIntentFilterVerifierComponent != null) { 2956 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2957 mIntentFilterVerifierComponent); 2958 } else { 2959 mIntentFilterVerifier = null; 2960 } 2961 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2962 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES, 2963 SharedLibraryInfo.VERSION_UNDEFINED); 2964 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2965 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED, 2966 SharedLibraryInfo.VERSION_UNDEFINED); 2967 } else { 2968 mRequiredVerifierPackage = null; 2969 mRequiredInstallerPackage = null; 2970 mRequiredUninstallerPackage = null; 2971 mIntentFilterVerifierComponent = null; 2972 mIntentFilterVerifier = null; 2973 mServicesSystemSharedLibraryPackageName = null; 2974 mSharedSystemSharedLibraryPackageName = null; 2975 } 2976 2977 mInstallerService = new PackageInstallerService(context, this); 2978 final Pair<ComponentName, String> instantAppResolverComponent = 2979 getInstantAppResolverLPr(); 2980 if (instantAppResolverComponent != null) { 2981 if (DEBUG_EPHEMERAL) { 2982 Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent); 2983 } 2984 mInstantAppResolverConnection = new EphemeralResolverConnection( 2985 mContext, instantAppResolverComponent.first, 2986 instantAppResolverComponent.second); 2987 mInstantAppResolverSettingsComponent = 2988 getInstantAppResolverSettingsLPr(instantAppResolverComponent.first); 2989 } else { 2990 mInstantAppResolverConnection = null; 2991 mInstantAppResolverSettingsComponent = null; 2992 } 2993 updateInstantAppInstallerLocked(null); 2994 2995 // Read and update the usage of dex files. 2996 // Do this at the end of PM init so that all the packages have their 2997 // data directory reconciled. 2998 // At this point we know the code paths of the packages, so we can validate 2999 // the disk file and build the internal cache. 3000 // The usage file is expected to be small so loading and verifying it 3001 // should take a fairly small time compare to the other activities (e.g. package 3002 // scanning). 3003 final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>(); 3004 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 3005 for (int userId : currentUserIds) { 3006 userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList()); 3007 } 3008 mDexManager.load(userPackages); 3009 } // synchronized (mPackages) 3010 } // synchronized (mInstallLock) 3011 3012 // Now after opening every single application zip, make sure they 3013 // are all flushed. Not really needed, but keeps things nice and 3014 // tidy. 3015 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC"); 3016 Runtime.getRuntime().gc(); 3017 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 3018 3019 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks"); 3020 FallbackCategoryProvider.loadFallbacks(); 3021 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 3022 3023 // The initial scanning above does many calls into installd while 3024 // holding the mPackages lock, but we're mostly interested in yelling 3025 // once we have a booted system. 3026 mInstaller.setWarnIfHeld(mPackages); 3027 3028 // Expose private service for system components to use. 3029 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 3030 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 3031 } 3032 3033 private void updateInstantAppInstallerLocked(String modifiedPackage) { 3034 // we're only interested in updating the installer appliction when 1) it's not 3035 // already set or 2) the modified package is the installer 3036 if (mInstantAppInstallerActivity != null 3037 && !mInstantAppInstallerActivity.getComponentName().getPackageName() 3038 .equals(modifiedPackage)) { 3039 return; 3040 } 3041 setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr()); 3042 } 3043 3044 private static File preparePackageParserCache(boolean isUpgrade) { 3045 if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) { 3046 return null; 3047 } 3048 3049 // Disable package parsing on eng builds to allow for faster incremental development. 3050 if ("eng".equals(Build.TYPE)) { 3051 return null; 3052 } 3053 3054 if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) { 3055 Slog.i(TAG, "Disabling package parser cache due to system property."); 3056 return null; 3057 } 3058 3059 // The base directory for the package parser cache lives under /data/system/. 3060 final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(), 3061 "package_cache"); 3062 if (cacheBaseDir == null) { 3063 return null; 3064 } 3065 3066 // If this is a system upgrade scenario, delete the contents of the package cache dir. 3067 // This also serves to "GC" unused entries when the package cache version changes (which 3068 // can only happen during upgrades). 3069 if (isUpgrade) { 3070 FileUtils.deleteContents(cacheBaseDir); 3071 } 3072 3073 3074 // Return the versioned package cache directory. This is something like 3075 // "/data/system/package_cache/1" 3076 File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION); 3077 3078 // The following is a workaround to aid development on non-numbered userdebug 3079 // builds or cases where "adb sync" is used on userdebug builds. If we detect that 3080 // the system partition is newer. 3081 // 3082 // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build 3083 // that starts with "eng." to signify that this is an engineering build and not 3084 // destined for release. 3085 if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) { 3086 Slog.w(TAG, "Wiping cache directory because the system partition changed."); 3087 3088 // Heuristic: If the /system directory has been modified recently due to an "adb sync" 3089 // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable 3090 // in general and should not be used for production changes. In this specific case, 3091 // we know that they will work. 3092 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 3093 if (cacheDir.lastModified() < frameworkDir.lastModified()) { 3094 FileUtils.deleteContents(cacheBaseDir); 3095 cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION); 3096 } 3097 } 3098 3099 return cacheDir; 3100 } 3101 3102 @Override 3103 public boolean isFirstBoot() { 3104 // allow instant applications 3105 return mFirstBoot; 3106 } 3107 3108 @Override 3109 public boolean isOnlyCoreApps() { 3110 // allow instant applications 3111 return mOnlyCore; 3112 } 3113 3114 @Override 3115 public boolean isUpgrade() { 3116 // allow instant applications 3117 return mIsUpgrade; 3118 } 3119 3120 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 3121 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 3122 3123 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 3124 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3125 UserHandle.USER_SYSTEM); 3126 if (matches.size() == 1) { 3127 return matches.get(0).getComponentInfo().packageName; 3128 } else if (matches.size() == 0) { 3129 Log.e(TAG, "There should probably be a verifier, but, none were found"); 3130 return null; 3131 } 3132 throw new RuntimeException("There must be exactly one verifier; found " + matches); 3133 } 3134 3135 private @NonNull String getRequiredSharedLibraryLPr(String name, int version) { 3136 synchronized (mPackages) { 3137 SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version); 3138 if (libraryEntry == null) { 3139 throw new IllegalStateException("Missing required shared library:" + name); 3140 } 3141 return libraryEntry.apk; 3142 } 3143 } 3144 3145 private @NonNull String getRequiredInstallerLPr() { 3146 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 3147 intent.addCategory(Intent.CATEGORY_DEFAULT); 3148 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 3149 3150 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3151 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3152 UserHandle.USER_SYSTEM); 3153 if (matches.size() == 1) { 3154 ResolveInfo resolveInfo = matches.get(0); 3155 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 3156 throw new RuntimeException("The installer must be a privileged app"); 3157 } 3158 return matches.get(0).getComponentInfo().packageName; 3159 } else { 3160 throw new RuntimeException("There must be exactly one installer; found " + matches); 3161 } 3162 } 3163 3164 private @NonNull String getRequiredUninstallerLPr() { 3165 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 3166 intent.addCategory(Intent.CATEGORY_DEFAULT); 3167 intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null)); 3168 3169 final ResolveInfo resolveInfo = resolveIntent(intent, null, 3170 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3171 UserHandle.USER_SYSTEM); 3172 if (resolveInfo == null || 3173 mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) { 3174 throw new RuntimeException("There must be exactly one uninstaller; found " 3175 + resolveInfo); 3176 } 3177 return resolveInfo.getComponentInfo().packageName; 3178 } 3179 3180 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 3181 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 3182 3183 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 3184 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3185 UserHandle.USER_SYSTEM); 3186 ResolveInfo best = null; 3187 final int N = matches.size(); 3188 for (int i = 0; i < N; i++) { 3189 final ResolveInfo cur = matches.get(i); 3190 final String packageName = cur.getComponentInfo().packageName; 3191 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 3192 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 3193 continue; 3194 } 3195 3196 if (best == null || cur.priority > best.priority) { 3197 best = cur; 3198 } 3199 } 3200 3201 if (best != null) { 3202 return best.getComponentInfo().getComponentName(); 3203 } 3204 Slog.w(TAG, "Intent filter verifier not found"); 3205 return null; 3206 } 3207 3208 @Override 3209 public @Nullable ComponentName getInstantAppResolverComponent() { 3210 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 3211 return null; 3212 } 3213 synchronized (mPackages) { 3214 final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr(); 3215 if (instantAppResolver == null) { 3216 return null; 3217 } 3218 return instantAppResolver.first; 3219 } 3220 } 3221 3222 private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() { 3223 final String[] packageArray = 3224 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 3225 if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) { 3226 if (DEBUG_EPHEMERAL) { 3227 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 3228 } 3229 return null; 3230 } 3231 3232 final int callingUid = Binder.getCallingUid(); 3233 final int resolveFlags = 3234 MATCH_DIRECT_BOOT_AWARE 3235 | MATCH_DIRECT_BOOT_UNAWARE 3236 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3237 String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE; 3238 final Intent resolverIntent = new Intent(actionName); 3239 List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 3240 resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/); 3241 // temporarily look for the old action 3242 if (resolvers.size() == 0) { 3243 if (DEBUG_EPHEMERAL) { 3244 Slog.d(TAG, "Ephemeral resolver not found with new action; try old one"); 3245 } 3246 actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE; 3247 resolverIntent.setAction(actionName); 3248 resolvers = queryIntentServicesInternal(resolverIntent, null, 3249 resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/); 3250 } 3251 final int N = resolvers.size(); 3252 if (N == 0) { 3253 if (DEBUG_EPHEMERAL) { 3254 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 3255 } 3256 return null; 3257 } 3258 3259 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 3260 for (int i = 0; i < N; i++) { 3261 final ResolveInfo info = resolvers.get(i); 3262 3263 if (info.serviceInfo == null) { 3264 continue; 3265 } 3266 3267 final String packageName = info.serviceInfo.packageName; 3268 if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) { 3269 if (DEBUG_EPHEMERAL) { 3270 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 3271 + " pkg: " + packageName + ", info:" + info); 3272 } 3273 continue; 3274 } 3275 3276 if (DEBUG_EPHEMERAL) { 3277 Slog.v(TAG, "Ephemeral resolver found;" 3278 + " pkg: " + packageName + ", info:" + info); 3279 } 3280 return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName); 3281 } 3282 if (DEBUG_EPHEMERAL) { 3283 Slog.v(TAG, "Ephemeral resolver NOT found"); 3284 } 3285 return null; 3286 } 3287 3288 private @Nullable ActivityInfo getInstantAppInstallerLPr() { 3289 final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE); 3290 intent.addCategory(Intent.CATEGORY_DEFAULT); 3291 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 3292 3293 final int resolveFlags = 3294 MATCH_DIRECT_BOOT_AWARE 3295 | MATCH_DIRECT_BOOT_UNAWARE 3296 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3297 List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3298 resolveFlags, UserHandle.USER_SYSTEM); 3299 // temporarily look for the old action 3300 if (matches.isEmpty()) { 3301 if (DEBUG_EPHEMERAL) { 3302 Slog.d(TAG, "Ephemeral installer not found with new action; try old one"); 3303 } 3304 intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 3305 matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3306 resolveFlags, UserHandle.USER_SYSTEM); 3307 } 3308 Iterator<ResolveInfo> iter = matches.iterator(); 3309 while (iter.hasNext()) { 3310 final ResolveInfo rInfo = iter.next(); 3311 final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName); 3312 if (ps != null) { 3313 final PermissionsState permissionsState = ps.getPermissionsState(); 3314 if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) { 3315 continue; 3316 } 3317 } 3318 iter.remove(); 3319 } 3320 if (matches.size() == 0) { 3321 return null; 3322 } else if (matches.size() == 1) { 3323 return (ActivityInfo) matches.get(0).getComponentInfo(); 3324 } else { 3325 throw new RuntimeException( 3326 "There must be at most one ephemeral installer; found " + matches); 3327 } 3328 } 3329 3330 private @Nullable ComponentName getInstantAppResolverSettingsLPr( 3331 @NonNull ComponentName resolver) { 3332 final Intent intent = new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS) 3333 .addCategory(Intent.CATEGORY_DEFAULT) 3334 .setPackage(resolver.getPackageName()); 3335 final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3336 List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags, 3337 UserHandle.USER_SYSTEM); 3338 // temporarily look for the old action 3339 if (matches.isEmpty()) { 3340 if (DEBUG_EPHEMERAL) { 3341 Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one"); 3342 } 3343 intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS); 3344 matches = queryIntentActivitiesInternal(intent, null, resolveFlags, 3345 UserHandle.USER_SYSTEM); 3346 } 3347 if (matches.isEmpty()) { 3348 return null; 3349 } 3350 return matches.get(0).getComponentInfo().getComponentName(); 3351 } 3352 3353 private void primeDomainVerificationsLPw(int userId) { 3354 if (DEBUG_DOMAIN_VERIFICATION) { 3355 Slog.d(TAG, "Priming domain verifications in user " + userId); 3356 } 3357 3358 SystemConfig systemConfig = SystemConfig.getInstance(); 3359 ArraySet<String> packages = systemConfig.getLinkedApps(); 3360 3361 for (String packageName : packages) { 3362 PackageParser.Package pkg = mPackages.get(packageName); 3363 if (pkg != null) { 3364 if (!pkg.isSystemApp()) { 3365 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 3366 continue; 3367 } 3368 3369 ArraySet<String> domains = null; 3370 for (PackageParser.Activity a : pkg.activities) { 3371 for (ActivityIntentInfo filter : a.intents) { 3372 if (hasValidDomains(filter)) { 3373 if (domains == null) { 3374 domains = new ArraySet<String>(); 3375 } 3376 domains.addAll(filter.getHostsList()); 3377 } 3378 } 3379 } 3380 3381 if (domains != null && domains.size() > 0) { 3382 if (DEBUG_DOMAIN_VERIFICATION) { 3383 Slog.v(TAG, " + " + packageName); 3384 } 3385 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 3386 // state w.r.t. the formal app-linkage "no verification attempted" state; 3387 // and then 'always' in the per-user state actually used for intent resolution. 3388 final IntentFilterVerificationInfo ivi; 3389 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains); 3390 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 3391 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 3392 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 3393 } else { 3394 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 3395 + "' does not handle web links"); 3396 } 3397 } else { 3398 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 3399 } 3400 } 3401 3402 scheduleWritePackageRestrictionsLocked(userId); 3403 scheduleWriteSettingsLocked(); 3404 } 3405 3406 private void applyFactoryDefaultBrowserLPw(int userId) { 3407 // The default browser app's package name is stored in a string resource, 3408 // with a product-specific overlay used for vendor customization. 3409 String browserPkg = mContext.getResources().getString( 3410 com.android.internal.R.string.default_browser); 3411 if (!TextUtils.isEmpty(browserPkg)) { 3412 // non-empty string => required to be a known package 3413 PackageSetting ps = mSettings.mPackages.get(browserPkg); 3414 if (ps == null) { 3415 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 3416 browserPkg = null; 3417 } else { 3418 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3419 } 3420 } 3421 3422 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3423 // default. If there's more than one, just leave everything alone. 3424 if (browserPkg == null) { 3425 calculateDefaultBrowserLPw(userId); 3426 } 3427 } 3428 3429 private void calculateDefaultBrowserLPw(int userId) { 3430 List<String> allBrowsers = resolveAllBrowserApps(userId); 3431 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3432 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3433 } 3434 3435 private List<String> resolveAllBrowserApps(int userId) { 3436 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3437 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3438 PackageManager.MATCH_ALL, userId); 3439 3440 final int count = list.size(); 3441 List<String> result = new ArrayList<String>(count); 3442 for (int i=0; i<count; i++) { 3443 ResolveInfo info = list.get(i); 3444 if (info.activityInfo == null 3445 || !info.handleAllWebDataURI 3446 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3447 || result.contains(info.activityInfo.packageName)) { 3448 continue; 3449 } 3450 result.add(info.activityInfo.packageName); 3451 } 3452 3453 return result; 3454 } 3455 3456 private boolean packageIsBrowser(String packageName, int userId) { 3457 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3458 PackageManager.MATCH_ALL, userId); 3459 final int N = list.size(); 3460 for (int i = 0; i < N; i++) { 3461 ResolveInfo info = list.get(i); 3462 if (packageName.equals(info.activityInfo.packageName)) { 3463 return true; 3464 } 3465 } 3466 return false; 3467 } 3468 3469 private void checkDefaultBrowser() { 3470 final int myUserId = UserHandle.myUserId(); 3471 final String packageName = getDefaultBrowserPackageName(myUserId); 3472 if (packageName != null) { 3473 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3474 if (info == null) { 3475 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3476 synchronized (mPackages) { 3477 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3478 } 3479 } 3480 } 3481 } 3482 3483 @Override 3484 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3485 throws RemoteException { 3486 try { 3487 return super.onTransact(code, data, reply, flags); 3488 } catch (RuntimeException e) { 3489 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3490 Slog.wtf(TAG, "Package Manager Crash", e); 3491 } 3492 throw e; 3493 } 3494 } 3495 3496 static int[] appendInts(int[] cur, int[] add) { 3497 if (add == null) return cur; 3498 if (cur == null) return add; 3499 final int N = add.length; 3500 for (int i=0; i<N; i++) { 3501 cur = appendInt(cur, add[i]); 3502 } 3503 return cur; 3504 } 3505 3506 /** 3507 * Returns whether or not a full application can see an instant application. 3508 * <p> 3509 * Currently, there are three cases in which this can occur: 3510 * <ol> 3511 * <li>The calling application is a "special" process. The special 3512 * processes are {@link Process#SYSTEM_UID}, {@link Process#SHELL_UID} 3513 * and {@code 0}</li> 3514 * <li>The calling application has the permission 3515 * {@link android.Manifest.permission#ACCESS_INSTANT_APPS}</li> 3516 * <li>[TODO] The calling application is the default launcher on the 3517 * system partition.</li> 3518 * </ol> 3519 */ 3520 private boolean canAccessInstantApps(int callingUid) { 3521 final boolean isSpecialProcess = 3522 callingUid == Process.SYSTEM_UID 3523 || callingUid == Process.SHELL_UID 3524 || callingUid == Process.ROOT_UID; 3525 final boolean allowMatchInstant = 3526 isSpecialProcess 3527 || mContext.checkCallingOrSelfPermission( 3528 android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED; 3529 return allowMatchInstant; 3530 } 3531 3532 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3533 if (!sUserManager.exists(userId)) return null; 3534 if (ps == null) { 3535 return null; 3536 } 3537 PackageParser.Package p = ps.pkg; 3538 if (p == null) { 3539 return null; 3540 } 3541 final int callingUid = Binder.getCallingUid(); 3542 // Filter out ephemeral app metadata: 3543 // * The system/shell/root can see metadata for any app 3544 // * An installed app can see metadata for 1) other installed apps 3545 // and 2) ephemeral apps that have explicitly interacted with it 3546 // * Ephemeral apps can only see their own data and exposed installed apps 3547 // * Holding a signature permission allows seeing instant apps 3548 if (filterAppAccessLPr(ps, callingUid, userId)) { 3549 return null; 3550 } 3551 3552 final PermissionsState permissionsState = ps.getPermissionsState(); 3553 3554 // Compute GIDs only if requested 3555 final int[] gids = (flags & PackageManager.GET_GIDS) == 0 3556 ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId); 3557 // Compute granted permissions only if package has requested permissions 3558 final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions) 3559 ? Collections.<String>emptySet() : permissionsState.getPermissions(userId); 3560 final PackageUserState state = ps.readUserState(userId); 3561 3562 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0 3563 && ps.isSystem()) { 3564 flags |= MATCH_ANY_USER; 3565 } 3566 3567 PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags, 3568 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3569 3570 if (packageInfo == null) { 3571 return null; 3572 } 3573 3574 rebaseEnabledOverlays(packageInfo.applicationInfo, userId); 3575 3576 packageInfo.packageName = packageInfo.applicationInfo.packageName = 3577 resolveExternalPackageNameLPr(p); 3578 3579 return packageInfo; 3580 } 3581 3582 @Override 3583 public void checkPackageStartable(String packageName, int userId) { 3584 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 3585 throw new SecurityException("Instant applications don't have access to this method"); 3586 } 3587 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3588 synchronized (mPackages) { 3589 final PackageSetting ps = mSettings.mPackages.get(packageName); 3590 if (ps == null) { 3591 throw new SecurityException("Package " + packageName + " was not found!"); 3592 } 3593 3594 if (!ps.getInstalled(userId)) { 3595 throw new SecurityException( 3596 "Package " + packageName + " was not installed for user " + userId + "!"); 3597 } 3598 3599 if (mSafeMode && !ps.isSystem()) { 3600 throw new SecurityException("Package " + packageName + " not a system app!"); 3601 } 3602 3603 if (mFrozenPackages.contains(packageName)) { 3604 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3605 } 3606 3607 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3608 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3609 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3610 } 3611 } 3612 } 3613 3614 @Override 3615 public boolean isPackageAvailable(String packageName, int userId) { 3616 if (!sUserManager.exists(userId)) return false; 3617 final int callingUid = Binder.getCallingUid(); 3618 enforceCrossUserPermission(callingUid, userId, 3619 false /*requireFullPermission*/, false /*checkShell*/, "is package available"); 3620 synchronized (mPackages) { 3621 PackageParser.Package p = mPackages.get(packageName); 3622 if (p != null) { 3623 final PackageSetting ps = (PackageSetting) p.mExtras; 3624 if (filterAppAccessLPr(ps, callingUid, userId)) { 3625 return false; 3626 } 3627 if (ps != null) { 3628 final PackageUserState state = ps.readUserState(userId); 3629 if (state != null) { 3630 return PackageParser.isAvailable(state); 3631 } 3632 } 3633 } 3634 } 3635 return false; 3636 } 3637 3638 @Override 3639 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3640 return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST, 3641 flags, userId); 3642 } 3643 3644 @Override 3645 public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage, 3646 int flags, int userId) { 3647 return getPackageInfoInternal(versionedPackage.getPackageName(), 3648 versionedPackage.getVersionCode(), flags, userId); 3649 } 3650 3651 private PackageInfo getPackageInfoInternal(String packageName, int versionCode, 3652 int flags, int userId) { 3653 if (!sUserManager.exists(userId)) return null; 3654 final int callingUid = Binder.getCallingUid(); 3655 flags = updateFlagsForPackage(flags, userId, packageName); 3656 enforceCrossUserPermission(callingUid, userId, 3657 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3658 3659 // reader 3660 synchronized (mPackages) { 3661 // Normalize package name to handle renamed packages and static libs 3662 packageName = resolveInternalPackageNameLPr(packageName, versionCode); 3663 3664 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3665 if (matchFactoryOnly) { 3666 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3667 if (ps != null) { 3668 if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) { 3669 return null; 3670 } 3671 if (filterAppAccessLPr(ps, callingUid, userId)) { 3672 return null; 3673 } 3674 return generatePackageInfo(ps, flags, userId); 3675 } 3676 } 3677 3678 PackageParser.Package p = mPackages.get(packageName); 3679 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3680 return null; 3681 } 3682 if (DEBUG_PACKAGE_INFO) 3683 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3684 if (p != null) { 3685 final PackageSetting ps = (PackageSetting) p.mExtras; 3686 if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) { 3687 return null; 3688 } 3689 if (ps != null && filterAppAccessLPr(ps, callingUid, userId)) { 3690 return null; 3691 } 3692 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3693 } 3694 if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) { 3695 final PackageSetting ps = mSettings.mPackages.get(packageName); 3696 if (ps == null) return null; 3697 if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) { 3698 return null; 3699 } 3700 if (filterAppAccessLPr(ps, callingUid, userId)) { 3701 return null; 3702 } 3703 return generatePackageInfo(ps, flags, userId); 3704 } 3705 } 3706 return null; 3707 } 3708 3709 private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) { 3710 if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) { 3711 return true; 3712 } 3713 if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) { 3714 return true; 3715 } 3716 if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) { 3717 return true; 3718 } 3719 return false; 3720 } 3721 3722 private boolean isComponentVisibleToInstantApp( 3723 @Nullable ComponentName component, @ComponentType int type) { 3724 if (type == TYPE_ACTIVITY) { 3725 final PackageParser.Activity activity = mActivities.mActivities.get(component); 3726 return activity != null 3727 ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0 3728 : false; 3729 } else if (type == TYPE_RECEIVER) { 3730 final PackageParser.Activity activity = mReceivers.mActivities.get(component); 3731 return activity != null 3732 ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0 3733 : false; 3734 } else if (type == TYPE_SERVICE) { 3735 final PackageParser.Service service = mServices.mServices.get(component); 3736 return service != null 3737 ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0 3738 : false; 3739 } else if (type == TYPE_PROVIDER) { 3740 final PackageParser.Provider provider = mProviders.mProviders.get(component); 3741 return provider != null 3742 ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0 3743 : false; 3744 } else if (type == TYPE_UNKNOWN) { 3745 return isComponentVisibleToInstantApp(component); 3746 } 3747 return false; 3748 } 3749 3750 /** 3751 * Returns whether or not access to the application should be filtered. 3752 * <p> 3753 * Access may be limited based upon whether the calling or target applications 3754 * are instant applications. 3755 * 3756 * @see #canAccessInstantApps(int) 3757 */ 3758 private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, 3759 @Nullable ComponentName component, @ComponentType int componentType, int userId) { 3760 // if we're in an isolated process, get the real calling UID 3761 if (Process.isIsolated(callingUid)) { 3762 callingUid = mIsolatedOwners.get(callingUid); 3763 } 3764 final String instantAppPkgName = getInstantAppPackageName(callingUid); 3765 final boolean callerIsInstantApp = instantAppPkgName != null; 3766 if (ps == null) { 3767 if (callerIsInstantApp) { 3768 // pretend the application exists, but, needs to be filtered 3769 return true; 3770 } 3771 return false; 3772 } 3773 // if the target and caller are the same application, don't filter 3774 if (isCallerSameApp(ps.name, callingUid)) { 3775 return false; 3776 } 3777 if (callerIsInstantApp) { 3778 // request for a specific component; if it hasn't been explicitly exposed, filter 3779 if (component != null) { 3780 return !isComponentVisibleToInstantApp(component, componentType); 3781 } 3782 // request for application; if no components have been explicitly exposed, filter 3783 return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps; 3784 } 3785 if (ps.getInstantApp(userId)) { 3786 // caller can see all components of all instant applications, don't filter 3787 if (canAccessInstantApps(callingUid)) { 3788 return false; 3789 } 3790 // request for a specific instant application component, filter 3791 if (component != null) { 3792 return true; 3793 } 3794 // request for an instant application; if the caller hasn't been granted access, filter 3795 return !mInstantAppRegistry.isInstantAccessGranted( 3796 userId, UserHandle.getAppId(callingUid), ps.appId); 3797 } 3798 return false; 3799 } 3800 3801 /** 3802 * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int) 3803 */ 3804 private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) { 3805 return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId); 3806 } 3807 3808 private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId, 3809 int flags) { 3810 // Callers can access only the libs they depend on, otherwise they need to explicitly 3811 // ask for the shared libraries given the caller is allowed to access all static libs. 3812 if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) { 3813 // System/shell/root get to see all static libs 3814 final int appId = UserHandle.getAppId(uid); 3815 if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID 3816 || appId == Process.ROOT_UID) { 3817 return false; 3818 } 3819 } 3820 3821 // No package means no static lib as it is always on internal storage 3822 if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) { 3823 return false; 3824 } 3825 3826 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName, 3827 ps.pkg.staticSharedLibVersion); 3828 if (libEntry == null) { 3829 return false; 3830 } 3831 3832 final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid)); 3833 final String[] uidPackageNames = getPackagesForUid(resolvedUid); 3834 if (uidPackageNames == null) { 3835 return true; 3836 } 3837 3838 for (String uidPackageName : uidPackageNames) { 3839 if (ps.name.equals(uidPackageName)) { 3840 return false; 3841 } 3842 PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName); 3843 if (uidPs != null) { 3844 final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries, 3845 libEntry.info.getName()); 3846 if (index < 0) { 3847 continue; 3848 } 3849 if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) { 3850 return false; 3851 } 3852 } 3853 } 3854 return true; 3855 } 3856 3857 @Override 3858 public String[] currentToCanonicalPackageNames(String[] names) { 3859 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 3860 return names; 3861 } 3862 String[] out = new String[names.length]; 3863 // reader 3864 synchronized (mPackages) { 3865 for (int i=names.length-1; i>=0; i--) { 3866 PackageSetting ps = mSettings.mPackages.get(names[i]); 3867 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3868 } 3869 } 3870 return out; 3871 } 3872 3873 @Override 3874 public String[] canonicalToCurrentPackageNames(String[] names) { 3875 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 3876 return names; 3877 } 3878 String[] out = new String[names.length]; 3879 // reader 3880 synchronized (mPackages) { 3881 for (int i=names.length-1; i>=0; i--) { 3882 String cur = mSettings.getRenamedPackageLPr(names[i]); 3883 out[i] = cur != null ? cur : names[i]; 3884 } 3885 } 3886 return out; 3887 } 3888 3889 @Override 3890 public int getPackageUid(String packageName, int flags, int userId) { 3891 if (!sUserManager.exists(userId)) return -1; 3892 final int callingUid = Binder.getCallingUid(); 3893 flags = updateFlagsForPackage(flags, userId, packageName); 3894 enforceCrossUserPermission(callingUid, userId, 3895 false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid"); 3896 3897 // reader 3898 synchronized (mPackages) { 3899 final PackageParser.Package p = mPackages.get(packageName); 3900 if (p != null && p.isMatch(flags)) { 3901 PackageSetting ps = (PackageSetting) p.mExtras; 3902 if (filterAppAccessLPr(ps, callingUid, userId)) { 3903 return -1; 3904 } 3905 return UserHandle.getUid(userId, p.applicationInfo.uid); 3906 } 3907 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3908 final PackageSetting ps = mSettings.mPackages.get(packageName); 3909 if (ps != null && ps.isMatch(flags) 3910 && !filterAppAccessLPr(ps, callingUid, userId)) { 3911 return UserHandle.getUid(userId, ps.appId); 3912 } 3913 } 3914 } 3915 3916 return -1; 3917 } 3918 3919 @Override 3920 public int[] getPackageGids(String packageName, int flags, int userId) { 3921 if (!sUserManager.exists(userId)) return null; 3922 final int callingUid = Binder.getCallingUid(); 3923 flags = updateFlagsForPackage(flags, userId, packageName); 3924 enforceCrossUserPermission(callingUid, userId, 3925 false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids"); 3926 3927 // reader 3928 synchronized (mPackages) { 3929 final PackageParser.Package p = mPackages.get(packageName); 3930 if (p != null && p.isMatch(flags)) { 3931 PackageSetting ps = (PackageSetting) p.mExtras; 3932 if (filterAppAccessLPr(ps, callingUid, userId)) { 3933 return null; 3934 } 3935 // TODO: Shouldn't this be checking for package installed state for userId and 3936 // return null? 3937 return ps.getPermissionsState().computeGids(userId); 3938 } 3939 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3940 final PackageSetting ps = mSettings.mPackages.get(packageName); 3941 if (ps != null && ps.isMatch(flags) 3942 && !filterAppAccessLPr(ps, callingUid, userId)) { 3943 return ps.getPermissionsState().computeGids(userId); 3944 } 3945 } 3946 } 3947 3948 return null; 3949 } 3950 3951 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3952 if (bp.perm != null) { 3953 return PackageParser.generatePermissionInfo(bp.perm, flags); 3954 } 3955 PermissionInfo pi = new PermissionInfo(); 3956 pi.name = bp.name; 3957 pi.packageName = bp.sourcePackage; 3958 pi.nonLocalizedLabel = bp.name; 3959 pi.protectionLevel = bp.protectionLevel; 3960 return pi; 3961 } 3962 3963 @Override 3964 public PermissionInfo getPermissionInfo(String name, int flags) { 3965 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 3966 return null; 3967 } 3968 // reader 3969 synchronized (mPackages) { 3970 final BasePermission p = mSettings.mPermissions.get(name); 3971 if (p != null) { 3972 return generatePermissionInfo(p, flags); 3973 } 3974 return null; 3975 } 3976 } 3977 3978 @Override 3979 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3980 int flags) { 3981 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 3982 return null; 3983 } 3984 // reader 3985 synchronized (mPackages) { 3986 if (group != null && !mPermissionGroups.containsKey(group)) { 3987 // This is thrown as NameNotFoundException 3988 return null; 3989 } 3990 3991 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3992 for (BasePermission p : mSettings.mPermissions.values()) { 3993 if (group == null) { 3994 if (p.perm == null || p.perm.info.group == null) { 3995 out.add(generatePermissionInfo(p, flags)); 3996 } 3997 } else { 3998 if (p.perm != null && group.equals(p.perm.info.group)) { 3999 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 4000 } 4001 } 4002 } 4003 return new ParceledListSlice<>(out); 4004 } 4005 } 4006 4007 @Override 4008 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 4009 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 4010 return null; 4011 } 4012 // reader 4013 synchronized (mPackages) { 4014 return PackageParser.generatePermissionGroupInfo( 4015 mPermissionGroups.get(name), flags); 4016 } 4017 } 4018 4019 @Override 4020 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 4021 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 4022 return ParceledListSlice.emptyList(); 4023 } 4024 // reader 4025 synchronized (mPackages) { 4026 final int N = mPermissionGroups.size(); 4027 ArrayList<PermissionGroupInfo> out 4028 = new ArrayList<PermissionGroupInfo>(N); 4029 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 4030 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 4031 } 4032 return new ParceledListSlice<>(out); 4033 } 4034 } 4035 4036 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 4037 int uid, int userId) { 4038 if (!sUserManager.exists(userId)) return null; 4039 PackageSetting ps = mSettings.mPackages.get(packageName); 4040 if (ps != null) { 4041 if (filterSharedLibPackageLPr(ps, uid, userId, flags)) { 4042 return null; 4043 } 4044 if (filterAppAccessLPr(ps, uid, userId)) { 4045 return null; 4046 } 4047 if (ps.pkg == null) { 4048 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 4049 if (pInfo != null) { 4050 return pInfo.applicationInfo; 4051 } 4052 return null; 4053 } 4054 ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 4055 ps.readUserState(userId), userId); 4056 if (ai != null) { 4057 rebaseEnabledOverlays(ai, userId); 4058 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 4059 } 4060 return ai; 4061 } 4062 return null; 4063 } 4064 4065 @Override 4066 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 4067 if (!sUserManager.exists(userId)) return null; 4068 flags = updateFlagsForApplication(flags, userId, packageName); 4069 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4070 false /* requireFullPermission */, false /* checkShell */, "get application info"); 4071 4072 // writer 4073 synchronized (mPackages) { 4074 // Normalize package name to handle renamed packages and static libs 4075 packageName = resolveInternalPackageNameLPr(packageName, 4076 PackageManager.VERSION_CODE_HIGHEST); 4077 4078 PackageParser.Package p = mPackages.get(packageName); 4079 if (DEBUG_PACKAGE_INFO) Log.v( 4080 TAG, "getApplicationInfo " + packageName 4081 + ": " + p); 4082 if (p != null) { 4083 PackageSetting ps = mSettings.mPackages.get(packageName); 4084 if (ps == null) return null; 4085 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) { 4086 return null; 4087 } 4088 if (filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) { 4089 return null; 4090 } 4091 // Note: isEnabledLP() does not apply here - always return info 4092 ApplicationInfo ai = PackageParser.generateApplicationInfo( 4093 p, flags, ps.readUserState(userId), userId); 4094 if (ai != null) { 4095 rebaseEnabledOverlays(ai, userId); 4096 ai.packageName = resolveExternalPackageNameLPr(p); 4097 } 4098 return ai; 4099 } 4100 if ("android".equals(packageName)||"system".equals(packageName)) { 4101 return mAndroidApplication; 4102 } 4103 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 4104 // Already generates the external package name 4105 return generateApplicationInfoFromSettingsLPw(packageName, 4106 Binder.getCallingUid(), flags, userId); 4107 } 4108 } 4109 return null; 4110 } 4111 4112 private void rebaseEnabledOverlays(@NonNull ApplicationInfo ai, int userId) { 4113 List<String> paths = new ArrayList<>(); 4114 ArrayMap<String, ArrayList<String>> userSpecificOverlays = 4115 mEnabledOverlayPaths.get(userId); 4116 if (userSpecificOverlays != null) { 4117 if (!"android".equals(ai.packageName)) { 4118 ArrayList<String> frameworkOverlays = userSpecificOverlays.get("android"); 4119 if (frameworkOverlays != null) { 4120 paths.addAll(frameworkOverlays); 4121 } 4122 } 4123 4124 ArrayList<String> appOverlays = userSpecificOverlays.get(ai.packageName); 4125 if (appOverlays != null) { 4126 paths.addAll(appOverlays); 4127 } 4128 } 4129 ai.resourceDirs = paths.size() > 0 ? paths.toArray(new String[paths.size()]) : null; 4130 } 4131 4132 private String normalizePackageNameLPr(String packageName) { 4133 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 4134 return normalizedPackageName != null ? normalizedPackageName : packageName; 4135 } 4136 4137 @Override 4138 public void deletePreloadsFileCache() { 4139 if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) { 4140 throw new SecurityException("Only system or settings may call deletePreloadsFileCache"); 4141 } 4142 File dir = Environment.getDataPreloadsFileCacheDirectory(); 4143 Slog.i(TAG, "Deleting preloaded file cache " + dir); 4144 FileUtils.deleteContents(dir); 4145 } 4146 4147 @Override 4148 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 4149 final IPackageDataObserver observer) { 4150 mContext.enforceCallingOrSelfPermission( 4151 android.Manifest.permission.CLEAR_APP_CACHE, null); 4152 mHandler.post(() -> { 4153 boolean success = false; 4154 try { 4155 freeStorage(volumeUuid, freeStorageSize, 0); 4156 success = true; 4157 } catch (IOException e) { 4158 Slog.w(TAG, e); 4159 } 4160 if (observer != null) { 4161 try { 4162 observer.onRemoveCompleted(null, success); 4163 } catch (RemoteException e) { 4164 Slog.w(TAG, e); 4165 } 4166 } 4167 }); 4168 } 4169 4170 @Override 4171 public void freeStorage(final String volumeUuid, final long freeStorageSize, 4172 final IntentSender pi) { 4173 mContext.enforceCallingOrSelfPermission( 4174 android.Manifest.permission.CLEAR_APP_CACHE, TAG); 4175 mHandler.post(() -> { 4176 boolean success = false; 4177 try { 4178 freeStorage(volumeUuid, freeStorageSize, 0); 4179 success = true; 4180 } catch (IOException e) { 4181 Slog.w(TAG, e); 4182 } 4183 if (pi != null) { 4184 try { 4185 pi.sendIntent(null, success ? 1 : 0, null, null, null); 4186 } catch (SendIntentException e) { 4187 Slog.w(TAG, e); 4188 } 4189 } 4190 }); 4191 } 4192 4193 /** 4194 * Blocking call to clear various types of cached data across the system 4195 * until the requested bytes are available. 4196 */ 4197 public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException { 4198 final StorageManager storage = mContext.getSystemService(StorageManager.class); 4199 final File file = storage.findPathForUuid(volumeUuid); 4200 if (file.getUsableSpace() >= bytes) return; 4201 4202 if (ENABLE_FREE_CACHE_V2) { 4203 final boolean aggressive = (storageFlags 4204 & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0; 4205 final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, 4206 volumeUuid); 4207 4208 // 1. Pre-flight to determine if we have any chance to succeed 4209 // 2. Consider preloaded data (after 1w honeymoon, unless aggressive) 4210 if (internalVolume && (aggressive || SystemProperties 4211 .getBoolean("persist.sys.preloads.file_cache_expired", false))) { 4212 deletePreloadsFileCache(); 4213 if (file.getUsableSpace() >= bytes) return; 4214 } 4215 4216 // 3. Consider parsed APK data (aggressive only) 4217 if (internalVolume && aggressive) { 4218 FileUtils.deleteContents(mCacheDir); 4219 if (file.getUsableSpace() >= bytes) return; 4220 } 4221 4222 // 4. Consider cached app data (above quotas) 4223 try { 4224 mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2); 4225 } catch (InstallerException ignored) { 4226 } 4227 if (file.getUsableSpace() >= bytes) return; 4228 4229 // 5. Consider shared libraries with refcount=0 and age>2h 4230 // 6. Consider dexopt output (aggressive only) 4231 // 7. Consider ephemeral apps not used in last week 4232 4233 // 8. Consider cached app data (below quotas) 4234 try { 4235 mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2 4236 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA); 4237 } catch (InstallerException ignored) { 4238 } 4239 if (file.getUsableSpace() >= bytes) return; 4240 4241 // 9. Consider DropBox entries 4242 // 10. Consider ephemeral cookies 4243 4244 } else { 4245 try { 4246 mInstaller.freeCache(volumeUuid, bytes, 0); 4247 } catch (InstallerException ignored) { 4248 } 4249 if (file.getUsableSpace() >= bytes) return; 4250 } 4251 4252 throw new IOException("Failed to free " + bytes + " on storage device at " + file); 4253 } 4254 4255 /** 4256 * Update given flags based on encryption status of current user. 4257 */ 4258 private int updateFlags(int flags, int userId) { 4259 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 4260 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 4261 // Caller expressed an explicit opinion about what encryption 4262 // aware/unaware components they want to see, so fall through and 4263 // give them what they want 4264 } else { 4265 // Caller expressed no opinion, so match based on user state 4266 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 4267 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 4268 } else { 4269 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 4270 } 4271 } 4272 return flags; 4273 } 4274 4275 private UserManagerInternal getUserManagerInternal() { 4276 if (mUserManagerInternal == null) { 4277 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 4278 } 4279 return mUserManagerInternal; 4280 } 4281 4282 private DeviceIdleController.LocalService getDeviceIdleController() { 4283 if (mDeviceIdleController == null) { 4284 mDeviceIdleController = 4285 LocalServices.getService(DeviceIdleController.LocalService.class); 4286 } 4287 return mDeviceIdleController; 4288 } 4289 4290 /** 4291 * Update given flags when being used to request {@link PackageInfo}. 4292 */ 4293 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 4294 final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM; 4295 boolean triaged = true; 4296 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 4297 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 4298 // Caller is asking for component details, so they'd better be 4299 // asking for specific encryption matching behavior, or be triaged 4300 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 4301 | PackageManager.MATCH_DIRECT_BOOT_AWARE 4302 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 4303 triaged = false; 4304 } 4305 } 4306 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 4307 | PackageManager.MATCH_SYSTEM_ONLY 4308 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 4309 triaged = false; 4310 } 4311 if ((flags & PackageManager.MATCH_ANY_USER) != 0) { 4312 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 4313 "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at " 4314 + Debug.getCallers(5)); 4315 } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser 4316 && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) { 4317 // If the caller wants all packages and has a restricted profile associated with it, 4318 // then match all users. This is to make sure that launchers that need to access work 4319 // profile apps don't start breaking. TODO: Remove this hack when launchers stop using 4320 // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380 4321 flags |= PackageManager.MATCH_ANY_USER; 4322 } 4323 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 4324 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 4325 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 4326 } 4327 return updateFlags(flags, userId); 4328 } 4329 4330 /** 4331 * Update given flags when being used to request {@link ApplicationInfo}. 4332 */ 4333 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 4334 return updateFlagsForPackage(flags, userId, cookie); 4335 } 4336 4337 /** 4338 * Update given flags when being used to request {@link ComponentInfo}. 4339 */ 4340 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 4341 if (cookie instanceof Intent) { 4342 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 4343 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 4344 } 4345 } 4346 4347 boolean triaged = true; 4348 // Caller is asking for component details, so they'd better be 4349 // asking for specific encryption matching behavior, or be triaged 4350 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 4351 | PackageManager.MATCH_DIRECT_BOOT_AWARE 4352 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 4353 triaged = false; 4354 } 4355 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 4356 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 4357 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 4358 } 4359 4360 return updateFlags(flags, userId); 4361 } 4362 4363 /** 4364 * Update given intent when being used to request {@link ResolveInfo}. 4365 */ 4366 private Intent updateIntentForResolve(Intent intent) { 4367 if (intent.getSelector() != null) { 4368 intent = intent.getSelector(); 4369 } 4370 if (DEBUG_PREFERRED) { 4371 intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4372 } 4373 return intent; 4374 } 4375 4376 /** 4377 * Update given flags when being used to request {@link ResolveInfo}. 4378 * <p>Instant apps are resolved specially, depending upon context. Minimally, 4379 * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT} 4380 * flag set. However, this flag is only honoured in three circumstances: 4381 * <ul> 4382 * <li>when called from a system process</li> 4383 * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li> 4384 * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW} 4385 * action and a {@code android.intent.category.BROWSABLE} category</li> 4386 * </ul> 4387 */ 4388 int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) { 4389 return updateFlagsForResolve(flags, userId, intent, callingUid, 4390 false /*wantInstantApps*/, false /*onlyExposedExplicitly*/); 4391 } 4392 int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid, 4393 boolean wantInstantApps) { 4394 return updateFlagsForResolve(flags, userId, intent, callingUid, 4395 wantInstantApps, false /*onlyExposedExplicitly*/); 4396 } 4397 int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid, 4398 boolean wantInstantApps, boolean onlyExposedExplicitly) { 4399 // Safe mode means we shouldn't match any third-party components 4400 if (mSafeMode) { 4401 flags |= PackageManager.MATCH_SYSTEM_ONLY; 4402 } 4403 if (getInstantAppPackageName(callingUid) != null) { 4404 // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components 4405 if (onlyExposedExplicitly) { 4406 flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY; 4407 } 4408 flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY; 4409 flags |= PackageManager.MATCH_INSTANT; 4410 } else { 4411 final boolean allowMatchInstant = 4412 (wantInstantApps 4413 && Intent.ACTION_VIEW.equals(intent.getAction()) 4414 && hasWebURI(intent)) 4415 || canAccessInstantApps(callingUid); 4416 flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY 4417 | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY); 4418 if (!allowMatchInstant) { 4419 flags &= ~PackageManager.MATCH_INSTANT; 4420 } 4421 } 4422 return updateFlagsForComponent(flags, userId, intent /*cookie*/); 4423 } 4424 4425 private ActivityInfo generateActivityInfo(ActivityInfo ai, int flags, PackageUserState state, 4426 int userId) { 4427 ActivityInfo ret = PackageParser.generateActivityInfo(ai, flags, state, userId); 4428 if (ret != null) { 4429 rebaseEnabledOverlays(ret.applicationInfo, userId); 4430 } 4431 return ret; 4432 } 4433 4434 private ActivityInfo generateActivityInfo(PackageParser.Activity a, int flags, 4435 PackageUserState state, int userId) { 4436 ActivityInfo ai = PackageParser.generateActivityInfo(a, flags, state, userId); 4437 if (ai != null) { 4438 rebaseEnabledOverlays(ai.applicationInfo, userId); 4439 } 4440 return ai; 4441 } 4442 4443 @Override 4444 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 4445 if (!sUserManager.exists(userId)) return null; 4446 final int callingUid = Binder.getCallingUid(); 4447 flags = updateFlagsForComponent(flags, userId, component); 4448 enforceCrossUserPermission(callingUid, userId, 4449 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 4450 synchronized (mPackages) { 4451 PackageParser.Activity a = mActivities.mActivities.get(component); 4452 4453 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 4454 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 4455 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4456 if (ps == null) return null; 4457 if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, userId)) { 4458 return null; 4459 } 4460 return generateActivityInfo(a, flags, ps.readUserState(userId), userId); 4461 } 4462 if (mResolveComponentName.equals(component)) { 4463 return generateActivityInfo(mResolveActivity, flags, new PackageUserState(), 4464 userId); 4465 } 4466 } 4467 return null; 4468 } 4469 4470 @Override 4471 public boolean activitySupportsIntent(ComponentName component, Intent intent, 4472 String resolvedType) { 4473 synchronized (mPackages) { 4474 if (component.equals(mResolveComponentName)) { 4475 // The resolver supports EVERYTHING! 4476 return true; 4477 } 4478 final int callingUid = Binder.getCallingUid(); 4479 final int callingUserId = UserHandle.getUserId(callingUid); 4480 PackageParser.Activity a = mActivities.mActivities.get(component); 4481 if (a == null) { 4482 return false; 4483 } 4484 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4485 if (ps == null) { 4486 return false; 4487 } 4488 if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) { 4489 return false; 4490 } 4491 for (int i=0; i<a.intents.size(); i++) { 4492 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 4493 intent.getData(), intent.getCategories(), TAG) >= 0) { 4494 return true; 4495 } 4496 } 4497 return false; 4498 } 4499 } 4500 4501 @Override 4502 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 4503 if (!sUserManager.exists(userId)) return null; 4504 final int callingUid = Binder.getCallingUid(); 4505 flags = updateFlagsForComponent(flags, userId, component); 4506 enforceCrossUserPermission(callingUid, userId, 4507 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 4508 synchronized (mPackages) { 4509 PackageParser.Activity a = mReceivers.mActivities.get(component); 4510 if (DEBUG_PACKAGE_INFO) Log.v( 4511 TAG, "getReceiverInfo " + component + ": " + a); 4512 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 4513 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4514 if (ps == null) return null; 4515 if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) { 4516 return null; 4517 } 4518 return generateActivityInfo(a, flags, ps.readUserState(userId), userId); 4519 } 4520 } 4521 return null; 4522 } 4523 4524 @Override 4525 public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName, 4526 int flags, int userId) { 4527 if (!sUserManager.exists(userId)) return null; 4528 Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0"); 4529 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 4530 return null; 4531 } 4532 4533 flags = updateFlagsForPackage(flags, userId, null); 4534 4535 final boolean canSeeStaticLibraries = 4536 mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES) 4537 == PERMISSION_GRANTED 4538 || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES) 4539 == PERMISSION_GRANTED 4540 || canRequestPackageInstallsInternal(packageName, 4541 PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId, 4542 false /* throwIfPermNotDeclared*/) 4543 || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES) 4544 == PERMISSION_GRANTED; 4545 4546 synchronized (mPackages) { 4547 List<SharedLibraryInfo> result = null; 4548 4549 final int libCount = mSharedLibraries.size(); 4550 for (int i = 0; i < libCount; i++) { 4551 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 4552 if (versionedLib == null) { 4553 continue; 4554 } 4555 4556 final int versionCount = versionedLib.size(); 4557 for (int j = 0; j < versionCount; j++) { 4558 SharedLibraryInfo libInfo = versionedLib.valueAt(j).info; 4559 if (!canSeeStaticLibraries && libInfo.isStatic()) { 4560 break; 4561 } 4562 final long identity = Binder.clearCallingIdentity(); 4563 try { 4564 PackageInfo packageInfo = getPackageInfoVersioned( 4565 libInfo.getDeclaringPackage(), flags 4566 | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId); 4567 if (packageInfo == null) { 4568 continue; 4569 } 4570 } finally { 4571 Binder.restoreCallingIdentity(identity); 4572 } 4573 4574 SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(), 4575 libInfo.getVersion(), libInfo.getType(), 4576 libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo, 4577 flags, userId)); 4578 4579 if (result == null) { 4580 result = new ArrayList<>(); 4581 } 4582 result.add(resLibInfo); 4583 } 4584 } 4585 4586 return result != null ? new ParceledListSlice<>(result) : null; 4587 } 4588 } 4589 4590 private List<VersionedPackage> getPackagesUsingSharedLibraryLPr( 4591 SharedLibraryInfo libInfo, int flags, int userId) { 4592 List<VersionedPackage> versionedPackages = null; 4593 final int packageCount = mSettings.mPackages.size(); 4594 for (int i = 0; i < packageCount; i++) { 4595 PackageSetting ps = mSettings.mPackages.valueAt(i); 4596 4597 if (ps == null) { 4598 continue; 4599 } 4600 4601 if (!ps.getUserState().get(userId).isAvailable(flags)) { 4602 continue; 4603 } 4604 4605 final String libName = libInfo.getName(); 4606 if (libInfo.isStatic()) { 4607 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 4608 if (libIdx < 0) { 4609 continue; 4610 } 4611 if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) { 4612 continue; 4613 } 4614 if (versionedPackages == null) { 4615 versionedPackages = new ArrayList<>(); 4616 } 4617 // If the dependent is a static shared lib, use the public package name 4618 String dependentPackageName = ps.name; 4619 if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) { 4620 dependentPackageName = ps.pkg.manifestPackageName; 4621 } 4622 versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode)); 4623 } else if (ps.pkg != null) { 4624 if (ArrayUtils.contains(ps.pkg.usesLibraries, libName) 4625 || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) { 4626 if (versionedPackages == null) { 4627 versionedPackages = new ArrayList<>(); 4628 } 4629 versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode)); 4630 } 4631 } 4632 } 4633 4634 return versionedPackages; 4635 } 4636 4637 @Override 4638 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 4639 if (!sUserManager.exists(userId)) return null; 4640 final int callingUid = Binder.getCallingUid(); 4641 flags = updateFlagsForComponent(flags, userId, component); 4642 enforceCrossUserPermission(callingUid, userId, 4643 false /* requireFullPermission */, false /* checkShell */, "get service info"); 4644 synchronized (mPackages) { 4645 PackageParser.Service s = mServices.mServices.get(component); 4646 if (DEBUG_PACKAGE_INFO) Log.v( 4647 TAG, "getServiceInfo " + component + ": " + s); 4648 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 4649 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4650 if (ps == null) return null; 4651 if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) { 4652 return null; 4653 } 4654 ServiceInfo si = PackageParser.generateServiceInfo(s, flags, 4655 ps.readUserState(userId), userId); 4656 if (si != null) { 4657 rebaseEnabledOverlays(si.applicationInfo, userId); 4658 } 4659 return si; 4660 } 4661 } 4662 return null; 4663 } 4664 4665 @Override 4666 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 4667 if (!sUserManager.exists(userId)) return null; 4668 final int callingUid = Binder.getCallingUid(); 4669 flags = updateFlagsForComponent(flags, userId, component); 4670 enforceCrossUserPermission(callingUid, userId, 4671 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 4672 synchronized (mPackages) { 4673 PackageParser.Provider p = mProviders.mProviders.get(component); 4674 if (DEBUG_PACKAGE_INFO) Log.v( 4675 TAG, "getProviderInfo " + component + ": " + p); 4676 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 4677 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4678 if (ps == null) return null; 4679 if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) { 4680 return null; 4681 } 4682 ProviderInfo pi = PackageParser.generateProviderInfo(p, flags, 4683 ps.readUserState(userId), userId); 4684 if (pi != null) { 4685 rebaseEnabledOverlays(pi.applicationInfo, userId); 4686 } 4687 return pi; 4688 } 4689 } 4690 return null; 4691 } 4692 4693 @Override 4694 public String[] getSystemSharedLibraryNames() { 4695 // allow instant applications 4696 synchronized (mPackages) { 4697 Set<String> libs = null; 4698 final int libCount = mSharedLibraries.size(); 4699 for (int i = 0; i < libCount; i++) { 4700 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 4701 if (versionedLib == null) { 4702 continue; 4703 } 4704 final int versionCount = versionedLib.size(); 4705 for (int j = 0; j < versionCount; j++) { 4706 SharedLibraryEntry libEntry = versionedLib.valueAt(j); 4707 if (!libEntry.info.isStatic()) { 4708 if (libs == null) { 4709 libs = new ArraySet<>(); 4710 } 4711 libs.add(libEntry.info.getName()); 4712 break; 4713 } 4714 PackageSetting ps = mSettings.getPackageLPr(libEntry.apk); 4715 if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(), 4716 UserHandle.getUserId(Binder.getCallingUid()), 4717 PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) { 4718 if (libs == null) { 4719 libs = new ArraySet<>(); 4720 } 4721 libs.add(libEntry.info.getName()); 4722 break; 4723 } 4724 } 4725 } 4726 4727 if (libs != null) { 4728 String[] libsArray = new String[libs.size()]; 4729 libs.toArray(libsArray); 4730 return libsArray; 4731 } 4732 4733 return null; 4734 } 4735 } 4736 4737 @Override 4738 public @NonNull String getServicesSystemSharedLibraryPackageName() { 4739 // allow instant applications 4740 synchronized (mPackages) { 4741 return mServicesSystemSharedLibraryPackageName; 4742 } 4743 } 4744 4745 @Override 4746 public @NonNull String getSharedSystemSharedLibraryPackageName() { 4747 // allow instant applications 4748 synchronized (mPackages) { 4749 return mSharedSystemSharedLibraryPackageName; 4750 } 4751 } 4752 4753 private void updateSequenceNumberLP(String packageName, int[] userList) { 4754 for (int i = userList.length - 1; i >= 0; --i) { 4755 final int userId = userList[i]; 4756 SparseArray<String> changedPackages = mChangedPackages.get(userId); 4757 if (changedPackages == null) { 4758 changedPackages = new SparseArray<>(); 4759 mChangedPackages.put(userId, changedPackages); 4760 } 4761 Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId); 4762 if (sequenceNumbers == null) { 4763 sequenceNumbers = new HashMap<>(); 4764 mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers); 4765 } 4766 final Integer sequenceNumber = sequenceNumbers.get(packageName); 4767 if (sequenceNumber != null) { 4768 changedPackages.remove(sequenceNumber); 4769 } 4770 changedPackages.put(mChangedPackagesSequenceNumber, packageName); 4771 sequenceNumbers.put(packageName, mChangedPackagesSequenceNumber); 4772 } 4773 mChangedPackagesSequenceNumber++; 4774 } 4775 4776 @Override 4777 public ChangedPackages getChangedPackages(int sequenceNumber, int userId) { 4778 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 4779 return null; 4780 } 4781 synchronized (mPackages) { 4782 if (sequenceNumber >= mChangedPackagesSequenceNumber) { 4783 return null; 4784 } 4785 final SparseArray<String> changedPackages = mChangedPackages.get(userId); 4786 if (changedPackages == null) { 4787 return null; 4788 } 4789 final List<String> packageNames = 4790 new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber); 4791 for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) { 4792 final String packageName = changedPackages.get(i); 4793 if (packageName != null) { 4794 packageNames.add(packageName); 4795 } 4796 } 4797 return packageNames.isEmpty() 4798 ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames); 4799 } 4800 } 4801 4802 @Override 4803 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 4804 // allow instant applications 4805 ArrayList<FeatureInfo> res; 4806 synchronized (mAvailableFeatures) { 4807 res = new ArrayList<>(mAvailableFeatures.size() + 1); 4808 res.addAll(mAvailableFeatures.values()); 4809 } 4810 final FeatureInfo fi = new FeatureInfo(); 4811 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 4812 FeatureInfo.GL_ES_VERSION_UNDEFINED); 4813 res.add(fi); 4814 4815 return new ParceledListSlice<>(res); 4816 } 4817 4818 @Override 4819 public boolean hasSystemFeature(String name, int version) { 4820 // allow instant applications 4821 synchronized (mAvailableFeatures) { 4822 final FeatureInfo feat = mAvailableFeatures.get(name); 4823 if (feat == null) { 4824 return false; 4825 } else { 4826 return feat.version >= version; 4827 } 4828 } 4829 } 4830 4831 @Override 4832 public int checkPermission(String permName, String pkgName, int userId) { 4833 if (!sUserManager.exists(userId)) { 4834 return PackageManager.PERMISSION_DENIED; 4835 } 4836 final int callingUid = Binder.getCallingUid(); 4837 4838 synchronized (mPackages) { 4839 final PackageParser.Package p = mPackages.get(pkgName); 4840 if (p != null && p.mExtras != null) { 4841 final PackageSetting ps = (PackageSetting) p.mExtras; 4842 if (filterAppAccessLPr(ps, callingUid, userId)) { 4843 return PackageManager.PERMISSION_DENIED; 4844 } 4845 final PermissionsState permissionsState = ps.getPermissionsState(); 4846 if (permissionsState.hasPermission(permName, userId)) { 4847 return PackageManager.PERMISSION_GRANTED; 4848 } 4849 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 4850 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 4851 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 4852 return PackageManager.PERMISSION_GRANTED; 4853 } 4854 } 4855 } 4856 4857 return PackageManager.PERMISSION_DENIED; 4858 } 4859 4860 @Override 4861 public int checkUidPermission(String permName, int uid) { 4862 final int callingUid = Binder.getCallingUid(); 4863 final int callingUserId = UserHandle.getUserId(callingUid); 4864 final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null; 4865 final int userId = UserHandle.getUserId(uid); 4866 if (!sUserManager.exists(userId)) { 4867 return PackageManager.PERMISSION_DENIED; 4868 } 4869 4870 synchronized (mPackages) { 4871 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4872 if (obj != null) { 4873 if (obj instanceof SharedUserSetting) { 4874 if (isCallerInstantApp) { 4875 return PackageManager.PERMISSION_DENIED; 4876 } 4877 } else if (obj instanceof PackageSetting) { 4878 final PackageSetting ps = (PackageSetting) obj; 4879 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 4880 return PackageManager.PERMISSION_DENIED; 4881 } 4882 } 4883 final SettingBase settingBase = (SettingBase) obj; 4884 final PermissionsState permissionsState = settingBase.getPermissionsState(); 4885 if (permissionsState.hasPermission(permName, userId)) { 4886 return PackageManager.PERMISSION_GRANTED; 4887 } 4888 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 4889 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 4890 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 4891 return PackageManager.PERMISSION_GRANTED; 4892 } 4893 } else { 4894 ArraySet<String> perms = mSystemPermissions.get(uid); 4895 if (perms != null) { 4896 if (perms.contains(permName)) { 4897 return PackageManager.PERMISSION_GRANTED; 4898 } 4899 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 4900 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 4901 return PackageManager.PERMISSION_GRANTED; 4902 } 4903 } 4904 } 4905 } 4906 4907 return PackageManager.PERMISSION_DENIED; 4908 } 4909 4910 @Override 4911 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 4912 if (UserHandle.getCallingUserId() != userId) { 4913 mContext.enforceCallingPermission( 4914 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4915 "isPermissionRevokedByPolicy for user " + userId); 4916 } 4917 4918 if (checkPermission(permission, packageName, userId) 4919 == PackageManager.PERMISSION_GRANTED) { 4920 return false; 4921 } 4922 4923 final int callingUid = Binder.getCallingUid(); 4924 if (getInstantAppPackageName(callingUid) != null) { 4925 if (!isCallerSameApp(packageName, callingUid)) { 4926 return false; 4927 } 4928 } else { 4929 if (isInstantApp(packageName, userId)) { 4930 return false; 4931 } 4932 } 4933 4934 final long identity = Binder.clearCallingIdentity(); 4935 try { 4936 final int flags = getPermissionFlags(permission, packageName, userId); 4937 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 4938 } finally { 4939 Binder.restoreCallingIdentity(identity); 4940 } 4941 } 4942 4943 @Override 4944 public String getPermissionControllerPackageName() { 4945 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 4946 throw new SecurityException("Instant applications don't have access to this method"); 4947 } 4948 synchronized (mPackages) { 4949 return mRequiredInstallerPackage; 4950 } 4951 } 4952 4953 /** 4954 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 4955 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 4956 * @param checkShell whether to prevent shell from access if there's a debugging restriction 4957 * @param message the message to log on security exception 4958 */ 4959 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 4960 boolean checkShell, String message) { 4961 if (userId < 0) { 4962 throw new IllegalArgumentException("Invalid userId " + userId); 4963 } 4964 if (checkShell) { 4965 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 4966 } 4967 if (userId == UserHandle.getUserId(callingUid)) return; 4968 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4969 if (requireFullPermission) { 4970 mContext.enforceCallingOrSelfPermission( 4971 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 4972 } else { 4973 try { 4974 mContext.enforceCallingOrSelfPermission( 4975 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 4976 } catch (SecurityException se) { 4977 mContext.enforceCallingOrSelfPermission( 4978 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 4979 } 4980 } 4981 } 4982 } 4983 4984 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 4985 if (callingUid == Process.SHELL_UID) { 4986 if (userHandle >= 0 4987 && sUserManager.hasUserRestriction(restriction, userHandle)) { 4988 throw new SecurityException("Shell does not have permission to access user " 4989 + userHandle); 4990 } else if (userHandle < 0) { 4991 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 4992 + Debug.getCallers(3)); 4993 } 4994 } 4995 } 4996 4997 private BasePermission findPermissionTreeLP(String permName) { 4998 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 4999 if (permName.startsWith(bp.name) && 5000 permName.length() > bp.name.length() && 5001 permName.charAt(bp.name.length()) == '.') { 5002 return bp; 5003 } 5004 } 5005 return null; 5006 } 5007 5008 private BasePermission checkPermissionTreeLP(String permName) { 5009 if (permName != null) { 5010 BasePermission bp = findPermissionTreeLP(permName); 5011 if (bp != null) { 5012 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 5013 return bp; 5014 } 5015 throw new SecurityException("Calling uid " 5016 + Binder.getCallingUid() 5017 + " is not allowed to add to permission tree " 5018 + bp.name + " owned by uid " + bp.uid); 5019 } 5020 } 5021 throw new SecurityException("No permission tree found for " + permName); 5022 } 5023 5024 static boolean compareStrings(CharSequence s1, CharSequence s2) { 5025 if (s1 == null) { 5026 return s2 == null; 5027 } 5028 if (s2 == null) { 5029 return false; 5030 } 5031 if (s1.getClass() != s2.getClass()) { 5032 return false; 5033 } 5034 return s1.equals(s2); 5035 } 5036 5037 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 5038 if (pi1.icon != pi2.icon) return false; 5039 if (pi1.logo != pi2.logo) return false; 5040 if (pi1.protectionLevel != pi2.protectionLevel) return false; 5041 if (!compareStrings(pi1.name, pi2.name)) return false; 5042 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 5043 // We'll take care of setting this one. 5044 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 5045 // These are not currently stored in settings. 5046 //if (!compareStrings(pi1.group, pi2.group)) return false; 5047 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 5048 //if (pi1.labelRes != pi2.labelRes) return false; 5049 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 5050 return true; 5051 } 5052 5053 int permissionInfoFootprint(PermissionInfo info) { 5054 int size = info.name.length(); 5055 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 5056 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 5057 return size; 5058 } 5059 5060 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 5061 int size = 0; 5062 for (BasePermission perm : mSettings.mPermissions.values()) { 5063 if (perm.uid == tree.uid) { 5064 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 5065 } 5066 } 5067 return size; 5068 } 5069 5070 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 5071 // We calculate the max size of permissions defined by this uid and throw 5072 // if that plus the size of 'info' would exceed our stated maximum. 5073 if (tree.uid != Process.SYSTEM_UID) { 5074 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 5075 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 5076 throw new SecurityException("Permission tree size cap exceeded"); 5077 } 5078 } 5079 } 5080 5081 boolean addPermissionLocked(PermissionInfo info, boolean async) { 5082 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5083 throw new SecurityException("Instant apps can't add permissions"); 5084 } 5085 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 5086 throw new SecurityException("Label must be specified in permission"); 5087 } 5088 BasePermission tree = checkPermissionTreeLP(info.name); 5089 BasePermission bp = mSettings.mPermissions.get(info.name); 5090 boolean added = bp == null; 5091 boolean changed = true; 5092 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 5093 if (added) { 5094 enforcePermissionCapLocked(info, tree); 5095 bp = new BasePermission(info.name, tree.sourcePackage, 5096 BasePermission.TYPE_DYNAMIC); 5097 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 5098 throw new SecurityException( 5099 "Not allowed to modify non-dynamic permission " 5100 + info.name); 5101 } else { 5102 if (bp.protectionLevel == fixedLevel 5103 && bp.perm.owner.equals(tree.perm.owner) 5104 && bp.uid == tree.uid 5105 && comparePermissionInfos(bp.perm.info, info)) { 5106 changed = false; 5107 } 5108 } 5109 bp.protectionLevel = fixedLevel; 5110 info = new PermissionInfo(info); 5111 info.protectionLevel = fixedLevel; 5112 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 5113 bp.perm.info.packageName = tree.perm.info.packageName; 5114 bp.uid = tree.uid; 5115 if (added) { 5116 mSettings.mPermissions.put(info.name, bp); 5117 } 5118 if (changed) { 5119 if (!async) { 5120 mSettings.writeLPr(); 5121 } else { 5122 scheduleWriteSettingsLocked(); 5123 } 5124 } 5125 return added; 5126 } 5127 5128 @Override 5129 public boolean addPermission(PermissionInfo info) { 5130 synchronized (mPackages) { 5131 return addPermissionLocked(info, false); 5132 } 5133 } 5134 5135 @Override 5136 public boolean addPermissionAsync(PermissionInfo info) { 5137 synchronized (mPackages) { 5138 return addPermissionLocked(info, true); 5139 } 5140 } 5141 5142 @Override 5143 public void removePermission(String name) { 5144 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5145 throw new SecurityException("Instant applications don't have access to this method"); 5146 } 5147 synchronized (mPackages) { 5148 checkPermissionTreeLP(name); 5149 BasePermission bp = mSettings.mPermissions.get(name); 5150 if (bp != null) { 5151 if (bp.type != BasePermission.TYPE_DYNAMIC) { 5152 throw new SecurityException( 5153 "Not allowed to modify non-dynamic permission " 5154 + name); 5155 } 5156 mSettings.mPermissions.remove(name); 5157 mSettings.writeLPr(); 5158 } 5159 } 5160 } 5161 5162 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission( 5163 PackageParser.Package pkg, BasePermission bp) { 5164 int index = pkg.requestedPermissions.indexOf(bp.name); 5165 if (index == -1) { 5166 throw new SecurityException("Package " + pkg.packageName 5167 + " has not requested permission " + bp.name); 5168 } 5169 if (!bp.isRuntime() && !bp.isDevelopment()) { 5170 throw new SecurityException("Permission " + bp.name 5171 + " is not a changeable permission type"); 5172 } 5173 } 5174 5175 @Override 5176 public void grantRuntimePermission(String packageName, String name, final int userId) { 5177 grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */); 5178 } 5179 5180 private void grantRuntimePermission(String packageName, String name, final int userId, 5181 boolean overridePolicy) { 5182 if (!sUserManager.exists(userId)) { 5183 Log.e(TAG, "No such user:" + userId); 5184 return; 5185 } 5186 5187 mContext.enforceCallingOrSelfPermission( 5188 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 5189 "grantRuntimePermission"); 5190 5191 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5192 true /* requireFullPermission */, true /* checkShell */, 5193 "grantRuntimePermission"); 5194 5195 final int uid; 5196 final SettingBase sb; 5197 5198 synchronized (mPackages) { 5199 final PackageParser.Package pkg = mPackages.get(packageName); 5200 if (pkg == null) { 5201 throw new IllegalArgumentException("Unknown package: " + packageName); 5202 } 5203 5204 final BasePermission bp = mSettings.mPermissions.get(name); 5205 if (bp == null) { 5206 throw new IllegalArgumentException("Unknown permission: " + name); 5207 } 5208 5209 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 5210 5211 // If a permission review is required for legacy apps we represent 5212 // their permissions as always granted runtime ones since we need 5213 // to keep the review required permission flag per user while an 5214 // install permission's state is shared across all users. 5215 if (mPermissionReviewRequired 5216 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 5217 && bp.isRuntime()) { 5218 return; 5219 } 5220 5221 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 5222 sb = (SettingBase) pkg.mExtras; 5223 if (sb == null) { 5224 throw new IllegalArgumentException("Unknown package: " + packageName); 5225 } 5226 5227 final PermissionsState permissionsState = sb.getPermissionsState(); 5228 5229 final int flags = permissionsState.getPermissionFlags(name, userId); 5230 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 5231 throw new SecurityException("Cannot grant system fixed permission " 5232 + name + " for package " + packageName); 5233 } 5234 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) { 5235 throw new SecurityException("Cannot grant policy fixed permission " 5236 + name + " for package " + packageName); 5237 } 5238 5239 if (bp.isDevelopment()) { 5240 // Development permissions must be handled specially, since they are not 5241 // normal runtime permissions. For now they apply to all users. 5242 if (permissionsState.grantInstallPermission(bp) != 5243 PermissionsState.PERMISSION_OPERATION_FAILURE) { 5244 scheduleWriteSettingsLocked(); 5245 } 5246 return; 5247 } 5248 5249 final PackageSetting ps = mSettings.mPackages.get(packageName); 5250 if (ps.getInstantApp(userId) && !bp.isInstant()) { 5251 throw new SecurityException("Cannot grant non-ephemeral permission" 5252 + name + " for package " + packageName); 5253 } 5254 5255 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 5256 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 5257 return; 5258 } 5259 5260 final int result = permissionsState.grantRuntimePermission(bp, userId); 5261 switch (result) { 5262 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 5263 return; 5264 } 5265 5266 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 5267 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 5268 mHandler.post(new Runnable() { 5269 @Override 5270 public void run() { 5271 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 5272 } 5273 }); 5274 } 5275 break; 5276 } 5277 5278 if (bp.isRuntime()) { 5279 logPermissionGranted(mContext, name, packageName); 5280 } 5281 5282 mOnPermissionChangeListeners.onPermissionsChanged(uid); 5283 5284 // Not critical if that is lost - app has to request again. 5285 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 5286 } 5287 5288 // Only need to do this if user is initialized. Otherwise it's a new user 5289 // and there are no processes running as the user yet and there's no need 5290 // to make an expensive call to remount processes for the changed permissions. 5291 if (READ_EXTERNAL_STORAGE.equals(name) 5292 || WRITE_EXTERNAL_STORAGE.equals(name)) { 5293 final long token = Binder.clearCallingIdentity(); 5294 try { 5295 if (sUserManager.isInitialized(userId)) { 5296 StorageManagerInternal storageManagerInternal = LocalServices.getService( 5297 StorageManagerInternal.class); 5298 storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName); 5299 } 5300 } finally { 5301 Binder.restoreCallingIdentity(token); 5302 } 5303 } 5304 } 5305 5306 @Override 5307 public void revokeRuntimePermission(String packageName, String name, int userId) { 5308 revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */); 5309 } 5310 5311 private void revokeRuntimePermission(String packageName, String name, int userId, 5312 boolean overridePolicy) { 5313 if (!sUserManager.exists(userId)) { 5314 Log.e(TAG, "No such user:" + userId); 5315 return; 5316 } 5317 5318 mContext.enforceCallingOrSelfPermission( 5319 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 5320 "revokeRuntimePermission"); 5321 5322 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5323 true /* requireFullPermission */, true /* checkShell */, 5324 "revokeRuntimePermission"); 5325 5326 final int appId; 5327 5328 synchronized (mPackages) { 5329 final PackageParser.Package pkg = mPackages.get(packageName); 5330 if (pkg == null) { 5331 throw new IllegalArgumentException("Unknown package: " + packageName); 5332 } 5333 5334 final BasePermission bp = mSettings.mPermissions.get(name); 5335 if (bp == null) { 5336 throw new IllegalArgumentException("Unknown permission: " + name); 5337 } 5338 5339 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 5340 5341 // If a permission review is required for legacy apps we represent 5342 // their permissions as always granted runtime ones since we need 5343 // to keep the review required permission flag per user while an 5344 // install permission's state is shared across all users. 5345 if (mPermissionReviewRequired 5346 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 5347 && bp.isRuntime()) { 5348 return; 5349 } 5350 5351 SettingBase sb = (SettingBase) pkg.mExtras; 5352 if (sb == null) { 5353 throw new IllegalArgumentException("Unknown package: " + packageName); 5354 } 5355 5356 final PermissionsState permissionsState = sb.getPermissionsState(); 5357 5358 final int flags = permissionsState.getPermissionFlags(name, userId); 5359 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 5360 throw new SecurityException("Cannot revoke system fixed permission " 5361 + name + " for package " + packageName); 5362 } 5363 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) { 5364 throw new SecurityException("Cannot revoke policy fixed permission " 5365 + name + " for package " + packageName); 5366 } 5367 5368 if (bp.isDevelopment()) { 5369 // Development permissions must be handled specially, since they are not 5370 // normal runtime permissions. For now they apply to all users. 5371 if (permissionsState.revokeInstallPermission(bp) != 5372 PermissionsState.PERMISSION_OPERATION_FAILURE) { 5373 scheduleWriteSettingsLocked(); 5374 } 5375 return; 5376 } 5377 5378 if (permissionsState.revokeRuntimePermission(bp, userId) == 5379 PermissionsState.PERMISSION_OPERATION_FAILURE) { 5380 return; 5381 } 5382 5383 if (bp.isRuntime()) { 5384 logPermissionRevoked(mContext, name, packageName); 5385 } 5386 5387 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 5388 5389 // Critical, after this call app should never have the permission. 5390 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 5391 5392 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 5393 } 5394 5395 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 5396 } 5397 5398 /** 5399 * Get the first event id for the permission. 5400 * 5401 * <p>There are four events for each permission: <ul> 5402 * <li>Request permission: first id + 0</li> 5403 * <li>Grant permission: first id + 1</li> 5404 * <li>Request for permission denied: first id + 2</li> 5405 * <li>Revoke permission: first id + 3</li> 5406 * </ul></p> 5407 * 5408 * @param name name of the permission 5409 * 5410 * @return The first event id for the permission 5411 */ 5412 private static int getBaseEventId(@NonNull String name) { 5413 int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name); 5414 5415 if (eventIdIndex == -1) { 5416 if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE 5417 || "user".equals(Build.TYPE)) { 5418 Log.i(TAG, "Unknown permission " + name); 5419 5420 return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN; 5421 } else { 5422 // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated. 5423 // 5424 // Also update 5425 // - EventLogger#ALL_DANGEROUS_PERMISSIONS 5426 // - metrics_constants.proto 5427 throw new IllegalStateException("Unknown permission " + name); 5428 } 5429 } 5430 5431 return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4; 5432 } 5433 5434 /** 5435 * Log that a permission was revoked. 5436 * 5437 * @param context Context of the caller 5438 * @param name name of the permission 5439 * @param packageName package permission if for 5440 */ 5441 private static void logPermissionRevoked(@NonNull Context context, @NonNull String name, 5442 @NonNull String packageName) { 5443 MetricsLogger.action(context, getBaseEventId(name) + 3, packageName); 5444 } 5445 5446 /** 5447 * Log that a permission request was granted. 5448 * 5449 * @param context Context of the caller 5450 * @param name name of the permission 5451 * @param packageName package permission if for 5452 */ 5453 private static void logPermissionGranted(@NonNull Context context, @NonNull String name, 5454 @NonNull String packageName) { 5455 MetricsLogger.action(context, getBaseEventId(name) + 1, packageName); 5456 } 5457 5458 @Override 5459 public void resetRuntimePermissions() { 5460 mContext.enforceCallingOrSelfPermission( 5461 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 5462 "revokeRuntimePermission"); 5463 5464 int callingUid = Binder.getCallingUid(); 5465 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 5466 mContext.enforceCallingOrSelfPermission( 5467 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5468 "resetRuntimePermissions"); 5469 } 5470 5471 synchronized (mPackages) { 5472 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 5473 for (int userId : UserManagerService.getInstance().getUserIds()) { 5474 final int packageCount = mPackages.size(); 5475 for (int i = 0; i < packageCount; i++) { 5476 PackageParser.Package pkg = mPackages.valueAt(i); 5477 if (!(pkg.mExtras instanceof PackageSetting)) { 5478 continue; 5479 } 5480 PackageSetting ps = (PackageSetting) pkg.mExtras; 5481 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 5482 } 5483 } 5484 } 5485 } 5486 5487 @Override 5488 public int getPermissionFlags(String name, String packageName, int userId) { 5489 if (!sUserManager.exists(userId)) { 5490 return 0; 5491 } 5492 5493 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 5494 5495 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5496 true /* requireFullPermission */, false /* checkShell */, 5497 "getPermissionFlags"); 5498 5499 synchronized (mPackages) { 5500 final PackageParser.Package pkg = mPackages.get(packageName); 5501 if (pkg == null) { 5502 return 0; 5503 } 5504 5505 final BasePermission bp = mSettings.mPermissions.get(name); 5506 if (bp == null) { 5507 return 0; 5508 } 5509 5510 SettingBase sb = (SettingBase) pkg.mExtras; 5511 if (sb == null) { 5512 return 0; 5513 } 5514 5515 PermissionsState permissionsState = sb.getPermissionsState(); 5516 return permissionsState.getPermissionFlags(name, userId); 5517 } 5518 } 5519 5520 @Override 5521 public void updatePermissionFlags(String name, String packageName, int flagMask, 5522 int flagValues, int userId) { 5523 if (!sUserManager.exists(userId)) { 5524 return; 5525 } 5526 5527 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 5528 5529 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5530 true /* requireFullPermission */, true /* checkShell */, 5531 "updatePermissionFlags"); 5532 5533 // Only the system can change these flags and nothing else. 5534 if (getCallingUid() != Process.SYSTEM_UID) { 5535 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5536 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5537 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 5538 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 5539 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 5540 } 5541 5542 synchronized (mPackages) { 5543 final PackageParser.Package pkg = mPackages.get(packageName); 5544 if (pkg == null) { 5545 throw new IllegalArgumentException("Unknown package: " + packageName); 5546 } 5547 5548 final BasePermission bp = mSettings.mPermissions.get(name); 5549 if (bp == null) { 5550 throw new IllegalArgumentException("Unknown permission: " + name); 5551 } 5552 5553 SettingBase sb = (SettingBase) pkg.mExtras; 5554 if (sb == null) { 5555 throw new IllegalArgumentException("Unknown package: " + packageName); 5556 } 5557 5558 PermissionsState permissionsState = sb.getPermissionsState(); 5559 5560 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 5561 5562 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 5563 // Install and runtime permissions are stored in different places, 5564 // so figure out what permission changed and persist the change. 5565 if (permissionsState.getInstallPermissionState(name) != null) { 5566 scheduleWriteSettingsLocked(); 5567 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 5568 || hadState) { 5569 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 5570 } 5571 } 5572 } 5573 } 5574 5575 /** 5576 * Update the permission flags for all packages and runtime permissions of a user in order 5577 * to allow device or profile owner to remove POLICY_FIXED. 5578 */ 5579 @Override 5580 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 5581 if (!sUserManager.exists(userId)) { 5582 return; 5583 } 5584 5585 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 5586 5587 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5588 true /* requireFullPermission */, true /* checkShell */, 5589 "updatePermissionFlagsForAllApps"); 5590 5591 // Only the system can change system fixed flags. 5592 if (getCallingUid() != Process.SYSTEM_UID) { 5593 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5594 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5595 } 5596 5597 synchronized (mPackages) { 5598 boolean changed = false; 5599 final int packageCount = mPackages.size(); 5600 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 5601 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 5602 SettingBase sb = (SettingBase) pkg.mExtras; 5603 if (sb == null) { 5604 continue; 5605 } 5606 PermissionsState permissionsState = sb.getPermissionsState(); 5607 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 5608 userId, flagMask, flagValues); 5609 } 5610 if (changed) { 5611 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 5612 } 5613 } 5614 } 5615 5616 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 5617 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 5618 != PackageManager.PERMISSION_GRANTED 5619 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 5620 != PackageManager.PERMISSION_GRANTED) { 5621 throw new SecurityException(message + " requires " 5622 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 5623 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 5624 } 5625 } 5626 5627 @Override 5628 public boolean shouldShowRequestPermissionRationale(String permissionName, 5629 String packageName, int userId) { 5630 if (UserHandle.getCallingUserId() != userId) { 5631 mContext.enforceCallingPermission( 5632 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5633 "canShowRequestPermissionRationale for user " + userId); 5634 } 5635 5636 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 5637 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 5638 return false; 5639 } 5640 5641 if (checkPermission(permissionName, packageName, userId) 5642 == PackageManager.PERMISSION_GRANTED) { 5643 return false; 5644 } 5645 5646 final int flags; 5647 5648 final long identity = Binder.clearCallingIdentity(); 5649 try { 5650 flags = getPermissionFlags(permissionName, 5651 packageName, userId); 5652 } finally { 5653 Binder.restoreCallingIdentity(identity); 5654 } 5655 5656 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 5657 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 5658 | PackageManager.FLAG_PERMISSION_USER_FIXED; 5659 5660 if ((flags & fixedFlags) != 0) { 5661 return false; 5662 } 5663 5664 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 5665 } 5666 5667 @Override 5668 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 5669 mContext.enforceCallingOrSelfPermission( 5670 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 5671 "addOnPermissionsChangeListener"); 5672 5673 synchronized (mPackages) { 5674 mOnPermissionChangeListeners.addListenerLocked(listener); 5675 } 5676 } 5677 5678 @Override 5679 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 5680 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5681 throw new SecurityException("Instant applications don't have access to this method"); 5682 } 5683 synchronized (mPackages) { 5684 mOnPermissionChangeListeners.removeListenerLocked(listener); 5685 } 5686 } 5687 5688 @Override 5689 public boolean isProtectedBroadcast(String actionName) { 5690 // allow instant applications 5691 synchronized (mPackages) { 5692 if (mProtectedBroadcasts.contains(actionName)) { 5693 return true; 5694 } else if (actionName != null) { 5695 // TODO: remove these terrible hacks 5696 if (actionName.startsWith("android.net.netmon.lingerExpired") 5697 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 5698 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 5699 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 5700 return true; 5701 } 5702 } 5703 } 5704 return false; 5705 } 5706 5707 @Override 5708 public int checkSignatures(String pkg1, String pkg2) { 5709 synchronized (mPackages) { 5710 final PackageParser.Package p1 = mPackages.get(pkg1); 5711 final PackageParser.Package p2 = mPackages.get(pkg2); 5712 if (p1 == null || p1.mExtras == null 5713 || p2 == null || p2.mExtras == null) { 5714 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5715 } 5716 final int callingUid = Binder.getCallingUid(); 5717 final int callingUserId = UserHandle.getUserId(callingUid); 5718 final PackageSetting ps1 = (PackageSetting) p1.mExtras; 5719 final PackageSetting ps2 = (PackageSetting) p2.mExtras; 5720 if (filterAppAccessLPr(ps1, callingUid, callingUserId) 5721 || filterAppAccessLPr(ps2, callingUid, callingUserId)) { 5722 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5723 } 5724 return compareSignatures(p1.mSignatures, p2.mSignatures); 5725 } 5726 } 5727 5728 @Override 5729 public int checkUidSignatures(int uid1, int uid2) { 5730 final int callingUid = Binder.getCallingUid(); 5731 final int callingUserId = UserHandle.getUserId(callingUid); 5732 final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null; 5733 // Map to base uids. 5734 uid1 = UserHandle.getAppId(uid1); 5735 uid2 = UserHandle.getAppId(uid2); 5736 // reader 5737 synchronized (mPackages) { 5738 Signature[] s1; 5739 Signature[] s2; 5740 Object obj = mSettings.getUserIdLPr(uid1); 5741 if (obj != null) { 5742 if (obj instanceof SharedUserSetting) { 5743 if (isCallerInstantApp) { 5744 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5745 } 5746 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 5747 } else if (obj instanceof PackageSetting) { 5748 final PackageSetting ps = (PackageSetting) obj; 5749 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 5750 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5751 } 5752 s1 = ps.signatures.mSignatures; 5753 } else { 5754 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5755 } 5756 } else { 5757 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5758 } 5759 obj = mSettings.getUserIdLPr(uid2); 5760 if (obj != null) { 5761 if (obj instanceof SharedUserSetting) { 5762 if (isCallerInstantApp) { 5763 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5764 } 5765 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 5766 } else if (obj instanceof PackageSetting) { 5767 final PackageSetting ps = (PackageSetting) obj; 5768 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 5769 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5770 } 5771 s2 = ps.signatures.mSignatures; 5772 } else { 5773 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5774 } 5775 } else { 5776 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5777 } 5778 return compareSignatures(s1, s2); 5779 } 5780 } 5781 5782 /** 5783 * This method should typically only be used when granting or revoking 5784 * permissions, since the app may immediately restart after this call. 5785 * <p> 5786 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 5787 * guard your work against the app being relaunched. 5788 */ 5789 private void killUid(int appId, int userId, String reason) { 5790 final long identity = Binder.clearCallingIdentity(); 5791 try { 5792 IActivityManager am = ActivityManager.getService(); 5793 if (am != null) { 5794 try { 5795 am.killUid(appId, userId, reason); 5796 } catch (RemoteException e) { 5797 /* ignore - same process */ 5798 } 5799 } 5800 } finally { 5801 Binder.restoreCallingIdentity(identity); 5802 } 5803 } 5804 5805 /** 5806 * Compares two sets of signatures. Returns: 5807 * <br /> 5808 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 5809 * <br /> 5810 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 5811 * <br /> 5812 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 5813 * <br /> 5814 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 5815 * <br /> 5816 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 5817 */ 5818 static int compareSignatures(Signature[] s1, Signature[] s2) { 5819 if (s1 == null) { 5820 return s2 == null 5821 ? PackageManager.SIGNATURE_NEITHER_SIGNED 5822 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 5823 } 5824 5825 if (s2 == null) { 5826 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 5827 } 5828 5829 if (s1.length != s2.length) { 5830 return PackageManager.SIGNATURE_NO_MATCH; 5831 } 5832 5833 // Since both signature sets are of size 1, we can compare without HashSets. 5834 if (s1.length == 1) { 5835 return s1[0].equals(s2[0]) ? 5836 PackageManager.SIGNATURE_MATCH : 5837 PackageManager.SIGNATURE_NO_MATCH; 5838 } 5839 5840 ArraySet<Signature> set1 = new ArraySet<Signature>(); 5841 for (Signature sig : s1) { 5842 set1.add(sig); 5843 } 5844 ArraySet<Signature> set2 = new ArraySet<Signature>(); 5845 for (Signature sig : s2) { 5846 set2.add(sig); 5847 } 5848 // Make sure s2 contains all signatures in s1. 5849 if (set1.equals(set2)) { 5850 return PackageManager.SIGNATURE_MATCH; 5851 } 5852 return PackageManager.SIGNATURE_NO_MATCH; 5853 } 5854 5855 /** 5856 * If the database version for this type of package (internal storage or 5857 * external storage) is less than the version where package signatures 5858 * were updated, return true. 5859 */ 5860 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 5861 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 5862 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 5863 } 5864 5865 /** 5866 * Used for backward compatibility to make sure any packages with 5867 * certificate chains get upgraded to the new style. {@code existingSigs} 5868 * will be in the old format (since they were stored on disk from before the 5869 * system upgrade) and {@code scannedSigs} will be in the newer format. 5870 */ 5871 private int compareSignaturesCompat(PackageSignatures existingSigs, 5872 PackageParser.Package scannedPkg) { 5873 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 5874 return PackageManager.SIGNATURE_NO_MATCH; 5875 } 5876 5877 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 5878 for (Signature sig : existingSigs.mSignatures) { 5879 existingSet.add(sig); 5880 } 5881 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 5882 for (Signature sig : scannedPkg.mSignatures) { 5883 try { 5884 Signature[] chainSignatures = sig.getChainSignatures(); 5885 for (Signature chainSig : chainSignatures) { 5886 scannedCompatSet.add(chainSig); 5887 } 5888 } catch (CertificateEncodingException e) { 5889 scannedCompatSet.add(sig); 5890 } 5891 } 5892 /* 5893 * Make sure the expanded scanned set contains all signatures in the 5894 * existing one. 5895 */ 5896 if (scannedCompatSet.equals(existingSet)) { 5897 // Migrate the old signatures to the new scheme. 5898 existingSigs.assignSignatures(scannedPkg.mSignatures); 5899 // The new KeySets will be re-added later in the scanning process. 5900 synchronized (mPackages) { 5901 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 5902 } 5903 return PackageManager.SIGNATURE_MATCH; 5904 } 5905 return PackageManager.SIGNATURE_NO_MATCH; 5906 } 5907 5908 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 5909 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 5910 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 5911 } 5912 5913 private int compareSignaturesRecover(PackageSignatures existingSigs, 5914 PackageParser.Package scannedPkg) { 5915 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 5916 return PackageManager.SIGNATURE_NO_MATCH; 5917 } 5918 5919 String msg = null; 5920 try { 5921 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 5922 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 5923 + scannedPkg.packageName); 5924 return PackageManager.SIGNATURE_MATCH; 5925 } 5926 } catch (CertificateException e) { 5927 msg = e.getMessage(); 5928 } 5929 5930 logCriticalInfo(Log.INFO, 5931 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 5932 return PackageManager.SIGNATURE_NO_MATCH; 5933 } 5934 5935 @Override 5936 public List<String> getAllPackages() { 5937 final int callingUid = Binder.getCallingUid(); 5938 final int callingUserId = UserHandle.getUserId(callingUid); 5939 synchronized (mPackages) { 5940 if (canAccessInstantApps(callingUid)) { 5941 return new ArrayList<String>(mPackages.keySet()); 5942 } 5943 final String instantAppPkgName = getInstantAppPackageName(callingUid); 5944 final List<String> result = new ArrayList<>(); 5945 if (instantAppPkgName != null) { 5946 // caller is an instant application; filter unexposed applications 5947 for (PackageParser.Package pkg : mPackages.values()) { 5948 if (!pkg.visibleToInstantApps) { 5949 continue; 5950 } 5951 result.add(pkg.packageName); 5952 } 5953 } else { 5954 // caller is a normal application; filter instant applications 5955 for (PackageParser.Package pkg : mPackages.values()) { 5956 final PackageSetting ps = 5957 pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null; 5958 if (ps != null 5959 && ps.getInstantApp(callingUserId) 5960 && !mInstantAppRegistry.isInstantAccessGranted( 5961 callingUserId, UserHandle.getAppId(callingUid), ps.appId)) { 5962 continue; 5963 } 5964 result.add(pkg.packageName); 5965 } 5966 } 5967 return result; 5968 } 5969 } 5970 5971 @Override 5972 public String[] getPackagesForUid(int uid) { 5973 final int callingUid = Binder.getCallingUid(); 5974 final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null; 5975 final int userId = UserHandle.getUserId(uid); 5976 uid = UserHandle.getAppId(uid); 5977 // reader 5978 synchronized (mPackages) { 5979 Object obj = mSettings.getUserIdLPr(uid); 5980 if (obj instanceof SharedUserSetting) { 5981 if (isCallerInstantApp) { 5982 return null; 5983 } 5984 final SharedUserSetting sus = (SharedUserSetting) obj; 5985 final int N = sus.packages.size(); 5986 String[] res = new String[N]; 5987 final Iterator<PackageSetting> it = sus.packages.iterator(); 5988 int i = 0; 5989 while (it.hasNext()) { 5990 PackageSetting ps = it.next(); 5991 if (ps.getInstalled(userId)) { 5992 res[i++] = ps.name; 5993 } else { 5994 res = ArrayUtils.removeElement(String.class, res, res[i]); 5995 } 5996 } 5997 return res; 5998 } else if (obj instanceof PackageSetting) { 5999 final PackageSetting ps = (PackageSetting) obj; 6000 if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) { 6001 return new String[]{ps.name}; 6002 } 6003 } 6004 } 6005 return null; 6006 } 6007 6008 @Override 6009 public String getNameForUid(int uid) { 6010 final int callingUid = Binder.getCallingUid(); 6011 if (getInstantAppPackageName(callingUid) != null) { 6012 return null; 6013 } 6014 synchronized (mPackages) { 6015 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 6016 if (obj instanceof SharedUserSetting) { 6017 final SharedUserSetting sus = (SharedUserSetting) obj; 6018 return sus.name + ":" + sus.userId; 6019 } else if (obj instanceof PackageSetting) { 6020 final PackageSetting ps = (PackageSetting) obj; 6021 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 6022 return null; 6023 } 6024 return ps.name; 6025 } 6026 } 6027 return null; 6028 } 6029 6030 @Override 6031 public int getUidForSharedUser(String sharedUserName) { 6032 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 6033 return -1; 6034 } 6035 if (sharedUserName == null) { 6036 return -1; 6037 } 6038 // reader 6039 synchronized (mPackages) { 6040 SharedUserSetting suid; 6041 try { 6042 suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 6043 if (suid != null) { 6044 return suid.userId; 6045 } 6046 } catch (PackageManagerException ignore) { 6047 // can't happen, but, still need to catch it 6048 } 6049 return -1; 6050 } 6051 } 6052 6053 @Override 6054 public int getFlagsForUid(int uid) { 6055 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 6056 return 0; 6057 } 6058 synchronized (mPackages) { 6059 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 6060 if (obj instanceof SharedUserSetting) { 6061 final SharedUserSetting sus = (SharedUserSetting) obj; 6062 return sus.pkgFlags; 6063 } else if (obj instanceof PackageSetting) { 6064 final PackageSetting ps = (PackageSetting) obj; 6065 return ps.pkgFlags; 6066 } 6067 } 6068 return 0; 6069 } 6070 6071 @Override 6072 public int getPrivateFlagsForUid(int uid) { 6073 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 6074 return 0; 6075 } 6076 synchronized (mPackages) { 6077 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 6078 if (obj instanceof SharedUserSetting) { 6079 final SharedUserSetting sus = (SharedUserSetting) obj; 6080 return sus.pkgPrivateFlags; 6081 } else if (obj instanceof PackageSetting) { 6082 final PackageSetting ps = (PackageSetting) obj; 6083 return ps.pkgPrivateFlags; 6084 } 6085 } 6086 return 0; 6087 } 6088 6089 @Override 6090 public boolean isUidPrivileged(int uid) { 6091 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 6092 return false; 6093 } 6094 uid = UserHandle.getAppId(uid); 6095 // reader 6096 synchronized (mPackages) { 6097 Object obj = mSettings.getUserIdLPr(uid); 6098 if (obj instanceof SharedUserSetting) { 6099 final SharedUserSetting sus = (SharedUserSetting) obj; 6100 final Iterator<PackageSetting> it = sus.packages.iterator(); 6101 while (it.hasNext()) { 6102 if (it.next().isPrivileged()) { 6103 return true; 6104 } 6105 } 6106 } else if (obj instanceof PackageSetting) { 6107 final PackageSetting ps = (PackageSetting) obj; 6108 return ps.isPrivileged(); 6109 } 6110 } 6111 return false; 6112 } 6113 6114 @Override 6115 public String[] getAppOpPermissionPackages(String permissionName) { 6116 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 6117 return null; 6118 } 6119 synchronized (mPackages) { 6120 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 6121 if (pkgs == null) { 6122 return null; 6123 } 6124 return pkgs.toArray(new String[pkgs.size()]); 6125 } 6126 } 6127 6128 @Override 6129 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 6130 int flags, int userId) { 6131 return resolveIntentInternal( 6132 intent, resolvedType, flags, userId, false /*includeInstantApps*/); 6133 } 6134 6135 private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType, 6136 int flags, int userId, boolean resolveForStart) { 6137 try { 6138 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 6139 6140 if (!sUserManager.exists(userId)) return null; 6141 final int callingUid = Binder.getCallingUid(); 6142 flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart); 6143 enforceCrossUserPermission(callingUid, userId, 6144 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 6145 6146 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 6147 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 6148 flags, userId, resolveForStart); 6149 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6150 6151 final ResolveInfo bestChoice = 6152 chooseBestActivity(intent, resolvedType, flags, query, userId); 6153 return bestChoice; 6154 } finally { 6155 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6156 } 6157 } 6158 6159 @Override 6160 public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) { 6161 if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) { 6162 throw new SecurityException( 6163 "findPersistentPreferredActivity can only be run by the system"); 6164 } 6165 if (!sUserManager.exists(userId)) { 6166 return null; 6167 } 6168 final int callingUid = Binder.getCallingUid(); 6169 intent = updateIntentForResolve(intent); 6170 final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver()); 6171 final int flags = updateFlagsForResolve( 6172 0, userId, intent, callingUid, false /*includeInstantApps*/); 6173 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 6174 userId); 6175 synchronized (mPackages) { 6176 return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false, 6177 userId); 6178 } 6179 } 6180 6181 @Override 6182 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 6183 IntentFilter filter, int match, ComponentName activity) { 6184 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 6185 return; 6186 } 6187 final int userId = UserHandle.getCallingUserId(); 6188 if (DEBUG_PREFERRED) { 6189 Log.v(TAG, "setLastChosenActivity intent=" + intent 6190 + " resolvedType=" + resolvedType 6191 + " flags=" + flags 6192 + " filter=" + filter 6193 + " match=" + match 6194 + " activity=" + activity); 6195 filter.dump(new PrintStreamPrinter(System.out), " "); 6196 } 6197 intent.setComponent(null); 6198 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 6199 userId); 6200 // Find any earlier preferred or last chosen entries and nuke them 6201 findPreferredActivity(intent, resolvedType, 6202 flags, query, 0, false, true, false, userId); 6203 // Add the new activity as the last chosen for this filter 6204 addPreferredActivityInternal(filter, match, null, activity, false, userId, 6205 "Setting last chosen"); 6206 } 6207 6208 @Override 6209 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 6210 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 6211 return null; 6212 } 6213 final int userId = UserHandle.getCallingUserId(); 6214 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 6215 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 6216 userId); 6217 return findPreferredActivity(intent, resolvedType, flags, query, 0, 6218 false, false, false, userId); 6219 } 6220 6221 /** 6222 * Returns whether or not instant apps have been disabled remotely. 6223 */ 6224 private boolean isEphemeralDisabled() { 6225 return mEphemeralAppsDisabled; 6226 } 6227 6228 private boolean isInstantAppAllowed( 6229 Intent intent, List<ResolveInfo> resolvedActivities, int userId, 6230 boolean skipPackageCheck) { 6231 if (mInstantAppResolverConnection == null) { 6232 return false; 6233 } 6234 if (mInstantAppInstallerActivity == null) { 6235 return false; 6236 } 6237 if (intent.getComponent() != null) { 6238 return false; 6239 } 6240 if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) { 6241 return false; 6242 } 6243 if (!skipPackageCheck && intent.getPackage() != null) { 6244 return false; 6245 } 6246 final boolean isWebUri = hasWebURI(intent); 6247 if (!isWebUri || intent.getData().getHost() == null) { 6248 return false; 6249 } 6250 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 6251 // Or if there's already an ephemeral app installed that handles the action 6252 synchronized (mPackages) { 6253 final int count = (resolvedActivities == null ? 0 : resolvedActivities.size()); 6254 for (int n = 0; n < count; n++) { 6255 final ResolveInfo info = resolvedActivities.get(n); 6256 final String packageName = info.activityInfo.packageName; 6257 final PackageSetting ps = mSettings.mPackages.get(packageName); 6258 if (ps != null) { 6259 // only check domain verification status if the app is not a browser 6260 if (!info.handleAllWebDataURI) { 6261 // Try to get the status from User settings first 6262 final long packedStatus = getDomainVerificationStatusLPr(ps, userId); 6263 final int status = (int) (packedStatus >> 32); 6264 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 6265 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 6266 if (DEBUG_EPHEMERAL) { 6267 Slog.v(TAG, "DENY instant app;" 6268 + " pkg: " + packageName + ", status: " + status); 6269 } 6270 return false; 6271 } 6272 } 6273 if (ps.getInstantApp(userId)) { 6274 if (DEBUG_EPHEMERAL) { 6275 Slog.v(TAG, "DENY instant app installed;" 6276 + " pkg: " + packageName); 6277 } 6278 return false; 6279 } 6280 } 6281 } 6282 } 6283 // We've exhausted all ways to deny ephemeral application; let the system look for them. 6284 return true; 6285 } 6286 6287 private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj, 6288 Intent origIntent, String resolvedType, String callingPackage, 6289 Bundle verificationBundle, int userId) { 6290 final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO, 6291 new InstantAppRequest(responseObj, origIntent, resolvedType, 6292 callingPackage, userId, verificationBundle)); 6293 mHandler.sendMessage(msg); 6294 } 6295 6296 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 6297 int flags, List<ResolveInfo> query, int userId) { 6298 if (query != null) { 6299 final int N = query.size(); 6300 if (N == 1) { 6301 return query.get(0); 6302 } else if (N > 1) { 6303 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 6304 // If there is more than one activity with the same priority, 6305 // then let the user decide between them. 6306 ResolveInfo r0 = query.get(0); 6307 ResolveInfo r1 = query.get(1); 6308 if (DEBUG_INTENT_MATCHING || debug) { 6309 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 6310 + r1.activityInfo.name + "=" + r1.priority); 6311 } 6312 // If the first activity has a higher priority, or a different 6313 // default, then it is always desirable to pick it. 6314 if (r0.priority != r1.priority 6315 || r0.preferredOrder != r1.preferredOrder 6316 || r0.isDefault != r1.isDefault) { 6317 return query.get(0); 6318 } 6319 // If we have saved a preference for a preferred activity for 6320 // this Intent, use that. 6321 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 6322 flags, query, r0.priority, true, false, debug, userId); 6323 if (ri != null) { 6324 return ri; 6325 } 6326 // If we have an ephemeral app, use it 6327 for (int i = 0; i < N; i++) { 6328 ri = query.get(i); 6329 if (ri.activityInfo.applicationInfo.isInstantApp()) { 6330 final String packageName = ri.activityInfo.packageName; 6331 final PackageSetting ps = mSettings.mPackages.get(packageName); 6332 final long packedStatus = getDomainVerificationStatusLPr(ps, userId); 6333 final int status = (int)(packedStatus >> 32); 6334 if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 6335 return ri; 6336 } 6337 } 6338 } 6339 ri = new ResolveInfo(mResolveInfo); 6340 ri.activityInfo = new ActivityInfo(ri.activityInfo); 6341 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 6342 // If all of the options come from the same package, show the application's 6343 // label and icon instead of the generic resolver's. 6344 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 6345 // and then throw away the ResolveInfo itself, meaning that the caller loses 6346 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 6347 // a fallback for this case; we only set the target package's resources on 6348 // the ResolveInfo, not the ActivityInfo. 6349 final String intentPackage = intent.getPackage(); 6350 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 6351 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 6352 ri.resolvePackageName = intentPackage; 6353 if (userNeedsBadging(userId)) { 6354 ri.noResourceId = true; 6355 } else { 6356 ri.icon = appi.icon; 6357 } 6358 ri.iconResourceId = appi.icon; 6359 ri.labelRes = appi.labelRes; 6360 } 6361 ri.activityInfo.applicationInfo = new ApplicationInfo( 6362 ri.activityInfo.applicationInfo); 6363 if (userId != 0) { 6364 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 6365 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 6366 } 6367 // Make sure that the resolver is displayable in car mode 6368 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 6369 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 6370 return ri; 6371 } 6372 } 6373 return null; 6374 } 6375 6376 /** 6377 * Return true if the given list is not empty and all of its contents have 6378 * an activityInfo with the given package name. 6379 */ 6380 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 6381 if (ArrayUtils.isEmpty(list)) { 6382 return false; 6383 } 6384 for (int i = 0, N = list.size(); i < N; i++) { 6385 final ResolveInfo ri = list.get(i); 6386 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 6387 if (ai == null || !packageName.equals(ai.packageName)) { 6388 return false; 6389 } 6390 } 6391 return true; 6392 } 6393 6394 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 6395 int flags, List<ResolveInfo> query, boolean debug, int userId) { 6396 final int N = query.size(); 6397 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 6398 .get(userId); 6399 // Get the list of persistent preferred activities that handle the intent 6400 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 6401 List<PersistentPreferredActivity> pprefs = ppir != null 6402 ? ppir.queryIntent(intent, resolvedType, 6403 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 6404 userId) 6405 : null; 6406 if (pprefs != null && pprefs.size() > 0) { 6407 final int M = pprefs.size(); 6408 for (int i=0; i<M; i++) { 6409 final PersistentPreferredActivity ppa = pprefs.get(i); 6410 if (DEBUG_PREFERRED || debug) { 6411 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 6412 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 6413 + "\n component=" + ppa.mComponent); 6414 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6415 } 6416 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 6417 flags | MATCH_DISABLED_COMPONENTS, userId); 6418 if (DEBUG_PREFERRED || debug) { 6419 Slog.v(TAG, "Found persistent preferred activity:"); 6420 if (ai != null) { 6421 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6422 } else { 6423 Slog.v(TAG, " null"); 6424 } 6425 } 6426 if (ai == null) { 6427 // This previously registered persistent preferred activity 6428 // component is no longer known. Ignore it and do NOT remove it. 6429 continue; 6430 } 6431 for (int j=0; j<N; j++) { 6432 final ResolveInfo ri = query.get(j); 6433 if (!ri.activityInfo.applicationInfo.packageName 6434 .equals(ai.applicationInfo.packageName)) { 6435 continue; 6436 } 6437 if (!ri.activityInfo.name.equals(ai.name)) { 6438 continue; 6439 } 6440 // Found a persistent preference that can handle the intent. 6441 if (DEBUG_PREFERRED || debug) { 6442 Slog.v(TAG, "Returning persistent preferred activity: " + 6443 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 6444 } 6445 return ri; 6446 } 6447 } 6448 } 6449 return null; 6450 } 6451 6452 // TODO: handle preferred activities missing while user has amnesia 6453 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 6454 List<ResolveInfo> query, int priority, boolean always, 6455 boolean removeMatches, boolean debug, int userId) { 6456 if (!sUserManager.exists(userId)) return null; 6457 final int callingUid = Binder.getCallingUid(); 6458 flags = updateFlagsForResolve( 6459 flags, userId, intent, callingUid, false /*includeInstantApps*/); 6460 intent = updateIntentForResolve(intent); 6461 // writer 6462 synchronized (mPackages) { 6463 // Try to find a matching persistent preferred activity. 6464 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 6465 debug, userId); 6466 6467 // If a persistent preferred activity matched, use it. 6468 if (pri != null) { 6469 return pri; 6470 } 6471 6472 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 6473 // Get the list of preferred activities that handle the intent 6474 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 6475 List<PreferredActivity> prefs = pir != null 6476 ? pir.queryIntent(intent, resolvedType, 6477 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 6478 userId) 6479 : null; 6480 if (prefs != null && prefs.size() > 0) { 6481 boolean changed = false; 6482 try { 6483 // First figure out how good the original match set is. 6484 // We will only allow preferred activities that came 6485 // from the same match quality. 6486 int match = 0; 6487 6488 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 6489 6490 final int N = query.size(); 6491 for (int j=0; j<N; j++) { 6492 final ResolveInfo ri = query.get(j); 6493 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 6494 + ": 0x" + Integer.toHexString(match)); 6495 if (ri.match > match) { 6496 match = ri.match; 6497 } 6498 } 6499 6500 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 6501 + Integer.toHexString(match)); 6502 6503 match &= IntentFilter.MATCH_CATEGORY_MASK; 6504 final int M = prefs.size(); 6505 for (int i=0; i<M; i++) { 6506 final PreferredActivity pa = prefs.get(i); 6507 if (DEBUG_PREFERRED || debug) { 6508 Slog.v(TAG, "Checking PreferredActivity ds=" 6509 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 6510 + "\n component=" + pa.mPref.mComponent); 6511 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6512 } 6513 if (pa.mPref.mMatch != match) { 6514 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 6515 + Integer.toHexString(pa.mPref.mMatch)); 6516 continue; 6517 } 6518 // If it's not an "always" type preferred activity and that's what we're 6519 // looking for, skip it. 6520 if (always && !pa.mPref.mAlways) { 6521 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 6522 continue; 6523 } 6524 final ActivityInfo ai = getActivityInfo( 6525 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 6526 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 6527 userId); 6528 if (DEBUG_PREFERRED || debug) { 6529 Slog.v(TAG, "Found preferred activity:"); 6530 if (ai != null) { 6531 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6532 } else { 6533 Slog.v(TAG, " null"); 6534 } 6535 } 6536 if (ai == null) { 6537 // This previously registered preferred activity 6538 // component is no longer known. Most likely an update 6539 // to the app was installed and in the new version this 6540 // component no longer exists. Clean it up by removing 6541 // it from the preferred activities list, and skip it. 6542 Slog.w(TAG, "Removing dangling preferred activity: " 6543 + pa.mPref.mComponent); 6544 pir.removeFilter(pa); 6545 changed = true; 6546 continue; 6547 } 6548 for (int j=0; j<N; j++) { 6549 final ResolveInfo ri = query.get(j); 6550 if (!ri.activityInfo.applicationInfo.packageName 6551 .equals(ai.applicationInfo.packageName)) { 6552 continue; 6553 } 6554 if (!ri.activityInfo.name.equals(ai.name)) { 6555 continue; 6556 } 6557 6558 if (removeMatches) { 6559 pir.removeFilter(pa); 6560 changed = true; 6561 if (DEBUG_PREFERRED) { 6562 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 6563 } 6564 break; 6565 } 6566 6567 // Okay we found a previously set preferred or last chosen app. 6568 // If the result set is different from when this 6569 // was created, we need to clear it and re-ask the 6570 // user their preference, if we're looking for an "always" type entry. 6571 if (always && !pa.mPref.sameSet(query)) { 6572 Slog.i(TAG, "Result set changed, dropping preferred activity for " 6573 + intent + " type " + resolvedType); 6574 if (DEBUG_PREFERRED) { 6575 Slog.v(TAG, "Removing preferred activity since set changed " 6576 + pa.mPref.mComponent); 6577 } 6578 pir.removeFilter(pa); 6579 // Re-add the filter as a "last chosen" entry (!always) 6580 PreferredActivity lastChosen = new PreferredActivity( 6581 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 6582 pir.addFilter(lastChosen); 6583 changed = true; 6584 return null; 6585 } 6586 6587 // Yay! Either the set matched or we're looking for the last chosen 6588 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 6589 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 6590 return ri; 6591 } 6592 } 6593 } finally { 6594 if (changed) { 6595 if (DEBUG_PREFERRED) { 6596 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 6597 } 6598 scheduleWritePackageRestrictionsLocked(userId); 6599 } 6600 } 6601 } 6602 } 6603 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 6604 return null; 6605 } 6606 6607 /* 6608 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 6609 */ 6610 @Override 6611 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 6612 int targetUserId) { 6613 mContext.enforceCallingOrSelfPermission( 6614 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 6615 List<CrossProfileIntentFilter> matches = 6616 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 6617 if (matches != null) { 6618 int size = matches.size(); 6619 for (int i = 0; i < size; i++) { 6620 if (matches.get(i).getTargetUserId() == targetUserId) return true; 6621 } 6622 } 6623 if (hasWebURI(intent)) { 6624 // cross-profile app linking works only towards the parent. 6625 final int callingUid = Binder.getCallingUid(); 6626 final UserInfo parent = getProfileParent(sourceUserId); 6627 synchronized(mPackages) { 6628 int flags = updateFlagsForResolve(0, parent.id, intent, callingUid, 6629 false /*includeInstantApps*/); 6630 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 6631 intent, resolvedType, flags, sourceUserId, parent.id); 6632 return xpDomainInfo != null; 6633 } 6634 } 6635 return false; 6636 } 6637 6638 private UserInfo getProfileParent(int userId) { 6639 final long identity = Binder.clearCallingIdentity(); 6640 try { 6641 return sUserManager.getProfileParent(userId); 6642 } finally { 6643 Binder.restoreCallingIdentity(identity); 6644 } 6645 } 6646 6647 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 6648 String resolvedType, int userId) { 6649 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 6650 if (resolver != null) { 6651 return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId); 6652 } 6653 return null; 6654 } 6655 6656 @Override 6657 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 6658 String resolvedType, int flags, int userId) { 6659 try { 6660 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 6661 6662 return new ParceledListSlice<>( 6663 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 6664 } finally { 6665 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6666 } 6667 } 6668 6669 /** 6670 * Returns the package name of the calling Uid if it's an instant app. If it isn't 6671 * instant, returns {@code null}. 6672 */ 6673 private String getInstantAppPackageName(int callingUid) { 6674 synchronized (mPackages) { 6675 // If the caller is an isolated app use the owner's uid for the lookup. 6676 if (Process.isIsolated(callingUid)) { 6677 callingUid = mIsolatedOwners.get(callingUid); 6678 } 6679 final int appId = UserHandle.getAppId(callingUid); 6680 final Object obj = mSettings.getUserIdLPr(appId); 6681 if (obj instanceof PackageSetting) { 6682 final PackageSetting ps = (PackageSetting) obj; 6683 final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid)); 6684 return isInstantApp ? ps.pkg.packageName : null; 6685 } 6686 } 6687 return null; 6688 } 6689 6690 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 6691 String resolvedType, int flags, int userId) { 6692 return queryIntentActivitiesInternal(intent, resolvedType, flags, userId, false); 6693 } 6694 6695 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 6696 String resolvedType, int flags, int userId, boolean resolveForStart) { 6697 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6698 final int callingUid = Binder.getCallingUid(); 6699 final String instantAppPkgName = getInstantAppPackageName(callingUid); 6700 enforceCrossUserPermission(callingUid, userId, 6701 false /* requireFullPermission */, false /* checkShell */, 6702 "query intent activities"); 6703 final String pkgName = intent.getPackage(); 6704 ComponentName comp = intent.getComponent(); 6705 if (comp == null) { 6706 if (intent.getSelector() != null) { 6707 intent = intent.getSelector(); 6708 comp = intent.getComponent(); 6709 } 6710 } 6711 6712 flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart, 6713 comp != null || pkgName != null /*onlyExposedExplicitly*/); 6714 if (comp != null) { 6715 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6716 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 6717 if (ai != null) { 6718 // When specifying an explicit component, we prevent the activity from being 6719 // used when either 1) the calling package is normal and the activity is within 6720 // an ephemeral application or 2) the calling package is ephemeral and the 6721 // activity is not visible to ephemeral applications. 6722 final boolean matchInstantApp = 6723 (flags & PackageManager.MATCH_INSTANT) != 0; 6724 final boolean matchVisibleToInstantAppOnly = 6725 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 6726 final boolean matchExplicitlyVisibleOnly = 6727 (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0; 6728 final boolean isCallerInstantApp = 6729 instantAppPkgName != null; 6730 final boolean isTargetSameInstantApp = 6731 comp.getPackageName().equals(instantAppPkgName); 6732 final boolean isTargetInstantApp = 6733 (ai.applicationInfo.privateFlags 6734 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 6735 final boolean isTargetVisibleToInstantApp = 6736 (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0; 6737 final boolean isTargetExplicitlyVisibleToInstantApp = 6738 isTargetVisibleToInstantApp 6739 && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0; 6740 final boolean isTargetHiddenFromInstantApp = 6741 !isTargetVisibleToInstantApp 6742 || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp); 6743 final boolean blockResolution = 6744 !isTargetSameInstantApp 6745 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 6746 || (matchVisibleToInstantAppOnly && isCallerInstantApp 6747 && isTargetHiddenFromInstantApp)); 6748 if (!blockResolution) { 6749 final ResolveInfo ri = new ResolveInfo(); 6750 ri.activityInfo = ai; 6751 list.add(ri); 6752 } 6753 } 6754 return applyPostResolutionFilter(list, instantAppPkgName); 6755 } 6756 6757 // reader 6758 boolean sortResult = false; 6759 boolean addEphemeral = false; 6760 List<ResolveInfo> result; 6761 final boolean ephemeralDisabled = isEphemeralDisabled(); 6762 synchronized (mPackages) { 6763 if (pkgName == null) { 6764 List<CrossProfileIntentFilter> matchingFilters = 6765 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 6766 // Check for results that need to skip the current profile. 6767 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 6768 resolvedType, flags, userId); 6769 if (xpResolveInfo != null) { 6770 List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1); 6771 xpResult.add(xpResolveInfo); 6772 return applyPostResolutionFilter( 6773 filterIfNotSystemUser(xpResult, userId), instantAppPkgName); 6774 } 6775 6776 // Check for results in the current profile. 6777 result = filterIfNotSystemUser(mActivities.queryIntent( 6778 intent, resolvedType, flags, userId), userId); 6779 addEphemeral = !ephemeralDisabled 6780 && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/); 6781 // Check for cross profile results. 6782 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 6783 xpResolveInfo = queryCrossProfileIntents( 6784 matchingFilters, intent, resolvedType, flags, userId, 6785 hasNonNegativePriorityResult); 6786 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 6787 boolean isVisibleToUser = filterIfNotSystemUser( 6788 Collections.singletonList(xpResolveInfo), userId).size() > 0; 6789 if (isVisibleToUser) { 6790 result.add(xpResolveInfo); 6791 sortResult = true; 6792 } 6793 } 6794 if (hasWebURI(intent)) { 6795 CrossProfileDomainInfo xpDomainInfo = null; 6796 final UserInfo parent = getProfileParent(userId); 6797 if (parent != null) { 6798 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 6799 flags, userId, parent.id); 6800 } 6801 if (xpDomainInfo != null) { 6802 if (xpResolveInfo != null) { 6803 // If we didn't remove it, the cross-profile ResolveInfo would be twice 6804 // in the result. 6805 result.remove(xpResolveInfo); 6806 } 6807 if (result.size() == 0 && !addEphemeral) { 6808 // No result in current profile, but found candidate in parent user. 6809 // And we are not going to add emphemeral app, so we can return the 6810 // result straight away. 6811 result.add(xpDomainInfo.resolveInfo); 6812 return applyPostResolutionFilter(result, instantAppPkgName); 6813 } 6814 } else if (result.size() <= 1 && !addEphemeral) { 6815 // No result in parent user and <= 1 result in current profile, and we 6816 // are not going to add emphemeral app, so we can return the result without 6817 // further processing. 6818 return applyPostResolutionFilter(result, instantAppPkgName); 6819 } 6820 // We have more than one candidate (combining results from current and parent 6821 // profile), so we need filtering and sorting. 6822 result = filterCandidatesWithDomainPreferredActivitiesLPr( 6823 intent, flags, result, xpDomainInfo, userId); 6824 sortResult = true; 6825 } 6826 } else { 6827 final PackageParser.Package pkg = mPackages.get(pkgName); 6828 result = null; 6829 if (pkg != null) { 6830 result = filterIfNotSystemUser( 6831 mActivities.queryIntentForPackage( 6832 intent, resolvedType, flags, pkg.activities, userId), 6833 userId); 6834 } 6835 if (result == null || result.size() == 0) { 6836 // the caller wants to resolve for a particular package; however, there 6837 // were no installed results, so, try to find an ephemeral result 6838 addEphemeral = !ephemeralDisabled 6839 && isInstantAppAllowed( 6840 intent, null /*result*/, userId, true /*skipPackageCheck*/); 6841 if (result == null) { 6842 result = new ArrayList<>(); 6843 } 6844 } 6845 } 6846 } 6847 if (addEphemeral) { 6848 result = maybeAddInstantAppInstaller(result, intent, resolvedType, flags, userId); 6849 } 6850 if (sortResult) { 6851 Collections.sort(result, mResolvePrioritySorter); 6852 } 6853 return applyPostResolutionFilter(result, instantAppPkgName); 6854 } 6855 6856 private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent, 6857 String resolvedType, int flags, int userId) { 6858 // first, check to see if we've got an instant app already installed 6859 final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0; 6860 ResolveInfo localInstantApp = null; 6861 boolean blockResolution = false; 6862 if (!alreadyResolvedLocally) { 6863 final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType, 6864 flags 6865 | PackageManager.GET_RESOLVED_FILTER 6866 | PackageManager.MATCH_INSTANT 6867 | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY, 6868 userId); 6869 for (int i = instantApps.size() - 1; i >= 0; --i) { 6870 final ResolveInfo info = instantApps.get(i); 6871 final String packageName = info.activityInfo.packageName; 6872 final PackageSetting ps = mSettings.mPackages.get(packageName); 6873 if (ps.getInstantApp(userId)) { 6874 final long packedStatus = getDomainVerificationStatusLPr(ps, userId); 6875 final int status = (int)(packedStatus >> 32); 6876 final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 6877 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6878 // there's a local instant application installed, but, the user has 6879 // chosen to never use it; skip resolution and don't acknowledge 6880 // an instant application is even available 6881 if (DEBUG_EPHEMERAL) { 6882 Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName); 6883 } 6884 blockResolution = true; 6885 break; 6886 } else { 6887 // we have a locally installed instant application; skip resolution 6888 // but acknowledge there's an instant application available 6889 if (DEBUG_EPHEMERAL) { 6890 Slog.v(TAG, "Found installed instant app; pkg: " + packageName); 6891 } 6892 localInstantApp = info; 6893 break; 6894 } 6895 } 6896 } 6897 } 6898 // no app installed, let's see if one's available 6899 AuxiliaryResolveInfo auxiliaryResponse = null; 6900 if (!blockResolution) { 6901 if (localInstantApp == null) { 6902 // we don't have an instant app locally, resolve externally 6903 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 6904 final InstantAppRequest requestObject = new InstantAppRequest( 6905 null /*responseObj*/, intent /*origIntent*/, resolvedType, 6906 null /*callingPackage*/, userId, null /*verificationBundle*/); 6907 auxiliaryResponse = 6908 InstantAppResolver.doInstantAppResolutionPhaseOne( 6909 mContext, mInstantAppResolverConnection, requestObject); 6910 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6911 } else { 6912 // we have an instant application locally, but, we can't admit that since 6913 // callers shouldn't be able to determine prior browsing. create a dummy 6914 // auxiliary response so the downstream code behaves as if there's an 6915 // instant application available externally. when it comes time to start 6916 // the instant application, we'll do the right thing. 6917 final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo; 6918 auxiliaryResponse = new AuxiliaryResolveInfo( 6919 ai.packageName, null /*splitName*/, ai.versionCode, null /*failureIntent*/); 6920 } 6921 } 6922 if (auxiliaryResponse != null) { 6923 if (DEBUG_EPHEMERAL) { 6924 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 6925 } 6926 final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo); 6927 final PackageSetting ps = 6928 mSettings.mPackages.get(mInstantAppInstallerActivity.packageName); 6929 if (ps != null) { 6930 ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo( 6931 mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId); 6932 ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token; 6933 ephemeralInstaller.auxiliaryInfo = auxiliaryResponse; 6934 // make sure this resolver is the default 6935 ephemeralInstaller.isDefault = true; 6936 ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 6937 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 6938 // add a non-generic filter 6939 ephemeralInstaller.filter = new IntentFilter(intent.getAction()); 6940 ephemeralInstaller.filter.addDataPath( 6941 intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL); 6942 ephemeralInstaller.isInstantAppAvailable = true; 6943 result.add(ephemeralInstaller); 6944 } 6945 } 6946 return result; 6947 } 6948 6949 private static class CrossProfileDomainInfo { 6950 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 6951 ResolveInfo resolveInfo; 6952 /* Best domain verification status of the activities found in the other profile */ 6953 int bestDomainVerificationStatus; 6954 } 6955 6956 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 6957 String resolvedType, int flags, int sourceUserId, int parentUserId) { 6958 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 6959 sourceUserId)) { 6960 return null; 6961 } 6962 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 6963 resolvedType, flags, parentUserId); 6964 6965 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 6966 return null; 6967 } 6968 CrossProfileDomainInfo result = null; 6969 int size = resultTargetUser.size(); 6970 for (int i = 0; i < size; i++) { 6971 ResolveInfo riTargetUser = resultTargetUser.get(i); 6972 // Intent filter verification is only for filters that specify a host. So don't return 6973 // those that handle all web uris. 6974 if (riTargetUser.handleAllWebDataURI) { 6975 continue; 6976 } 6977 String packageName = riTargetUser.activityInfo.packageName; 6978 PackageSetting ps = mSettings.mPackages.get(packageName); 6979 if (ps == null) { 6980 continue; 6981 } 6982 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 6983 int status = (int)(verificationState >> 32); 6984 if (result == null) { 6985 result = new CrossProfileDomainInfo(); 6986 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 6987 sourceUserId, parentUserId); 6988 result.bestDomainVerificationStatus = status; 6989 } else { 6990 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 6991 result.bestDomainVerificationStatus); 6992 } 6993 } 6994 // Don't consider matches with status NEVER across profiles. 6995 if (result != null && result.bestDomainVerificationStatus 6996 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6997 return null; 6998 } 6999 return result; 7000 } 7001 7002 /** 7003 * Verification statuses are ordered from the worse to the best, except for 7004 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 7005 */ 7006 private int bestDomainVerificationStatus(int status1, int status2) { 7007 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 7008 return status2; 7009 } 7010 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 7011 return status1; 7012 } 7013 return (int) MathUtils.max(status1, status2); 7014 } 7015 7016 private boolean isUserEnabled(int userId) { 7017 long callingId = Binder.clearCallingIdentity(); 7018 try { 7019 UserInfo userInfo = sUserManager.getUserInfo(userId); 7020 return userInfo != null && userInfo.isEnabled(); 7021 } finally { 7022 Binder.restoreCallingIdentity(callingId); 7023 } 7024 } 7025 7026 /** 7027 * Filter out activities with systemUserOnly flag set, when current user is not System. 7028 * 7029 * @return filtered list 7030 */ 7031 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 7032 if (userId == UserHandle.USER_SYSTEM) { 7033 return resolveInfos; 7034 } 7035 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 7036 ResolveInfo info = resolveInfos.get(i); 7037 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 7038 resolveInfos.remove(i); 7039 } 7040 } 7041 return resolveInfos; 7042 } 7043 7044 /** 7045 * Filters out ephemeral activities. 7046 * <p>When resolving for an ephemeral app, only activities that 1) are defined in the 7047 * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned. 7048 * 7049 * @param resolveInfos The pre-filtered list of resolved activities 7050 * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering 7051 * is performed. 7052 * @return A filtered list of resolved activities. 7053 */ 7054 private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos, 7055 String ephemeralPkgName) { 7056 // TODO: When adding on-demand split support for non-instant apps, remove this check 7057 // and always apply post filtering 7058 if (ephemeralPkgName == null) { 7059 return resolveInfos; 7060 } 7061 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 7062 final ResolveInfo info = resolveInfos.get(i); 7063 final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp(); 7064 // allow activities that are defined in the provided package 7065 if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) { 7066 if (info.activityInfo.splitName != null 7067 && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames, 7068 info.activityInfo.splitName)) { 7069 // requested activity is defined in a split that hasn't been installed yet. 7070 // add the installer to the resolve list 7071 if (DEBUG_EPHEMERAL) { 7072 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 7073 } 7074 final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo); 7075 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 7076 info.activityInfo.packageName, info.activityInfo.splitName, 7077 info.activityInfo.applicationInfo.versionCode, null /*failureIntent*/); 7078 // make sure this resolver is the default 7079 installerInfo.isDefault = true; 7080 installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 7081 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 7082 // add a non-generic filter 7083 installerInfo.filter = new IntentFilter(); 7084 // load resources from the correct package 7085 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 7086 resolveInfos.set(i, installerInfo); 7087 } 7088 continue; 7089 } 7090 // allow activities that have been explicitly exposed to ephemeral apps 7091 if (!isEphemeralApp 7092 && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) { 7093 continue; 7094 } 7095 resolveInfos.remove(i); 7096 } 7097 return resolveInfos; 7098 } 7099 7100 /** 7101 * @param resolveInfos list of resolve infos in descending priority order 7102 * @return if the list contains a resolve info with non-negative priority 7103 */ 7104 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 7105 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 7106 } 7107 7108 private static boolean hasWebURI(Intent intent) { 7109 if (intent.getData() == null) { 7110 return false; 7111 } 7112 final String scheme = intent.getScheme(); 7113 if (TextUtils.isEmpty(scheme)) { 7114 return false; 7115 } 7116 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 7117 } 7118 7119 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 7120 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 7121 int userId) { 7122 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 7123 7124 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 7125 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 7126 candidates.size()); 7127 } 7128 7129 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 7130 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 7131 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 7132 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 7133 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 7134 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 7135 7136 synchronized (mPackages) { 7137 final int count = candidates.size(); 7138 // First, try to use linked apps. Partition the candidates into four lists: 7139 // one for the final results, one for the "do not use ever", one for "undefined status" 7140 // and finally one for "browser app type". 7141 for (int n=0; n<count; n++) { 7142 ResolveInfo info = candidates.get(n); 7143 String packageName = info.activityInfo.packageName; 7144 PackageSetting ps = mSettings.mPackages.get(packageName); 7145 if (ps != null) { 7146 // Add to the special match all list (Browser use case) 7147 if (info.handleAllWebDataURI) { 7148 matchAllList.add(info); 7149 continue; 7150 } 7151 // Try to get the status from User settings first 7152 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 7153 int status = (int)(packedStatus >> 32); 7154 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 7155 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 7156 if (DEBUG_DOMAIN_VERIFICATION || debug) { 7157 Slog.i(TAG, " + always: " + info.activityInfo.packageName 7158 + " : linkgen=" + linkGeneration); 7159 } 7160 // Use link-enabled generation as preferredOrder, i.e. 7161 // prefer newly-enabled over earlier-enabled. 7162 info.preferredOrder = linkGeneration; 7163 alwaysList.add(info); 7164 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 7165 if (DEBUG_DOMAIN_VERIFICATION || debug) { 7166 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 7167 } 7168 neverList.add(info); 7169 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 7170 if (DEBUG_DOMAIN_VERIFICATION || debug) { 7171 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 7172 } 7173 alwaysAskList.add(info); 7174 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 7175 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 7176 if (DEBUG_DOMAIN_VERIFICATION || debug) { 7177 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 7178 } 7179 undefinedList.add(info); 7180 } 7181 } 7182 } 7183 7184 // We'll want to include browser possibilities in a few cases 7185 boolean includeBrowser = false; 7186 7187 // First try to add the "always" resolution(s) for the current user, if any 7188 if (alwaysList.size() > 0) { 7189 result.addAll(alwaysList); 7190 } else { 7191 // Add all undefined apps as we want them to appear in the disambiguation dialog. 7192 result.addAll(undefinedList); 7193 // Maybe add one for the other profile. 7194 if (xpDomainInfo != null && ( 7195 xpDomainInfo.bestDomainVerificationStatus 7196 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 7197 result.add(xpDomainInfo.resolveInfo); 7198 } 7199 includeBrowser = true; 7200 } 7201 7202 // The presence of any 'always ask' alternatives means we'll also offer browsers. 7203 // If there were 'always' entries their preferred order has been set, so we also 7204 // back that off to make the alternatives equivalent 7205 if (alwaysAskList.size() > 0) { 7206 for (ResolveInfo i : result) { 7207 i.preferredOrder = 0; 7208 } 7209 result.addAll(alwaysAskList); 7210 includeBrowser = true; 7211 } 7212 7213 if (includeBrowser) { 7214 // Also add browsers (all of them or only the default one) 7215 if (DEBUG_DOMAIN_VERIFICATION) { 7216 Slog.v(TAG, " ...including browsers in candidate set"); 7217 } 7218 if ((matchFlags & MATCH_ALL) != 0) { 7219 result.addAll(matchAllList); 7220 } else { 7221 // Browser/generic handling case. If there's a default browser, go straight 7222 // to that (but only if there is no other higher-priority match). 7223 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 7224 int maxMatchPrio = 0; 7225 ResolveInfo defaultBrowserMatch = null; 7226 final int numCandidates = matchAllList.size(); 7227 for (int n = 0; n < numCandidates; n++) { 7228 ResolveInfo info = matchAllList.get(n); 7229 // track the highest overall match priority... 7230 if (info.priority > maxMatchPrio) { 7231 maxMatchPrio = info.priority; 7232 } 7233 // ...and the highest-priority default browser match 7234 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 7235 if (defaultBrowserMatch == null 7236 || (defaultBrowserMatch.priority < info.priority)) { 7237 if (debug) { 7238 Slog.v(TAG, "Considering default browser match " + info); 7239 } 7240 defaultBrowserMatch = info; 7241 } 7242 } 7243 } 7244 if (defaultBrowserMatch != null 7245 && defaultBrowserMatch.priority >= maxMatchPrio 7246 && !TextUtils.isEmpty(defaultBrowserPackageName)) 7247 { 7248 if (debug) { 7249 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 7250 } 7251 result.add(defaultBrowserMatch); 7252 } else { 7253 result.addAll(matchAllList); 7254 } 7255 } 7256 7257 // If there is nothing selected, add all candidates and remove the ones that the user 7258 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 7259 if (result.size() == 0) { 7260 result.addAll(candidates); 7261 result.removeAll(neverList); 7262 } 7263 } 7264 } 7265 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 7266 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 7267 result.size()); 7268 for (ResolveInfo info : result) { 7269 Slog.v(TAG, " + " + info.activityInfo); 7270 } 7271 } 7272 return result; 7273 } 7274 7275 // Returns a packed value as a long: 7276 // 7277 // high 'int'-sized word: link status: undefined/ask/never/always. 7278 // low 'int'-sized word: relative priority among 'always' results. 7279 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 7280 long result = ps.getDomainVerificationStatusForUser(userId); 7281 // if none available, get the master status 7282 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 7283 if (ps.getIntentFilterVerificationInfo() != null) { 7284 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 7285 } 7286 } 7287 return result; 7288 } 7289 7290 private ResolveInfo querySkipCurrentProfileIntents( 7291 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 7292 int flags, int sourceUserId) { 7293 if (matchingFilters != null) { 7294 int size = matchingFilters.size(); 7295 for (int i = 0; i < size; i ++) { 7296 CrossProfileIntentFilter filter = matchingFilters.get(i); 7297 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 7298 // Checking if there are activities in the target user that can handle the 7299 // intent. 7300 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 7301 resolvedType, flags, sourceUserId); 7302 if (resolveInfo != null) { 7303 return resolveInfo; 7304 } 7305 } 7306 } 7307 } 7308 return null; 7309 } 7310 7311 // Return matching ResolveInfo in target user if any. 7312 private ResolveInfo queryCrossProfileIntents( 7313 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 7314 int flags, int sourceUserId, boolean matchInCurrentProfile) { 7315 if (matchingFilters != null) { 7316 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 7317 // match the same intent. For performance reasons, it is better not to 7318 // run queryIntent twice for the same userId 7319 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 7320 int size = matchingFilters.size(); 7321 for (int i = 0; i < size; i++) { 7322 CrossProfileIntentFilter filter = matchingFilters.get(i); 7323 int targetUserId = filter.getTargetUserId(); 7324 boolean skipCurrentProfile = 7325 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 7326 boolean skipCurrentProfileIfNoMatchFound = 7327 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 7328 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 7329 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 7330 // Checking if there are activities in the target user that can handle the 7331 // intent. 7332 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 7333 resolvedType, flags, sourceUserId); 7334 if (resolveInfo != null) return resolveInfo; 7335 alreadyTriedUserIds.put(targetUserId, true); 7336 } 7337 } 7338 } 7339 return null; 7340 } 7341 7342 /** 7343 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 7344 * will forward the intent to the filter's target user. 7345 * Otherwise, returns null. 7346 */ 7347 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 7348 String resolvedType, int flags, int sourceUserId) { 7349 int targetUserId = filter.getTargetUserId(); 7350 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 7351 resolvedType, flags, targetUserId); 7352 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 7353 // If all the matches in the target profile are suspended, return null. 7354 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 7355 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 7356 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 7357 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 7358 targetUserId); 7359 } 7360 } 7361 } 7362 return null; 7363 } 7364 7365 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 7366 int sourceUserId, int targetUserId) { 7367 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 7368 long ident = Binder.clearCallingIdentity(); 7369 boolean targetIsProfile; 7370 try { 7371 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 7372 } finally { 7373 Binder.restoreCallingIdentity(ident); 7374 } 7375 String className; 7376 if (targetIsProfile) { 7377 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 7378 } else { 7379 className = FORWARD_INTENT_TO_PARENT; 7380 } 7381 ComponentName forwardingActivityComponentName = new ComponentName( 7382 mAndroidApplication.packageName, className); 7383 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 7384 sourceUserId); 7385 if (!targetIsProfile) { 7386 forwardingActivityInfo.showUserIcon = targetUserId; 7387 forwardingResolveInfo.noResourceId = true; 7388 } 7389 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 7390 forwardingResolveInfo.priority = 0; 7391 forwardingResolveInfo.preferredOrder = 0; 7392 forwardingResolveInfo.match = 0; 7393 forwardingResolveInfo.isDefault = true; 7394 forwardingResolveInfo.filter = filter; 7395 forwardingResolveInfo.targetUserId = targetUserId; 7396 return forwardingResolveInfo; 7397 } 7398 7399 @Override 7400 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 7401 Intent[] specifics, String[] specificTypes, Intent intent, 7402 String resolvedType, int flags, int userId) { 7403 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 7404 specificTypes, intent, resolvedType, flags, userId)); 7405 } 7406 7407 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 7408 Intent[] specifics, String[] specificTypes, Intent intent, 7409 String resolvedType, int flags, int userId) { 7410 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7411 final int callingUid = Binder.getCallingUid(); 7412 flags = updateFlagsForResolve(flags, userId, intent, callingUid, 7413 false /*includeInstantApps*/); 7414 enforceCrossUserPermission(callingUid, userId, 7415 false /*requireFullPermission*/, false /*checkShell*/, 7416 "query intent activity options"); 7417 final String resultsAction = intent.getAction(); 7418 7419 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 7420 | PackageManager.GET_RESOLVED_FILTER, userId); 7421 7422 if (DEBUG_INTENT_MATCHING) { 7423 Log.v(TAG, "Query " + intent + ": " + results); 7424 } 7425 7426 int specificsPos = 0; 7427 int N; 7428 7429 // todo: note that the algorithm used here is O(N^2). This 7430 // isn't a problem in our current environment, but if we start running 7431 // into situations where we have more than 5 or 10 matches then this 7432 // should probably be changed to something smarter... 7433 7434 // First we go through and resolve each of the specific items 7435 // that were supplied, taking care of removing any corresponding 7436 // duplicate items in the generic resolve list. 7437 if (specifics != null) { 7438 for (int i=0; i<specifics.length; i++) { 7439 final Intent sintent = specifics[i]; 7440 if (sintent == null) { 7441 continue; 7442 } 7443 7444 if (DEBUG_INTENT_MATCHING) { 7445 Log.v(TAG, "Specific #" + i + ": " + sintent); 7446 } 7447 7448 String action = sintent.getAction(); 7449 if (resultsAction != null && resultsAction.equals(action)) { 7450 // If this action was explicitly requested, then don't 7451 // remove things that have it. 7452 action = null; 7453 } 7454 7455 ResolveInfo ri = null; 7456 ActivityInfo ai = null; 7457 7458 ComponentName comp = sintent.getComponent(); 7459 if (comp == null) { 7460 ri = resolveIntent( 7461 sintent, 7462 specificTypes != null ? specificTypes[i] : null, 7463 flags, userId); 7464 if (ri == null) { 7465 continue; 7466 } 7467 if (ri == mResolveInfo) { 7468 // ACK! Must do something better with this. 7469 } 7470 ai = ri.activityInfo; 7471 comp = new ComponentName(ai.applicationInfo.packageName, 7472 ai.name); 7473 } else { 7474 ai = getActivityInfo(comp, flags, userId); 7475 if (ai == null) { 7476 continue; 7477 } 7478 } 7479 7480 // Look for any generic query activities that are duplicates 7481 // of this specific one, and remove them from the results. 7482 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 7483 N = results.size(); 7484 int j; 7485 for (j=specificsPos; j<N; j++) { 7486 ResolveInfo sri = results.get(j); 7487 if ((sri.activityInfo.name.equals(comp.getClassName()) 7488 && sri.activityInfo.applicationInfo.packageName.equals( 7489 comp.getPackageName())) 7490 || (action != null && sri.filter.matchAction(action))) { 7491 results.remove(j); 7492 if (DEBUG_INTENT_MATCHING) Log.v( 7493 TAG, "Removing duplicate item from " + j 7494 + " due to specific " + specificsPos); 7495 if (ri == null) { 7496 ri = sri; 7497 } 7498 j--; 7499 N--; 7500 } 7501 } 7502 7503 // Add this specific item to its proper place. 7504 if (ri == null) { 7505 ri = new ResolveInfo(); 7506 ri.activityInfo = ai; 7507 } 7508 results.add(specificsPos, ri); 7509 ri.specificIndex = i; 7510 specificsPos++; 7511 } 7512 } 7513 7514 // Now we go through the remaining generic results and remove any 7515 // duplicate actions that are found here. 7516 N = results.size(); 7517 for (int i=specificsPos; i<N-1; i++) { 7518 final ResolveInfo rii = results.get(i); 7519 if (rii.filter == null) { 7520 continue; 7521 } 7522 7523 // Iterate over all of the actions of this result's intent 7524 // filter... typically this should be just one. 7525 final Iterator<String> it = rii.filter.actionsIterator(); 7526 if (it == null) { 7527 continue; 7528 } 7529 while (it.hasNext()) { 7530 final String action = it.next(); 7531 if (resultsAction != null && resultsAction.equals(action)) { 7532 // If this action was explicitly requested, then don't 7533 // remove things that have it. 7534 continue; 7535 } 7536 for (int j=i+1; j<N; j++) { 7537 final ResolveInfo rij = results.get(j); 7538 if (rij.filter != null && rij.filter.hasAction(action)) { 7539 results.remove(j); 7540 if (DEBUG_INTENT_MATCHING) Log.v( 7541 TAG, "Removing duplicate item from " + j 7542 + " due to action " + action + " at " + i); 7543 j--; 7544 N--; 7545 } 7546 } 7547 } 7548 7549 // If the caller didn't request filter information, drop it now 7550 // so we don't have to marshall/unmarshall it. 7551 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 7552 rii.filter = null; 7553 } 7554 } 7555 7556 // Filter out the caller activity if so requested. 7557 if (caller != null) { 7558 N = results.size(); 7559 for (int i=0; i<N; i++) { 7560 ActivityInfo ainfo = results.get(i).activityInfo; 7561 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 7562 && caller.getClassName().equals(ainfo.name)) { 7563 results.remove(i); 7564 break; 7565 } 7566 } 7567 } 7568 7569 // If the caller didn't request filter information, 7570 // drop them now so we don't have to 7571 // marshall/unmarshall it. 7572 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 7573 N = results.size(); 7574 for (int i=0; i<N; i++) { 7575 results.get(i).filter = null; 7576 } 7577 } 7578 7579 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 7580 return results; 7581 } 7582 7583 @Override 7584 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 7585 String resolvedType, int flags, int userId) { 7586 return new ParceledListSlice<>( 7587 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 7588 } 7589 7590 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 7591 String resolvedType, int flags, int userId) { 7592 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7593 final int callingUid = Binder.getCallingUid(); 7594 final String instantAppPkgName = getInstantAppPackageName(callingUid); 7595 flags = updateFlagsForResolve(flags, userId, intent, callingUid, 7596 false /*includeInstantApps*/); 7597 ComponentName comp = intent.getComponent(); 7598 if (comp == null) { 7599 if (intent.getSelector() != null) { 7600 intent = intent.getSelector(); 7601 comp = intent.getComponent(); 7602 } 7603 } 7604 if (comp != null) { 7605 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7606 final ActivityInfo ai = getReceiverInfo(comp, flags, userId); 7607 if (ai != null) { 7608 // When specifying an explicit component, we prevent the activity from being 7609 // used when either 1) the calling package is normal and the activity is within 7610 // an instant application or 2) the calling package is ephemeral and the 7611 // activity is not visible to instant applications. 7612 final boolean matchInstantApp = 7613 (flags & PackageManager.MATCH_INSTANT) != 0; 7614 final boolean matchVisibleToInstantAppOnly = 7615 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 7616 final boolean matchExplicitlyVisibleOnly = 7617 (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0; 7618 final boolean isCallerInstantApp = 7619 instantAppPkgName != null; 7620 final boolean isTargetSameInstantApp = 7621 comp.getPackageName().equals(instantAppPkgName); 7622 final boolean isTargetInstantApp = 7623 (ai.applicationInfo.privateFlags 7624 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 7625 final boolean isTargetVisibleToInstantApp = 7626 (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0; 7627 final boolean isTargetExplicitlyVisibleToInstantApp = 7628 isTargetVisibleToInstantApp 7629 && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0; 7630 final boolean isTargetHiddenFromInstantApp = 7631 !isTargetVisibleToInstantApp 7632 || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp); 7633 final boolean blockResolution = 7634 !isTargetSameInstantApp 7635 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 7636 || (matchVisibleToInstantAppOnly && isCallerInstantApp 7637 && isTargetHiddenFromInstantApp)); 7638 if (!blockResolution) { 7639 ResolveInfo ri = new ResolveInfo(); 7640 ri.activityInfo = ai; 7641 list.add(ri); 7642 } 7643 } 7644 return applyPostResolutionFilter(list, instantAppPkgName); 7645 } 7646 7647 // reader 7648 synchronized (mPackages) { 7649 String pkgName = intent.getPackage(); 7650 if (pkgName == null) { 7651 final List<ResolveInfo> result = 7652 mReceivers.queryIntent(intent, resolvedType, flags, userId); 7653 return applyPostResolutionFilter(result, instantAppPkgName); 7654 } 7655 final PackageParser.Package pkg = mPackages.get(pkgName); 7656 if (pkg != null) { 7657 final List<ResolveInfo> result = mReceivers.queryIntentForPackage( 7658 intent, resolvedType, flags, pkg.receivers, userId); 7659 return applyPostResolutionFilter(result, instantAppPkgName); 7660 } 7661 return Collections.emptyList(); 7662 } 7663 } 7664 7665 @Override 7666 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 7667 final int callingUid = Binder.getCallingUid(); 7668 return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid); 7669 } 7670 7671 private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags, 7672 int userId, int callingUid) { 7673 if (!sUserManager.exists(userId)) return null; 7674 flags = updateFlagsForResolve( 7675 flags, userId, intent, callingUid, false /*includeInstantApps*/); 7676 List<ResolveInfo> query = queryIntentServicesInternal( 7677 intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/); 7678 if (query != null) { 7679 if (query.size() >= 1) { 7680 // If there is more than one service with the same priority, 7681 // just arbitrarily pick the first one. 7682 return query.get(0); 7683 } 7684 } 7685 return null; 7686 } 7687 7688 @Override 7689 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 7690 String resolvedType, int flags, int userId) { 7691 final int callingUid = Binder.getCallingUid(); 7692 return new ParceledListSlice<>(queryIntentServicesInternal( 7693 intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/)); 7694 } 7695 7696 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 7697 String resolvedType, int flags, int userId, int callingUid, 7698 boolean includeInstantApps) { 7699 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7700 final String instantAppPkgName = getInstantAppPackageName(callingUid); 7701 flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps); 7702 ComponentName comp = intent.getComponent(); 7703 if (comp == null) { 7704 if (intent.getSelector() != null) { 7705 intent = intent.getSelector(); 7706 comp = intent.getComponent(); 7707 } 7708 } 7709 if (comp != null) { 7710 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7711 final ServiceInfo si = getServiceInfo(comp, flags, userId); 7712 if (si != null) { 7713 // When specifying an explicit component, we prevent the service from being 7714 // used when either 1) the service is in an instant application and the 7715 // caller is not the same instant application or 2) the calling package is 7716 // ephemeral and the activity is not visible to ephemeral applications. 7717 final boolean matchInstantApp = 7718 (flags & PackageManager.MATCH_INSTANT) != 0; 7719 final boolean matchVisibleToInstantAppOnly = 7720 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 7721 final boolean isCallerInstantApp = 7722 instantAppPkgName != null; 7723 final boolean isTargetSameInstantApp = 7724 comp.getPackageName().equals(instantAppPkgName); 7725 final boolean isTargetInstantApp = 7726 (si.applicationInfo.privateFlags 7727 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 7728 final boolean isTargetHiddenFromInstantApp = 7729 (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0; 7730 final boolean blockResolution = 7731 !isTargetSameInstantApp 7732 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 7733 || (matchVisibleToInstantAppOnly && isCallerInstantApp 7734 && isTargetHiddenFromInstantApp)); 7735 if (!blockResolution) { 7736 final ResolveInfo ri = new ResolveInfo(); 7737 ri.serviceInfo = si; 7738 list.add(ri); 7739 } 7740 } 7741 return list; 7742 } 7743 7744 // reader 7745 synchronized (mPackages) { 7746 String pkgName = intent.getPackage(); 7747 if (pkgName == null) { 7748 return applyPostServiceResolutionFilter( 7749 mServices.queryIntent(intent, resolvedType, flags, userId), 7750 instantAppPkgName); 7751 } 7752 final PackageParser.Package pkg = mPackages.get(pkgName); 7753 if (pkg != null) { 7754 return applyPostServiceResolutionFilter( 7755 mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 7756 userId), 7757 instantAppPkgName); 7758 } 7759 return Collections.emptyList(); 7760 } 7761 } 7762 7763 private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos, 7764 String instantAppPkgName) { 7765 // TODO: When adding on-demand split support for non-instant apps, remove this check 7766 // and always apply post filtering 7767 if (instantAppPkgName == null) { 7768 return resolveInfos; 7769 } 7770 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 7771 final ResolveInfo info = resolveInfos.get(i); 7772 final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp(); 7773 // allow services that are defined in the provided package 7774 if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) { 7775 if (info.serviceInfo.splitName != null 7776 && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames, 7777 info.serviceInfo.splitName)) { 7778 // requested service is defined in a split that hasn't been installed yet. 7779 // add the installer to the resolve list 7780 if (DEBUG_EPHEMERAL) { 7781 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 7782 } 7783 final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo); 7784 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 7785 info.serviceInfo.packageName, info.serviceInfo.splitName, 7786 info.serviceInfo.applicationInfo.versionCode, null /*failureIntent*/); 7787 // make sure this resolver is the default 7788 installerInfo.isDefault = true; 7789 installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 7790 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 7791 // add a non-generic filter 7792 installerInfo.filter = new IntentFilter(); 7793 // load resources from the correct package 7794 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 7795 resolveInfos.set(i, installerInfo); 7796 } 7797 continue; 7798 } 7799 // allow services that have been explicitly exposed to ephemeral apps 7800 if (!isEphemeralApp 7801 && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) { 7802 continue; 7803 } 7804 resolveInfos.remove(i); 7805 } 7806 return resolveInfos; 7807 } 7808 7809 @Override 7810 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 7811 String resolvedType, int flags, int userId) { 7812 return new ParceledListSlice<>( 7813 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 7814 } 7815 7816 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 7817 Intent intent, String resolvedType, int flags, int userId) { 7818 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7819 final int callingUid = Binder.getCallingUid(); 7820 final String instantAppPkgName = getInstantAppPackageName(callingUid); 7821 flags = updateFlagsForResolve(flags, userId, intent, callingUid, 7822 false /*includeInstantApps*/); 7823 ComponentName comp = intent.getComponent(); 7824 if (comp == null) { 7825 if (intent.getSelector() != null) { 7826 intent = intent.getSelector(); 7827 comp = intent.getComponent(); 7828 } 7829 } 7830 if (comp != null) { 7831 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7832 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 7833 if (pi != null) { 7834 // When specifying an explicit component, we prevent the provider from being 7835 // used when either 1) the provider is in an instant application and the 7836 // caller is not the same instant application or 2) the calling package is an 7837 // instant application and the provider is not visible to instant applications. 7838 final boolean matchInstantApp = 7839 (flags & PackageManager.MATCH_INSTANT) != 0; 7840 final boolean matchVisibleToInstantAppOnly = 7841 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 7842 final boolean isCallerInstantApp = 7843 instantAppPkgName != null; 7844 final boolean isTargetSameInstantApp = 7845 comp.getPackageName().equals(instantAppPkgName); 7846 final boolean isTargetInstantApp = 7847 (pi.applicationInfo.privateFlags 7848 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 7849 final boolean isTargetHiddenFromInstantApp = 7850 (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0; 7851 final boolean blockResolution = 7852 !isTargetSameInstantApp 7853 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 7854 || (matchVisibleToInstantAppOnly && isCallerInstantApp 7855 && isTargetHiddenFromInstantApp)); 7856 if (!blockResolution) { 7857 final ResolveInfo ri = new ResolveInfo(); 7858 ri.providerInfo = pi; 7859 list.add(ri); 7860 } 7861 } 7862 return list; 7863 } 7864 7865 // reader 7866 synchronized (mPackages) { 7867 String pkgName = intent.getPackage(); 7868 if (pkgName == null) { 7869 return applyPostContentProviderResolutionFilter( 7870 mProviders.queryIntent(intent, resolvedType, flags, userId), 7871 instantAppPkgName); 7872 } 7873 final PackageParser.Package pkg = mPackages.get(pkgName); 7874 if (pkg != null) { 7875 return applyPostContentProviderResolutionFilter( 7876 mProviders.queryIntentForPackage( 7877 intent, resolvedType, flags, pkg.providers, userId), 7878 instantAppPkgName); 7879 } 7880 return Collections.emptyList(); 7881 } 7882 } 7883 7884 private List<ResolveInfo> applyPostContentProviderResolutionFilter( 7885 List<ResolveInfo> resolveInfos, String instantAppPkgName) { 7886 // TODO: When adding on-demand split support for non-instant applications, remove 7887 // this check and always apply post filtering 7888 if (instantAppPkgName == null) { 7889 return resolveInfos; 7890 } 7891 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 7892 final ResolveInfo info = resolveInfos.get(i); 7893 final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp(); 7894 // allow providers that are defined in the provided package 7895 if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) { 7896 if (info.providerInfo.splitName != null 7897 && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames, 7898 info.providerInfo.splitName)) { 7899 // requested provider is defined in a split that hasn't been installed yet. 7900 // add the installer to the resolve list 7901 if (DEBUG_EPHEMERAL) { 7902 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 7903 } 7904 final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo); 7905 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 7906 info.providerInfo.packageName, info.providerInfo.splitName, 7907 info.providerInfo.applicationInfo.versionCode, null /*failureIntent*/); 7908 // make sure this resolver is the default 7909 installerInfo.isDefault = true; 7910 installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 7911 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 7912 // add a non-generic filter 7913 installerInfo.filter = new IntentFilter(); 7914 // load resources from the correct package 7915 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 7916 resolveInfos.set(i, installerInfo); 7917 } 7918 continue; 7919 } 7920 // allow providers that have been explicitly exposed to instant applications 7921 if (!isEphemeralApp 7922 && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) { 7923 continue; 7924 } 7925 resolveInfos.remove(i); 7926 } 7927 return resolveInfos; 7928 } 7929 7930 @Override 7931 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 7932 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 7933 return ParceledListSlice.emptyList(); 7934 } 7935 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7936 flags = updateFlagsForPackage(flags, userId, null); 7937 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7938 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7939 true /* requireFullPermission */, false /* checkShell */, 7940 "get installed packages"); 7941 7942 // writer 7943 synchronized (mPackages) { 7944 ArrayList<PackageInfo> list; 7945 if (listUninstalled) { 7946 list = new ArrayList<>(mSettings.mPackages.size()); 7947 for (PackageSetting ps : mSettings.mPackages.values()) { 7948 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) { 7949 continue; 7950 } 7951 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 7952 if (pi != null) { 7953 list.add(pi); 7954 } 7955 } 7956 } else { 7957 list = new ArrayList<>(mPackages.size()); 7958 for (PackageParser.Package p : mPackages.values()) { 7959 if (filterSharedLibPackageLPr((PackageSetting) p.mExtras, 7960 Binder.getCallingUid(), userId, flags)) { 7961 continue; 7962 } 7963 final PackageInfo pi = generatePackageInfo((PackageSetting) 7964 p.mExtras, flags, userId); 7965 if (pi != null) { 7966 list.add(pi); 7967 } 7968 } 7969 } 7970 7971 return new ParceledListSlice<>(list); 7972 } 7973 } 7974 7975 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 7976 String[] permissions, boolean[] tmp, int flags, int userId) { 7977 int numMatch = 0; 7978 final PermissionsState permissionsState = ps.getPermissionsState(); 7979 for (int i=0; i<permissions.length; i++) { 7980 final String permission = permissions[i]; 7981 if (permissionsState.hasPermission(permission, userId)) { 7982 tmp[i] = true; 7983 numMatch++; 7984 } else { 7985 tmp[i] = false; 7986 } 7987 } 7988 if (numMatch == 0) { 7989 return; 7990 } 7991 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 7992 7993 // The above might return null in cases of uninstalled apps or install-state 7994 // skew across users/profiles. 7995 if (pi != null) { 7996 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 7997 if (numMatch == permissions.length) { 7998 pi.requestedPermissions = permissions; 7999 } else { 8000 pi.requestedPermissions = new String[numMatch]; 8001 numMatch = 0; 8002 for (int i=0; i<permissions.length; i++) { 8003 if (tmp[i]) { 8004 pi.requestedPermissions[numMatch] = permissions[i]; 8005 numMatch++; 8006 } 8007 } 8008 } 8009 } 8010 list.add(pi); 8011 } 8012 } 8013 8014 @Override 8015 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 8016 String[] permissions, int flags, int userId) { 8017 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 8018 flags = updateFlagsForPackage(flags, userId, permissions); 8019 enforceCrossUserPermission(Binder.getCallingUid(), userId, 8020 true /* requireFullPermission */, false /* checkShell */, 8021 "get packages holding permissions"); 8022 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 8023 8024 // writer 8025 synchronized (mPackages) { 8026 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 8027 boolean[] tmpBools = new boolean[permissions.length]; 8028 if (listUninstalled) { 8029 for (PackageSetting ps : mSettings.mPackages.values()) { 8030 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 8031 userId); 8032 } 8033 } else { 8034 for (PackageParser.Package pkg : mPackages.values()) { 8035 PackageSetting ps = (PackageSetting)pkg.mExtras; 8036 if (ps != null) { 8037 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 8038 userId); 8039 } 8040 } 8041 } 8042 8043 return new ParceledListSlice<PackageInfo>(list); 8044 } 8045 } 8046 8047 @Override 8048 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 8049 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 8050 return ParceledListSlice.emptyList(); 8051 } 8052 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 8053 flags = updateFlagsForApplication(flags, userId, null); 8054 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 8055 8056 // writer 8057 synchronized (mPackages) { 8058 ArrayList<ApplicationInfo> list; 8059 if (listUninstalled) { 8060 list = new ArrayList<>(mSettings.mPackages.size()); 8061 for (PackageSetting ps : mSettings.mPackages.values()) { 8062 ApplicationInfo ai; 8063 int effectiveFlags = flags; 8064 if (ps.isSystem()) { 8065 effectiveFlags |= PackageManager.MATCH_ANY_USER; 8066 } 8067 if (ps.pkg != null) { 8068 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) { 8069 continue; 8070 } 8071 ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags, 8072 ps.readUserState(userId), userId); 8073 if (ai != null) { 8074 rebaseEnabledOverlays(ai, userId); 8075 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 8076 } 8077 } else { 8078 // Shared lib filtering done in generateApplicationInfoFromSettingsLPw 8079 // and already converts to externally visible package name 8080 ai = generateApplicationInfoFromSettingsLPw(ps.name, 8081 Binder.getCallingUid(), effectiveFlags, userId); 8082 } 8083 if (ai != null) { 8084 list.add(ai); 8085 } 8086 } 8087 } else { 8088 list = new ArrayList<>(mPackages.size()); 8089 for (PackageParser.Package p : mPackages.values()) { 8090 if (p.mExtras != null) { 8091 PackageSetting ps = (PackageSetting) p.mExtras; 8092 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) { 8093 continue; 8094 } 8095 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 8096 ps.readUserState(userId), userId); 8097 if (ai != null) { 8098 rebaseEnabledOverlays(ai, userId); 8099 ai.packageName = resolveExternalPackageNameLPr(p); 8100 list.add(ai); 8101 } 8102 } 8103 } 8104 } 8105 8106 return new ParceledListSlice<>(list); 8107 } 8108 } 8109 8110 @Override 8111 public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) { 8112 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 8113 return null; 8114 } 8115 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS, 8116 "getEphemeralApplications"); 8117 enforceCrossUserPermission(Binder.getCallingUid(), userId, 8118 true /* requireFullPermission */, false /* checkShell */, 8119 "getEphemeralApplications"); 8120 synchronized (mPackages) { 8121 List<InstantAppInfo> instantApps = mInstantAppRegistry 8122 .getInstantAppsLPr(userId); 8123 if (instantApps != null) { 8124 return new ParceledListSlice<>(instantApps); 8125 } 8126 } 8127 return null; 8128 } 8129 8130 @Override 8131 public boolean isInstantApp(String packageName, int userId) { 8132 enforceCrossUserPermission(Binder.getCallingUid(), userId, 8133 true /* requireFullPermission */, false /* checkShell */, 8134 "isInstantApp"); 8135 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 8136 return false; 8137 } 8138 int callingUid = Binder.getCallingUid(); 8139 if (Process.isIsolated(callingUid)) { 8140 callingUid = mIsolatedOwners.get(callingUid); 8141 } 8142 8143 synchronized (mPackages) { 8144 final PackageSetting ps = mSettings.mPackages.get(packageName); 8145 PackageParser.Package pkg = mPackages.get(packageName); 8146 final boolean returnAllowed = 8147 ps != null 8148 && (isCallerSameApp(packageName, callingUid) 8149 || mContext.checkCallingOrSelfPermission( 8150 android.Manifest.permission.ACCESS_INSTANT_APPS) 8151 == PERMISSION_GRANTED 8152 || mInstantAppRegistry.isInstantAccessGranted( 8153 userId, UserHandle.getAppId(callingUid), ps.appId)); 8154 if (returnAllowed) { 8155 return ps.getInstantApp(userId); 8156 } 8157 } 8158 return false; 8159 } 8160 8161 @Override 8162 public byte[] getInstantAppCookie(String packageName, int userId) { 8163 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 8164 return null; 8165 } 8166 8167 enforceCrossUserPermission(Binder.getCallingUid(), userId, 8168 true /* requireFullPermission */, false /* checkShell */, 8169 "getInstantAppCookie"); 8170 if (!isCallerSameApp(packageName, Binder.getCallingUid())) { 8171 return null; 8172 } 8173 synchronized (mPackages) { 8174 return mInstantAppRegistry.getInstantAppCookieLPw( 8175 packageName, userId); 8176 } 8177 } 8178 8179 @Override 8180 public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) { 8181 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 8182 return true; 8183 } 8184 8185 enforceCrossUserPermission(Binder.getCallingUid(), userId, 8186 true /* requireFullPermission */, true /* checkShell */, 8187 "setInstantAppCookie"); 8188 if (!isCallerSameApp(packageName, Binder.getCallingUid())) { 8189 return false; 8190 } 8191 synchronized (mPackages) { 8192 return mInstantAppRegistry.setInstantAppCookieLPw( 8193 packageName, cookie, userId); 8194 } 8195 } 8196 8197 @Override 8198 public Bitmap getInstantAppIcon(String packageName, int userId) { 8199 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 8200 return null; 8201 } 8202 8203 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS, 8204 "getInstantAppIcon"); 8205 8206 enforceCrossUserPermission(Binder.getCallingUid(), userId, 8207 true /* requireFullPermission */, false /* checkShell */, 8208 "getInstantAppIcon"); 8209 8210 synchronized (mPackages) { 8211 return mInstantAppRegistry.getInstantAppIconLPw( 8212 packageName, userId); 8213 } 8214 } 8215 8216 private boolean isCallerSameApp(String packageName, int uid) { 8217 PackageParser.Package pkg = mPackages.get(packageName); 8218 return pkg != null 8219 && UserHandle.getAppId(uid) == pkg.applicationInfo.uid; 8220 } 8221 8222 @Override 8223 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 8224 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 8225 return ParceledListSlice.emptyList(); 8226 } 8227 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 8228 } 8229 8230 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 8231 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 8232 8233 // reader 8234 synchronized (mPackages) { 8235 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 8236 final int userId = UserHandle.getCallingUserId(); 8237 while (i.hasNext()) { 8238 final PackageParser.Package p = i.next(); 8239 if (p.applicationInfo == null) continue; 8240 8241 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 8242 && !p.applicationInfo.isDirectBootAware(); 8243 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 8244 && p.applicationInfo.isDirectBootAware(); 8245 8246 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 8247 && (!mSafeMode || isSystemApp(p)) 8248 && (matchesUnaware || matchesAware)) { 8249 PackageSetting ps = mSettings.mPackages.get(p.packageName); 8250 if (ps != null) { 8251 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 8252 ps.readUserState(userId), userId); 8253 if (ai != null) { 8254 rebaseEnabledOverlays(ai, userId); 8255 finalList.add(ai); 8256 } 8257 } 8258 } 8259 } 8260 } 8261 8262 return finalList; 8263 } 8264 8265 @Override 8266 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 8267 if (!sUserManager.exists(userId)) return null; 8268 flags = updateFlagsForComponent(flags, userId, name); 8269 final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid()); 8270 // reader 8271 synchronized (mPackages) { 8272 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 8273 PackageSetting ps = provider != null 8274 ? mSettings.mPackages.get(provider.owner.packageName) 8275 : null; 8276 if (ps != null) { 8277 final boolean isInstantApp = ps.getInstantApp(userId); 8278 // normal application; filter out instant application provider 8279 if (instantAppPkgName == null && isInstantApp) { 8280 return null; 8281 } 8282 // instant application; filter out other instant applications 8283 if (instantAppPkgName != null 8284 && isInstantApp 8285 && !provider.owner.packageName.equals(instantAppPkgName)) { 8286 return null; 8287 } 8288 // instant application; filter out non-exposed provider 8289 if (instantAppPkgName != null 8290 && !isInstantApp 8291 && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) { 8292 return null; 8293 } 8294 // provider not enabled 8295 if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) { 8296 return null; 8297 } 8298 return PackageParser.generateProviderInfo( 8299 provider, flags, ps.readUserState(userId), userId); 8300 } 8301 return null; 8302 } 8303 } 8304 8305 /** 8306 * @deprecated 8307 */ 8308 @Deprecated 8309 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 8310 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 8311 return; 8312 } 8313 // reader 8314 synchronized (mPackages) { 8315 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 8316 .entrySet().iterator(); 8317 final int userId = UserHandle.getCallingUserId(); 8318 while (i.hasNext()) { 8319 Map.Entry<String, PackageParser.Provider> entry = i.next(); 8320 PackageParser.Provider p = entry.getValue(); 8321 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 8322 8323 if (ps != null && p.syncable 8324 && (!mSafeMode || (p.info.applicationInfo.flags 8325 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 8326 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 8327 ps.readUserState(userId), userId); 8328 if (info != null) { 8329 outNames.add(entry.getKey()); 8330 outInfo.add(info); 8331 } 8332 } 8333 } 8334 } 8335 } 8336 8337 @Override 8338 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 8339 int uid, int flags, String metaDataKey) { 8340 final int callingUid = Binder.getCallingUid(); 8341 final int userId = processName != null ? UserHandle.getUserId(uid) 8342 : UserHandle.getCallingUserId(); 8343 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 8344 flags = updateFlagsForComponent(flags, userId, processName); 8345 ArrayList<ProviderInfo> finalList = null; 8346 // reader 8347 synchronized (mPackages) { 8348 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 8349 while (i.hasNext()) { 8350 final PackageParser.Provider p = i.next(); 8351 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 8352 if (ps != null && p.info.authority != null 8353 && (processName == null 8354 || (p.info.processName.equals(processName) 8355 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 8356 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 8357 8358 // See PM.queryContentProviders()'s javadoc for why we have the metaData 8359 // parameter. 8360 if (metaDataKey != null 8361 && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) { 8362 continue; 8363 } 8364 final ComponentName component = 8365 new ComponentName(p.info.packageName, p.info.name); 8366 if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) { 8367 continue; 8368 } 8369 if (finalList == null) { 8370 finalList = new ArrayList<ProviderInfo>(3); 8371 } 8372 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 8373 ps.readUserState(userId), userId); 8374 if (info != null) { 8375 finalList.add(info); 8376 } 8377 } 8378 } 8379 } 8380 8381 if (finalList != null) { 8382 Collections.sort(finalList, mProviderInitOrderSorter); 8383 return new ParceledListSlice<ProviderInfo>(finalList); 8384 } 8385 8386 return ParceledListSlice.emptyList(); 8387 } 8388 8389 @Override 8390 public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) { 8391 // reader 8392 synchronized (mPackages) { 8393 final int callingUid = Binder.getCallingUid(); 8394 final int callingUserId = UserHandle.getUserId(callingUid); 8395 final PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 8396 if (ps == null) return null; 8397 if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) { 8398 return null; 8399 } 8400 final PackageParser.Instrumentation i = mInstrumentation.get(component); 8401 return PackageParser.generateInstrumentationInfo(i, flags); 8402 } 8403 } 8404 8405 @Override 8406 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 8407 String targetPackage, int flags) { 8408 final int callingUid = Binder.getCallingUid(); 8409 final int callingUserId = UserHandle.getUserId(callingUid); 8410 final PackageSetting ps = mSettings.mPackages.get(targetPackage); 8411 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 8412 return ParceledListSlice.emptyList(); 8413 } 8414 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 8415 } 8416 8417 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 8418 int flags) { 8419 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 8420 8421 // reader 8422 synchronized (mPackages) { 8423 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 8424 while (i.hasNext()) { 8425 final PackageParser.Instrumentation p = i.next(); 8426 if (targetPackage == null 8427 || targetPackage.equals(p.info.targetPackage)) { 8428 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 8429 flags); 8430 if (ii != null) { 8431 finalList.add(ii); 8432 } 8433 } 8434 } 8435 } 8436 8437 return finalList; 8438 } 8439 8440 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 8441 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]"); 8442 try { 8443 scanDirLI(dir, parseFlags, scanFlags, currentTime); 8444 } finally { 8445 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8446 } 8447 } 8448 8449 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 8450 final File[] files = dir.listFiles(); 8451 if (ArrayUtils.isEmpty(files)) { 8452 Log.d(TAG, "No files in app dir " + dir); 8453 return; 8454 } 8455 8456 if (DEBUG_PACKAGE_SCANNING) { 8457 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 8458 + " flags=0x" + Integer.toHexString(parseFlags)); 8459 } 8460 ParallelPackageParser parallelPackageParser = new ParallelPackageParser( 8461 mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir, 8462 mParallelPackageParserCallback); 8463 8464 // Submit files for parsing in parallel 8465 int fileCount = 0; 8466 for (File file : files) { 8467 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 8468 && !PackageInstallerService.isStageName(file.getName()); 8469 if (!isPackage) { 8470 // Ignore entries which are not packages 8471 continue; 8472 } 8473 parallelPackageParser.submit(file, parseFlags); 8474 fileCount++; 8475 } 8476 8477 // Process results one by one 8478 for (; fileCount > 0; fileCount--) { 8479 ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take(); 8480 Throwable throwable = parseResult.throwable; 8481 int errorCode = PackageManager.INSTALL_SUCCEEDED; 8482 8483 if (throwable == null) { 8484 // Static shared libraries have synthetic package names 8485 if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) { 8486 renameStaticSharedLibraryPackage(parseResult.pkg); 8487 } 8488 try { 8489 if (errorCode == PackageManager.INSTALL_SUCCEEDED) { 8490 scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags, 8491 currentTime, null); 8492 } 8493 } catch (PackageManagerException e) { 8494 errorCode = e.error; 8495 Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage()); 8496 } 8497 } else if (throwable instanceof PackageParser.PackageParserException) { 8498 PackageParser.PackageParserException e = (PackageParser.PackageParserException) 8499 throwable; 8500 errorCode = e.error; 8501 Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage()); 8502 } else { 8503 throw new IllegalStateException("Unexpected exception occurred while parsing " 8504 + parseResult.scanFile, throwable); 8505 } 8506 8507 // Delete invalid userdata apps 8508 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 8509 errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) { 8510 logCriticalInfo(Log.WARN, 8511 "Deleting invalid package at " + parseResult.scanFile); 8512 removeCodePathLI(parseResult.scanFile); 8513 } 8514 } 8515 parallelPackageParser.close(); 8516 } 8517 8518 private static File getSettingsProblemFile() { 8519 File dataDir = Environment.getDataDirectory(); 8520 File systemDir = new File(dataDir, "system"); 8521 File fname = new File(systemDir, "uiderrors.txt"); 8522 return fname; 8523 } 8524 8525 static void reportSettingsProblem(int priority, String msg) { 8526 logCriticalInfo(priority, msg); 8527 } 8528 8529 public static void logCriticalInfo(int priority, String msg) { 8530 Slog.println(priority, TAG, msg); 8531 EventLogTags.writePmCriticalInfo(msg); 8532 try { 8533 File fname = getSettingsProblemFile(); 8534 FileOutputStream out = new FileOutputStream(fname, true); 8535 PrintWriter pw = new FastPrintWriter(out); 8536 SimpleDateFormat formatter = new SimpleDateFormat(); 8537 String dateString = formatter.format(new Date(System.currentTimeMillis())); 8538 pw.println(dateString + ": " + msg); 8539 pw.close(); 8540 FileUtils.setPermissions( 8541 fname.toString(), 8542 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 8543 -1, -1); 8544 } catch (java.io.IOException e) { 8545 } 8546 } 8547 8548 private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) { 8549 if (srcFile.isDirectory()) { 8550 final File baseFile = new File(pkg.baseCodePath); 8551 long maxModifiedTime = baseFile.lastModified(); 8552 if (pkg.splitCodePaths != null) { 8553 for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) { 8554 final File splitFile = new File(pkg.splitCodePaths[i]); 8555 maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified()); 8556 } 8557 } 8558 return maxModifiedTime; 8559 } 8560 return srcFile.lastModified(); 8561 } 8562 8563 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 8564 final int policyFlags) throws PackageManagerException { 8565 // When upgrading from pre-N MR1, verify the package time stamp using the package 8566 // directory and not the APK file. 8567 final long lastModifiedTime = mIsPreNMR1Upgrade 8568 ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile); 8569 if (ps != null 8570 && ps.codePath.equals(srcFile) 8571 && ps.timeStamp == lastModifiedTime 8572 && !isCompatSignatureUpdateNeeded(pkg) 8573 && !isRecoverSignatureUpdateNeeded(pkg)) { 8574 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 8575 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8576 ArraySet<PublicKey> signingKs; 8577 synchronized (mPackages) { 8578 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 8579 } 8580 if (ps.signatures.mSignatures != null 8581 && ps.signatures.mSignatures.length != 0 8582 && signingKs != null) { 8583 // Optimization: reuse the existing cached certificates 8584 // if the package appears to be unchanged. 8585 pkg.mSignatures = ps.signatures.mSignatures; 8586 pkg.mSigningKeys = signingKs; 8587 return; 8588 } 8589 8590 Slog.w(TAG, "PackageSetting for " + ps.name 8591 + " is missing signatures. Collecting certs again to recover them."); 8592 } else { 8593 Slog.i(TAG, srcFile.toString() + " changed; collecting certs"); 8594 } 8595 8596 try { 8597 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 8598 PackageParser.collectCertificates(pkg, policyFlags); 8599 } catch (PackageParserException e) { 8600 throw PackageManagerException.from(e); 8601 } finally { 8602 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8603 } 8604 } 8605 8606 /** 8607 * Traces a package scan. 8608 * @see #scanPackageLI(File, int, int, long, UserHandle) 8609 */ 8610 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 8611 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 8612 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]"); 8613 try { 8614 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 8615 } finally { 8616 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8617 } 8618 } 8619 8620 /** 8621 * Scans a package and returns the newly parsed package. 8622 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 8623 */ 8624 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 8625 long currentTime, UserHandle user) throws PackageManagerException { 8626 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 8627 PackageParser pp = new PackageParser(); 8628 pp.setSeparateProcesses(mSeparateProcesses); 8629 pp.setOnlyCoreApps(mOnlyCore); 8630 pp.setDisplayMetrics(mMetrics); 8631 pp.setCallback(mPackageParserCallback); 8632 8633 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 8634 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 8635 } 8636 8637 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 8638 final PackageParser.Package pkg; 8639 try { 8640 pkg = pp.parsePackage(scanFile, parseFlags); 8641 } catch (PackageParserException e) { 8642 throw PackageManagerException.from(e); 8643 } finally { 8644 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8645 } 8646 8647 // Static shared libraries have synthetic package names 8648 if (pkg.applicationInfo.isStaticSharedLibrary()) { 8649 renameStaticSharedLibraryPackage(pkg); 8650 } 8651 8652 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 8653 } 8654 8655 /** 8656 * Scans a package and returns the newly parsed package. 8657 * @throws PackageManagerException on a parse error. 8658 */ 8659 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 8660 final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user) 8661 throws PackageManagerException { 8662 // If the package has children and this is the first dive in the function 8663 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 8664 // packages (parent and children) would be successfully scanned before the 8665 // actual scan since scanning mutates internal state and we want to atomically 8666 // install the package and its children. 8667 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8668 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 8669 scanFlags |= SCAN_CHECK_ONLY; 8670 } 8671 } else { 8672 scanFlags &= ~SCAN_CHECK_ONLY; 8673 } 8674 8675 // Scan the parent 8676 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 8677 scanFlags, currentTime, user); 8678 8679 // Scan the children 8680 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8681 for (int i = 0; i < childCount; i++) { 8682 PackageParser.Package childPackage = pkg.childPackages.get(i); 8683 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 8684 currentTime, user); 8685 } 8686 8687 8688 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8689 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 8690 } 8691 8692 return scannedPkg; 8693 } 8694 8695 /** 8696 * Scans a package and returns the newly parsed package. 8697 * @throws PackageManagerException on a parse error. 8698 */ 8699 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 8700 int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user) 8701 throws PackageManagerException { 8702 PackageSetting ps = null; 8703 PackageSetting updatedPkg; 8704 // reader 8705 synchronized (mPackages) { 8706 // Look to see if we already know about this package. 8707 String oldName = mSettings.getRenamedPackageLPr(pkg.packageName); 8708 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 8709 // This package has been renamed to its original name. Let's 8710 // use that. 8711 ps = mSettings.getPackageLPr(oldName); 8712 } 8713 // If there was no original package, see one for the real package name. 8714 if (ps == null) { 8715 ps = mSettings.getPackageLPr(pkg.packageName); 8716 } 8717 // Check to see if this package could be hiding/updating a system 8718 // package. Must look for it either under the original or real 8719 // package name depending on our state. 8720 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 8721 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 8722 8723 // If this is a package we don't know about on the system partition, we 8724 // may need to remove disabled child packages on the system partition 8725 // or may need to not add child packages if the parent apk is updated 8726 // on the data partition and no longer defines this child package. 8727 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 8728 // If this is a parent package for an updated system app and this system 8729 // app got an OTA update which no longer defines some of the child packages 8730 // we have to prune them from the disabled system packages. 8731 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 8732 if (disabledPs != null) { 8733 final int scannedChildCount = (pkg.childPackages != null) 8734 ? pkg.childPackages.size() : 0; 8735 final int disabledChildCount = disabledPs.childPackageNames != null 8736 ? disabledPs.childPackageNames.size() : 0; 8737 for (int i = 0; i < disabledChildCount; i++) { 8738 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 8739 boolean disabledPackageAvailable = false; 8740 for (int j = 0; j < scannedChildCount; j++) { 8741 PackageParser.Package childPkg = pkg.childPackages.get(j); 8742 if (childPkg.packageName.equals(disabledChildPackageName)) { 8743 disabledPackageAvailable = true; 8744 break; 8745 } 8746 } 8747 if (!disabledPackageAvailable) { 8748 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 8749 } 8750 } 8751 } 8752 } 8753 } 8754 8755 boolean updatedPkgBetter = false; 8756 // First check if this is a system package that may involve an update 8757 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 8758 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 8759 // it needs to drop FLAG_PRIVILEGED. 8760 if (locationIsPrivileged(scanFile)) { 8761 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 8762 } else { 8763 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 8764 } 8765 8766 if (ps != null && !ps.codePath.equals(scanFile)) { 8767 // The path has changed from what was last scanned... check the 8768 // version of the new path against what we have stored to determine 8769 // what to do. 8770 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 8771 if (pkg.mVersionCode <= ps.versionCode) { 8772 // The system package has been updated and the code path does not match 8773 // Ignore entry. Skip it. 8774 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 8775 + " ignored: updated version " + ps.versionCode 8776 + " better than this " + pkg.mVersionCode); 8777 if (!updatedPkg.codePath.equals(scanFile)) { 8778 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 8779 + ps.name + " changing from " + updatedPkg.codePathString 8780 + " to " + scanFile); 8781 updatedPkg.codePath = scanFile; 8782 updatedPkg.codePathString = scanFile.toString(); 8783 updatedPkg.resourcePath = scanFile; 8784 updatedPkg.resourcePathString = scanFile.toString(); 8785 } 8786 updatedPkg.pkg = pkg; 8787 updatedPkg.versionCode = pkg.mVersionCode; 8788 8789 // Update the disabled system child packages to point to the package too. 8790 final int childCount = updatedPkg.childPackageNames != null 8791 ? updatedPkg.childPackageNames.size() : 0; 8792 for (int i = 0; i < childCount; i++) { 8793 String childPackageName = updatedPkg.childPackageNames.get(i); 8794 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 8795 childPackageName); 8796 if (updatedChildPkg != null) { 8797 updatedChildPkg.pkg = pkg; 8798 updatedChildPkg.versionCode = pkg.mVersionCode; 8799 } 8800 } 8801 8802 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 8803 + scanFile + " ignored: updated version " + ps.versionCode 8804 + " better than this " + pkg.mVersionCode); 8805 } else { 8806 // The current app on the system partition is better than 8807 // what we have updated to on the data partition; switch 8808 // back to the system partition version. 8809 // At this point, its safely assumed that package installation for 8810 // apps in system partition will go through. If not there won't be a working 8811 // version of the app 8812 // writer 8813 synchronized (mPackages) { 8814 // Just remove the loaded entries from package lists. 8815 mPackages.remove(ps.name); 8816 } 8817 8818 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 8819 + " reverting from " + ps.codePathString 8820 + ": new version " + pkg.mVersionCode 8821 + " better than installed " + ps.versionCode); 8822 8823 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 8824 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 8825 synchronized (mInstallLock) { 8826 args.cleanUpResourcesLI(); 8827 } 8828 synchronized (mPackages) { 8829 mSettings.enableSystemPackageLPw(ps.name); 8830 } 8831 updatedPkgBetter = true; 8832 } 8833 } 8834 } 8835 8836 if (updatedPkg != null) { 8837 // An updated system app will not have the PARSE_IS_SYSTEM flag set 8838 // initially 8839 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 8840 8841 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 8842 // flag set initially 8843 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 8844 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 8845 } 8846 } 8847 8848 // Verify certificates against what was last scanned 8849 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 8850 8851 /* 8852 * A new system app appeared, but we already had a non-system one of the 8853 * same name installed earlier. 8854 */ 8855 boolean shouldHideSystemApp = false; 8856 if (updatedPkg == null && ps != null 8857 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 8858 /* 8859 * Check to make sure the signatures match first. If they don't, 8860 * wipe the installed application and its data. 8861 */ 8862 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 8863 != PackageManager.SIGNATURE_MATCH) { 8864 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 8865 + " signatures don't match existing userdata copy; removing"); 8866 try (PackageFreezer freezer = freezePackage(pkg.packageName, 8867 "scanPackageInternalLI")) { 8868 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 8869 } 8870 ps = null; 8871 } else { 8872 /* 8873 * If the newly-added system app is an older version than the 8874 * already installed version, hide it. It will be scanned later 8875 * and re-added like an update. 8876 */ 8877 if (pkg.mVersionCode <= ps.versionCode) { 8878 shouldHideSystemApp = true; 8879 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 8880 + " but new version " + pkg.mVersionCode + " better than installed " 8881 + ps.versionCode + "; hiding system"); 8882 } else { 8883 /* 8884 * The newly found system app is a newer version that the 8885 * one previously installed. Simply remove the 8886 * already-installed application and replace it with our own 8887 * while keeping the application data. 8888 */ 8889 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 8890 + " reverting from " + ps.codePathString + ": new version " 8891 + pkg.mVersionCode + " better than installed " + ps.versionCode); 8892 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 8893 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 8894 synchronized (mInstallLock) { 8895 args.cleanUpResourcesLI(); 8896 } 8897 } 8898 } 8899 } 8900 8901 // The apk is forward locked (not public) if its code and resources 8902 // are kept in different files. (except for app in either system or 8903 // vendor path). 8904 // TODO grab this value from PackageSettings 8905 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8906 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 8907 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 8908 } 8909 } 8910 8911 // TODO: extend to support forward-locked splits 8912 String resourcePath = null; 8913 String baseResourcePath = null; 8914 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 8915 if (ps != null && ps.resourcePathString != null) { 8916 resourcePath = ps.resourcePathString; 8917 baseResourcePath = ps.resourcePathString; 8918 } else { 8919 // Should not happen at all. Just log an error. 8920 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 8921 } 8922 } else { 8923 resourcePath = pkg.codePath; 8924 baseResourcePath = pkg.baseCodePath; 8925 } 8926 8927 // Set application objects path explicitly. 8928 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 8929 pkg.setApplicationInfoCodePath(pkg.codePath); 8930 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 8931 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 8932 pkg.setApplicationInfoResourcePath(resourcePath); 8933 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 8934 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 8935 8936 final int userId = ((user == null) ? 0 : user.getIdentifier()); 8937 if (ps != null && ps.getInstantApp(userId)) { 8938 scanFlags |= SCAN_AS_INSTANT_APP; 8939 } 8940 8941 // Note that we invoke the following method only if we are about to unpack an application 8942 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 8943 | SCAN_UPDATE_SIGNATURE, currentTime, user); 8944 8945 /* 8946 * If the system app should be overridden by a previously installed 8947 * data, hide the system app now and let the /data/app scan pick it up 8948 * again. 8949 */ 8950 if (shouldHideSystemApp) { 8951 synchronized (mPackages) { 8952 mSettings.disableSystemPackageLPw(pkg.packageName, true); 8953 } 8954 } 8955 8956 return scannedPkg; 8957 } 8958 8959 private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) { 8960 // Derive the new package synthetic package name 8961 pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER 8962 + pkg.staticSharedLibVersion); 8963 } 8964 8965 private static String fixProcessName(String defProcessName, 8966 String processName) { 8967 if (processName == null) { 8968 return defProcessName; 8969 } 8970 return processName; 8971 } 8972 8973 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 8974 throws PackageManagerException { 8975 if (pkgSetting.signatures.mSignatures != null) { 8976 // Already existing package. Make sure signatures match 8977 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 8978 == PackageManager.SIGNATURE_MATCH; 8979 if (!match) { 8980 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 8981 == PackageManager.SIGNATURE_MATCH; 8982 } 8983 if (!match) { 8984 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 8985 == PackageManager.SIGNATURE_MATCH; 8986 } 8987 if (!match) { 8988 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 8989 + pkg.packageName + " signatures do not match the " 8990 + "previously installed version; ignoring!"); 8991 } 8992 } 8993 8994 // Check for shared user signatures 8995 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 8996 // Already existing package. Make sure signatures match 8997 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8998 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 8999 if (!match) { 9000 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 9001 == PackageManager.SIGNATURE_MATCH; 9002 } 9003 if (!match) { 9004 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 9005 == PackageManager.SIGNATURE_MATCH; 9006 } 9007 if (!match) { 9008 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 9009 "Package " + pkg.packageName 9010 + " has no signatures that match those in shared user " 9011 + pkgSetting.sharedUser.name + "; ignoring!"); 9012 } 9013 } 9014 } 9015 9016 /** 9017 * Enforces that only the system UID or root's UID can call a method exposed 9018 * via Binder. 9019 * 9020 * @param message used as message if SecurityException is thrown 9021 * @throws SecurityException if the caller is not system or root 9022 */ 9023 private static final void enforceSystemOrRoot(String message) { 9024 final int uid = Binder.getCallingUid(); 9025 if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) { 9026 throw new SecurityException(message); 9027 } 9028 } 9029 9030 @Override 9031 public void performFstrimIfNeeded() { 9032 enforceSystemOrRoot("Only the system can request fstrim"); 9033 9034 // Before everything else, see whether we need to fstrim. 9035 try { 9036 IStorageManager sm = PackageHelper.getStorageManager(); 9037 if (sm != null) { 9038 boolean doTrim = false; 9039 final long interval = android.provider.Settings.Global.getLong( 9040 mContext.getContentResolver(), 9041 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 9042 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 9043 if (interval > 0) { 9044 final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance(); 9045 if (timeSinceLast > interval) { 9046 doTrim = true; 9047 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 9048 + "; running immediately"); 9049 } 9050 } 9051 if (doTrim) { 9052 final boolean dexOptDialogShown; 9053 synchronized (mPackages) { 9054 dexOptDialogShown = mDexOptDialogShown; 9055 } 9056 if (!isFirstBoot() && dexOptDialogShown) { 9057 try { 9058 ActivityManager.getService().showBootMessage( 9059 mContext.getResources().getString( 9060 R.string.android_upgrading_fstrim), true); 9061 } catch (RemoteException e) { 9062 } 9063 } 9064 sm.runMaintenance(); 9065 } 9066 } else { 9067 Slog.e(TAG, "storageManager service unavailable!"); 9068 } 9069 } catch (RemoteException e) { 9070 // Can't happen; StorageManagerService is local 9071 } 9072 } 9073 9074 @Override 9075 public void updatePackagesIfNeeded() { 9076 enforceSystemOrRoot("Only the system can request package update"); 9077 9078 // We need to re-extract after an OTA. 9079 boolean causeUpgrade = isUpgrade(); 9080 9081 // First boot or factory reset. 9082 // Note: we also handle devices that are upgrading to N right now as if it is their 9083 // first boot, as they do not have profile data. 9084 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 9085 9086 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 9087 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 9088 9089 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 9090 return; 9091 } 9092 9093 List<PackageParser.Package> pkgs; 9094 synchronized (mPackages) { 9095 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 9096 } 9097 9098 final long startTime = System.nanoTime(); 9099 final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */, 9100 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT)); 9101 9102 final int elapsedTimeSeconds = 9103 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 9104 9105 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]); 9106 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]); 9107 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]); 9108 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 9109 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 9110 } 9111 9112 /** 9113 * Performs dexopt on the set of packages in {@code packages} and returns an int array 9114 * containing statistics about the invocation. The array consists of three elements, 9115 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped} 9116 * and {@code numberOfPackagesFailed}. 9117 */ 9118 private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog, 9119 String compilerFilter) { 9120 9121 int numberOfPackagesVisited = 0; 9122 int numberOfPackagesOptimized = 0; 9123 int numberOfPackagesSkipped = 0; 9124 int numberOfPackagesFailed = 0; 9125 final int numberOfPackagesToDexopt = pkgs.size(); 9126 9127 for (PackageParser.Package pkg : pkgs) { 9128 numberOfPackagesVisited++; 9129 9130 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 9131 if (DEBUG_DEXOPT) { 9132 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 9133 } 9134 numberOfPackagesSkipped++; 9135 continue; 9136 } 9137 9138 if (DEBUG_DEXOPT) { 9139 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 9140 numberOfPackagesToDexopt + ": " + pkg.packageName); 9141 } 9142 9143 if (showDialog) { 9144 try { 9145 ActivityManager.getService().showBootMessage( 9146 mContext.getResources().getString(R.string.android_upgrading_apk, 9147 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 9148 } catch (RemoteException e) { 9149 } 9150 synchronized (mPackages) { 9151 mDexOptDialogShown = true; 9152 } 9153 } 9154 9155 // If the OTA updates a system app which was previously preopted to a non-preopted state 9156 // the app might end up being verified at runtime. That's because by default the apps 9157 // are verify-profile but for preopted apps there's no profile. 9158 // Do a hacky check to ensure that if we have no profiles (a reasonable indication 9159 // that before the OTA the app was preopted) the app gets compiled with a non-profile 9160 // filter (by default 'quicken'). 9161 // Note that at this stage unused apps are already filtered. 9162 if (isSystemApp(pkg) && 9163 DexFile.isProfileGuidedCompilerFilter(compilerFilter) && 9164 !Environment.getReferenceProfile(pkg.packageName).exists()) { 9165 compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter); 9166 } 9167 9168 // checkProfiles is false to avoid merging profiles during boot which 9169 // might interfere with background compilation (b/28612421). 9170 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 9171 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 9172 // trade-off worth doing to save boot time work. 9173 int dexOptStatus = performDexOptTraced(pkg.packageName, 9174 false /* checkProfiles */, 9175 compilerFilter, 9176 false /* force */); 9177 switch (dexOptStatus) { 9178 case PackageDexOptimizer.DEX_OPT_PERFORMED: 9179 numberOfPackagesOptimized++; 9180 break; 9181 case PackageDexOptimizer.DEX_OPT_SKIPPED: 9182 numberOfPackagesSkipped++; 9183 break; 9184 case PackageDexOptimizer.DEX_OPT_FAILED: 9185 numberOfPackagesFailed++; 9186 break; 9187 default: 9188 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus); 9189 break; 9190 } 9191 } 9192 9193 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped, 9194 numberOfPackagesFailed }; 9195 } 9196 9197 @Override 9198 public void notifyPackageUse(String packageName, int reason) { 9199 synchronized (mPackages) { 9200 final int callingUid = Binder.getCallingUid(); 9201 final int callingUserId = UserHandle.getUserId(callingUid); 9202 if (getInstantAppPackageName(callingUid) != null) { 9203 if (!isCallerSameApp(packageName, callingUid)) { 9204 return; 9205 } 9206 } else { 9207 if (isInstantApp(packageName, callingUserId)) { 9208 return; 9209 } 9210 } 9211 final PackageParser.Package p = mPackages.get(packageName); 9212 if (p == null) { 9213 return; 9214 } 9215 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 9216 } 9217 } 9218 9219 @Override 9220 public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) { 9221 int userId = UserHandle.getCallingUserId(); 9222 ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId); 9223 if (ai == null) { 9224 Slog.w(TAG, "Loading a package that does not exist for the calling user. package=" 9225 + loadingPackageName + ", user=" + userId); 9226 return; 9227 } 9228 mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId); 9229 } 9230 9231 @Override 9232 public boolean performDexOpt(String packageName, 9233 boolean checkProfiles, int compileReason, boolean force) { 9234 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 9235 getCompilerFilterForReason(compileReason), force); 9236 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 9237 } 9238 9239 @Override 9240 public boolean performDexOptMode(String packageName, 9241 boolean checkProfiles, String targetCompilerFilter, boolean force) { 9242 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 9243 return false; 9244 } 9245 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 9246 targetCompilerFilter, force); 9247 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 9248 } 9249 9250 private int performDexOptTraced(String packageName, 9251 boolean checkProfiles, String targetCompilerFilter, boolean force) { 9252 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 9253 try { 9254 return performDexOptInternal(packageName, checkProfiles, 9255 targetCompilerFilter, force); 9256 } finally { 9257 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9258 } 9259 } 9260 9261 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 9262 // if the package can now be considered up to date for the given filter. 9263 private int performDexOptInternal(String packageName, 9264 boolean checkProfiles, String targetCompilerFilter, boolean force) { 9265 PackageParser.Package p; 9266 synchronized (mPackages) { 9267 p = mPackages.get(packageName); 9268 if (p == null) { 9269 // Package could not be found. Report failure. 9270 return PackageDexOptimizer.DEX_OPT_FAILED; 9271 } 9272 mPackageUsage.maybeWriteAsync(mPackages); 9273 mCompilerStats.maybeWriteAsync(); 9274 } 9275 long callingId = Binder.clearCallingIdentity(); 9276 try { 9277 synchronized (mInstallLock) { 9278 return performDexOptInternalWithDependenciesLI(p, checkProfiles, 9279 targetCompilerFilter, force); 9280 } 9281 } finally { 9282 Binder.restoreCallingIdentity(callingId); 9283 } 9284 } 9285 9286 public ArraySet<String> getOptimizablePackages() { 9287 ArraySet<String> pkgs = new ArraySet<String>(); 9288 synchronized (mPackages) { 9289 for (PackageParser.Package p : mPackages.values()) { 9290 if (PackageDexOptimizer.canOptimizePackage(p)) { 9291 pkgs.add(p.packageName); 9292 } 9293 } 9294 } 9295 return pkgs; 9296 } 9297 9298 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 9299 boolean checkProfiles, String targetCompilerFilter, 9300 boolean force) { 9301 // Select the dex optimizer based on the force parameter. 9302 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 9303 // allocate an object here. 9304 PackageDexOptimizer pdo = force 9305 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 9306 : mPackageDexOptimizer; 9307 9308 // Dexopt all dependencies first. Note: we ignore the return value and march on 9309 // on errors. 9310 // Note that we are going to call performDexOpt on those libraries as many times as 9311 // they are referenced in packages. When we do a batch of performDexOpt (for example 9312 // at boot, or background job), the passed 'targetCompilerFilter' stays the same, 9313 // and the first package that uses the library will dexopt it. The 9314 // others will see that the compiled code for the library is up to date. 9315 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 9316 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 9317 if (!deps.isEmpty()) { 9318 for (PackageParser.Package depPackage : deps) { 9319 // TODO: Analyze and investigate if we (should) profile libraries. 9320 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 9321 false /* checkProfiles */, 9322 targetCompilerFilter, 9323 getOrCreateCompilerPackageStats(depPackage), 9324 true /* isUsedByOtherApps */); 9325 } 9326 } 9327 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 9328 targetCompilerFilter, getOrCreateCompilerPackageStats(p), 9329 mDexManager.isUsedByOtherApps(p.packageName)); 9330 } 9331 9332 // Performs dexopt on the used secondary dex files belonging to the given package. 9333 // Returns true if all dex files were process successfully (which could mean either dexopt or 9334 // skip). Returns false if any of the files caused errors. 9335 @Override 9336 public boolean performDexOptSecondary(String packageName, String compilerFilter, 9337 boolean force) { 9338 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 9339 return false; 9340 } 9341 mDexManager.reconcileSecondaryDexFiles(packageName); 9342 return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force); 9343 } 9344 9345 public boolean performDexOptSecondary(String packageName, int compileReason, 9346 boolean force) { 9347 return mDexManager.dexoptSecondaryDex(packageName, compileReason, force); 9348 } 9349 9350 /** 9351 * Reconcile the information we have about the secondary dex files belonging to 9352 * {@code packagName} and the actual dex files. For all dex files that were 9353 * deleted, update the internal records and delete the generated oat files. 9354 */ 9355 @Override 9356 public void reconcileSecondaryDexFiles(String packageName) { 9357 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 9358 return; 9359 } 9360 mDexManager.reconcileSecondaryDexFiles(packageName); 9361 } 9362 9363 // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject 9364 // a reference there. 9365 /*package*/ DexManager getDexManager() { 9366 return mDexManager; 9367 } 9368 9369 /** 9370 * Execute the background dexopt job immediately. 9371 */ 9372 @Override 9373 public boolean runBackgroundDexoptJob() { 9374 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 9375 return false; 9376 } 9377 return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext); 9378 } 9379 9380 List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 9381 if (p.usesLibraries != null || p.usesOptionalLibraries != null 9382 || p.usesStaticLibraries != null) { 9383 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 9384 Set<String> collectedNames = new HashSet<>(); 9385 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 9386 9387 retValue.remove(p); 9388 9389 return retValue; 9390 } else { 9391 return Collections.emptyList(); 9392 } 9393 } 9394 9395 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 9396 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) { 9397 if (!collectedNames.contains(p.packageName)) { 9398 collectedNames.add(p.packageName); 9399 collected.add(p); 9400 9401 if (p.usesLibraries != null) { 9402 findSharedNonSystemLibrariesRecursive(p.usesLibraries, 9403 null, collected, collectedNames); 9404 } 9405 if (p.usesOptionalLibraries != null) { 9406 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, 9407 null, collected, collectedNames); 9408 } 9409 if (p.usesStaticLibraries != null) { 9410 findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries, 9411 p.usesStaticLibrariesVersions, collected, collectedNames); 9412 } 9413 } 9414 } 9415 9416 private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions, 9417 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) { 9418 final int libNameCount = libs.size(); 9419 for (int i = 0; i < libNameCount; i++) { 9420 String libName = libs.get(i); 9421 int version = (versions != null && versions.length == libNameCount) 9422 ? versions[i] : PackageManager.VERSION_CODE_HIGHEST; 9423 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version); 9424 if (libPkg != null) { 9425 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 9426 } 9427 } 9428 } 9429 9430 private PackageParser.Package findSharedNonSystemLibrary(String name, int version) { 9431 synchronized (mPackages) { 9432 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version); 9433 if (libEntry != null) { 9434 return mPackages.get(libEntry.apk); 9435 } 9436 return null; 9437 } 9438 } 9439 9440 private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) { 9441 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 9442 if (versionedLib == null) { 9443 return null; 9444 } 9445 return versionedLib.get(version); 9446 } 9447 9448 private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) { 9449 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get( 9450 pkg.staticSharedLibName); 9451 if (versionedLib == null) { 9452 return null; 9453 } 9454 int previousLibVersion = -1; 9455 final int versionCount = versionedLib.size(); 9456 for (int i = 0; i < versionCount; i++) { 9457 final int libVersion = versionedLib.keyAt(i); 9458 if (libVersion < pkg.staticSharedLibVersion) { 9459 previousLibVersion = Math.max(previousLibVersion, libVersion); 9460 } 9461 } 9462 if (previousLibVersion >= 0) { 9463 return versionedLib.get(previousLibVersion); 9464 } 9465 return null; 9466 } 9467 9468 public void shutdown() { 9469 mPackageUsage.writeNow(mPackages); 9470 mCompilerStats.writeNow(); 9471 } 9472 9473 @Override 9474 public void dumpProfiles(String packageName) { 9475 PackageParser.Package pkg; 9476 synchronized (mPackages) { 9477 pkg = mPackages.get(packageName); 9478 if (pkg == null) { 9479 throw new IllegalArgumentException("Unknown package: " + packageName); 9480 } 9481 } 9482 /* Only the shell, root, or the app user should be able to dump profiles. */ 9483 int callingUid = Binder.getCallingUid(); 9484 if (callingUid != Process.SHELL_UID && 9485 callingUid != Process.ROOT_UID && 9486 callingUid != pkg.applicationInfo.uid) { 9487 throw new SecurityException("dumpProfiles"); 9488 } 9489 9490 synchronized (mInstallLock) { 9491 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles"); 9492 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 9493 try { 9494 List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly(); 9495 String codePaths = TextUtils.join(";", allCodePaths); 9496 mInstaller.dumpProfiles(sharedGid, packageName, codePaths); 9497 } catch (InstallerException e) { 9498 Slog.w(TAG, "Failed to dump profiles", e); 9499 } 9500 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9501 } 9502 } 9503 9504 @Override 9505 public void forceDexOpt(String packageName) { 9506 enforceSystemOrRoot("forceDexOpt"); 9507 9508 PackageParser.Package pkg; 9509 synchronized (mPackages) { 9510 pkg = mPackages.get(packageName); 9511 if (pkg == null) { 9512 throw new IllegalArgumentException("Unknown package: " + packageName); 9513 } 9514 } 9515 9516 synchronized (mInstallLock) { 9517 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 9518 9519 // Whoever is calling forceDexOpt wants a compiled package. 9520 // Don't use profiles since that may cause compilation to be skipped. 9521 final int res = performDexOptInternalWithDependenciesLI(pkg, 9522 false /* checkProfiles */, getDefaultCompilerFilter(), 9523 true /* force */); 9524 9525 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9526 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 9527 throw new IllegalStateException("Failed to dexopt: " + res); 9528 } 9529 } 9530 } 9531 9532 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 9533 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 9534 Slog.w(TAG, "Unable to update from " + oldPkg.name 9535 + " to " + newPkg.packageName 9536 + ": old package not in system partition"); 9537 return false; 9538 } else if (mPackages.get(oldPkg.name) != null) { 9539 Slog.w(TAG, "Unable to update from " + oldPkg.name 9540 + " to " + newPkg.packageName 9541 + ": old package still exists"); 9542 return false; 9543 } 9544 return true; 9545 } 9546 9547 void removeCodePathLI(File codePath) { 9548 if (codePath.isDirectory()) { 9549 try { 9550 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 9551 } catch (InstallerException e) { 9552 Slog.w(TAG, "Failed to remove code path", e); 9553 } 9554 } else { 9555 codePath.delete(); 9556 } 9557 } 9558 9559 private int[] resolveUserIds(int userId) { 9560 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 9561 } 9562 9563 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 9564 if (pkg == null) { 9565 Slog.wtf(TAG, "Package was null!", new Throwable()); 9566 return; 9567 } 9568 clearAppDataLeafLIF(pkg, userId, flags); 9569 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9570 for (int i = 0; i < childCount; i++) { 9571 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 9572 } 9573 } 9574 9575 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 9576 final PackageSetting ps; 9577 synchronized (mPackages) { 9578 ps = mSettings.mPackages.get(pkg.packageName); 9579 } 9580 for (int realUserId : resolveUserIds(userId)) { 9581 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 9582 try { 9583 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 9584 ceDataInode); 9585 } catch (InstallerException e) { 9586 Slog.w(TAG, String.valueOf(e)); 9587 } 9588 } 9589 } 9590 9591 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 9592 if (pkg == null) { 9593 Slog.wtf(TAG, "Package was null!", new Throwable()); 9594 return; 9595 } 9596 destroyAppDataLeafLIF(pkg, userId, flags); 9597 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9598 for (int i = 0; i < childCount; i++) { 9599 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 9600 } 9601 } 9602 9603 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 9604 final PackageSetting ps; 9605 synchronized (mPackages) { 9606 ps = mSettings.mPackages.get(pkg.packageName); 9607 } 9608 for (int realUserId : resolveUserIds(userId)) { 9609 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 9610 try { 9611 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 9612 ceDataInode); 9613 } catch (InstallerException e) { 9614 Slog.w(TAG, String.valueOf(e)); 9615 } 9616 mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId); 9617 } 9618 } 9619 9620 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 9621 if (pkg == null) { 9622 Slog.wtf(TAG, "Package was null!", new Throwable()); 9623 return; 9624 } 9625 destroyAppProfilesLeafLIF(pkg); 9626 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9627 for (int i = 0; i < childCount; i++) { 9628 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 9629 } 9630 } 9631 9632 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 9633 try { 9634 mInstaller.destroyAppProfiles(pkg.packageName); 9635 } catch (InstallerException e) { 9636 Slog.w(TAG, String.valueOf(e)); 9637 } 9638 } 9639 9640 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 9641 if (pkg == null) { 9642 Slog.wtf(TAG, "Package was null!", new Throwable()); 9643 return; 9644 } 9645 clearAppProfilesLeafLIF(pkg); 9646 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9647 for (int i = 0; i < childCount; i++) { 9648 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 9649 } 9650 } 9651 9652 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 9653 try { 9654 mInstaller.clearAppProfiles(pkg.packageName); 9655 } catch (InstallerException e) { 9656 Slog.w(TAG, String.valueOf(e)); 9657 } 9658 } 9659 9660 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 9661 long lastUpdateTime) { 9662 // Set parent install/update time 9663 PackageSetting ps = (PackageSetting) pkg.mExtras; 9664 if (ps != null) { 9665 ps.firstInstallTime = firstInstallTime; 9666 ps.lastUpdateTime = lastUpdateTime; 9667 } 9668 // Set children install/update time 9669 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9670 for (int i = 0; i < childCount; i++) { 9671 PackageParser.Package childPkg = pkg.childPackages.get(i); 9672 ps = (PackageSetting) childPkg.mExtras; 9673 if (ps != null) { 9674 ps.firstInstallTime = firstInstallTime; 9675 ps.lastUpdateTime = lastUpdateTime; 9676 } 9677 } 9678 } 9679 9680 private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 9681 PackageParser.Package changingLib) { 9682 if (file.path != null) { 9683 usesLibraryFiles.add(file.path); 9684 return; 9685 } 9686 PackageParser.Package p = mPackages.get(file.apk); 9687 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 9688 // If we are doing this while in the middle of updating a library apk, 9689 // then we need to make sure to use that new apk for determining the 9690 // dependencies here. (We haven't yet finished committing the new apk 9691 // to the package manager state.) 9692 if (p == null || p.packageName.equals(changingLib.packageName)) { 9693 p = changingLib; 9694 } 9695 } 9696 if (p != null) { 9697 usesLibraryFiles.addAll(p.getAllCodePaths()); 9698 if (p.usesLibraryFiles != null) { 9699 Collections.addAll(usesLibraryFiles, p.usesLibraryFiles); 9700 } 9701 } 9702 } 9703 9704 private void updateSharedLibrariesLPr(PackageParser.Package pkg, 9705 PackageParser.Package changingLib) throws PackageManagerException { 9706 if (pkg == null) { 9707 return; 9708 } 9709 ArraySet<String> usesLibraryFiles = null; 9710 if (pkg.usesLibraries != null) { 9711 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries, 9712 null, null, pkg.packageName, changingLib, true, null); 9713 } 9714 if (pkg.usesStaticLibraries != null) { 9715 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries, 9716 pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests, 9717 pkg.packageName, changingLib, true, usesLibraryFiles); 9718 } 9719 if (pkg.usesOptionalLibraries != null) { 9720 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries, 9721 null, null, pkg.packageName, changingLib, false, usesLibraryFiles); 9722 } 9723 if (!ArrayUtils.isEmpty(usesLibraryFiles)) { 9724 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]); 9725 } else { 9726 pkg.usesLibraryFiles = null; 9727 } 9728 } 9729 9730 private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries, 9731 @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests, 9732 @NonNull String packageName, @Nullable PackageParser.Package changingLib, 9733 boolean required, @Nullable ArraySet<String> outUsedLibraries) 9734 throws PackageManagerException { 9735 final int libCount = requestedLibraries.size(); 9736 for (int i = 0; i < libCount; i++) { 9737 final String libName = requestedLibraries.get(i); 9738 final int libVersion = requiredVersions != null ? requiredVersions[i] 9739 : SharedLibraryInfo.VERSION_UNDEFINED; 9740 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion); 9741 if (libEntry == null) { 9742 if (required) { 9743 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9744 "Package " + packageName + " requires unavailable shared library " 9745 + libName + "; failing!"); 9746 } else if (DEBUG_SHARED_LIBRARIES) { 9747 Slog.i(TAG, "Package " + packageName 9748 + " desires unavailable shared library " 9749 + libName + "; ignoring!"); 9750 } 9751 } else { 9752 if (requiredVersions != null && requiredCertDigests != null) { 9753 if (libEntry.info.getVersion() != requiredVersions[i]) { 9754 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9755 "Package " + packageName + " requires unavailable static shared" 9756 + " library " + libName + " version " 9757 + libEntry.info.getVersion() + "; failing!"); 9758 } 9759 9760 PackageParser.Package libPkg = mPackages.get(libEntry.apk); 9761 if (libPkg == null) { 9762 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9763 "Package " + packageName + " requires unavailable static shared" 9764 + " library; failing!"); 9765 } 9766 9767 String expectedCertDigest = requiredCertDigests[i]; 9768 String libCertDigest = PackageUtils.computeCertSha256Digest( 9769 libPkg.mSignatures[0]); 9770 if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) { 9771 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9772 "Package " + packageName + " requires differently signed" + 9773 " static shared library; failing!"); 9774 } 9775 } 9776 9777 if (outUsedLibraries == null) { 9778 outUsedLibraries = new ArraySet<>(); 9779 } 9780 addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib); 9781 } 9782 } 9783 return outUsedLibraries; 9784 } 9785 9786 private static boolean hasString(List<String> list, List<String> which) { 9787 if (list == null) { 9788 return false; 9789 } 9790 for (int i=list.size()-1; i>=0; i--) { 9791 for (int j=which.size()-1; j>=0; j--) { 9792 if (which.get(j).equals(list.get(i))) { 9793 return true; 9794 } 9795 } 9796 } 9797 return false; 9798 } 9799 9800 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 9801 PackageParser.Package changingPkg) { 9802 ArrayList<PackageParser.Package> res = null; 9803 for (PackageParser.Package pkg : mPackages.values()) { 9804 if (changingPkg != null 9805 && !hasString(pkg.usesLibraries, changingPkg.libraryNames) 9806 && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames) 9807 && !ArrayUtils.contains(pkg.usesStaticLibraries, 9808 changingPkg.staticSharedLibName)) { 9809 return null; 9810 } 9811 if (res == null) { 9812 res = new ArrayList<>(); 9813 } 9814 res.add(pkg); 9815 try { 9816 updateSharedLibrariesLPr(pkg, changingPkg); 9817 } catch (PackageManagerException e) { 9818 // If a system app update or an app and a required lib missing we 9819 // delete the package and for updated system apps keep the data as 9820 // it is better for the user to reinstall than to be in an limbo 9821 // state. Also libs disappearing under an app should never happen 9822 // - just in case. 9823 if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) { 9824 final int flags = pkg.isUpdatedSystemApp() 9825 ? PackageManager.DELETE_KEEP_DATA : 0; 9826 deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(), 9827 flags , null, true, null); 9828 } 9829 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 9830 } 9831 } 9832 return res; 9833 } 9834 9835 /** 9836 * Derive the value of the {@code cpuAbiOverride} based on the provided 9837 * value and an optional stored value from the package settings. 9838 */ 9839 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 9840 String cpuAbiOverride = null; 9841 9842 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 9843 cpuAbiOverride = null; 9844 } else if (abiOverride != null) { 9845 cpuAbiOverride = abiOverride; 9846 } else if (settings != null) { 9847 cpuAbiOverride = settings.cpuAbiOverrideString; 9848 } 9849 9850 return cpuAbiOverride; 9851 } 9852 9853 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 9854 final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user) 9855 throws PackageManagerException { 9856 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 9857 // If the package has children and this is the first dive in the function 9858 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 9859 // whether all packages (parent and children) would be successfully scanned 9860 // before the actual scan since scanning mutates internal state and we want 9861 // to atomically install the package and its children. 9862 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 9863 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 9864 scanFlags |= SCAN_CHECK_ONLY; 9865 } 9866 } else { 9867 scanFlags &= ~SCAN_CHECK_ONLY; 9868 } 9869 9870 final PackageParser.Package scannedPkg; 9871 try { 9872 // Scan the parent 9873 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 9874 // Scan the children 9875 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9876 for (int i = 0; i < childCount; i++) { 9877 PackageParser.Package childPkg = pkg.childPackages.get(i); 9878 scanPackageLI(childPkg, policyFlags, 9879 scanFlags, currentTime, user); 9880 } 9881 } finally { 9882 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9883 } 9884 9885 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 9886 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 9887 } 9888 9889 return scannedPkg; 9890 } 9891 9892 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 9893 int scanFlags, long currentTime, @Nullable UserHandle user) 9894 throws PackageManagerException { 9895 boolean success = false; 9896 try { 9897 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 9898 currentTime, user); 9899 success = true; 9900 return res; 9901 } finally { 9902 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 9903 // DELETE_DATA_ON_FAILURES is only used by frozen paths 9904 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 9905 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 9906 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 9907 } 9908 } 9909 } 9910 9911 /** 9912 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 9913 */ 9914 private static boolean apkHasCode(String fileName) { 9915 StrictJarFile jarFile = null; 9916 try { 9917 jarFile = new StrictJarFile(fileName, 9918 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 9919 return jarFile.findEntry("classes.dex") != null; 9920 } catch (IOException ignore) { 9921 } finally { 9922 try { 9923 if (jarFile != null) { 9924 jarFile.close(); 9925 } 9926 } catch (IOException ignore) {} 9927 } 9928 return false; 9929 } 9930 9931 /** 9932 * Enforces code policy for the package. This ensures that if an APK has 9933 * declared hasCode="true" in its manifest that the APK actually contains 9934 * code. 9935 * 9936 * @throws PackageManagerException If bytecode could not be found when it should exist 9937 */ 9938 private static void assertCodePolicy(PackageParser.Package pkg) 9939 throws PackageManagerException { 9940 final boolean shouldHaveCode = 9941 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 9942 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 9943 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 9944 "Package " + pkg.baseCodePath + " code is missing"); 9945 } 9946 9947 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 9948 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 9949 final boolean splitShouldHaveCode = 9950 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 9951 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 9952 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 9953 "Package " + pkg.splitCodePaths[i] + " code is missing"); 9954 } 9955 } 9956 } 9957 } 9958 9959 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 9960 final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user) 9961 throws PackageManagerException { 9962 if (DEBUG_PACKAGE_SCANNING) { 9963 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 9964 Log.d(TAG, "Scanning package " + pkg.packageName); 9965 } 9966 9967 applyPolicy(pkg, policyFlags); 9968 9969 assertPackageIsValid(pkg, policyFlags, scanFlags); 9970 9971 // Initialize package source and resource directories 9972 final File scanFile = new File(pkg.codePath); 9973 final File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 9974 final File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 9975 9976 SharedUserSetting suid = null; 9977 PackageSetting pkgSetting = null; 9978 9979 // Getting the package setting may have a side-effect, so if we 9980 // are only checking if scan would succeed, stash a copy of the 9981 // old setting to restore at the end. 9982 PackageSetting nonMutatedPs = null; 9983 9984 // We keep references to the derived CPU Abis from settings in oder to reuse 9985 // them in the case where we're not upgrading or booting for the first time. 9986 String primaryCpuAbiFromSettings = null; 9987 String secondaryCpuAbiFromSettings = null; 9988 9989 // writer 9990 synchronized (mPackages) { 9991 if (pkg.mSharedUserId != null) { 9992 // SIDE EFFECTS; may potentially allocate a new shared user 9993 suid = mSettings.getSharedUserLPw( 9994 pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/); 9995 if (DEBUG_PACKAGE_SCANNING) { 9996 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 9997 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 9998 + "): packages=" + suid.packages); 9999 } 10000 } 10001 10002 // Check if we are renaming from an original package name. 10003 PackageSetting origPackage = null; 10004 String realName = null; 10005 if (pkg.mOriginalPackages != null) { 10006 // This package may need to be renamed to a previously 10007 // installed name. Let's check on that... 10008 final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage); 10009 if (pkg.mOriginalPackages.contains(renamed)) { 10010 // This package had originally been installed as the 10011 // original name, and we have already taken care of 10012 // transitioning to the new one. Just update the new 10013 // one to continue using the old name. 10014 realName = pkg.mRealPackage; 10015 if (!pkg.packageName.equals(renamed)) { 10016 // Callers into this function may have already taken 10017 // care of renaming the package; only do it here if 10018 // it is not already done. 10019 pkg.setPackageName(renamed); 10020 } 10021 } else { 10022 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 10023 if ((origPackage = mSettings.getPackageLPr( 10024 pkg.mOriginalPackages.get(i))) != null) { 10025 // We do have the package already installed under its 10026 // original name... should we use it? 10027 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 10028 // New package is not compatible with original. 10029 origPackage = null; 10030 continue; 10031 } else if (origPackage.sharedUser != null) { 10032 // Make sure uid is compatible between packages. 10033 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 10034 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 10035 + " to " + pkg.packageName + ": old uid " 10036 + origPackage.sharedUser.name 10037 + " differs from " + pkg.mSharedUserId); 10038 origPackage = null; 10039 continue; 10040 } 10041 // TODO: Add case when shared user id is added [b/28144775] 10042 } else { 10043 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 10044 + pkg.packageName + " to old name " + origPackage.name); 10045 } 10046 break; 10047 } 10048 } 10049 } 10050 } 10051 10052 if (mTransferedPackages.contains(pkg.packageName)) { 10053 Slog.w(TAG, "Package " + pkg.packageName 10054 + " was transferred to another, but its .apk remains"); 10055 } 10056 10057 // See comments in nonMutatedPs declaration 10058 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 10059 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName); 10060 if (foundPs != null) { 10061 nonMutatedPs = new PackageSetting(foundPs); 10062 } 10063 } 10064 10065 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) { 10066 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName); 10067 if (foundPs != null) { 10068 primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString; 10069 secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString; 10070 } 10071 } 10072 10073 pkgSetting = mSettings.getPackageLPr(pkg.packageName); 10074 if (pkgSetting != null && pkgSetting.sharedUser != suid) { 10075 PackageManagerService.reportSettingsProblem(Log.WARN, 10076 "Package " + pkg.packageName + " shared user changed from " 10077 + (pkgSetting.sharedUser != null 10078 ? pkgSetting.sharedUser.name : "<nothing>") 10079 + " to " 10080 + (suid != null ? suid.name : "<nothing>") 10081 + "; replacing with new"); 10082 pkgSetting = null; 10083 } 10084 final PackageSetting oldPkgSetting = 10085 pkgSetting == null ? null : new PackageSetting(pkgSetting); 10086 final PackageSetting disabledPkgSetting = 10087 mSettings.getDisabledSystemPkgLPr(pkg.packageName); 10088 10089 String[] usesStaticLibraries = null; 10090 if (pkg.usesStaticLibraries != null) { 10091 usesStaticLibraries = new String[pkg.usesStaticLibraries.size()]; 10092 pkg.usesStaticLibraries.toArray(usesStaticLibraries); 10093 } 10094 10095 if (pkgSetting == null) { 10096 final String parentPackageName = (pkg.parentPackage != null) 10097 ? pkg.parentPackage.packageName : null; 10098 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 10099 // REMOVE SharedUserSetting from method; update in a separate call 10100 pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage, 10101 disabledPkgSetting, realName, suid, destCodeFile, destResourceFile, 10102 pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi, 10103 pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode, 10104 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user, 10105 true /*allowInstall*/, instantApp, parentPackageName, 10106 pkg.getChildPackageNames(), UserManagerService.getInstance(), 10107 usesStaticLibraries, pkg.usesStaticLibrariesVersions); 10108 // SIDE EFFECTS; updates system state; move elsewhere 10109 if (origPackage != null) { 10110 mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name); 10111 } 10112 mSettings.addUserToSettingLPw(pkgSetting); 10113 } else { 10114 // REMOVE SharedUserSetting from method; update in a separate call. 10115 // 10116 // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi, 10117 // secondaryCpuAbi are not known at this point so we always update them 10118 // to null here, only to reset them at a later point. 10119 Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile, 10120 pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi, 10121 pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags, 10122 pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(), 10123 UserManagerService.getInstance(), usesStaticLibraries, 10124 pkg.usesStaticLibrariesVersions); 10125 } 10126 // SIDE EFFECTS; persists system state to files on disk; move elsewhere 10127 mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting); 10128 10129 // SIDE EFFECTS; modifies system state; move elsewhere 10130 if (pkgSetting.origPackage != null) { 10131 // If we are first transitioning from an original package, 10132 // fix up the new package's name now. We need to do this after 10133 // looking up the package under its new name, so getPackageLP 10134 // can take care of fiddling things correctly. 10135 pkg.setPackageName(origPackage.name); 10136 10137 // File a report about this. 10138 String msg = "New package " + pkgSetting.realName 10139 + " renamed to replace old package " + pkgSetting.name; 10140 reportSettingsProblem(Log.WARN, msg); 10141 10142 // Make a note of it. 10143 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 10144 mTransferedPackages.add(origPackage.name); 10145 } 10146 10147 // No longer need to retain this. 10148 pkgSetting.origPackage = null; 10149 } 10150 10151 // SIDE EFFECTS; modifies system state; move elsewhere 10152 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 10153 // Make a note of it. 10154 mTransferedPackages.add(pkg.packageName); 10155 } 10156 10157 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 10158 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 10159 } 10160 10161 if ((scanFlags & SCAN_BOOTING) == 0 10162 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 10163 // Check all shared libraries and map to their actual file path. 10164 // We only do this here for apps not on a system dir, because those 10165 // are the only ones that can fail an install due to this. We 10166 // will take care of the system apps by updating all of their 10167 // library paths after the scan is done. Also during the initial 10168 // scan don't update any libs as we do this wholesale after all 10169 // apps are scanned to avoid dependency based scanning. 10170 updateSharedLibrariesLPr(pkg, null); 10171 } 10172 10173 if (mFoundPolicyFile) { 10174 SELinuxMMAC.assignSeInfoValue(pkg); 10175 } 10176 pkg.applicationInfo.uid = pkgSetting.appId; 10177 pkg.mExtras = pkgSetting; 10178 10179 10180 // Static shared libs have same package with different versions where 10181 // we internally use a synthetic package name to allow multiple versions 10182 // of the same package, therefore we need to compare signatures against 10183 // the package setting for the latest library version. 10184 PackageSetting signatureCheckPs = pkgSetting; 10185 if (pkg.applicationInfo.isStaticSharedLibrary()) { 10186 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg); 10187 if (libraryEntry != null) { 10188 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk); 10189 } 10190 } 10191 10192 if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) { 10193 if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) { 10194 // We just determined the app is signed correctly, so bring 10195 // over the latest parsed certs. 10196 pkgSetting.signatures.mSignatures = pkg.mSignatures; 10197 } else { 10198 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 10199 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 10200 "Package " + pkg.packageName + " upgrade keys do not match the " 10201 + "previously installed version"); 10202 } else { 10203 pkgSetting.signatures.mSignatures = pkg.mSignatures; 10204 String msg = "System package " + pkg.packageName 10205 + " signature changed; retaining data."; 10206 reportSettingsProblem(Log.WARN, msg); 10207 } 10208 } 10209 } else { 10210 try { 10211 // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService 10212 verifySignaturesLP(signatureCheckPs, pkg); 10213 // We just determined the app is signed correctly, so bring 10214 // over the latest parsed certs. 10215 pkgSetting.signatures.mSignatures = pkg.mSignatures; 10216 } catch (PackageManagerException e) { 10217 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 10218 throw e; 10219 } 10220 // The signature has changed, but this package is in the system 10221 // image... let's recover! 10222 pkgSetting.signatures.mSignatures = pkg.mSignatures; 10223 // However... if this package is part of a shared user, but it 10224 // doesn't match the signature of the shared user, let's fail. 10225 // What this means is that you can't change the signatures 10226 // associated with an overall shared user, which doesn't seem all 10227 // that unreasonable. 10228 if (signatureCheckPs.sharedUser != null) { 10229 if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures, 10230 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 10231 throw new PackageManagerException( 10232 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 10233 "Signature mismatch for shared user: " 10234 + pkgSetting.sharedUser); 10235 } 10236 } 10237 // File a report about this. 10238 String msg = "System package " + pkg.packageName 10239 + " signature changed; retaining data."; 10240 reportSettingsProblem(Log.WARN, msg); 10241 } 10242 } 10243 10244 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 10245 // This package wants to adopt ownership of permissions from 10246 // another package. 10247 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 10248 final String origName = pkg.mAdoptPermissions.get(i); 10249 final PackageSetting orig = mSettings.getPackageLPr(origName); 10250 if (orig != null) { 10251 if (verifyPackageUpdateLPr(orig, pkg)) { 10252 Slog.i(TAG, "Adopting permissions from " + origName + " to " 10253 + pkg.packageName); 10254 // SIDE EFFECTS; updates permissions system state; move elsewhere 10255 mSettings.transferPermissionsLPw(origName, pkg.packageName); 10256 } 10257 } 10258 } 10259 } 10260 } 10261 10262 pkg.applicationInfo.processName = fixProcessName( 10263 pkg.applicationInfo.packageName, 10264 pkg.applicationInfo.processName); 10265 10266 if (pkg != mPlatformPackage) { 10267 // Get all of our default paths setup 10268 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 10269 } 10270 10271 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 10272 10273 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 10274 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) { 10275 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi"); 10276 derivePackageAbi( 10277 pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir); 10278 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10279 10280 // Some system apps still use directory structure for native libraries 10281 // in which case we might end up not detecting abi solely based on apk 10282 // structure. Try to detect abi based on directory structure. 10283 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 10284 pkg.applicationInfo.primaryCpuAbi == null) { 10285 setBundledAppAbisAndRoots(pkg, pkgSetting); 10286 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 10287 } 10288 } else { 10289 // This is not a first boot or an upgrade, don't bother deriving the 10290 // ABI during the scan. Instead, trust the value that was stored in the 10291 // package setting. 10292 pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings; 10293 pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings; 10294 10295 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 10296 10297 if (DEBUG_ABI_SELECTION) { 10298 Slog.i(TAG, "Using ABIS and native lib paths from settings : " + 10299 pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " + 10300 pkg.applicationInfo.secondaryCpuAbi); 10301 } 10302 } 10303 } else { 10304 if ((scanFlags & SCAN_MOVE) != 0) { 10305 // We haven't run dex-opt for this move (since we've moved the compiled output too) 10306 // but we already have this packages package info in the PackageSetting. We just 10307 // use that and derive the native library path based on the new codepath. 10308 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 10309 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 10310 } 10311 10312 // Set native library paths again. For moves, the path will be updated based on the 10313 // ABIs we've determined above. For non-moves, the path will be updated based on the 10314 // ABIs we determined during compilation, but the path will depend on the final 10315 // package path (after the rename away from the stage path). 10316 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 10317 } 10318 10319 // This is a special case for the "system" package, where the ABI is 10320 // dictated by the zygote configuration (and init.rc). We should keep track 10321 // of this ABI so that we can deal with "normal" applications that run under 10322 // the same UID correctly. 10323 if (mPlatformPackage == pkg) { 10324 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 10325 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 10326 } 10327 10328 // If there's a mismatch between the abi-override in the package setting 10329 // and the abiOverride specified for the install. Warn about this because we 10330 // would've already compiled the app without taking the package setting into 10331 // account. 10332 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 10333 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 10334 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 10335 " for package " + pkg.packageName); 10336 } 10337 } 10338 10339 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 10340 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 10341 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 10342 10343 // Copy the derived override back to the parsed package, so that we can 10344 // update the package settings accordingly. 10345 pkg.cpuAbiOverride = cpuAbiOverride; 10346 10347 if (DEBUG_ABI_SELECTION) { 10348 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 10349 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 10350 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 10351 } 10352 10353 // Push the derived path down into PackageSettings so we know what to 10354 // clean up at uninstall time. 10355 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 10356 10357 if (DEBUG_ABI_SELECTION) { 10358 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 10359 " primary=" + pkg.applicationInfo.primaryCpuAbi + 10360 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 10361 } 10362 10363 // SIDE EFFECTS; removes DEX files from disk; move elsewhere 10364 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 10365 // We don't do this here during boot because we can do it all 10366 // at once after scanning all existing packages. 10367 // 10368 // We also do this *before* we perform dexopt on this package, so that 10369 // we can avoid redundant dexopts, and also to make sure we've got the 10370 // code and package path correct. 10371 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg); 10372 } 10373 10374 if (mFactoryTest && pkg.requestedPermissions.contains( 10375 android.Manifest.permission.FACTORY_TEST)) { 10376 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 10377 } 10378 10379 if (isSystemApp(pkg)) { 10380 pkgSetting.isOrphaned = true; 10381 } 10382 10383 // Take care of first install / last update times. 10384 final long scanFileTime = getLastModifiedTime(pkg, scanFile); 10385 if (currentTime != 0) { 10386 if (pkgSetting.firstInstallTime == 0) { 10387 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 10388 } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) { 10389 pkgSetting.lastUpdateTime = currentTime; 10390 } 10391 } else if (pkgSetting.firstInstallTime == 0) { 10392 // We need *something*. Take time time stamp of the file. 10393 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 10394 } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 10395 if (scanFileTime != pkgSetting.timeStamp) { 10396 // A package on the system image has changed; consider this 10397 // to be an update. 10398 pkgSetting.lastUpdateTime = scanFileTime; 10399 } 10400 } 10401 pkgSetting.setTimeStamp(scanFileTime); 10402 10403 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 10404 if (nonMutatedPs != null) { 10405 synchronized (mPackages) { 10406 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 10407 } 10408 } 10409 } else { 10410 final int userId = user == null ? 0 : user.getIdentifier(); 10411 // Modify state for the given package setting 10412 commitPackageSettings(pkg, pkgSetting, user, scanFlags, 10413 (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/); 10414 if (pkgSetting.getInstantApp(userId)) { 10415 mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId); 10416 } 10417 } 10418 return pkg; 10419 } 10420 10421 /** 10422 * Applies policy to the parsed package based upon the given policy flags. 10423 * Ensures the package is in a good state. 10424 * <p> 10425 * Implementation detail: This method must NOT have any side effect. It would 10426 * ideally be static, but, it requires locks to read system state. 10427 */ 10428 private void applyPolicy(PackageParser.Package pkg, int policyFlags) { 10429 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 10430 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 10431 if (pkg.applicationInfo.isDirectBootAware()) { 10432 // we're direct boot aware; set for all components 10433 for (PackageParser.Service s : pkg.services) { 10434 s.info.encryptionAware = s.info.directBootAware = true; 10435 } 10436 for (PackageParser.Provider p : pkg.providers) { 10437 p.info.encryptionAware = p.info.directBootAware = true; 10438 } 10439 for (PackageParser.Activity a : pkg.activities) { 10440 a.info.encryptionAware = a.info.directBootAware = true; 10441 } 10442 for (PackageParser.Activity r : pkg.receivers) { 10443 r.info.encryptionAware = r.info.directBootAware = true; 10444 } 10445 } 10446 } else { 10447 // Only allow system apps to be flagged as core apps. 10448 pkg.coreApp = false; 10449 // clear flags not applicable to regular apps 10450 pkg.applicationInfo.privateFlags &= 10451 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 10452 pkg.applicationInfo.privateFlags &= 10453 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 10454 } 10455 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 10456 10457 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 10458 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 10459 } 10460 10461 if (!isSystemApp(pkg)) { 10462 // Only system apps can use these features. 10463 pkg.mOriginalPackages = null; 10464 pkg.mRealPackage = null; 10465 pkg.mAdoptPermissions = null; 10466 } 10467 } 10468 10469 /** 10470 * Asserts the parsed package is valid according to the given policy. If the 10471 * package is invalid, for whatever reason, throws {@link PackageManagerException}. 10472 * <p> 10473 * Implementation detail: This method must NOT have any side effects. It would 10474 * ideally be static, but, it requires locks to read system state. 10475 * 10476 * @throws PackageManagerException If the package fails any of the validation checks 10477 */ 10478 private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags) 10479 throws PackageManagerException { 10480 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 10481 assertCodePolicy(pkg); 10482 } 10483 10484 if (pkg.applicationInfo.getCodePath() == null || 10485 pkg.applicationInfo.getResourcePath() == null) { 10486 // Bail out. The resource and code paths haven't been set. 10487 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 10488 "Code and resource paths haven't been set correctly"); 10489 } 10490 10491 // Make sure we're not adding any bogus keyset info 10492 KeySetManagerService ksms = mSettings.mKeySetManagerService; 10493 ksms.assertScannedPackageValid(pkg); 10494 10495 synchronized (mPackages) { 10496 // The special "android" package can only be defined once 10497 if (pkg.packageName.equals("android")) { 10498 if (mAndroidApplication != null) { 10499 Slog.w(TAG, "*************************************************"); 10500 Slog.w(TAG, "Core android package being redefined. Skipping."); 10501 Slog.w(TAG, " codePath=" + pkg.codePath); 10502 Slog.w(TAG, "*************************************************"); 10503 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 10504 "Core android package being redefined. Skipping."); 10505 } 10506 } 10507 10508 // A package name must be unique; don't allow duplicates 10509 if (mPackages.containsKey(pkg.packageName)) { 10510 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 10511 "Application package " + pkg.packageName 10512 + " already installed. Skipping duplicate."); 10513 } 10514 10515 if (pkg.applicationInfo.isStaticSharedLibrary()) { 10516 // Static libs have a synthetic package name containing the version 10517 // but we still want the base name to be unique. 10518 if (mPackages.containsKey(pkg.manifestPackageName)) { 10519 throw new PackageManagerException( 10520 "Duplicate static shared lib provider package"); 10521 } 10522 10523 // Static shared libraries should have at least O target SDK 10524 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) { 10525 throw new PackageManagerException( 10526 "Packages declaring static-shared libs must target O SDK or higher"); 10527 } 10528 10529 // Package declaring static a shared lib cannot be instant apps 10530 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 10531 throw new PackageManagerException( 10532 "Packages declaring static-shared libs cannot be instant apps"); 10533 } 10534 10535 // Package declaring static a shared lib cannot be renamed since the package 10536 // name is synthetic and apps can't code around package manager internals. 10537 if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) { 10538 throw new PackageManagerException( 10539 "Packages declaring static-shared libs cannot be renamed"); 10540 } 10541 10542 // Package declaring static a shared lib cannot declare child packages 10543 if (!ArrayUtils.isEmpty(pkg.childPackages)) { 10544 throw new PackageManagerException( 10545 "Packages declaring static-shared libs cannot have child packages"); 10546 } 10547 10548 // Package declaring static a shared lib cannot declare dynamic libs 10549 if (!ArrayUtils.isEmpty(pkg.libraryNames)) { 10550 throw new PackageManagerException( 10551 "Packages declaring static-shared libs cannot declare dynamic libs"); 10552 } 10553 10554 // Package declaring static a shared lib cannot declare shared users 10555 if (pkg.mSharedUserId != null) { 10556 throw new PackageManagerException( 10557 "Packages declaring static-shared libs cannot declare shared users"); 10558 } 10559 10560 // Static shared libs cannot declare activities 10561 if (!pkg.activities.isEmpty()) { 10562 throw new PackageManagerException( 10563 "Static shared libs cannot declare activities"); 10564 } 10565 10566 // Static shared libs cannot declare services 10567 if (!pkg.services.isEmpty()) { 10568 throw new PackageManagerException( 10569 "Static shared libs cannot declare services"); 10570 } 10571 10572 // Static shared libs cannot declare providers 10573 if (!pkg.providers.isEmpty()) { 10574 throw new PackageManagerException( 10575 "Static shared libs cannot declare content providers"); 10576 } 10577 10578 // Static shared libs cannot declare receivers 10579 if (!pkg.receivers.isEmpty()) { 10580 throw new PackageManagerException( 10581 "Static shared libs cannot declare broadcast receivers"); 10582 } 10583 10584 // Static shared libs cannot declare permission groups 10585 if (!pkg.permissionGroups.isEmpty()) { 10586 throw new PackageManagerException( 10587 "Static shared libs cannot declare permission groups"); 10588 } 10589 10590 // Static shared libs cannot declare permissions 10591 if (!pkg.permissions.isEmpty()) { 10592 throw new PackageManagerException( 10593 "Static shared libs cannot declare permissions"); 10594 } 10595 10596 // Static shared libs cannot declare protected broadcasts 10597 if (pkg.protectedBroadcasts != null) { 10598 throw new PackageManagerException( 10599 "Static shared libs cannot declare protected broadcasts"); 10600 } 10601 10602 // Static shared libs cannot be overlay targets 10603 if (pkg.mOverlayTarget != null) { 10604 throw new PackageManagerException( 10605 "Static shared libs cannot be overlay targets"); 10606 } 10607 10608 // The version codes must be ordered as lib versions 10609 int minVersionCode = Integer.MIN_VALUE; 10610 int maxVersionCode = Integer.MAX_VALUE; 10611 10612 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get( 10613 pkg.staticSharedLibName); 10614 if (versionedLib != null) { 10615 final int versionCount = versionedLib.size(); 10616 for (int i = 0; i < versionCount; i++) { 10617 SharedLibraryInfo libInfo = versionedLib.valueAt(i).info; 10618 // TODO: We will change version code to long, so in the new API it is long 10619 final int libVersionCode = (int) libInfo.getDeclaringPackage() 10620 .getVersionCode(); 10621 if (libInfo.getVersion() < pkg.staticSharedLibVersion) { 10622 minVersionCode = Math.max(minVersionCode, libVersionCode + 1); 10623 } else if (libInfo.getVersion() > pkg.staticSharedLibVersion) { 10624 maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1); 10625 } else { 10626 minVersionCode = maxVersionCode = libVersionCode; 10627 break; 10628 } 10629 } 10630 } 10631 if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) { 10632 throw new PackageManagerException("Static shared" 10633 + " lib version codes must be ordered as lib versions"); 10634 } 10635 } 10636 10637 // Only privileged apps and updated privileged apps can add child packages. 10638 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 10639 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 10640 throw new PackageManagerException("Only privileged apps can add child " 10641 + "packages. Ignoring package " + pkg.packageName); 10642 } 10643 final int childCount = pkg.childPackages.size(); 10644 for (int i = 0; i < childCount; i++) { 10645 PackageParser.Package childPkg = pkg.childPackages.get(i); 10646 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 10647 childPkg.packageName)) { 10648 throw new PackageManagerException("Can't override child of " 10649 + "another disabled app. Ignoring package " + pkg.packageName); 10650 } 10651 } 10652 } 10653 10654 // If we're only installing presumed-existing packages, require that the 10655 // scanned APK is both already known and at the path previously established 10656 // for it. Previously unknown packages we pick up normally, but if we have an 10657 // a priori expectation about this package's install presence, enforce it. 10658 // With a singular exception for new system packages. When an OTA contains 10659 // a new system package, we allow the codepath to change from a system location 10660 // to the user-installed location. If we don't allow this change, any newer, 10661 // user-installed version of the application will be ignored. 10662 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 10663 if (mExpectingBetter.containsKey(pkg.packageName)) { 10664 logCriticalInfo(Log.WARN, 10665 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 10666 } else { 10667 PackageSetting known = mSettings.getPackageLPr(pkg.packageName); 10668 if (known != null) { 10669 if (DEBUG_PACKAGE_SCANNING) { 10670 Log.d(TAG, "Examining " + pkg.codePath 10671 + " and requiring known paths " + known.codePathString 10672 + " & " + known.resourcePathString); 10673 } 10674 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 10675 || !pkg.applicationInfo.getResourcePath().equals( 10676 known.resourcePathString)) { 10677 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 10678 "Application package " + pkg.packageName 10679 + " found at " + pkg.applicationInfo.getCodePath() 10680 + " but expected at " + known.codePathString 10681 + "; ignoring."); 10682 } 10683 } 10684 } 10685 } 10686 10687 // Verify that this new package doesn't have any content providers 10688 // that conflict with existing packages. Only do this if the 10689 // package isn't already installed, since we don't want to break 10690 // things that are installed. 10691 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 10692 final int N = pkg.providers.size(); 10693 int i; 10694 for (i=0; i<N; i++) { 10695 PackageParser.Provider p = pkg.providers.get(i); 10696 if (p.info.authority != null) { 10697 String names[] = p.info.authority.split(";"); 10698 for (int j = 0; j < names.length; j++) { 10699 if (mProvidersByAuthority.containsKey(names[j])) { 10700 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 10701 final String otherPackageName = 10702 ((other != null && other.getComponentName() != null) ? 10703 other.getComponentName().getPackageName() : "?"); 10704 throw new PackageManagerException( 10705 INSTALL_FAILED_CONFLICTING_PROVIDER, 10706 "Can't install because provider name " + names[j] 10707 + " (in package " + pkg.applicationInfo.packageName 10708 + ") is already used by " + otherPackageName); 10709 } 10710 } 10711 } 10712 } 10713 } 10714 } 10715 } 10716 10717 private boolean addSharedLibraryLPw(String path, String apk, String name, int version, 10718 int type, String declaringPackageName, int declaringVersionCode) { 10719 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 10720 if (versionedLib == null) { 10721 versionedLib = new SparseArray<>(); 10722 mSharedLibraries.put(name, versionedLib); 10723 if (type == SharedLibraryInfo.TYPE_STATIC) { 10724 mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib); 10725 } 10726 } else if (versionedLib.indexOfKey(version) >= 0) { 10727 return false; 10728 } 10729 SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name, 10730 version, type, declaringPackageName, declaringVersionCode); 10731 versionedLib.put(version, libEntry); 10732 return true; 10733 } 10734 10735 private boolean removeSharedLibraryLPw(String name, int version) { 10736 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 10737 if (versionedLib == null) { 10738 return false; 10739 } 10740 final int libIdx = versionedLib.indexOfKey(version); 10741 if (libIdx < 0) { 10742 return false; 10743 } 10744 SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx); 10745 versionedLib.remove(version); 10746 if (versionedLib.size() <= 0) { 10747 mSharedLibraries.remove(name); 10748 if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) { 10749 mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage() 10750 .getPackageName()); 10751 } 10752 } 10753 return true; 10754 } 10755 10756 /** 10757 * Adds a scanned package to the system. When this method is finished, the package will 10758 * be available for query, resolution, etc... 10759 */ 10760 private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting, 10761 UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException { 10762 final String pkgName = pkg.packageName; 10763 if (mCustomResolverComponentName != null && 10764 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 10765 setUpCustomResolverActivity(pkg); 10766 } 10767 10768 if (pkg.packageName.equals("android")) { 10769 synchronized (mPackages) { 10770 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 10771 // Set up information for our fall-back user intent resolution activity. 10772 mPlatformPackage = pkg; 10773 pkg.mVersionCode = mSdkVersion; 10774 mAndroidApplication = pkg.applicationInfo; 10775 if (!mResolverReplaced) { 10776 mResolveActivity.applicationInfo = mAndroidApplication; 10777 mResolveActivity.name = ResolverActivity.class.getName(); 10778 mResolveActivity.packageName = mAndroidApplication.packageName; 10779 mResolveActivity.processName = "system:ui"; 10780 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 10781 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 10782 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 10783 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 10784 mResolveActivity.exported = true; 10785 mResolveActivity.enabled = true; 10786 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 10787 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 10788 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 10789 | ActivityInfo.CONFIG_SCREEN_LAYOUT 10790 | ActivityInfo.CONFIG_ORIENTATION 10791 | ActivityInfo.CONFIG_KEYBOARD 10792 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 10793 mResolveInfo.activityInfo = mResolveActivity; 10794 mResolveInfo.priority = 0; 10795 mResolveInfo.preferredOrder = 0; 10796 mResolveInfo.match = 0; 10797 mResolveComponentName = new ComponentName( 10798 mAndroidApplication.packageName, mResolveActivity.name); 10799 } 10800 } 10801 } 10802 } 10803 10804 ArrayList<PackageParser.Package> clientLibPkgs = null; 10805 // writer 10806 synchronized (mPackages) { 10807 boolean hasStaticSharedLibs = false; 10808 10809 // Any app can add new static shared libraries 10810 if (pkg.staticSharedLibName != null) { 10811 // Static shared libs don't allow renaming as they have synthetic package 10812 // names to allow install of multiple versions, so use name from manifest. 10813 if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName, 10814 pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC, 10815 pkg.manifestPackageName, pkg.mVersionCode)) { 10816 hasStaticSharedLibs = true; 10817 } else { 10818 Slog.w(TAG, "Package " + pkg.packageName + " library " 10819 + pkg.staticSharedLibName + " already exists; skipping"); 10820 } 10821 // Static shared libs cannot be updated once installed since they 10822 // use synthetic package name which includes the version code, so 10823 // not need to update other packages's shared lib dependencies. 10824 } 10825 10826 if (!hasStaticSharedLibs 10827 && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 10828 // Only system apps can add new dynamic shared libraries. 10829 if (pkg.libraryNames != null) { 10830 for (int i = 0; i < pkg.libraryNames.size(); i++) { 10831 String name = pkg.libraryNames.get(i); 10832 boolean allowed = false; 10833 if (pkg.isUpdatedSystemApp()) { 10834 // New library entries can only be added through the 10835 // system image. This is important to get rid of a lot 10836 // of nasty edge cases: for example if we allowed a non- 10837 // system update of the app to add a library, then uninstalling 10838 // the update would make the library go away, and assumptions 10839 // we made such as through app install filtering would now 10840 // have allowed apps on the device which aren't compatible 10841 // with it. Better to just have the restriction here, be 10842 // conservative, and create many fewer cases that can negatively 10843 // impact the user experience. 10844 final PackageSetting sysPs = mSettings 10845 .getDisabledSystemPkgLPr(pkg.packageName); 10846 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 10847 for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) { 10848 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 10849 allowed = true; 10850 break; 10851 } 10852 } 10853 } 10854 } else { 10855 allowed = true; 10856 } 10857 if (allowed) { 10858 if (!addSharedLibraryLPw(null, pkg.packageName, name, 10859 SharedLibraryInfo.VERSION_UNDEFINED, 10860 SharedLibraryInfo.TYPE_DYNAMIC, 10861 pkg.packageName, pkg.mVersionCode)) { 10862 Slog.w(TAG, "Package " + pkg.packageName + " library " 10863 + name + " already exists; skipping"); 10864 } 10865 } else { 10866 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 10867 + name + " that is not declared on system image; skipping"); 10868 } 10869 } 10870 10871 if ((scanFlags & SCAN_BOOTING) == 0) { 10872 // If we are not booting, we need to update any applications 10873 // that are clients of our shared library. If we are booting, 10874 // this will all be done once the scan is complete. 10875 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 10876 } 10877 } 10878 } 10879 } 10880 10881 if ((scanFlags & SCAN_BOOTING) != 0) { 10882 // No apps can run during boot scan, so they don't need to be frozen 10883 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 10884 // Caller asked to not kill app, so it's probably not frozen 10885 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 10886 // Caller asked us to ignore frozen check for some reason; they 10887 // probably didn't know the package name 10888 } else { 10889 // We're doing major surgery on this package, so it better be frozen 10890 // right now to keep it from launching 10891 checkPackageFrozen(pkgName); 10892 } 10893 10894 // Also need to kill any apps that are dependent on the library. 10895 if (clientLibPkgs != null) { 10896 for (int i=0; i<clientLibPkgs.size(); i++) { 10897 PackageParser.Package clientPkg = clientLibPkgs.get(i); 10898 killApplication(clientPkg.applicationInfo.packageName, 10899 clientPkg.applicationInfo.uid, "update lib"); 10900 } 10901 } 10902 10903 // writer 10904 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 10905 10906 synchronized (mPackages) { 10907 // We don't expect installation to fail beyond this point 10908 10909 // Add the new setting to mSettings 10910 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 10911 // Add the new setting to mPackages 10912 mPackages.put(pkg.applicationInfo.packageName, pkg); 10913 // Make sure we don't accidentally delete its data. 10914 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 10915 while (iter.hasNext()) { 10916 PackageCleanItem item = iter.next(); 10917 if (pkgName.equals(item.packageName)) { 10918 iter.remove(); 10919 } 10920 } 10921 10922 // Add the package's KeySets to the global KeySetManagerService 10923 KeySetManagerService ksms = mSettings.mKeySetManagerService; 10924 ksms.addScannedPackageLPw(pkg); 10925 10926 int N = pkg.providers.size(); 10927 StringBuilder r = null; 10928 int i; 10929 for (i=0; i<N; i++) { 10930 PackageParser.Provider p = pkg.providers.get(i); 10931 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 10932 p.info.processName); 10933 mProviders.addProvider(p); 10934 p.syncable = p.info.isSyncable; 10935 if (p.info.authority != null) { 10936 String names[] = p.info.authority.split(";"); 10937 p.info.authority = null; 10938 for (int j = 0; j < names.length; j++) { 10939 if (j == 1 && p.syncable) { 10940 // We only want the first authority for a provider to possibly be 10941 // syncable, so if we already added this provider using a different 10942 // authority clear the syncable flag. We copy the provider before 10943 // changing it because the mProviders object contains a reference 10944 // to a provider that we don't want to change. 10945 // Only do this for the second authority since the resulting provider 10946 // object can be the same for all future authorities for this provider. 10947 p = new PackageParser.Provider(p); 10948 p.syncable = false; 10949 } 10950 if (!mProvidersByAuthority.containsKey(names[j])) { 10951 mProvidersByAuthority.put(names[j], p); 10952 if (p.info.authority == null) { 10953 p.info.authority = names[j]; 10954 } else { 10955 p.info.authority = p.info.authority + ";" + names[j]; 10956 } 10957 if (DEBUG_PACKAGE_SCANNING) { 10958 if (chatty) 10959 Log.d(TAG, "Registered content provider: " + names[j] 10960 + ", className = " + p.info.name + ", isSyncable = " 10961 + p.info.isSyncable); 10962 } 10963 } else { 10964 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 10965 Slog.w(TAG, "Skipping provider name " + names[j] + 10966 " (in package " + pkg.applicationInfo.packageName + 10967 "): name already used by " 10968 + ((other != null && other.getComponentName() != null) 10969 ? other.getComponentName().getPackageName() : "?")); 10970 } 10971 } 10972 } 10973 if (chatty) { 10974 if (r == null) { 10975 r = new StringBuilder(256); 10976 } else { 10977 r.append(' '); 10978 } 10979 r.append(p.info.name); 10980 } 10981 } 10982 if (r != null) { 10983 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 10984 } 10985 10986 N = pkg.services.size(); 10987 r = null; 10988 for (i=0; i<N; i++) { 10989 PackageParser.Service s = pkg.services.get(i); 10990 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 10991 s.info.processName); 10992 mServices.addService(s); 10993 if (chatty) { 10994 if (r == null) { 10995 r = new StringBuilder(256); 10996 } else { 10997 r.append(' '); 10998 } 10999 r.append(s.info.name); 11000 } 11001 } 11002 if (r != null) { 11003 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 11004 } 11005 11006 N = pkg.receivers.size(); 11007 r = null; 11008 for (i=0; i<N; i++) { 11009 PackageParser.Activity a = pkg.receivers.get(i); 11010 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 11011 a.info.processName); 11012 mReceivers.addActivity(a, "receiver"); 11013 if (chatty) { 11014 if (r == null) { 11015 r = new StringBuilder(256); 11016 } else { 11017 r.append(' '); 11018 } 11019 r.append(a.info.name); 11020 } 11021 } 11022 if (r != null) { 11023 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 11024 } 11025 11026 N = pkg.activities.size(); 11027 r = null; 11028 for (i=0; i<N; i++) { 11029 PackageParser.Activity a = pkg.activities.get(i); 11030 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 11031 a.info.processName); 11032 mActivities.addActivity(a, "activity"); 11033 if (chatty) { 11034 if (r == null) { 11035 r = new StringBuilder(256); 11036 } else { 11037 r.append(' '); 11038 } 11039 r.append(a.info.name); 11040 } 11041 } 11042 if (r != null) { 11043 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 11044 } 11045 11046 N = pkg.permissionGroups.size(); 11047 r = null; 11048 for (i=0; i<N; i++) { 11049 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 11050 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 11051 final String curPackageName = cur == null ? null : cur.info.packageName; 11052 // Dont allow ephemeral apps to define new permission groups. 11053 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 11054 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 11055 + pg.info.packageName 11056 + " ignored: instant apps cannot define new permission groups."); 11057 continue; 11058 } 11059 final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName); 11060 if (cur == null || isPackageUpdate) { 11061 mPermissionGroups.put(pg.info.name, pg); 11062 if (chatty) { 11063 if (r == null) { 11064 r = new StringBuilder(256); 11065 } else { 11066 r.append(' '); 11067 } 11068 if (isPackageUpdate) { 11069 r.append("UPD:"); 11070 } 11071 r.append(pg.info.name); 11072 } 11073 } else { 11074 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 11075 + pg.info.packageName + " ignored: original from " 11076 + cur.info.packageName); 11077 if (chatty) { 11078 if (r == null) { 11079 r = new StringBuilder(256); 11080 } else { 11081 r.append(' '); 11082 } 11083 r.append("DUP:"); 11084 r.append(pg.info.name); 11085 } 11086 } 11087 } 11088 if (r != null) { 11089 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 11090 } 11091 11092 N = pkg.permissions.size(); 11093 r = null; 11094 for (i=0; i<N; i++) { 11095 PackageParser.Permission p = pkg.permissions.get(i); 11096 11097 // Dont allow ephemeral apps to define new permissions. 11098 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 11099 Slog.w(TAG, "Permission " + p.info.name + " from package " 11100 + p.info.packageName 11101 + " ignored: instant apps cannot define new permissions."); 11102 continue; 11103 } 11104 11105 // Assume by default that we did not install this permission into the system. 11106 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 11107 11108 // Now that permission groups have a special meaning, we ignore permission 11109 // groups for legacy apps to prevent unexpected behavior. In particular, 11110 // permissions for one app being granted to someone just because they happen 11111 // to be in a group defined by another app (before this had no implications). 11112 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 11113 p.group = mPermissionGroups.get(p.info.group); 11114 // Warn for a permission in an unknown group. 11115 if (DEBUG_PERMISSIONS && p.info.group != null && p.group == null) { 11116 Slog.i(TAG, "Permission " + p.info.name + " from package " 11117 + p.info.packageName + " in an unknown group " + p.info.group); 11118 } 11119 } 11120 11121 ArrayMap<String, BasePermission> permissionMap = 11122 p.tree ? mSettings.mPermissionTrees 11123 : mSettings.mPermissions; 11124 BasePermission bp = permissionMap.get(p.info.name); 11125 11126 // Allow system apps to redefine non-system permissions 11127 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 11128 final boolean currentOwnerIsSystem = (bp.perm != null 11129 && isSystemApp(bp.perm.owner)); 11130 if (isSystemApp(p.owner)) { 11131 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 11132 // It's a built-in permission and no owner, take ownership now 11133 bp.packageSetting = pkgSetting; 11134 bp.perm = p; 11135 bp.uid = pkg.applicationInfo.uid; 11136 bp.sourcePackage = p.info.packageName; 11137 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 11138 } else if (!currentOwnerIsSystem) { 11139 String msg = "New decl " + p.owner + " of permission " 11140 + p.info.name + " is system; overriding " + bp.sourcePackage; 11141 reportSettingsProblem(Log.WARN, msg); 11142 bp = null; 11143 } 11144 } 11145 } 11146 11147 if (bp == null) { 11148 bp = new BasePermission(p.info.name, p.info.packageName, 11149 BasePermission.TYPE_NORMAL); 11150 permissionMap.put(p.info.name, bp); 11151 } 11152 11153 if (bp.perm == null) { 11154 if (bp.sourcePackage == null 11155 || bp.sourcePackage.equals(p.info.packageName)) { 11156 BasePermission tree = findPermissionTreeLP(p.info.name); 11157 if (tree == null 11158 || tree.sourcePackage.equals(p.info.packageName)) { 11159 bp.packageSetting = pkgSetting; 11160 bp.perm = p; 11161 bp.uid = pkg.applicationInfo.uid; 11162 bp.sourcePackage = p.info.packageName; 11163 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 11164 if (chatty) { 11165 if (r == null) { 11166 r = new StringBuilder(256); 11167 } else { 11168 r.append(' '); 11169 } 11170 r.append(p.info.name); 11171 } 11172 } else { 11173 Slog.w(TAG, "Permission " + p.info.name + " from package " 11174 + p.info.packageName + " ignored: base tree " 11175 + tree.name + " is from package " 11176 + tree.sourcePackage); 11177 } 11178 } else { 11179 Slog.w(TAG, "Permission " + p.info.name + " from package " 11180 + p.info.packageName + " ignored: original from " 11181 + bp.sourcePackage); 11182 } 11183 } else if (chatty) { 11184 if (r == null) { 11185 r = new StringBuilder(256); 11186 } else { 11187 r.append(' '); 11188 } 11189 r.append("DUP:"); 11190 r.append(p.info.name); 11191 } 11192 if (bp.perm == p) { 11193 bp.protectionLevel = p.info.protectionLevel; 11194 } 11195 } 11196 11197 if (r != null) { 11198 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 11199 } 11200 11201 N = pkg.instrumentation.size(); 11202 r = null; 11203 for (i=0; i<N; i++) { 11204 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 11205 a.info.packageName = pkg.applicationInfo.packageName; 11206 a.info.sourceDir = pkg.applicationInfo.sourceDir; 11207 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 11208 a.info.splitNames = pkg.splitNames; 11209 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 11210 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 11211 a.info.splitDependencies = pkg.applicationInfo.splitDependencies; 11212 a.info.dataDir = pkg.applicationInfo.dataDir; 11213 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 11214 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 11215 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 11216 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 11217 mInstrumentation.put(a.getComponentName(), a); 11218 if (chatty) { 11219 if (r == null) { 11220 r = new StringBuilder(256); 11221 } else { 11222 r.append(' '); 11223 } 11224 r.append(a.info.name); 11225 } 11226 } 11227 if (r != null) { 11228 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 11229 } 11230 11231 if (pkg.protectedBroadcasts != null) { 11232 N = pkg.protectedBroadcasts.size(); 11233 for (i=0; i<N; i++) { 11234 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 11235 } 11236 } 11237 } 11238 11239 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11240 } 11241 11242 /** 11243 * Derive the ABI of a non-system package located at {@code scanFile}. This information 11244 * is derived purely on the basis of the contents of {@code scanFile} and 11245 * {@code cpuAbiOverride}. 11246 * 11247 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 11248 */ 11249 private static void derivePackageAbi(PackageParser.Package pkg, File scanFile, 11250 String cpuAbiOverride, boolean extractLibs, 11251 File appLib32InstallDir) 11252 throws PackageManagerException { 11253 // Give ourselves some initial paths; we'll come back for another 11254 // pass once we've determined ABI below. 11255 setNativeLibraryPaths(pkg, appLib32InstallDir); 11256 11257 // We would never need to extract libs for forward-locked and external packages, 11258 // since the container service will do it for us. We shouldn't attempt to 11259 // extract libs from system app when it was not updated. 11260 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 11261 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 11262 extractLibs = false; 11263 } 11264 11265 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 11266 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 11267 11268 NativeLibraryHelper.Handle handle = null; 11269 try { 11270 handle = NativeLibraryHelper.Handle.create(pkg); 11271 // TODO(multiArch): This can be null for apps that didn't go through the 11272 // usual installation process. We can calculate it again, like we 11273 // do during install time. 11274 // 11275 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 11276 // unnecessary. 11277 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 11278 11279 // Null out the abis so that they can be recalculated. 11280 pkg.applicationInfo.primaryCpuAbi = null; 11281 pkg.applicationInfo.secondaryCpuAbi = null; 11282 if (isMultiArch(pkg.applicationInfo)) { 11283 // Warn if we've set an abiOverride for multi-lib packages.. 11284 // By definition, we need to copy both 32 and 64 bit libraries for 11285 // such packages. 11286 if (pkg.cpuAbiOverride != null 11287 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 11288 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 11289 } 11290 11291 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 11292 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 11293 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 11294 if (extractLibs) { 11295 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 11296 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 11297 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 11298 useIsaSpecificSubdirs); 11299 } else { 11300 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 11301 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 11302 } 11303 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11304 } 11305 11306 maybeThrowExceptionForMultiArchCopy( 11307 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 11308 11309 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 11310 if (extractLibs) { 11311 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 11312 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 11313 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 11314 useIsaSpecificSubdirs); 11315 } else { 11316 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 11317 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 11318 } 11319 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11320 } 11321 11322 maybeThrowExceptionForMultiArchCopy( 11323 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 11324 11325 if (abi64 >= 0) { 11326 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 11327 } 11328 11329 if (abi32 >= 0) { 11330 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 11331 if (abi64 >= 0) { 11332 if (pkg.use32bitAbi) { 11333 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 11334 pkg.applicationInfo.primaryCpuAbi = abi; 11335 } else { 11336 pkg.applicationInfo.secondaryCpuAbi = abi; 11337 } 11338 } else { 11339 pkg.applicationInfo.primaryCpuAbi = abi; 11340 } 11341 } 11342 11343 } else { 11344 String[] abiList = (cpuAbiOverride != null) ? 11345 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 11346 11347 // Enable gross and lame hacks for apps that are built with old 11348 // SDK tools. We must scan their APKs for renderscript bitcode and 11349 // not launch them if it's present. Don't bother checking on devices 11350 // that don't have 64 bit support. 11351 boolean needsRenderScriptOverride = false; 11352 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 11353 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 11354 abiList = Build.SUPPORTED_32_BIT_ABIS; 11355 needsRenderScriptOverride = true; 11356 } 11357 11358 final int copyRet; 11359 if (extractLibs) { 11360 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 11361 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 11362 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 11363 } else { 11364 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 11365 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 11366 } 11367 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11368 11369 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 11370 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 11371 "Error unpackaging native libs for app, errorCode=" + copyRet); 11372 } 11373 11374 if (copyRet >= 0) { 11375 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 11376 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 11377 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 11378 } else if (needsRenderScriptOverride) { 11379 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 11380 } 11381 } 11382 } catch (IOException ioe) { 11383 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 11384 } finally { 11385 IoUtils.closeQuietly(handle); 11386 } 11387 11388 // Now that we've calculated the ABIs and determined if it's an internal app, 11389 // we will go ahead and populate the nativeLibraryPath. 11390 setNativeLibraryPaths(pkg, appLib32InstallDir); 11391 } 11392 11393 /** 11394 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 11395 * i.e, so that all packages can be run inside a single process if required. 11396 * 11397 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 11398 * this function will either try and make the ABI for all packages in {@code packagesForUser} 11399 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 11400 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 11401 * updating a package that belongs to a shared user. 11402 * 11403 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 11404 * adds unnecessary complexity. 11405 */ 11406 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 11407 PackageParser.Package scannedPackage) { 11408 String requiredInstructionSet = null; 11409 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 11410 requiredInstructionSet = VMRuntime.getInstructionSet( 11411 scannedPackage.applicationInfo.primaryCpuAbi); 11412 } 11413 11414 PackageSetting requirer = null; 11415 for (PackageSetting ps : packagesForUser) { 11416 // If packagesForUser contains scannedPackage, we skip it. This will happen 11417 // when scannedPackage is an update of an existing package. Without this check, 11418 // we will never be able to change the ABI of any package belonging to a shared 11419 // user, even if it's compatible with other packages. 11420 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 11421 if (ps.primaryCpuAbiString == null) { 11422 continue; 11423 } 11424 11425 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 11426 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 11427 // We have a mismatch between instruction sets (say arm vs arm64) warn about 11428 // this but there's not much we can do. 11429 String errorMessage = "Instruction set mismatch, " 11430 + ((requirer == null) ? "[caller]" : requirer) 11431 + " requires " + requiredInstructionSet + " whereas " + ps 11432 + " requires " + instructionSet; 11433 Slog.w(TAG, errorMessage); 11434 } 11435 11436 if (requiredInstructionSet == null) { 11437 requiredInstructionSet = instructionSet; 11438 requirer = ps; 11439 } 11440 } 11441 } 11442 11443 if (requiredInstructionSet != null) { 11444 String adjustedAbi; 11445 if (requirer != null) { 11446 // requirer != null implies that either scannedPackage was null or that scannedPackage 11447 // did not require an ABI, in which case we have to adjust scannedPackage to match 11448 // the ABI of the set (which is the same as requirer's ABI) 11449 adjustedAbi = requirer.primaryCpuAbiString; 11450 if (scannedPackage != null) { 11451 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 11452 } 11453 } else { 11454 // requirer == null implies that we're updating all ABIs in the set to 11455 // match scannedPackage. 11456 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 11457 } 11458 11459 for (PackageSetting ps : packagesForUser) { 11460 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 11461 if (ps.primaryCpuAbiString != null) { 11462 continue; 11463 } 11464 11465 ps.primaryCpuAbiString = adjustedAbi; 11466 if (ps.pkg != null && ps.pkg.applicationInfo != null && 11467 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 11468 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 11469 if (DEBUG_ABI_SELECTION) { 11470 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 11471 + " (requirer=" 11472 + (requirer != null ? requirer.pkg : "null") 11473 + ", scannedPackage=" 11474 + (scannedPackage != null ? scannedPackage : "null") 11475 + ")"); 11476 } 11477 try { 11478 mInstaller.rmdex(ps.codePathString, 11479 getDexCodeInstructionSet(getPreferredInstructionSet())); 11480 } catch (InstallerException ignored) { 11481 } 11482 } 11483 } 11484 } 11485 } 11486 } 11487 11488 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 11489 synchronized (mPackages) { 11490 mResolverReplaced = true; 11491 // Set up information for custom user intent resolution activity. 11492 mResolveActivity.applicationInfo = pkg.applicationInfo; 11493 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 11494 mResolveActivity.packageName = pkg.applicationInfo.packageName; 11495 mResolveActivity.processName = pkg.applicationInfo.packageName; 11496 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 11497 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 11498 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 11499 mResolveActivity.theme = 0; 11500 mResolveActivity.exported = true; 11501 mResolveActivity.enabled = true; 11502 mResolveInfo.activityInfo = mResolveActivity; 11503 mResolveInfo.priority = 0; 11504 mResolveInfo.preferredOrder = 0; 11505 mResolveInfo.match = 0; 11506 mResolveComponentName = mCustomResolverComponentName; 11507 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 11508 mResolveComponentName); 11509 } 11510 } 11511 11512 private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) { 11513 if (installerActivity == null) { 11514 if (DEBUG_EPHEMERAL) { 11515 Slog.d(TAG, "Clear ephemeral installer activity"); 11516 } 11517 mInstantAppInstallerActivity = null; 11518 return; 11519 } 11520 11521 if (DEBUG_EPHEMERAL) { 11522 Slog.d(TAG, "Set ephemeral installer activity: " 11523 + installerActivity.getComponentName()); 11524 } 11525 // Set up information for ephemeral installer activity 11526 mInstantAppInstallerActivity = installerActivity; 11527 mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS 11528 | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 11529 mInstantAppInstallerActivity.exported = true; 11530 mInstantAppInstallerActivity.enabled = true; 11531 mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity; 11532 mInstantAppInstallerInfo.priority = 0; 11533 mInstantAppInstallerInfo.preferredOrder = 1; 11534 mInstantAppInstallerInfo.isDefault = true; 11535 mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 11536 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 11537 } 11538 11539 private static String calculateBundledApkRoot(final String codePathString) { 11540 final File codePath = new File(codePathString); 11541 final File codeRoot; 11542 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 11543 codeRoot = Environment.getRootDirectory(); 11544 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 11545 codeRoot = Environment.getOemDirectory(); 11546 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 11547 codeRoot = Environment.getVendorDirectory(); 11548 } else { 11549 // Unrecognized code path; take its top real segment as the apk root: 11550 // e.g. /something/app/blah.apk => /something 11551 try { 11552 File f = codePath.getCanonicalFile(); 11553 File parent = f.getParentFile(); // non-null because codePath is a file 11554 File tmp; 11555 while ((tmp = parent.getParentFile()) != null) { 11556 f = parent; 11557 parent = tmp; 11558 } 11559 codeRoot = f; 11560 Slog.w(TAG, "Unrecognized code path " 11561 + codePath + " - using " + codeRoot); 11562 } catch (IOException e) { 11563 // Can't canonicalize the code path -- shenanigans? 11564 Slog.w(TAG, "Can't canonicalize code path " + codePath); 11565 return Environment.getRootDirectory().getPath(); 11566 } 11567 } 11568 return codeRoot.getPath(); 11569 } 11570 11571 /** 11572 * Derive and set the location of native libraries for the given package, 11573 * which varies depending on where and how the package was installed. 11574 */ 11575 private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) { 11576 final ApplicationInfo info = pkg.applicationInfo; 11577 final String codePath = pkg.codePath; 11578 final File codeFile = new File(codePath); 11579 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 11580 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 11581 11582 info.nativeLibraryRootDir = null; 11583 info.nativeLibraryRootRequiresIsa = false; 11584 info.nativeLibraryDir = null; 11585 info.secondaryNativeLibraryDir = null; 11586 11587 if (isApkFile(codeFile)) { 11588 // Monolithic install 11589 if (bundledApp) { 11590 // If "/system/lib64/apkname" exists, assume that is the per-package 11591 // native library directory to use; otherwise use "/system/lib/apkname". 11592 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 11593 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 11594 getPrimaryInstructionSet(info)); 11595 11596 // This is a bundled system app so choose the path based on the ABI. 11597 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 11598 // is just the default path. 11599 final String apkName = deriveCodePathName(codePath); 11600 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 11601 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 11602 apkName).getAbsolutePath(); 11603 11604 if (info.secondaryCpuAbi != null) { 11605 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 11606 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 11607 secondaryLibDir, apkName).getAbsolutePath(); 11608 } 11609 } else if (asecApp) { 11610 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 11611 .getAbsolutePath(); 11612 } else { 11613 final String apkName = deriveCodePathName(codePath); 11614 info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName) 11615 .getAbsolutePath(); 11616 } 11617 11618 info.nativeLibraryRootRequiresIsa = false; 11619 info.nativeLibraryDir = info.nativeLibraryRootDir; 11620 } else { 11621 // Cluster install 11622 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 11623 info.nativeLibraryRootRequiresIsa = true; 11624 11625 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 11626 getPrimaryInstructionSet(info)).getAbsolutePath(); 11627 11628 if (info.secondaryCpuAbi != null) { 11629 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 11630 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 11631 } 11632 } 11633 } 11634 11635 /** 11636 * Calculate the abis and roots for a bundled app. These can uniquely 11637 * be determined from the contents of the system partition, i.e whether 11638 * it contains 64 or 32 bit shared libraries etc. We do not validate any 11639 * of this information, and instead assume that the system was built 11640 * sensibly. 11641 */ 11642 private static void setBundledAppAbisAndRoots(PackageParser.Package pkg, 11643 PackageSetting pkgSetting) { 11644 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 11645 11646 // If "/system/lib64/apkname" exists, assume that is the per-package 11647 // native library directory to use; otherwise use "/system/lib/apkname". 11648 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 11649 setBundledAppAbi(pkg, apkRoot, apkName); 11650 // pkgSetting might be null during rescan following uninstall of updates 11651 // to a bundled app, so accommodate that possibility. The settings in 11652 // that case will be established later from the parsed package. 11653 // 11654 // If the settings aren't null, sync them up with what we've just derived. 11655 // note that apkRoot isn't stored in the package settings. 11656 if (pkgSetting != null) { 11657 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 11658 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 11659 } 11660 } 11661 11662 /** 11663 * Deduces the ABI of a bundled app and sets the relevant fields on the 11664 * parsed pkg object. 11665 * 11666 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 11667 * under which system libraries are installed. 11668 * @param apkName the name of the installed package. 11669 */ 11670 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 11671 final File codeFile = new File(pkg.codePath); 11672 11673 final boolean has64BitLibs; 11674 final boolean has32BitLibs; 11675 if (isApkFile(codeFile)) { 11676 // Monolithic install 11677 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 11678 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 11679 } else { 11680 // Cluster install 11681 final File rootDir = new File(codeFile, LIB_DIR_NAME); 11682 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 11683 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 11684 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 11685 has64BitLibs = (new File(rootDir, isa)).exists(); 11686 } else { 11687 has64BitLibs = false; 11688 } 11689 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 11690 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 11691 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 11692 has32BitLibs = (new File(rootDir, isa)).exists(); 11693 } else { 11694 has32BitLibs = false; 11695 } 11696 } 11697 11698 if (has64BitLibs && !has32BitLibs) { 11699 // The package has 64 bit libs, but not 32 bit libs. Its primary 11700 // ABI should be 64 bit. We can safely assume here that the bundled 11701 // native libraries correspond to the most preferred ABI in the list. 11702 11703 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 11704 pkg.applicationInfo.secondaryCpuAbi = null; 11705 } else if (has32BitLibs && !has64BitLibs) { 11706 // The package has 32 bit libs but not 64 bit libs. Its primary 11707 // ABI should be 32 bit. 11708 11709 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 11710 pkg.applicationInfo.secondaryCpuAbi = null; 11711 } else if (has32BitLibs && has64BitLibs) { 11712 // The application has both 64 and 32 bit bundled libraries. We check 11713 // here that the app declares multiArch support, and warn if it doesn't. 11714 // 11715 // We will be lenient here and record both ABIs. The primary will be the 11716 // ABI that's higher on the list, i.e, a device that's configured to prefer 11717 // 64 bit apps will see a 64 bit primary ABI, 11718 11719 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 11720 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 11721 } 11722 11723 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 11724 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 11725 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 11726 } else { 11727 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 11728 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 11729 } 11730 } else { 11731 pkg.applicationInfo.primaryCpuAbi = null; 11732 pkg.applicationInfo.secondaryCpuAbi = null; 11733 } 11734 } 11735 11736 private void killApplication(String pkgName, int appId, String reason) { 11737 killApplication(pkgName, appId, UserHandle.USER_ALL, reason); 11738 } 11739 11740 private void killApplication(String pkgName, int appId, int userId, String reason) { 11741 // Request the ActivityManager to kill the process(only for existing packages) 11742 // so that we do not end up in a confused state while the user is still using the older 11743 // version of the application while the new one gets installed. 11744 final long token = Binder.clearCallingIdentity(); 11745 try { 11746 IActivityManager am = ActivityManager.getService(); 11747 if (am != null) { 11748 try { 11749 am.killApplication(pkgName, appId, userId, reason); 11750 } catch (RemoteException e) { 11751 } 11752 } 11753 } finally { 11754 Binder.restoreCallingIdentity(token); 11755 } 11756 } 11757 11758 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 11759 // Remove the parent package setting 11760 PackageSetting ps = (PackageSetting) pkg.mExtras; 11761 if (ps != null) { 11762 removePackageLI(ps, chatty); 11763 } 11764 // Remove the child package setting 11765 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 11766 for (int i = 0; i < childCount; i++) { 11767 PackageParser.Package childPkg = pkg.childPackages.get(i); 11768 ps = (PackageSetting) childPkg.mExtras; 11769 if (ps != null) { 11770 removePackageLI(ps, chatty); 11771 } 11772 } 11773 } 11774 11775 void removePackageLI(PackageSetting ps, boolean chatty) { 11776 if (DEBUG_INSTALL) { 11777 if (chatty) 11778 Log.d(TAG, "Removing package " + ps.name); 11779 } 11780 11781 // writer 11782 synchronized (mPackages) { 11783 mPackages.remove(ps.name); 11784 final PackageParser.Package pkg = ps.pkg; 11785 if (pkg != null) { 11786 cleanPackageDataStructuresLILPw(pkg, chatty); 11787 } 11788 } 11789 } 11790 11791 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 11792 if (DEBUG_INSTALL) { 11793 if (chatty) 11794 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 11795 } 11796 11797 // writer 11798 synchronized (mPackages) { 11799 // Remove the parent package 11800 mPackages.remove(pkg.applicationInfo.packageName); 11801 cleanPackageDataStructuresLILPw(pkg, chatty); 11802 11803 // Remove the child packages 11804 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 11805 for (int i = 0; i < childCount; i++) { 11806 PackageParser.Package childPkg = pkg.childPackages.get(i); 11807 mPackages.remove(childPkg.applicationInfo.packageName); 11808 cleanPackageDataStructuresLILPw(childPkg, chatty); 11809 } 11810 } 11811 } 11812 11813 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 11814 int N = pkg.providers.size(); 11815 StringBuilder r = null; 11816 int i; 11817 for (i=0; i<N; i++) { 11818 PackageParser.Provider p = pkg.providers.get(i); 11819 mProviders.removeProvider(p); 11820 if (p.info.authority == null) { 11821 11822 /* There was another ContentProvider with this authority when 11823 * this app was installed so this authority is null, 11824 * Ignore it as we don't have to unregister the provider. 11825 */ 11826 continue; 11827 } 11828 String names[] = p.info.authority.split(";"); 11829 for (int j = 0; j < names.length; j++) { 11830 if (mProvidersByAuthority.get(names[j]) == p) { 11831 mProvidersByAuthority.remove(names[j]); 11832 if (DEBUG_REMOVE) { 11833 if (chatty) 11834 Log.d(TAG, "Unregistered content provider: " + names[j] 11835 + ", className = " + p.info.name + ", isSyncable = " 11836 + p.info.isSyncable); 11837 } 11838 } 11839 } 11840 if (DEBUG_REMOVE && chatty) { 11841 if (r == null) { 11842 r = new StringBuilder(256); 11843 } else { 11844 r.append(' '); 11845 } 11846 r.append(p.info.name); 11847 } 11848 } 11849 if (r != null) { 11850 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 11851 } 11852 11853 N = pkg.services.size(); 11854 r = null; 11855 for (i=0; i<N; i++) { 11856 PackageParser.Service s = pkg.services.get(i); 11857 mServices.removeService(s); 11858 if (chatty) { 11859 if (r == null) { 11860 r = new StringBuilder(256); 11861 } else { 11862 r.append(' '); 11863 } 11864 r.append(s.info.name); 11865 } 11866 } 11867 if (r != null) { 11868 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 11869 } 11870 11871 N = pkg.receivers.size(); 11872 r = null; 11873 for (i=0; i<N; i++) { 11874 PackageParser.Activity a = pkg.receivers.get(i); 11875 mReceivers.removeActivity(a, "receiver"); 11876 if (DEBUG_REMOVE && chatty) { 11877 if (r == null) { 11878 r = new StringBuilder(256); 11879 } else { 11880 r.append(' '); 11881 } 11882 r.append(a.info.name); 11883 } 11884 } 11885 if (r != null) { 11886 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 11887 } 11888 11889 N = pkg.activities.size(); 11890 r = null; 11891 for (i=0; i<N; i++) { 11892 PackageParser.Activity a = pkg.activities.get(i); 11893 mActivities.removeActivity(a, "activity"); 11894 if (DEBUG_REMOVE && chatty) { 11895 if (r == null) { 11896 r = new StringBuilder(256); 11897 } else { 11898 r.append(' '); 11899 } 11900 r.append(a.info.name); 11901 } 11902 } 11903 if (r != null) { 11904 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 11905 } 11906 11907 N = pkg.permissions.size(); 11908 r = null; 11909 for (i=0; i<N; i++) { 11910 PackageParser.Permission p = pkg.permissions.get(i); 11911 BasePermission bp = mSettings.mPermissions.get(p.info.name); 11912 if (bp == null) { 11913 bp = mSettings.mPermissionTrees.get(p.info.name); 11914 } 11915 if (bp != null && bp.perm == p) { 11916 bp.perm = null; 11917 if (DEBUG_REMOVE && chatty) { 11918 if (r == null) { 11919 r = new StringBuilder(256); 11920 } else { 11921 r.append(' '); 11922 } 11923 r.append(p.info.name); 11924 } 11925 } 11926 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 11927 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 11928 if (appOpPkgs != null) { 11929 appOpPkgs.remove(pkg.packageName); 11930 } 11931 } 11932 } 11933 if (r != null) { 11934 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 11935 } 11936 11937 N = pkg.requestedPermissions.size(); 11938 r = null; 11939 for (i=0; i<N; i++) { 11940 String perm = pkg.requestedPermissions.get(i); 11941 BasePermission bp = mSettings.mPermissions.get(perm); 11942 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 11943 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 11944 if (appOpPkgs != null) { 11945 appOpPkgs.remove(pkg.packageName); 11946 if (appOpPkgs.isEmpty()) { 11947 mAppOpPermissionPackages.remove(perm); 11948 } 11949 } 11950 } 11951 } 11952 if (r != null) { 11953 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 11954 } 11955 11956 N = pkg.instrumentation.size(); 11957 r = null; 11958 for (i=0; i<N; i++) { 11959 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 11960 mInstrumentation.remove(a.getComponentName()); 11961 if (DEBUG_REMOVE && chatty) { 11962 if (r == null) { 11963 r = new StringBuilder(256); 11964 } else { 11965 r.append(' '); 11966 } 11967 r.append(a.info.name); 11968 } 11969 } 11970 if (r != null) { 11971 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 11972 } 11973 11974 r = null; 11975 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 11976 // Only system apps can hold shared libraries. 11977 if (pkg.libraryNames != null) { 11978 for (i = 0; i < pkg.libraryNames.size(); i++) { 11979 String name = pkg.libraryNames.get(i); 11980 if (removeSharedLibraryLPw(name, 0)) { 11981 if (DEBUG_REMOVE && chatty) { 11982 if (r == null) { 11983 r = new StringBuilder(256); 11984 } else { 11985 r.append(' '); 11986 } 11987 r.append(name); 11988 } 11989 } 11990 } 11991 } 11992 } 11993 11994 r = null; 11995 11996 // Any package can hold static shared libraries. 11997 if (pkg.staticSharedLibName != null) { 11998 if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) { 11999 if (DEBUG_REMOVE && chatty) { 12000 if (r == null) { 12001 r = new StringBuilder(256); 12002 } else { 12003 r.append(' '); 12004 } 12005 r.append(pkg.staticSharedLibName); 12006 } 12007 } 12008 } 12009 12010 if (r != null) { 12011 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 12012 } 12013 } 12014 12015 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 12016 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 12017 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 12018 return true; 12019 } 12020 } 12021 return false; 12022 } 12023 12024 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 12025 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 12026 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 12027 12028 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 12029 // Update the parent permissions 12030 updatePermissionsLPw(pkg.packageName, pkg, flags); 12031 // Update the child permissions 12032 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 12033 for (int i = 0; i < childCount; i++) { 12034 PackageParser.Package childPkg = pkg.childPackages.get(i); 12035 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 12036 } 12037 } 12038 12039 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 12040 int flags) { 12041 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 12042 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 12043 } 12044 12045 private void updatePermissionsLPw(String changingPkg, 12046 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 12047 // Make sure there are no dangling permission trees. 12048 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 12049 while (it.hasNext()) { 12050 final BasePermission bp = it.next(); 12051 if (bp.packageSetting == null) { 12052 // We may not yet have parsed the package, so just see if 12053 // we still know about its settings. 12054 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 12055 } 12056 if (bp.packageSetting == null) { 12057 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 12058 + " from package " + bp.sourcePackage); 12059 it.remove(); 12060 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 12061 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 12062 Slog.i(TAG, "Removing old permission tree: " + bp.name 12063 + " from package " + bp.sourcePackage); 12064 flags |= UPDATE_PERMISSIONS_ALL; 12065 it.remove(); 12066 } 12067 } 12068 } 12069 12070 // Make sure all dynamic permissions have been assigned to a package, 12071 // and make sure there are no dangling permissions. 12072 it = mSettings.mPermissions.values().iterator(); 12073 while (it.hasNext()) { 12074 final BasePermission bp = it.next(); 12075 if (bp.type == BasePermission.TYPE_DYNAMIC) { 12076 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 12077 + bp.name + " pkg=" + bp.sourcePackage 12078 + " info=" + bp.pendingInfo); 12079 if (bp.packageSetting == null && bp.pendingInfo != null) { 12080 final BasePermission tree = findPermissionTreeLP(bp.name); 12081 if (tree != null && tree.perm != null) { 12082 bp.packageSetting = tree.packageSetting; 12083 bp.perm = new PackageParser.Permission(tree.perm.owner, 12084 new PermissionInfo(bp.pendingInfo)); 12085 bp.perm.info.packageName = tree.perm.info.packageName; 12086 bp.perm.info.name = bp.name; 12087 bp.uid = tree.uid; 12088 } 12089 } 12090 } 12091 if (bp.packageSetting == null) { 12092 // We may not yet have parsed the package, so just see if 12093 // we still know about its settings. 12094 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 12095 } 12096 if (bp.packageSetting == null) { 12097 Slog.w(TAG, "Removing dangling permission: " + bp.name 12098 + " from package " + bp.sourcePackage); 12099 it.remove(); 12100 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 12101 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 12102 Slog.i(TAG, "Removing old permission: " + bp.name 12103 + " from package " + bp.sourcePackage); 12104 flags |= UPDATE_PERMISSIONS_ALL; 12105 it.remove(); 12106 } 12107 } 12108 } 12109 12110 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 12111 // Now update the permissions for all packages, in particular 12112 // replace the granted permissions of the system packages. 12113 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 12114 for (PackageParser.Package pkg : mPackages.values()) { 12115 if (pkg != pkgInfo) { 12116 // Only replace for packages on requested volume 12117 final String volumeUuid = getVolumeUuidForPackage(pkg); 12118 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 12119 && Objects.equals(replaceVolumeUuid, volumeUuid); 12120 grantPermissionsLPw(pkg, replace, changingPkg); 12121 } 12122 } 12123 } 12124 12125 if (pkgInfo != null) { 12126 // Only replace for packages on requested volume 12127 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 12128 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 12129 && Objects.equals(replaceVolumeUuid, volumeUuid); 12130 grantPermissionsLPw(pkgInfo, replace, changingPkg); 12131 } 12132 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12133 } 12134 12135 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 12136 String packageOfInterest) { 12137 // IMPORTANT: There are two types of permissions: install and runtime. 12138 // Install time permissions are granted when the app is installed to 12139 // all device users and users added in the future. Runtime permissions 12140 // are granted at runtime explicitly to specific users. Normal and signature 12141 // protected permissions are install time permissions. Dangerous permissions 12142 // are install permissions if the app's target SDK is Lollipop MR1 or older, 12143 // otherwise they are runtime permissions. This function does not manage 12144 // runtime permissions except for the case an app targeting Lollipop MR1 12145 // being upgraded to target a newer SDK, in which case dangerous permissions 12146 // are transformed from install time to runtime ones. 12147 12148 final PackageSetting ps = (PackageSetting) pkg.mExtras; 12149 if (ps == null) { 12150 return; 12151 } 12152 12153 PermissionsState permissionsState = ps.getPermissionsState(); 12154 PermissionsState origPermissions = permissionsState; 12155 12156 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 12157 12158 boolean runtimePermissionsRevoked = false; 12159 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 12160 12161 boolean changedInstallPermission = false; 12162 12163 if (replace) { 12164 ps.installPermissionsFixed = false; 12165 if (!ps.isSharedUser()) { 12166 origPermissions = new PermissionsState(permissionsState); 12167 permissionsState.reset(); 12168 } else { 12169 // We need to know only about runtime permission changes since the 12170 // calling code always writes the install permissions state but 12171 // the runtime ones are written only if changed. The only cases of 12172 // changed runtime permissions here are promotion of an install to 12173 // runtime and revocation of a runtime from a shared user. 12174 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 12175 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 12176 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 12177 runtimePermissionsRevoked = true; 12178 } 12179 } 12180 } 12181 12182 permissionsState.setGlobalGids(mGlobalGids); 12183 12184 final int N = pkg.requestedPermissions.size(); 12185 for (int i=0; i<N; i++) { 12186 final String name = pkg.requestedPermissions.get(i); 12187 final BasePermission bp = mSettings.mPermissions.get(name); 12188 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 12189 >= Build.VERSION_CODES.M; 12190 12191 if (DEBUG_INSTALL) { 12192 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 12193 } 12194 12195 if (bp == null || bp.packageSetting == null) { 12196 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 12197 if (DEBUG_PERMISSIONS) { 12198 Slog.i(TAG, "Unknown permission " + name 12199 + " in package " + pkg.packageName); 12200 } 12201 } 12202 continue; 12203 } 12204 12205 12206 // Limit ephemeral apps to ephemeral allowed permissions. 12207 if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) { 12208 if (DEBUG_PERMISSIONS) { 12209 Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package " 12210 + pkg.packageName); 12211 } 12212 continue; 12213 } 12214 12215 if (bp.isRuntimeOnly() && !appSupportsRuntimePermissions) { 12216 if (DEBUG_PERMISSIONS) { 12217 Log.i(TAG, "Denying runtime-only permission " + bp.name + " for package " 12218 + pkg.packageName); 12219 } 12220 continue; 12221 } 12222 12223 final String perm = bp.name; 12224 boolean allowedSig = false; 12225 int grant = GRANT_DENIED; 12226 12227 // Keep track of app op permissions. 12228 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 12229 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 12230 if (pkgs == null) { 12231 pkgs = new ArraySet<>(); 12232 mAppOpPermissionPackages.put(bp.name, pkgs); 12233 } 12234 pkgs.add(pkg.packageName); 12235 } 12236 12237 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 12238 switch (level) { 12239 case PermissionInfo.PROTECTION_NORMAL: { 12240 // For all apps normal permissions are install time ones. 12241 grant = GRANT_INSTALL; 12242 } break; 12243 12244 case PermissionInfo.PROTECTION_DANGEROUS: { 12245 // If a permission review is required for legacy apps we represent 12246 // their permissions as always granted runtime ones since we need 12247 // to keep the review required permission flag per user while an 12248 // install permission's state is shared across all users. 12249 if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) { 12250 // For legacy apps dangerous permissions are install time ones. 12251 grant = GRANT_INSTALL; 12252 } else if (origPermissions.hasInstallPermission(bp.name)) { 12253 // For legacy apps that became modern, install becomes runtime. 12254 grant = GRANT_UPGRADE; 12255 } else if (mPromoteSystemApps 12256 && isSystemApp(ps) 12257 && mExistingSystemPackages.contains(ps.name)) { 12258 // For legacy system apps, install becomes runtime. 12259 // We cannot check hasInstallPermission() for system apps since those 12260 // permissions were granted implicitly and not persisted pre-M. 12261 grant = GRANT_UPGRADE; 12262 } else { 12263 // For modern apps keep runtime permissions unchanged. 12264 grant = GRANT_RUNTIME; 12265 } 12266 } break; 12267 12268 case PermissionInfo.PROTECTION_SIGNATURE: { 12269 // For all apps signature permissions are install time ones. 12270 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 12271 if (allowedSig) { 12272 grant = GRANT_INSTALL; 12273 } 12274 } break; 12275 } 12276 12277 if (DEBUG_PERMISSIONS) { 12278 Slog.i(TAG, "Granting permission " + perm + " to package " + pkg.packageName); 12279 } 12280 12281 if (grant != GRANT_DENIED) { 12282 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 12283 // If this is an existing, non-system package, then 12284 // we can't add any new permissions to it. 12285 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 12286 // Except... if this is a permission that was added 12287 // to the platform (note: need to only do this when 12288 // updating the platform). 12289 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 12290 grant = GRANT_DENIED; 12291 } 12292 } 12293 } 12294 12295 switch (grant) { 12296 case GRANT_INSTALL: { 12297 // Revoke this as runtime permission to handle the case of 12298 // a runtime permission being downgraded to an install one. 12299 // Also in permission review mode we keep dangerous permissions 12300 // for legacy apps 12301 for (int userId : UserManagerService.getInstance().getUserIds()) { 12302 if (origPermissions.getRuntimePermissionState( 12303 bp.name, userId) != null) { 12304 // Revoke the runtime permission and clear the flags. 12305 origPermissions.revokeRuntimePermission(bp, userId); 12306 origPermissions.updatePermissionFlags(bp, userId, 12307 PackageManager.MASK_PERMISSION_FLAGS, 0); 12308 // If we revoked a permission permission, we have to write. 12309 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 12310 changedRuntimePermissionUserIds, userId); 12311 } 12312 } 12313 // Grant an install permission. 12314 if (permissionsState.grantInstallPermission(bp) != 12315 PermissionsState.PERMISSION_OPERATION_FAILURE) { 12316 changedInstallPermission = true; 12317 } 12318 } break; 12319 12320 case GRANT_RUNTIME: { 12321 // Grant previously granted runtime permissions. 12322 for (int userId : UserManagerService.getInstance().getUserIds()) { 12323 PermissionState permissionState = origPermissions 12324 .getRuntimePermissionState(bp.name, userId); 12325 int flags = permissionState != null 12326 ? permissionState.getFlags() : 0; 12327 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 12328 // Don't propagate the permission in a permission review mode if 12329 // the former was revoked, i.e. marked to not propagate on upgrade. 12330 // Note that in a permission review mode install permissions are 12331 // represented as constantly granted runtime ones since we need to 12332 // keep a per user state associated with the permission. Also the 12333 // revoke on upgrade flag is no longer applicable and is reset. 12334 final boolean revokeOnUpgrade = (flags & PackageManager 12335 .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 12336 if (revokeOnUpgrade) { 12337 flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 12338 // Since we changed the flags, we have to write. 12339 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 12340 changedRuntimePermissionUserIds, userId); 12341 } 12342 if (!mPermissionReviewRequired || !revokeOnUpgrade) { 12343 if (permissionsState.grantRuntimePermission(bp, userId) == 12344 PermissionsState.PERMISSION_OPERATION_FAILURE) { 12345 // If we cannot put the permission as it was, 12346 // we have to write. 12347 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 12348 changedRuntimePermissionUserIds, userId); 12349 } 12350 } 12351 12352 // If the app supports runtime permissions no need for a review. 12353 if (mPermissionReviewRequired 12354 && appSupportsRuntimePermissions 12355 && (flags & PackageManager 12356 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 12357 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 12358 // Since we changed the flags, we have to write. 12359 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 12360 changedRuntimePermissionUserIds, userId); 12361 } 12362 } else if (mPermissionReviewRequired 12363 && !appSupportsRuntimePermissions) { 12364 // For legacy apps that need a permission review, every new 12365 // runtime permission is granted but it is pending a review. 12366 // We also need to review only platform defined runtime 12367 // permissions as these are the only ones the platform knows 12368 // how to disable the API to simulate revocation as legacy 12369 // apps don't expect to run with revoked permissions. 12370 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 12371 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 12372 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 12373 // We changed the flags, hence have to write. 12374 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 12375 changedRuntimePermissionUserIds, userId); 12376 } 12377 } 12378 if (permissionsState.grantRuntimePermission(bp, userId) 12379 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 12380 // We changed the permission, hence have to write. 12381 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 12382 changedRuntimePermissionUserIds, userId); 12383 } 12384 } 12385 // Propagate the permission flags. 12386 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 12387 } 12388 } break; 12389 12390 case GRANT_UPGRADE: { 12391 // Grant runtime permissions for a previously held install permission. 12392 PermissionState permissionState = origPermissions 12393 .getInstallPermissionState(bp.name); 12394 final int flags = permissionState != null ? permissionState.getFlags() : 0; 12395 12396 if (origPermissions.revokeInstallPermission(bp) 12397 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 12398 // We will be transferring the permission flags, so clear them. 12399 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 12400 PackageManager.MASK_PERMISSION_FLAGS, 0); 12401 changedInstallPermission = true; 12402 } 12403 12404 // If the permission is not to be promoted to runtime we ignore it and 12405 // also its other flags as they are not applicable to install permissions. 12406 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 12407 for (int userId : currentUserIds) { 12408 if (permissionsState.grantRuntimePermission(bp, userId) != 12409 PermissionsState.PERMISSION_OPERATION_FAILURE) { 12410 // Transfer the permission flags. 12411 permissionsState.updatePermissionFlags(bp, userId, 12412 flags, flags); 12413 // If we granted the permission, we have to write. 12414 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 12415 changedRuntimePermissionUserIds, userId); 12416 } 12417 } 12418 } 12419 } break; 12420 12421 default: { 12422 if (packageOfInterest == null 12423 || packageOfInterest.equals(pkg.packageName)) { 12424 if (DEBUG_PERMISSIONS) { 12425 Slog.i(TAG, "Not granting permission " + perm 12426 + " to package " + pkg.packageName 12427 + " because it was previously installed without"); 12428 } 12429 } 12430 } break; 12431 } 12432 } else { 12433 if (permissionsState.revokeInstallPermission(bp) != 12434 PermissionsState.PERMISSION_OPERATION_FAILURE) { 12435 // Also drop the permission flags. 12436 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 12437 PackageManager.MASK_PERMISSION_FLAGS, 0); 12438 changedInstallPermission = true; 12439 Slog.i(TAG, "Un-granting permission " + perm 12440 + " from package " + pkg.packageName 12441 + " (protectionLevel=" + bp.protectionLevel 12442 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 12443 + ")"); 12444 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 12445 // Don't print warning for app op permissions, since it is fine for them 12446 // not to be granted, there is a UI for the user to decide. 12447 if (DEBUG_PERMISSIONS 12448 && (packageOfInterest == null 12449 || packageOfInterest.equals(pkg.packageName))) { 12450 Slog.i(TAG, "Not granting permission " + perm 12451 + " to package " + pkg.packageName 12452 + " (protectionLevel=" + bp.protectionLevel 12453 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 12454 + ")"); 12455 } 12456 } 12457 } 12458 } 12459 12460 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 12461 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 12462 // This is the first that we have heard about this package, so the 12463 // permissions we have now selected are fixed until explicitly 12464 // changed. 12465 ps.installPermissionsFixed = true; 12466 } 12467 12468 // Persist the runtime permissions state for users with changes. If permissions 12469 // were revoked because no app in the shared user declares them we have to 12470 // write synchronously to avoid losing runtime permissions state. 12471 for (int userId : changedRuntimePermissionUserIds) { 12472 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 12473 } 12474 } 12475 12476 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 12477 boolean allowed = false; 12478 final int NP = PackageParser.NEW_PERMISSIONS.length; 12479 for (int ip=0; ip<NP; ip++) { 12480 final PackageParser.NewPermissionInfo npi 12481 = PackageParser.NEW_PERMISSIONS[ip]; 12482 if (npi.name.equals(perm) 12483 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 12484 allowed = true; 12485 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 12486 + pkg.packageName); 12487 break; 12488 } 12489 } 12490 return allowed; 12491 } 12492 12493 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 12494 BasePermission bp, PermissionsState origPermissions) { 12495 boolean privilegedPermission = (bp.protectionLevel 12496 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0; 12497 boolean privappPermissionsDisable = 12498 RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE; 12499 boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage); 12500 boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName); 12501 if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp() 12502 && !platformPackage && platformPermission) { 12503 ArraySet<String> wlPermissions = SystemConfig.getInstance() 12504 .getPrivAppPermissions(pkg.packageName); 12505 boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm); 12506 if (!whitelisted) { 12507 Slog.w(TAG, "Privileged permission " + perm + " for package " 12508 + pkg.packageName + " - not in privapp-permissions whitelist"); 12509 // Only report violations for apps on system image 12510 if (!mSystemReady && !pkg.isUpdatedSystemApp()) { 12511 if (mPrivappPermissionsViolations == null) { 12512 mPrivappPermissionsViolations = new ArraySet<>(); 12513 } 12514 mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm); 12515 } 12516 if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) { 12517 return false; 12518 } 12519 } 12520 } 12521 boolean allowed = (compareSignatures( 12522 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 12523 == PackageManager.SIGNATURE_MATCH) 12524 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 12525 == PackageManager.SIGNATURE_MATCH); 12526 if (!allowed && privilegedPermission) { 12527 if (isSystemApp(pkg)) { 12528 // For updated system applications, a system permission 12529 // is granted only if it had been defined by the original application. 12530 if (pkg.isUpdatedSystemApp()) { 12531 final PackageSetting sysPs = mSettings 12532 .getDisabledSystemPkgLPr(pkg.packageName); 12533 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 12534 // If the original was granted this permission, we take 12535 // that grant decision as read and propagate it to the 12536 // update. 12537 if (sysPs.isPrivileged()) { 12538 allowed = true; 12539 } 12540 } else { 12541 // The system apk may have been updated with an older 12542 // version of the one on the data partition, but which 12543 // granted a new system permission that it didn't have 12544 // before. In this case we do want to allow the app to 12545 // now get the new permission if the ancestral apk is 12546 // privileged to get it. 12547 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 12548 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 12549 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 12550 allowed = true; 12551 break; 12552 } 12553 } 12554 } 12555 // Also if a privileged parent package on the system image or any of 12556 // its children requested a privileged permission, the updated child 12557 // packages can also get the permission. 12558 if (pkg.parentPackage != null) { 12559 final PackageSetting disabledSysParentPs = mSettings 12560 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 12561 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 12562 && disabledSysParentPs.isPrivileged()) { 12563 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 12564 allowed = true; 12565 } else if (disabledSysParentPs.pkg.childPackages != null) { 12566 final int count = disabledSysParentPs.pkg.childPackages.size(); 12567 for (int i = 0; i < count; i++) { 12568 PackageParser.Package disabledSysChildPkg = 12569 disabledSysParentPs.pkg.childPackages.get(i); 12570 if (isPackageRequestingPermission(disabledSysChildPkg, 12571 perm)) { 12572 allowed = true; 12573 break; 12574 } 12575 } 12576 } 12577 } 12578 } 12579 } 12580 } else { 12581 allowed = isPrivilegedApp(pkg); 12582 } 12583 } 12584 } 12585 if (!allowed) { 12586 if (!allowed && (bp.protectionLevel 12587 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 12588 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 12589 // If this was a previously normal/dangerous permission that got moved 12590 // to a system permission as part of the runtime permission redesign, then 12591 // we still want to blindly grant it to old apps. 12592 allowed = true; 12593 } 12594 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 12595 && pkg.packageName.equals(mRequiredInstallerPackage)) { 12596 // If this permission is to be granted to the system installer and 12597 // this app is an installer, then it gets the permission. 12598 allowed = true; 12599 } 12600 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 12601 && pkg.packageName.equals(mRequiredVerifierPackage)) { 12602 // If this permission is to be granted to the system verifier and 12603 // this app is a verifier, then it gets the permission. 12604 allowed = true; 12605 } 12606 if (!allowed && (bp.protectionLevel 12607 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 12608 && isSystemApp(pkg)) { 12609 // Any pre-installed system app is allowed to get this permission. 12610 allowed = true; 12611 } 12612 if (!allowed && (bp.protectionLevel 12613 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 12614 // For development permissions, a development permission 12615 // is granted only if it was already granted. 12616 allowed = origPermissions.hasInstallPermission(perm); 12617 } 12618 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 12619 && pkg.packageName.equals(mSetupWizardPackage)) { 12620 // If this permission is to be granted to the system setup wizard and 12621 // this app is a setup wizard, then it gets the permission. 12622 allowed = true; 12623 } 12624 } 12625 return allowed; 12626 } 12627 12628 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 12629 final int permCount = pkg.requestedPermissions.size(); 12630 for (int j = 0; j < permCount; j++) { 12631 String requestedPermission = pkg.requestedPermissions.get(j); 12632 if (permission.equals(requestedPermission)) { 12633 return true; 12634 } 12635 } 12636 return false; 12637 } 12638 12639 final class ActivityIntentResolver 12640 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 12641 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12642 boolean defaultOnly, int userId) { 12643 if (!sUserManager.exists(userId)) return null; 12644 mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0); 12645 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 12646 } 12647 12648 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12649 int userId) { 12650 if (!sUserManager.exists(userId)) return null; 12651 mFlags = flags; 12652 return super.queryIntent(intent, resolvedType, 12653 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12654 userId); 12655 } 12656 12657 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12658 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 12659 if (!sUserManager.exists(userId)) return null; 12660 if (packageActivities == null) { 12661 return null; 12662 } 12663 mFlags = flags; 12664 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 12665 final int N = packageActivities.size(); 12666 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 12667 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 12668 12669 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 12670 for (int i = 0; i < N; ++i) { 12671 intentFilters = packageActivities.get(i).intents; 12672 if (intentFilters != null && intentFilters.size() > 0) { 12673 PackageParser.ActivityIntentInfo[] array = 12674 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 12675 intentFilters.toArray(array); 12676 listCut.add(array); 12677 } 12678 } 12679 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 12680 } 12681 12682 /** 12683 * Finds a privileged activity that matches the specified activity names. 12684 */ 12685 private PackageParser.Activity findMatchingActivity( 12686 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 12687 for (PackageParser.Activity sysActivity : activityList) { 12688 if (sysActivity.info.name.equals(activityInfo.name)) { 12689 return sysActivity; 12690 } 12691 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 12692 return sysActivity; 12693 } 12694 if (sysActivity.info.targetActivity != null) { 12695 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 12696 return sysActivity; 12697 } 12698 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 12699 return sysActivity; 12700 } 12701 } 12702 } 12703 return null; 12704 } 12705 12706 public class IterGenerator<E> { 12707 public Iterator<E> generate(ActivityIntentInfo info) { 12708 return null; 12709 } 12710 } 12711 12712 public class ActionIterGenerator extends IterGenerator<String> { 12713 @Override 12714 public Iterator<String> generate(ActivityIntentInfo info) { 12715 return info.actionsIterator(); 12716 } 12717 } 12718 12719 public class CategoriesIterGenerator extends IterGenerator<String> { 12720 @Override 12721 public Iterator<String> generate(ActivityIntentInfo info) { 12722 return info.categoriesIterator(); 12723 } 12724 } 12725 12726 public class SchemesIterGenerator extends IterGenerator<String> { 12727 @Override 12728 public Iterator<String> generate(ActivityIntentInfo info) { 12729 return info.schemesIterator(); 12730 } 12731 } 12732 12733 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 12734 @Override 12735 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 12736 return info.authoritiesIterator(); 12737 } 12738 } 12739 12740 /** 12741 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 12742 * MODIFIED. Do not pass in a list that should not be changed. 12743 */ 12744 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 12745 IterGenerator<T> generator, Iterator<T> searchIterator) { 12746 // loop through the set of actions; every one must be found in the intent filter 12747 while (searchIterator.hasNext()) { 12748 // we must have at least one filter in the list to consider a match 12749 if (intentList.size() == 0) { 12750 break; 12751 } 12752 12753 final T searchAction = searchIterator.next(); 12754 12755 // loop through the set of intent filters 12756 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 12757 while (intentIter.hasNext()) { 12758 final ActivityIntentInfo intentInfo = intentIter.next(); 12759 boolean selectionFound = false; 12760 12761 // loop through the intent filter's selection criteria; at least one 12762 // of them must match the searched criteria 12763 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 12764 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 12765 final T intentSelection = intentSelectionIter.next(); 12766 if (intentSelection != null && intentSelection.equals(searchAction)) { 12767 selectionFound = true; 12768 break; 12769 } 12770 } 12771 12772 // the selection criteria wasn't found in this filter's set; this filter 12773 // is not a potential match 12774 if (!selectionFound) { 12775 intentIter.remove(); 12776 } 12777 } 12778 } 12779 } 12780 12781 private boolean isProtectedAction(ActivityIntentInfo filter) { 12782 final Iterator<String> actionsIter = filter.actionsIterator(); 12783 while (actionsIter != null && actionsIter.hasNext()) { 12784 final String filterAction = actionsIter.next(); 12785 if (PROTECTED_ACTIONS.contains(filterAction)) { 12786 return true; 12787 } 12788 } 12789 return false; 12790 } 12791 12792 /** 12793 * Adjusts the priority of the given intent filter according to policy. 12794 * <p> 12795 * <ul> 12796 * <li>The priority for non privileged applications is capped to '0'</li> 12797 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 12798 * <li>The priority for unbundled updates to privileged applications is capped to the 12799 * priority defined on the system partition</li> 12800 * </ul> 12801 * <p> 12802 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 12803 * allowed to obtain any priority on any action. 12804 */ 12805 private void adjustPriority( 12806 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 12807 // nothing to do; priority is fine as-is 12808 if (intent.getPriority() <= 0) { 12809 return; 12810 } 12811 12812 final ActivityInfo activityInfo = intent.activity.info; 12813 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 12814 12815 final boolean privilegedApp = 12816 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 12817 if (!privilegedApp) { 12818 // non-privileged applications can never define a priority >0 12819 if (DEBUG_FILTERS) { 12820 Slog.i(TAG, "Non-privileged app; cap priority to 0;" 12821 + " package: " + applicationInfo.packageName 12822 + " activity: " + intent.activity.className 12823 + " origPrio: " + intent.getPriority()); 12824 } 12825 intent.setPriority(0); 12826 return; 12827 } 12828 12829 if (systemActivities == null) { 12830 // the system package is not disabled; we're parsing the system partition 12831 if (isProtectedAction(intent)) { 12832 if (mDeferProtectedFilters) { 12833 // We can't deal with these just yet. No component should ever obtain a 12834 // >0 priority for a protected actions, with ONE exception -- the setup 12835 // wizard. The setup wizard, however, cannot be known until we're able to 12836 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 12837 // until all intent filters have been processed. Chicken, meet egg. 12838 // Let the filter temporarily have a high priority and rectify the 12839 // priorities after all system packages have been scanned. 12840 mProtectedFilters.add(intent); 12841 if (DEBUG_FILTERS) { 12842 Slog.i(TAG, "Protected action; save for later;" 12843 + " package: " + applicationInfo.packageName 12844 + " activity: " + intent.activity.className 12845 + " origPrio: " + intent.getPriority()); 12846 } 12847 return; 12848 } else { 12849 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 12850 Slog.i(TAG, "No setup wizard;" 12851 + " All protected intents capped to priority 0"); 12852 } 12853 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 12854 if (DEBUG_FILTERS) { 12855 Slog.i(TAG, "Found setup wizard;" 12856 + " allow priority " + intent.getPriority() + ";" 12857 + " package: " + intent.activity.info.packageName 12858 + " activity: " + intent.activity.className 12859 + " priority: " + intent.getPriority()); 12860 } 12861 // setup wizard gets whatever it wants 12862 return; 12863 } 12864 if (DEBUG_FILTERS) { 12865 Slog.i(TAG, "Protected action; cap priority to 0;" 12866 + " package: " + intent.activity.info.packageName 12867 + " activity: " + intent.activity.className 12868 + " origPrio: " + intent.getPriority()); 12869 } 12870 intent.setPriority(0); 12871 return; 12872 } 12873 } 12874 // privileged apps on the system image get whatever priority they request 12875 return; 12876 } 12877 12878 // privileged app unbundled update ... try to find the same activity 12879 final PackageParser.Activity foundActivity = 12880 findMatchingActivity(systemActivities, activityInfo); 12881 if (foundActivity == null) { 12882 // this is a new activity; it cannot obtain >0 priority 12883 if (DEBUG_FILTERS) { 12884 Slog.i(TAG, "New activity; cap priority to 0;" 12885 + " package: " + applicationInfo.packageName 12886 + " activity: " + intent.activity.className 12887 + " origPrio: " + intent.getPriority()); 12888 } 12889 intent.setPriority(0); 12890 return; 12891 } 12892 12893 // found activity, now check for filter equivalence 12894 12895 // a shallow copy is enough; we modify the list, not its contents 12896 final List<ActivityIntentInfo> intentListCopy = 12897 new ArrayList<>(foundActivity.intents); 12898 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 12899 12900 // find matching action subsets 12901 final Iterator<String> actionsIterator = intent.actionsIterator(); 12902 if (actionsIterator != null) { 12903 getIntentListSubset( 12904 intentListCopy, new ActionIterGenerator(), actionsIterator); 12905 if (intentListCopy.size() == 0) { 12906 // no more intents to match; we're not equivalent 12907 if (DEBUG_FILTERS) { 12908 Slog.i(TAG, "Mismatched action; cap priority to 0;" 12909 + " package: " + applicationInfo.packageName 12910 + " activity: " + intent.activity.className 12911 + " origPrio: " + intent.getPriority()); 12912 } 12913 intent.setPriority(0); 12914 return; 12915 } 12916 } 12917 12918 // find matching category subsets 12919 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 12920 if (categoriesIterator != null) { 12921 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 12922 categoriesIterator); 12923 if (intentListCopy.size() == 0) { 12924 // no more intents to match; we're not equivalent 12925 if (DEBUG_FILTERS) { 12926 Slog.i(TAG, "Mismatched category; cap priority to 0;" 12927 + " package: " + applicationInfo.packageName 12928 + " activity: " + intent.activity.className 12929 + " origPrio: " + intent.getPriority()); 12930 } 12931 intent.setPriority(0); 12932 return; 12933 } 12934 } 12935 12936 // find matching schemes subsets 12937 final Iterator<String> schemesIterator = intent.schemesIterator(); 12938 if (schemesIterator != null) { 12939 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 12940 schemesIterator); 12941 if (intentListCopy.size() == 0) { 12942 // no more intents to match; we're not equivalent 12943 if (DEBUG_FILTERS) { 12944 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 12945 + " package: " + applicationInfo.packageName 12946 + " activity: " + intent.activity.className 12947 + " origPrio: " + intent.getPriority()); 12948 } 12949 intent.setPriority(0); 12950 return; 12951 } 12952 } 12953 12954 // find matching authorities subsets 12955 final Iterator<IntentFilter.AuthorityEntry> 12956 authoritiesIterator = intent.authoritiesIterator(); 12957 if (authoritiesIterator != null) { 12958 getIntentListSubset(intentListCopy, 12959 new AuthoritiesIterGenerator(), 12960 authoritiesIterator); 12961 if (intentListCopy.size() == 0) { 12962 // no more intents to match; we're not equivalent 12963 if (DEBUG_FILTERS) { 12964 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 12965 + " package: " + applicationInfo.packageName 12966 + " activity: " + intent.activity.className 12967 + " origPrio: " + intent.getPriority()); 12968 } 12969 intent.setPriority(0); 12970 return; 12971 } 12972 } 12973 12974 // we found matching filter(s); app gets the max priority of all intents 12975 int cappedPriority = 0; 12976 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 12977 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 12978 } 12979 if (intent.getPriority() > cappedPriority) { 12980 if (DEBUG_FILTERS) { 12981 Slog.i(TAG, "Found matching filter(s);" 12982 + " cap priority to " + cappedPriority + ";" 12983 + " package: " + applicationInfo.packageName 12984 + " activity: " + intent.activity.className 12985 + " origPrio: " + intent.getPriority()); 12986 } 12987 intent.setPriority(cappedPriority); 12988 return; 12989 } 12990 // all this for nothing; the requested priority was <= what was on the system 12991 } 12992 12993 public final void addActivity(PackageParser.Activity a, String type) { 12994 mActivities.put(a.getComponentName(), a); 12995 if (DEBUG_SHOW_INFO) 12996 Log.v( 12997 TAG, " " + type + " " + 12998 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 12999 if (DEBUG_SHOW_INFO) 13000 Log.v(TAG, " Class=" + a.info.name); 13001 final int NI = a.intents.size(); 13002 for (int j=0; j<NI; j++) { 13003 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 13004 if ("activity".equals(type)) { 13005 final PackageSetting ps = 13006 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 13007 final List<PackageParser.Activity> systemActivities = 13008 ps != null && ps.pkg != null ? ps.pkg.activities : null; 13009 adjustPriority(systemActivities, intent); 13010 } 13011 if (DEBUG_SHOW_INFO) { 13012 Log.v(TAG, " IntentFilter:"); 13013 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 13014 } 13015 if (!intent.debugCheck()) { 13016 Log.w(TAG, "==> For Activity " + a.info.name); 13017 } 13018 addFilter(intent); 13019 } 13020 } 13021 13022 public final void removeActivity(PackageParser.Activity a, String type) { 13023 mActivities.remove(a.getComponentName()); 13024 if (DEBUG_SHOW_INFO) { 13025 Log.v(TAG, " " + type + " " 13026 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 13027 : a.info.name) + ":"); 13028 Log.v(TAG, " Class=" + a.info.name); 13029 } 13030 final int NI = a.intents.size(); 13031 for (int j=0; j<NI; j++) { 13032 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 13033 if (DEBUG_SHOW_INFO) { 13034 Log.v(TAG, " IntentFilter:"); 13035 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 13036 } 13037 removeFilter(intent); 13038 } 13039 } 13040 13041 @Override 13042 protected boolean allowFilterResult( 13043 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 13044 ActivityInfo filterAi = filter.activity.info; 13045 for (int i=dest.size()-1; i>=0; i--) { 13046 ActivityInfo destAi = dest.get(i).activityInfo; 13047 if (destAi.name == filterAi.name 13048 && destAi.packageName == filterAi.packageName) { 13049 return false; 13050 } 13051 } 13052 return true; 13053 } 13054 13055 @Override 13056 protected ActivityIntentInfo[] newArray(int size) { 13057 return new ActivityIntentInfo[size]; 13058 } 13059 13060 @Override 13061 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 13062 if (!sUserManager.exists(userId)) return true; 13063 PackageParser.Package p = filter.activity.owner; 13064 if (p != null) { 13065 PackageSetting ps = (PackageSetting)p.mExtras; 13066 if (ps != null) { 13067 // System apps are never considered stopped for purposes of 13068 // filtering, because there may be no way for the user to 13069 // actually re-launch them. 13070 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 13071 && ps.getStopped(userId); 13072 } 13073 } 13074 return false; 13075 } 13076 13077 @Override 13078 protected boolean isPackageForFilter(String packageName, 13079 PackageParser.ActivityIntentInfo info) { 13080 return packageName.equals(info.activity.owner.packageName); 13081 } 13082 13083 @Override 13084 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 13085 int match, int userId) { 13086 if (!sUserManager.exists(userId)) return null; 13087 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 13088 return null; 13089 } 13090 final PackageParser.Activity activity = info.activity; 13091 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 13092 if (ps == null) { 13093 return null; 13094 } 13095 final PackageUserState userState = ps.readUserState(userId); 13096 ActivityInfo ai = generateActivityInfo(activity, mFlags, userState, userId); 13097 if (ai == null) { 13098 return null; 13099 } 13100 final boolean matchExplicitlyVisibleOnly = 13101 (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0; 13102 final boolean matchVisibleToInstantApp = 13103 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 13104 final boolean componentVisible = 13105 matchVisibleToInstantApp 13106 && info.isVisibleToInstantApp() 13107 && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp()); 13108 final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 13109 // throw out filters that aren't visible to ephemeral apps 13110 if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) { 13111 return null; 13112 } 13113 // throw out instant app filters if we're not explicitly requesting them 13114 if (!matchInstantApp && userState.instantApp) { 13115 return null; 13116 } 13117 // throw out instant app filters if updates are available; will trigger 13118 // instant app resolution 13119 if (userState.instantApp && ps.isUpdateAvailable()) { 13120 return null; 13121 } 13122 final ResolveInfo res = new ResolveInfo(); 13123 res.activityInfo = ai; 13124 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 13125 res.filter = info; 13126 } 13127 if (info != null) { 13128 res.handleAllWebDataURI = info.handleAllWebDataURI(); 13129 } 13130 res.priority = info.getPriority(); 13131 res.preferredOrder = activity.owner.mPreferredOrder; 13132 //System.out.println("Result: " + res.activityInfo.className + 13133 // " = " + res.priority); 13134 res.match = match; 13135 res.isDefault = info.hasDefault; 13136 res.labelRes = info.labelRes; 13137 res.nonLocalizedLabel = info.nonLocalizedLabel; 13138 if (userNeedsBadging(userId)) { 13139 res.noResourceId = true; 13140 } else { 13141 res.icon = info.icon; 13142 } 13143 res.iconResourceId = info.icon; 13144 res.system = res.activityInfo.applicationInfo.isSystemApp(); 13145 res.isInstantAppAvailable = userState.instantApp; 13146 return res; 13147 } 13148 13149 @Override 13150 protected void sortResults(List<ResolveInfo> results) { 13151 Collections.sort(results, mResolvePrioritySorter); 13152 } 13153 13154 @Override 13155 protected void dumpFilter(PrintWriter out, String prefix, 13156 PackageParser.ActivityIntentInfo filter) { 13157 out.print(prefix); out.print( 13158 Integer.toHexString(System.identityHashCode(filter.activity))); 13159 out.print(' '); 13160 filter.activity.printComponentShortName(out); 13161 out.print(" filter "); 13162 out.println(Integer.toHexString(System.identityHashCode(filter))); 13163 } 13164 13165 @Override 13166 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 13167 return filter.activity; 13168 } 13169 13170 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 13171 PackageParser.Activity activity = (PackageParser.Activity)label; 13172 out.print(prefix); out.print( 13173 Integer.toHexString(System.identityHashCode(activity))); 13174 out.print(' '); 13175 activity.printComponentShortName(out); 13176 if (count > 1) { 13177 out.print(" ("); out.print(count); out.print(" filters)"); 13178 } 13179 out.println(); 13180 } 13181 13182 // Keys are String (activity class name), values are Activity. 13183 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 13184 = new ArrayMap<ComponentName, PackageParser.Activity>(); 13185 private int mFlags; 13186 } 13187 13188 private final class ServiceIntentResolver 13189 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 13190 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 13191 boolean defaultOnly, int userId) { 13192 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 13193 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 13194 } 13195 13196 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 13197 int userId) { 13198 if (!sUserManager.exists(userId)) return null; 13199 mFlags = flags; 13200 return super.queryIntent(intent, resolvedType, 13201 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 13202 userId); 13203 } 13204 13205 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 13206 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 13207 if (!sUserManager.exists(userId)) return null; 13208 if (packageServices == null) { 13209 return null; 13210 } 13211 mFlags = flags; 13212 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 13213 final int N = packageServices.size(); 13214 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 13215 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 13216 13217 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 13218 for (int i = 0; i < N; ++i) { 13219 intentFilters = packageServices.get(i).intents; 13220 if (intentFilters != null && intentFilters.size() > 0) { 13221 PackageParser.ServiceIntentInfo[] array = 13222 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 13223 intentFilters.toArray(array); 13224 listCut.add(array); 13225 } 13226 } 13227 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 13228 } 13229 13230 public final void addService(PackageParser.Service s) { 13231 mServices.put(s.getComponentName(), s); 13232 if (DEBUG_SHOW_INFO) { 13233 Log.v(TAG, " " 13234 + (s.info.nonLocalizedLabel != null 13235 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 13236 Log.v(TAG, " Class=" + s.info.name); 13237 } 13238 final int NI = s.intents.size(); 13239 int j; 13240 for (j=0; j<NI; j++) { 13241 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 13242 if (DEBUG_SHOW_INFO) { 13243 Log.v(TAG, " IntentFilter:"); 13244 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 13245 } 13246 if (!intent.debugCheck()) { 13247 Log.w(TAG, "==> For Service " + s.info.name); 13248 } 13249 addFilter(intent); 13250 } 13251 } 13252 13253 public final void removeService(PackageParser.Service s) { 13254 mServices.remove(s.getComponentName()); 13255 if (DEBUG_SHOW_INFO) { 13256 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 13257 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 13258 Log.v(TAG, " Class=" + s.info.name); 13259 } 13260 final int NI = s.intents.size(); 13261 int j; 13262 for (j=0; j<NI; j++) { 13263 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 13264 if (DEBUG_SHOW_INFO) { 13265 Log.v(TAG, " IntentFilter:"); 13266 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 13267 } 13268 removeFilter(intent); 13269 } 13270 } 13271 13272 @Override 13273 protected boolean allowFilterResult( 13274 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 13275 ServiceInfo filterSi = filter.service.info; 13276 for (int i=dest.size()-1; i>=0; i--) { 13277 ServiceInfo destAi = dest.get(i).serviceInfo; 13278 if (destAi.name == filterSi.name 13279 && destAi.packageName == filterSi.packageName) { 13280 return false; 13281 } 13282 } 13283 return true; 13284 } 13285 13286 @Override 13287 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 13288 return new PackageParser.ServiceIntentInfo[size]; 13289 } 13290 13291 @Override 13292 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 13293 if (!sUserManager.exists(userId)) return true; 13294 PackageParser.Package p = filter.service.owner; 13295 if (p != null) { 13296 PackageSetting ps = (PackageSetting)p.mExtras; 13297 if (ps != null) { 13298 // System apps are never considered stopped for purposes of 13299 // filtering, because there may be no way for the user to 13300 // actually re-launch them. 13301 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 13302 && ps.getStopped(userId); 13303 } 13304 } 13305 return false; 13306 } 13307 13308 @Override 13309 protected boolean isPackageForFilter(String packageName, 13310 PackageParser.ServiceIntentInfo info) { 13311 return packageName.equals(info.service.owner.packageName); 13312 } 13313 13314 @Override 13315 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 13316 int match, int userId) { 13317 if (!sUserManager.exists(userId)) return null; 13318 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 13319 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 13320 return null; 13321 } 13322 final PackageParser.Service service = info.service; 13323 PackageSetting ps = (PackageSetting) service.owner.mExtras; 13324 if (ps == null) { 13325 return null; 13326 } 13327 final PackageUserState userState = ps.readUserState(userId); 13328 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 13329 userState, userId); 13330 if (si == null) { 13331 return null; 13332 } 13333 final boolean matchVisibleToInstantApp = 13334 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 13335 final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 13336 // throw out filters that aren't visible to ephemeral apps 13337 if (matchVisibleToInstantApp 13338 && !(info.isVisibleToInstantApp() || userState.instantApp)) { 13339 return null; 13340 } 13341 // throw out ephemeral filters if we're not explicitly requesting them 13342 if (!isInstantApp && userState.instantApp) { 13343 return null; 13344 } 13345 // throw out instant app filters if updates are available; will trigger 13346 // instant app resolution 13347 if (userState.instantApp && ps.isUpdateAvailable()) { 13348 return null; 13349 } 13350 final ResolveInfo res = new ResolveInfo(); 13351 res.serviceInfo = si; 13352 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 13353 res.filter = filter; 13354 } 13355 res.priority = info.getPriority(); 13356 res.preferredOrder = service.owner.mPreferredOrder; 13357 res.match = match; 13358 res.isDefault = info.hasDefault; 13359 res.labelRes = info.labelRes; 13360 res.nonLocalizedLabel = info.nonLocalizedLabel; 13361 res.icon = info.icon; 13362 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 13363 return res; 13364 } 13365 13366 @Override 13367 protected void sortResults(List<ResolveInfo> results) { 13368 Collections.sort(results, mResolvePrioritySorter); 13369 } 13370 13371 @Override 13372 protected void dumpFilter(PrintWriter out, String prefix, 13373 PackageParser.ServiceIntentInfo filter) { 13374 out.print(prefix); out.print( 13375 Integer.toHexString(System.identityHashCode(filter.service))); 13376 out.print(' '); 13377 filter.service.printComponentShortName(out); 13378 out.print(" filter "); 13379 out.println(Integer.toHexString(System.identityHashCode(filter))); 13380 } 13381 13382 @Override 13383 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 13384 return filter.service; 13385 } 13386 13387 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 13388 PackageParser.Service service = (PackageParser.Service)label; 13389 out.print(prefix); out.print( 13390 Integer.toHexString(System.identityHashCode(service))); 13391 out.print(' '); 13392 service.printComponentShortName(out); 13393 if (count > 1) { 13394 out.print(" ("); out.print(count); out.print(" filters)"); 13395 } 13396 out.println(); 13397 } 13398 13399// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 13400// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 13401// final List<ResolveInfo> retList = Lists.newArrayList(); 13402// while (i.hasNext()) { 13403// final ResolveInfo resolveInfo = (ResolveInfo) i; 13404// if (isEnabledLP(resolveInfo.serviceInfo)) { 13405// retList.add(resolveInfo); 13406// } 13407// } 13408// return retList; 13409// } 13410 13411 // Keys are String (activity class name), values are Activity. 13412 private final ArrayMap<ComponentName, PackageParser.Service> mServices 13413 = new ArrayMap<ComponentName, PackageParser.Service>(); 13414 private int mFlags; 13415 } 13416 13417 private final class ProviderIntentResolver 13418 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 13419 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 13420 boolean defaultOnly, int userId) { 13421 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 13422 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 13423 } 13424 13425 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 13426 int userId) { 13427 if (!sUserManager.exists(userId)) 13428 return null; 13429 mFlags = flags; 13430 return super.queryIntent(intent, resolvedType, 13431 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 13432 userId); 13433 } 13434 13435 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 13436 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 13437 if (!sUserManager.exists(userId)) 13438 return null; 13439 if (packageProviders == null) { 13440 return null; 13441 } 13442 mFlags = flags; 13443 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 13444 final int N = packageProviders.size(); 13445 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 13446 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 13447 13448 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 13449 for (int i = 0; i < N; ++i) { 13450 intentFilters = packageProviders.get(i).intents; 13451 if (intentFilters != null && intentFilters.size() > 0) { 13452 PackageParser.ProviderIntentInfo[] array = 13453 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 13454 intentFilters.toArray(array); 13455 listCut.add(array); 13456 } 13457 } 13458 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 13459 } 13460 13461 public final void addProvider(PackageParser.Provider p) { 13462 if (mProviders.containsKey(p.getComponentName())) { 13463 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 13464 return; 13465 } 13466 13467 mProviders.put(p.getComponentName(), p); 13468 if (DEBUG_SHOW_INFO) { 13469 Log.v(TAG, " " 13470 + (p.info.nonLocalizedLabel != null 13471 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 13472 Log.v(TAG, " Class=" + p.info.name); 13473 } 13474 final int NI = p.intents.size(); 13475 int j; 13476 for (j = 0; j < NI; j++) { 13477 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 13478 if (DEBUG_SHOW_INFO) { 13479 Log.v(TAG, " IntentFilter:"); 13480 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 13481 } 13482 if (!intent.debugCheck()) { 13483 Log.w(TAG, "==> For Provider " + p.info.name); 13484 } 13485 addFilter(intent); 13486 } 13487 } 13488 13489 public final void removeProvider(PackageParser.Provider p) { 13490 mProviders.remove(p.getComponentName()); 13491 if (DEBUG_SHOW_INFO) { 13492 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 13493 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 13494 Log.v(TAG, " Class=" + p.info.name); 13495 } 13496 final int NI = p.intents.size(); 13497 int j; 13498 for (j = 0; j < NI; j++) { 13499 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 13500 if (DEBUG_SHOW_INFO) { 13501 Log.v(TAG, " IntentFilter:"); 13502 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 13503 } 13504 removeFilter(intent); 13505 } 13506 } 13507 13508 @Override 13509 protected boolean allowFilterResult( 13510 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 13511 ProviderInfo filterPi = filter.provider.info; 13512 for (int i = dest.size() - 1; i >= 0; i--) { 13513 ProviderInfo destPi = dest.get(i).providerInfo; 13514 if (destPi.name == filterPi.name 13515 && destPi.packageName == filterPi.packageName) { 13516 return false; 13517 } 13518 } 13519 return true; 13520 } 13521 13522 @Override 13523 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 13524 return new PackageParser.ProviderIntentInfo[size]; 13525 } 13526 13527 @Override 13528 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 13529 if (!sUserManager.exists(userId)) 13530 return true; 13531 PackageParser.Package p = filter.provider.owner; 13532 if (p != null) { 13533 PackageSetting ps = (PackageSetting) p.mExtras; 13534 if (ps != null) { 13535 // System apps are never considered stopped for purposes of 13536 // filtering, because there may be no way for the user to 13537 // actually re-launch them. 13538 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 13539 && ps.getStopped(userId); 13540 } 13541 } 13542 return false; 13543 } 13544 13545 @Override 13546 protected boolean isPackageForFilter(String packageName, 13547 PackageParser.ProviderIntentInfo info) { 13548 return packageName.equals(info.provider.owner.packageName); 13549 } 13550 13551 @Override 13552 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 13553 int match, int userId) { 13554 if (!sUserManager.exists(userId)) 13555 return null; 13556 final PackageParser.ProviderIntentInfo info = filter; 13557 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 13558 return null; 13559 } 13560 final PackageParser.Provider provider = info.provider; 13561 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 13562 if (ps == null) { 13563 return null; 13564 } 13565 final PackageUserState userState = ps.readUserState(userId); 13566 final boolean matchVisibleToInstantApp = 13567 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 13568 final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 13569 // throw out filters that aren't visible to instant applications 13570 if (matchVisibleToInstantApp 13571 && !(info.isVisibleToInstantApp() || userState.instantApp)) { 13572 return null; 13573 } 13574 // throw out instant application filters if we're not explicitly requesting them 13575 if (!isInstantApp && userState.instantApp) { 13576 return null; 13577 } 13578 // throw out instant application filters if updates are available; will trigger 13579 // instant application resolution 13580 if (userState.instantApp && ps.isUpdateAvailable()) { 13581 return null; 13582 } 13583 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 13584 userState, userId); 13585 if (pi == null) { 13586 return null; 13587 } 13588 final ResolveInfo res = new ResolveInfo(); 13589 res.providerInfo = pi; 13590 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 13591 res.filter = filter; 13592 } 13593 res.priority = info.getPriority(); 13594 res.preferredOrder = provider.owner.mPreferredOrder; 13595 res.match = match; 13596 res.isDefault = info.hasDefault; 13597 res.labelRes = info.labelRes; 13598 res.nonLocalizedLabel = info.nonLocalizedLabel; 13599 res.icon = info.icon; 13600 res.system = res.providerInfo.applicationInfo.isSystemApp(); 13601 return res; 13602 } 13603 13604 @Override 13605 protected void sortResults(List<ResolveInfo> results) { 13606 Collections.sort(results, mResolvePrioritySorter); 13607 } 13608 13609 @Override 13610 protected void dumpFilter(PrintWriter out, String prefix, 13611 PackageParser.ProviderIntentInfo filter) { 13612 out.print(prefix); 13613 out.print( 13614 Integer.toHexString(System.identityHashCode(filter.provider))); 13615 out.print(' '); 13616 filter.provider.printComponentShortName(out); 13617 out.print(" filter "); 13618 out.println(Integer.toHexString(System.identityHashCode(filter))); 13619 } 13620 13621 @Override 13622 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 13623 return filter.provider; 13624 } 13625 13626 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 13627 PackageParser.Provider provider = (PackageParser.Provider)label; 13628 out.print(prefix); out.print( 13629 Integer.toHexString(System.identityHashCode(provider))); 13630 out.print(' '); 13631 provider.printComponentShortName(out); 13632 if (count > 1) { 13633 out.print(" ("); out.print(count); out.print(" filters)"); 13634 } 13635 out.println(); 13636 } 13637 13638 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 13639 = new ArrayMap<ComponentName, PackageParser.Provider>(); 13640 private int mFlags; 13641 } 13642 13643 static final class EphemeralIntentResolver 13644 extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> { 13645 /** 13646 * The result that has the highest defined order. Ordering applies on a 13647 * per-package basis. Mapping is from package name to Pair of order and 13648 * EphemeralResolveInfo. 13649 * <p> 13650 * NOTE: This is implemented as a field variable for convenience and efficiency. 13651 * By having a field variable, we're able to track filter ordering as soon as 13652 * a non-zero order is defined. Otherwise, multiple loops across the result set 13653 * would be needed to apply ordering. If the intent resolver becomes re-entrant, 13654 * this needs to be contained entirely within {@link #filterResults}. 13655 */ 13656 final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>(); 13657 13658 @Override 13659 protected AuxiliaryResolveInfo[] newArray(int size) { 13660 return new AuxiliaryResolveInfo[size]; 13661 } 13662 13663 @Override 13664 protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) { 13665 return true; 13666 } 13667 13668 @Override 13669 protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match, 13670 int userId) { 13671 if (!sUserManager.exists(userId)) { 13672 return null; 13673 } 13674 final String packageName = responseObj.resolveInfo.getPackageName(); 13675 final Integer order = responseObj.getOrder(); 13676 final Pair<Integer, InstantAppResolveInfo> lastOrderResult = 13677 mOrderResult.get(packageName); 13678 // ordering is enabled and this item's order isn't high enough 13679 if (lastOrderResult != null && lastOrderResult.first >= order) { 13680 return null; 13681 } 13682 final InstantAppResolveInfo res = responseObj.resolveInfo; 13683 if (order > 0) { 13684 // non-zero order, enable ordering 13685 mOrderResult.put(packageName, new Pair<>(order, res)); 13686 } 13687 return responseObj; 13688 } 13689 13690 @Override 13691 protected void filterResults(List<AuxiliaryResolveInfo> results) { 13692 // only do work if ordering is enabled [most of the time it won't be] 13693 if (mOrderResult.size() == 0) { 13694 return; 13695 } 13696 int resultSize = results.size(); 13697 for (int i = 0; i < resultSize; i++) { 13698 final InstantAppResolveInfo info = results.get(i).resolveInfo; 13699 final String packageName = info.getPackageName(); 13700 final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName); 13701 if (savedInfo == null) { 13702 // package doesn't having ordering 13703 continue; 13704 } 13705 if (savedInfo.second == info) { 13706 // circled back to the highest ordered item; remove from order list 13707 mOrderResult.remove(savedInfo); 13708 if (mOrderResult.size() == 0) { 13709 // no more ordered items 13710 break; 13711 } 13712 continue; 13713 } 13714 // item has a worse order, remove it from the result list 13715 results.remove(i); 13716 resultSize--; 13717 i--; 13718 } 13719 } 13720 } 13721 13722 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 13723 new Comparator<ResolveInfo>() { 13724 public int compare(ResolveInfo r1, ResolveInfo r2) { 13725 int v1 = r1.priority; 13726 int v2 = r2.priority; 13727 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 13728 if (v1 != v2) { 13729 return (v1 > v2) ? -1 : 1; 13730 } 13731 v1 = r1.preferredOrder; 13732 v2 = r2.preferredOrder; 13733 if (v1 != v2) { 13734 return (v1 > v2) ? -1 : 1; 13735 } 13736 if (r1.isDefault != r2.isDefault) { 13737 return r1.isDefault ? -1 : 1; 13738 } 13739 v1 = r1.match; 13740 v2 = r2.match; 13741 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 13742 if (v1 != v2) { 13743 return (v1 > v2) ? -1 : 1; 13744 } 13745 if (r1.system != r2.system) { 13746 return r1.system ? -1 : 1; 13747 } 13748 if (r1.activityInfo != null) { 13749 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 13750 } 13751 if (r1.serviceInfo != null) { 13752 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 13753 } 13754 if (r1.providerInfo != null) { 13755 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 13756 } 13757 return 0; 13758 } 13759 }; 13760 13761 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 13762 new Comparator<ProviderInfo>() { 13763 public int compare(ProviderInfo p1, ProviderInfo p2) { 13764 final int v1 = p1.initOrder; 13765 final int v2 = p2.initOrder; 13766 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 13767 } 13768 }; 13769 13770 public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 13771 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 13772 final int[] userIds) { 13773 mHandler.post(new Runnable() { 13774 @Override 13775 public void run() { 13776 try { 13777 final IActivityManager am = ActivityManager.getService(); 13778 if (am == null) return; 13779 final int[] resolvedUserIds; 13780 if (userIds == null) { 13781 resolvedUserIds = am.getRunningUserIds(); 13782 } else { 13783 resolvedUserIds = userIds; 13784 } 13785 for (int id : resolvedUserIds) { 13786 final Intent intent = new Intent(action, 13787 pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null); 13788 if (extras != null) { 13789 intent.putExtras(extras); 13790 } 13791 if (targetPkg != null) { 13792 intent.setPackage(targetPkg); 13793 } 13794 // Modify the UID when posting to other users 13795 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 13796 if (uid > 0 && UserHandle.getUserId(uid) != id) { 13797 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 13798 intent.putExtra(Intent.EXTRA_UID, uid); 13799 } 13800 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 13801 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 13802 if (DEBUG_BROADCASTS) { 13803 RuntimeException here = new RuntimeException("here"); 13804 here.fillInStackTrace(); 13805 Slog.d(TAG, "Sending to user " + id + ": " 13806 + intent.toShortString(false, true, false, false) 13807 + " " + intent.getExtras(), here); 13808 } 13809 am.broadcastIntent(null, intent, null, finishedReceiver, 13810 0, null, null, null, android.app.AppOpsManager.OP_NONE, 13811 null, finishedReceiver != null, false, id); 13812 } 13813 } catch (RemoteException ex) { 13814 } 13815 } 13816 }); 13817 } 13818 13819 /** 13820 * Check if the external storage media is available. This is true if there 13821 * is a mounted external storage medium or if the external storage is 13822 * emulated. 13823 */ 13824 private boolean isExternalMediaAvailable() { 13825 return mMediaMounted || Environment.isExternalStorageEmulated(); 13826 } 13827 13828 @Override 13829 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 13830 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 13831 return null; 13832 } 13833 // writer 13834 synchronized (mPackages) { 13835 if (!isExternalMediaAvailable()) { 13836 // If the external storage is no longer mounted at this point, 13837 // the caller may not have been able to delete all of this 13838 // packages files and can not delete any more. Bail. 13839 return null; 13840 } 13841 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 13842 if (lastPackage != null) { 13843 pkgs.remove(lastPackage); 13844 } 13845 if (pkgs.size() > 0) { 13846 return pkgs.get(0); 13847 } 13848 } 13849 return null; 13850 } 13851 13852 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 13853 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 13854 userId, andCode ? 1 : 0, packageName); 13855 if (mSystemReady) { 13856 msg.sendToTarget(); 13857 } else { 13858 if (mPostSystemReadyMessages == null) { 13859 mPostSystemReadyMessages = new ArrayList<>(); 13860 } 13861 mPostSystemReadyMessages.add(msg); 13862 } 13863 } 13864 13865 void startCleaningPackages() { 13866 // reader 13867 if (!isExternalMediaAvailable()) { 13868 return; 13869 } 13870 synchronized (mPackages) { 13871 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 13872 return; 13873 } 13874 } 13875 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 13876 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 13877 IActivityManager am = ActivityManager.getService(); 13878 if (am != null) { 13879 int dcsUid = -1; 13880 synchronized (mPackages) { 13881 if (!mDefaultContainerWhitelisted) { 13882 mDefaultContainerWhitelisted = true; 13883 PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE); 13884 dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId); 13885 } 13886 } 13887 try { 13888 if (dcsUid > 0) { 13889 am.backgroundWhitelistUid(dcsUid); 13890 } 13891 am.startService(null, intent, null, false, mContext.getOpPackageName(), 13892 UserHandle.USER_SYSTEM); 13893 } catch (RemoteException e) { 13894 } 13895 } 13896 } 13897 13898 @Override 13899 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 13900 int installFlags, String installerPackageName, int userId) { 13901 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 13902 13903 final int callingUid = Binder.getCallingUid(); 13904 enforceCrossUserPermission(callingUid, userId, 13905 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 13906 13907 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 13908 try { 13909 if (observer != null) { 13910 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 13911 } 13912 } catch (RemoteException re) { 13913 } 13914 return; 13915 } 13916 13917 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 13918 installFlags |= PackageManager.INSTALL_FROM_ADB; 13919 13920 } else { 13921 // Caller holds INSTALL_PACKAGES permission, so we're less strict 13922 // about installerPackageName. 13923 13924 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 13925 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 13926 } 13927 13928 UserHandle user; 13929 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 13930 user = UserHandle.ALL; 13931 } else { 13932 user = new UserHandle(userId); 13933 } 13934 13935 // Only system components can circumvent runtime permissions when installing. 13936 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 13937 && mContext.checkCallingOrSelfPermission(Manifest.permission 13938 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 13939 throw new SecurityException("You need the " 13940 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 13941 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 13942 } 13943 13944 if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0 13945 || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 13946 throw new IllegalArgumentException( 13947 "New installs into ASEC containers no longer supported"); 13948 } 13949 13950 final File originFile = new File(originPath); 13951 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 13952 13953 final Message msg = mHandler.obtainMessage(INIT_COPY); 13954 final VerificationInfo verificationInfo = new VerificationInfo( 13955 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 13956 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 13957 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 13958 null /*packageAbiOverride*/, null /*grantedPermissions*/, 13959 null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN); 13960 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 13961 msg.obj = params; 13962 13963 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 13964 System.identityHashCode(msg.obj)); 13965 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 13966 System.identityHashCode(msg.obj)); 13967 13968 mHandler.sendMessage(msg); 13969 } 13970 13971 13972 /** 13973 * Ensure that the install reason matches what we know about the package installer (e.g. whether 13974 * it is acting on behalf on an enterprise or the user). 13975 * 13976 * Note that the ordering of the conditionals in this method is important. The checks we perform 13977 * are as follows, in this order: 13978 * 13979 * 1) If the install is being performed by a system app, we can trust the app to have set the 13980 * install reason correctly. Thus, we pass through the install reason unchanged, no matter 13981 * what it is. 13982 * 2) If the install is being performed by a device or profile owner app, the install reason 13983 * should be enterprise policy. However, we cannot be sure that the device or profile owner 13984 * set the install reason correctly. If the app targets an older SDK version where install 13985 * reasons did not exist yet, or if the app author simply forgot, the install reason may be 13986 * unset or wrong. Thus, we force the install reason to be enterprise policy. 13987 * 3) In all other cases, the install is being performed by a regular app that is neither part 13988 * of the system nor a device or profile owner. We have no reason to believe that this app is 13989 * acting on behalf of the enterprise admin. Thus, we check whether the install reason was 13990 * set to enterprise policy and if so, change it to unknown instead. 13991 */ 13992 private int fixUpInstallReason(String installerPackageName, int installerUid, 13993 int installReason) { 13994 if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid) 13995 == PERMISSION_GRANTED) { 13996 // If the install is being performed by a system app, we trust that app to have set the 13997 // install reason correctly. 13998 return installReason; 13999 } 14000 14001 final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 14002 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 14003 if (dpm != null) { 14004 ComponentName owner = null; 14005 try { 14006 owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */); 14007 if (owner == null) { 14008 owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid)); 14009 } 14010 } catch (RemoteException e) { 14011 } 14012 if (owner != null && owner.getPackageName().equals(installerPackageName)) { 14013 // If the install is being performed by a device or profile owner, the install 14014 // reason should be enterprise policy. 14015 return PackageManager.INSTALL_REASON_POLICY; 14016 } 14017 } 14018 14019 if (installReason == PackageManager.INSTALL_REASON_POLICY) { 14020 // If the install is being performed by a regular app (i.e. neither system app nor 14021 // device or profile owner), we have no reason to believe that the app is acting on 14022 // behalf of an enterprise. If the app set the install reason to enterprise policy, 14023 // change it to unknown instead. 14024 return PackageManager.INSTALL_REASON_UNKNOWN; 14025 } 14026 14027 // If the install is being performed by a regular app and the install reason was set to any 14028 // value but enterprise policy, leave the install reason unchanged. 14029 return installReason; 14030 } 14031 14032 void installStage(String packageName, File stagedDir, String stagedCid, 14033 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 14034 String installerPackageName, int installerUid, UserHandle user, 14035 Certificate[][] certificates) { 14036 if (DEBUG_EPHEMERAL) { 14037 if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) { 14038 Slog.d(TAG, "Ephemeral install of " + packageName); 14039 } 14040 } 14041 final VerificationInfo verificationInfo = new VerificationInfo( 14042 sessionParams.originatingUri, sessionParams.referrerUri, 14043 sessionParams.originatingUid, installerUid); 14044 14045 final OriginInfo origin; 14046 if (stagedDir != null) { 14047 origin = OriginInfo.fromStagedFile(stagedDir); 14048 } else { 14049 origin = OriginInfo.fromStagedContainer(stagedCid); 14050 } 14051 14052 final Message msg = mHandler.obtainMessage(INIT_COPY); 14053 final int installReason = fixUpInstallReason(installerPackageName, installerUid, 14054 sessionParams.installReason); 14055 final InstallParams params = new InstallParams(origin, null, observer, 14056 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 14057 verificationInfo, user, sessionParams.abiOverride, 14058 sessionParams.grantedRuntimePermissions, certificates, installReason); 14059 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 14060 msg.obj = params; 14061 14062 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 14063 System.identityHashCode(msg.obj)); 14064 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 14065 System.identityHashCode(msg.obj)); 14066 14067 mHandler.sendMessage(msg); 14068 } 14069 14070 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 14071 int userId) { 14072 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 14073 sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId); 14074 14075 // Send a session commit broadcast 14076 final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo(); 14077 info.installReason = pkgSetting.getInstallReason(userId); 14078 info.appPackageName = packageName; 14079 sendSessionCommitBroadcast(info, userId); 14080 } 14081 14082 public void sendPackageAddedForNewUsers(String packageName, boolean isSystem, int appId, int... userIds) { 14083 if (ArrayUtils.isEmpty(userIds)) { 14084 return; 14085 } 14086 Bundle extras = new Bundle(1); 14087 // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast 14088 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId)); 14089 14090 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 14091 packageName, extras, 0, null, null, userIds); 14092 if (isSystem) { 14093 mHandler.post(() -> { 14094 for (int userId : userIds) { 14095 sendBootCompletedBroadcastToSystemApp(packageName, userId); 14096 } 14097 } 14098 ); 14099 } 14100 } 14101 14102 /** 14103 * The just-installed/enabled app is bundled on the system, so presumed to be able to run 14104 * automatically without needing an explicit launch. 14105 * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones. 14106 */ 14107 private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) { 14108 // If user is not running, the app didn't miss any broadcast 14109 if (!mUserManagerInternal.isUserRunning(userId)) { 14110 return; 14111 } 14112 final IActivityManager am = ActivityManager.getService(); 14113 try { 14114 // Deliver LOCKED_BOOT_COMPLETED first 14115 Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED) 14116 .setPackage(packageName); 14117 final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED}; 14118 am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions, 14119 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 14120 14121 // Deliver BOOT_COMPLETED only if user is unlocked 14122 if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) { 14123 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName); 14124 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions, 14125 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 14126 } 14127 } catch (RemoteException e) { 14128 throw e.rethrowFromSystemServer(); 14129 } 14130 } 14131 14132 @Override 14133 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 14134 int userId) { 14135 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 14136 PackageSetting pkgSetting; 14137 final int uid = Binder.getCallingUid(); 14138 enforceCrossUserPermission(uid, userId, 14139 true /* requireFullPermission */, true /* checkShell */, 14140 "setApplicationHiddenSetting for user " + userId); 14141 14142 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 14143 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 14144 return false; 14145 } 14146 14147 long callingId = Binder.clearCallingIdentity(); 14148 try { 14149 boolean sendAdded = false; 14150 boolean sendRemoved = false; 14151 // writer 14152 synchronized (mPackages) { 14153 pkgSetting = mSettings.mPackages.get(packageName); 14154 if (pkgSetting == null) { 14155 return false; 14156 } 14157 // Do not allow "android" is being disabled 14158 if ("android".equals(packageName)) { 14159 Slog.w(TAG, "Cannot hide package: android"); 14160 return false; 14161 } 14162 // Cannot hide static shared libs as they are considered 14163 // a part of the using app (emulating static linking). Also 14164 // static libs are installed always on internal storage. 14165 PackageParser.Package pkg = mPackages.get(packageName); 14166 if (pkg != null && pkg.staticSharedLibName != null) { 14167 Slog.w(TAG, "Cannot hide package: " + packageName 14168 + " providing static shared library: " 14169 + pkg.staticSharedLibName); 14170 return false; 14171 } 14172 // Only allow protected packages to hide themselves. 14173 if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId) 14174 && mProtectedPackages.isPackageStateProtected(userId, packageName)) { 14175 Slog.w(TAG, "Not hiding protected package: " + packageName); 14176 return false; 14177 } 14178 14179 if (pkgSetting.getHidden(userId) != hidden) { 14180 pkgSetting.setHidden(hidden, userId); 14181 mSettings.writePackageRestrictionsLPr(userId); 14182 if (hidden) { 14183 sendRemoved = true; 14184 } else { 14185 sendAdded = true; 14186 } 14187 } 14188 } 14189 if (sendAdded) { 14190 sendPackageAddedForUser(packageName, pkgSetting, userId); 14191 return true; 14192 } 14193 if (sendRemoved) { 14194 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 14195 "hiding pkg"); 14196 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 14197 return true; 14198 } 14199 } finally { 14200 Binder.restoreCallingIdentity(callingId); 14201 } 14202 return false; 14203 } 14204 14205 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 14206 int userId) { 14207 final PackageRemovedInfo info = new PackageRemovedInfo(this); 14208 info.removedPackage = packageName; 14209 info.installerPackageName = pkgSetting.installerPackageName; 14210 info.removedUsers = new int[] {userId}; 14211 info.broadcastUsers = new int[] {userId}; 14212 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 14213 info.sendPackageRemovedBroadcasts(true /*killApp*/); 14214 } 14215 14216 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 14217 if (pkgList.length > 0) { 14218 Bundle extras = new Bundle(1); 14219 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 14220 14221 sendPackageBroadcast( 14222 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 14223 : Intent.ACTION_PACKAGES_UNSUSPENDED, 14224 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 14225 new int[] {userId}); 14226 } 14227 } 14228 14229 /** 14230 * Returns true if application is not found or there was an error. Otherwise it returns 14231 * the hidden state of the package for the given user. 14232 */ 14233 @Override 14234 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 14235 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 14236 enforceCrossUserPermission(Binder.getCallingUid(), userId, 14237 true /* requireFullPermission */, false /* checkShell */, 14238 "getApplicationHidden for user " + userId); 14239 PackageSetting pkgSetting; 14240 long callingId = Binder.clearCallingIdentity(); 14241 try { 14242 // writer 14243 synchronized (mPackages) { 14244 pkgSetting = mSettings.mPackages.get(packageName); 14245 if (pkgSetting == null) { 14246 return true; 14247 } 14248 return pkgSetting.getHidden(userId); 14249 } 14250 } finally { 14251 Binder.restoreCallingIdentity(callingId); 14252 } 14253 } 14254 14255 /** 14256 * @hide 14257 */ 14258 @Override 14259 public int installExistingPackageAsUser(String packageName, int userId, int installFlags, 14260 int installReason) { 14261 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 14262 null); 14263 PackageSetting pkgSetting; 14264 final int uid = Binder.getCallingUid(); 14265 enforceCrossUserPermission(uid, userId, 14266 true /* requireFullPermission */, true /* checkShell */, 14267 "installExistingPackage for user " + userId); 14268 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 14269 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 14270 } 14271 14272 long callingId = Binder.clearCallingIdentity(); 14273 try { 14274 boolean installed = false; 14275 final boolean instantApp = 14276 (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 14277 final boolean fullApp = 14278 (installFlags & PackageManager.INSTALL_FULL_APP) != 0; 14279 14280 // writer 14281 synchronized (mPackages) { 14282 pkgSetting = mSettings.mPackages.get(packageName); 14283 if (pkgSetting == null) { 14284 return PackageManager.INSTALL_FAILED_INVALID_URI; 14285 } 14286 if (!pkgSetting.getInstalled(userId)) { 14287 pkgSetting.setInstalled(true, userId); 14288 pkgSetting.setHidden(false, userId); 14289 pkgSetting.setInstallReason(installReason, userId); 14290 mSettings.writePackageRestrictionsLPr(userId); 14291 mSettings.writeKernelMappingLPr(pkgSetting); 14292 installed = true; 14293 } else if (fullApp && pkgSetting.getInstantApp(userId)) { 14294 // upgrade app from instant to full; we don't allow app downgrade 14295 installed = true; 14296 } 14297 setInstantAppForUser(pkgSetting, userId, instantApp, fullApp); 14298 } 14299 14300 if (installed) { 14301 if (pkgSetting.pkg != null) { 14302 synchronized (mInstallLock) { 14303 // We don't need to freeze for a brand new install 14304 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 14305 } 14306 } 14307 sendPackageAddedForUser(packageName, pkgSetting, userId); 14308 synchronized (mPackages) { 14309 updateSequenceNumberLP(packageName, new int[]{ userId }); 14310 } 14311 } 14312 } finally { 14313 Binder.restoreCallingIdentity(callingId); 14314 } 14315 14316 return PackageManager.INSTALL_SUCCEEDED; 14317 } 14318 14319 void setInstantAppForUser(PackageSetting pkgSetting, int userId, 14320 boolean instantApp, boolean fullApp) { 14321 // no state specified; do nothing 14322 if (!instantApp && !fullApp) { 14323 return; 14324 } 14325 if (userId != UserHandle.USER_ALL) { 14326 if (instantApp && !pkgSetting.getInstantApp(userId)) { 14327 pkgSetting.setInstantApp(true /*instantApp*/, userId); 14328 } else if (fullApp && pkgSetting.getInstantApp(userId)) { 14329 pkgSetting.setInstantApp(false /*instantApp*/, userId); 14330 } 14331 } else { 14332 for (int currentUserId : sUserManager.getUserIds()) { 14333 if (instantApp && !pkgSetting.getInstantApp(currentUserId)) { 14334 pkgSetting.setInstantApp(true /*instantApp*/, currentUserId); 14335 } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) { 14336 pkgSetting.setInstantApp(false /*instantApp*/, currentUserId); 14337 } 14338 } 14339 } 14340 } 14341 14342 boolean isUserRestricted(int userId, String restrictionKey) { 14343 Bundle restrictions = sUserManager.getUserRestrictions(userId); 14344 if (restrictions.getBoolean(restrictionKey, false)) { 14345 Log.w(TAG, "User is restricted: " + restrictionKey); 14346 return true; 14347 } 14348 return false; 14349 } 14350 14351 @Override 14352 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 14353 int userId) { 14354 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 14355 enforceCrossUserPermission(Binder.getCallingUid(), userId, 14356 true /* requireFullPermission */, true /* checkShell */, 14357 "setPackagesSuspended for user " + userId); 14358 14359 if (ArrayUtils.isEmpty(packageNames)) { 14360 return packageNames; 14361 } 14362 14363 // List of package names for whom the suspended state has changed. 14364 List<String> changedPackages = new ArrayList<>(packageNames.length); 14365 // List of package names for whom the suspended state is not set as requested in this 14366 // method. 14367 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 14368 long callingId = Binder.clearCallingIdentity(); 14369 try { 14370 for (int i = 0; i < packageNames.length; i++) { 14371 String packageName = packageNames[i]; 14372 boolean changed = false; 14373 final int appId; 14374 synchronized (mPackages) { 14375 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 14376 if (pkgSetting == null) { 14377 Slog.w(TAG, "Could not find package setting for package \"" + packageName 14378 + "\". Skipping suspending/un-suspending."); 14379 unactionedPackages.add(packageName); 14380 continue; 14381 } 14382 appId = pkgSetting.appId; 14383 if (pkgSetting.getSuspended(userId) != suspended) { 14384 if (!canSuspendPackageForUserLocked(packageName, userId)) { 14385 unactionedPackages.add(packageName); 14386 continue; 14387 } 14388 pkgSetting.setSuspended(suspended, userId); 14389 mSettings.writePackageRestrictionsLPr(userId); 14390 changed = true; 14391 changedPackages.add(packageName); 14392 } 14393 } 14394 14395 if (changed && suspended) { 14396 killApplication(packageName, UserHandle.getUid(userId, appId), 14397 "suspending package"); 14398 } 14399 } 14400 } finally { 14401 Binder.restoreCallingIdentity(callingId); 14402 } 14403 14404 if (!changedPackages.isEmpty()) { 14405 sendPackagesSuspendedForUser(changedPackages.toArray( 14406 new String[changedPackages.size()]), userId, suspended); 14407 } 14408 14409 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 14410 } 14411 14412 @Override 14413 public boolean isPackageSuspendedForUser(String packageName, int userId) { 14414 final int callingUid = Binder.getCallingUid(); 14415 enforceCrossUserPermission(callingUid, userId, 14416 true /* requireFullPermission */, false /* checkShell */, 14417 "isPackageSuspendedForUser for user " + userId); 14418 synchronized (mPackages) { 14419 final PackageSetting ps = mSettings.mPackages.get(packageName); 14420 if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) { 14421 throw new IllegalArgumentException("Unknown target package: " + packageName); 14422 } 14423 return ps.getSuspended(userId); 14424 } 14425 } 14426 14427 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 14428 if (isPackageDeviceAdmin(packageName, userId)) { 14429 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 14430 + "\": has an active device admin"); 14431 return false; 14432 } 14433 14434 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 14435 if (packageName.equals(activeLauncherPackageName)) { 14436 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 14437 + "\": contains the active launcher"); 14438 return false; 14439 } 14440 14441 if (packageName.equals(mRequiredInstallerPackage)) { 14442 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 14443 + "\": required for package installation"); 14444 return false; 14445 } 14446 14447 if (packageName.equals(mRequiredUninstallerPackage)) { 14448 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 14449 + "\": required for package uninstallation"); 14450 return false; 14451 } 14452 14453 if (packageName.equals(mRequiredVerifierPackage)) { 14454 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 14455 + "\": required for package verification"); 14456 return false; 14457 } 14458 14459 if (packageName.equals(getDefaultDialerPackageName(userId))) { 14460 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 14461 + "\": is the default dialer"); 14462 return false; 14463 } 14464 14465 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 14466 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 14467 + "\": protected package"); 14468 return false; 14469 } 14470 14471 // Cannot suspend static shared libs as they are considered 14472 // a part of the using app (emulating static linking). Also 14473 // static libs are installed always on internal storage. 14474 PackageParser.Package pkg = mPackages.get(packageName); 14475 if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) { 14476 Slog.w(TAG, "Cannot suspend package: " + packageName 14477 + " providing static shared library: " 14478 + pkg.staticSharedLibName); 14479 return false; 14480 } 14481 14482 return true; 14483 } 14484 14485 private String getActiveLauncherPackageName(int userId) { 14486 Intent intent = new Intent(Intent.ACTION_MAIN); 14487 intent.addCategory(Intent.CATEGORY_HOME); 14488 ResolveInfo resolveInfo = resolveIntent( 14489 intent, 14490 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 14491 PackageManager.MATCH_DEFAULT_ONLY, 14492 userId); 14493 14494 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 14495 } 14496 14497 private String getDefaultDialerPackageName(int userId) { 14498 synchronized (mPackages) { 14499 return mSettings.getDefaultDialerPackageNameLPw(userId); 14500 } 14501 } 14502 14503 @Override 14504 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 14505 mContext.enforceCallingOrSelfPermission( 14506 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 14507 "Only package verification agents can verify applications"); 14508 14509 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 14510 final PackageVerificationResponse response = new PackageVerificationResponse( 14511 verificationCode, Binder.getCallingUid()); 14512 msg.arg1 = id; 14513 msg.obj = response; 14514 mHandler.sendMessage(msg); 14515 } 14516 14517 @Override 14518 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 14519 long millisecondsToDelay) { 14520 mContext.enforceCallingOrSelfPermission( 14521 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 14522 "Only package verification agents can extend verification timeouts"); 14523 14524 final PackageVerificationState state = mPendingVerification.get(id); 14525 final PackageVerificationResponse response = new PackageVerificationResponse( 14526 verificationCodeAtTimeout, Binder.getCallingUid()); 14527 14528 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 14529 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 14530 } 14531 if (millisecondsToDelay < 0) { 14532 millisecondsToDelay = 0; 14533 } 14534 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 14535 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 14536 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 14537 } 14538 14539 if ((state != null) && !state.timeoutExtended()) { 14540 state.extendTimeout(); 14541 14542 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 14543 msg.arg1 = id; 14544 msg.obj = response; 14545 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 14546 } 14547 } 14548 14549 private void broadcastPackageVerified(int verificationId, Uri packageUri, 14550 int verificationCode, UserHandle user) { 14551 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 14552 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 14553 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 14554 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 14555 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 14556 14557 mContext.sendBroadcastAsUser(intent, user, 14558 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 14559 } 14560 14561 private ComponentName matchComponentForVerifier(String packageName, 14562 List<ResolveInfo> receivers) { 14563 ActivityInfo targetReceiver = null; 14564 14565 final int NR = receivers.size(); 14566 for (int i = 0; i < NR; i++) { 14567 final ResolveInfo info = receivers.get(i); 14568 if (info.activityInfo == null) { 14569 continue; 14570 } 14571 14572 if (packageName.equals(info.activityInfo.packageName)) { 14573 targetReceiver = info.activityInfo; 14574 break; 14575 } 14576 } 14577 14578 if (targetReceiver == null) { 14579 return null; 14580 } 14581 14582 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 14583 } 14584 14585 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 14586 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 14587 if (pkgInfo.verifiers.length == 0) { 14588 return null; 14589 } 14590 14591 final int N = pkgInfo.verifiers.length; 14592 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 14593 for (int i = 0; i < N; i++) { 14594 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 14595 14596 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 14597 receivers); 14598 if (comp == null) { 14599 continue; 14600 } 14601 14602 final int verifierUid = getUidForVerifier(verifierInfo); 14603 if (verifierUid == -1) { 14604 continue; 14605 } 14606 14607 if (DEBUG_VERIFY) { 14608 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 14609 + " with the correct signature"); 14610 } 14611 sufficientVerifiers.add(comp); 14612 verificationState.addSufficientVerifier(verifierUid); 14613 } 14614 14615 return sufficientVerifiers; 14616 } 14617 14618 private int getUidForVerifier(VerifierInfo verifierInfo) { 14619 synchronized (mPackages) { 14620 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 14621 if (pkg == null) { 14622 return -1; 14623 } else if (pkg.mSignatures.length != 1) { 14624 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 14625 + " has more than one signature; ignoring"); 14626 return -1; 14627 } 14628 14629 /* 14630 * If the public key of the package's signature does not match 14631 * our expected public key, then this is a different package and 14632 * we should skip. 14633 */ 14634 14635 final byte[] expectedPublicKey; 14636 try { 14637 final Signature verifierSig = pkg.mSignatures[0]; 14638 final PublicKey publicKey = verifierSig.getPublicKey(); 14639 expectedPublicKey = publicKey.getEncoded(); 14640 } catch (CertificateException e) { 14641 return -1; 14642 } 14643 14644 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 14645 14646 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 14647 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 14648 + " does not have the expected public key; ignoring"); 14649 return -1; 14650 } 14651 14652 return pkg.applicationInfo.uid; 14653 } 14654 } 14655 14656 @Override 14657 public void finishPackageInstall(int token, boolean didLaunch) { 14658 enforceSystemOrRoot("Only the system is allowed to finish installs"); 14659 14660 if (DEBUG_INSTALL) { 14661 Slog.v(TAG, "BM finishing package install for " + token); 14662 } 14663 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 14664 14665 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 14666 mHandler.sendMessage(msg); 14667 } 14668 14669 /** 14670 * Get the verification agent timeout. Used for both the APK verifier and the 14671 * intent filter verifier. 14672 * 14673 * @return verification timeout in milliseconds 14674 */ 14675 private long getVerificationTimeout() { 14676 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 14677 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 14678 DEFAULT_VERIFICATION_TIMEOUT); 14679 } 14680 14681 /** 14682 * Get the default verification agent response code. 14683 * 14684 * @return default verification response code 14685 */ 14686 private int getDefaultVerificationResponse(UserHandle user) { 14687 if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) { 14688 return PackageManager.VERIFICATION_REJECT; 14689 } 14690 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 14691 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 14692 DEFAULT_VERIFICATION_RESPONSE); 14693 } 14694 14695 /** 14696 * Check whether or not package verification has been enabled. 14697 * 14698 * @return true if verification should be performed 14699 */ 14700 private boolean isVerificationEnabled(int userId, int installFlags) { 14701 if (!DEFAULT_VERIFY_ENABLE) { 14702 return false; 14703 } 14704 14705 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 14706 14707 // Check if installing from ADB 14708 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 14709 // Do not run verification in a test harness environment 14710 if (ActivityManager.isRunningInTestHarness()) { 14711 return false; 14712 } 14713 if (ensureVerifyAppsEnabled) { 14714 return true; 14715 } 14716 // Check if the developer does not want package verification for ADB installs 14717 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 14718 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 14719 return false; 14720 } 14721 } 14722 14723 if (ensureVerifyAppsEnabled) { 14724 return true; 14725 } 14726 14727 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 14728 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 14729 } 14730 14731 @Override 14732 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 14733 throws RemoteException { 14734 mContext.enforceCallingOrSelfPermission( 14735 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 14736 "Only intentfilter verification agents can verify applications"); 14737 14738 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 14739 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 14740 Binder.getCallingUid(), verificationCode, failedDomains); 14741 msg.arg1 = id; 14742 msg.obj = response; 14743 mHandler.sendMessage(msg); 14744 } 14745 14746 @Override 14747 public int getIntentVerificationStatus(String packageName, int userId) { 14748 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 14749 return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 14750 } 14751 synchronized (mPackages) { 14752 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 14753 } 14754 } 14755 14756 @Override 14757 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 14758 mContext.enforceCallingOrSelfPermission( 14759 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14760 14761 boolean result = false; 14762 synchronized (mPackages) { 14763 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 14764 } 14765 if (result) { 14766 scheduleWritePackageRestrictionsLocked(userId); 14767 } 14768 return result; 14769 } 14770 14771 @Override 14772 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 14773 String packageName) { 14774 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 14775 return ParceledListSlice.emptyList(); 14776 } 14777 synchronized (mPackages) { 14778 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 14779 } 14780 } 14781 14782 @Override 14783 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 14784 if (TextUtils.isEmpty(packageName)) { 14785 return ParceledListSlice.emptyList(); 14786 } 14787 final int callingUid = Binder.getCallingUid(); 14788 final int callingUserId = UserHandle.getUserId(callingUid); 14789 synchronized (mPackages) { 14790 PackageParser.Package pkg = mPackages.get(packageName); 14791 if (pkg == null || pkg.activities == null) { 14792 return ParceledListSlice.emptyList(); 14793 } 14794 if (pkg.mExtras == null) { 14795 return ParceledListSlice.emptyList(); 14796 } 14797 final PackageSetting ps = (PackageSetting) pkg.mExtras; 14798 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 14799 return ParceledListSlice.emptyList(); 14800 } 14801 final int count = pkg.activities.size(); 14802 ArrayList<IntentFilter> result = new ArrayList<>(); 14803 for (int n=0; n<count; n++) { 14804 PackageParser.Activity activity = pkg.activities.get(n); 14805 if (activity.intents != null && activity.intents.size() > 0) { 14806 result.addAll(activity.intents); 14807 } 14808 } 14809 return new ParceledListSlice<>(result); 14810 } 14811 } 14812 14813 @Override 14814 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 14815 mContext.enforceCallingOrSelfPermission( 14816 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14817 14818 synchronized (mPackages) { 14819 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 14820 if (packageName != null) { 14821 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 14822 packageName, userId); 14823 } 14824 return result; 14825 } 14826 } 14827 14828 @Override 14829 public String getDefaultBrowserPackageName(int userId) { 14830 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 14831 return null; 14832 } 14833 synchronized (mPackages) { 14834 return mSettings.getDefaultBrowserPackageNameLPw(userId); 14835 } 14836 } 14837 14838 /** 14839 * Get the "allow unknown sources" setting. 14840 * 14841 * @return the current "allow unknown sources" setting 14842 */ 14843 private int getUnknownSourcesSettings() { 14844 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 14845 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 14846 -1); 14847 } 14848 14849 @Override 14850 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 14851 final int callingUid = Binder.getCallingUid(); 14852 if (getInstantAppPackageName(callingUid) != null) { 14853 return; 14854 } 14855 // writer 14856 synchronized (mPackages) { 14857 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 14858 if (targetPackageSetting == null) { 14859 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 14860 } 14861 14862 PackageSetting installerPackageSetting; 14863 if (installerPackageName != null) { 14864 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 14865 if (installerPackageSetting == null) { 14866 throw new IllegalArgumentException("Unknown installer package: " 14867 + installerPackageName); 14868 } 14869 } else { 14870 installerPackageSetting = null; 14871 } 14872 14873 Signature[] callerSignature; 14874 Object obj = mSettings.getUserIdLPr(callingUid); 14875 if (obj != null) { 14876 if (obj instanceof SharedUserSetting) { 14877 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 14878 } else if (obj instanceof PackageSetting) { 14879 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 14880 } else { 14881 throw new SecurityException("Bad object " + obj + " for uid " + callingUid); 14882 } 14883 } else { 14884 throw new SecurityException("Unknown calling UID: " + callingUid); 14885 } 14886 14887 // Verify: can't set installerPackageName to a package that is 14888 // not signed with the same cert as the caller. 14889 if (installerPackageSetting != null) { 14890 if (compareSignatures(callerSignature, 14891 installerPackageSetting.signatures.mSignatures) 14892 != PackageManager.SIGNATURE_MATCH) { 14893 throw new SecurityException( 14894 "Caller does not have same cert as new installer package " 14895 + installerPackageName); 14896 } 14897 } 14898 14899 // Verify: if target already has an installer package, it must 14900 // be signed with the same cert as the caller. 14901 if (targetPackageSetting.installerPackageName != null) { 14902 PackageSetting setting = mSettings.mPackages.get( 14903 targetPackageSetting.installerPackageName); 14904 // If the currently set package isn't valid, then it's always 14905 // okay to change it. 14906 if (setting != null) { 14907 if (compareSignatures(callerSignature, 14908 setting.signatures.mSignatures) 14909 != PackageManager.SIGNATURE_MATCH) { 14910 throw new SecurityException( 14911 "Caller does not have same cert as old installer package " 14912 + targetPackageSetting.installerPackageName); 14913 } 14914 } 14915 } 14916 14917 // Okay! 14918 targetPackageSetting.installerPackageName = installerPackageName; 14919 if (installerPackageName != null) { 14920 mSettings.mInstallerPackages.add(installerPackageName); 14921 } 14922 scheduleWriteSettingsLocked(); 14923 } 14924 } 14925 14926 @Override 14927 public void setApplicationCategoryHint(String packageName, int categoryHint, 14928 String callerPackageName) { 14929 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 14930 throw new SecurityException("Instant applications don't have access to this method"); 14931 } 14932 mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(), 14933 callerPackageName); 14934 synchronized (mPackages) { 14935 PackageSetting ps = mSettings.mPackages.get(packageName); 14936 if (ps == null) { 14937 throw new IllegalArgumentException("Unknown target package " + packageName); 14938 } 14939 14940 if (!Objects.equals(callerPackageName, ps.installerPackageName)) { 14941 throw new IllegalArgumentException("Calling package " + callerPackageName 14942 + " is not installer for " + packageName); 14943 } 14944 14945 if (ps.categoryHint != categoryHint) { 14946 ps.categoryHint = categoryHint; 14947 scheduleWriteSettingsLocked(); 14948 } 14949 } 14950 } 14951 14952 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 14953 // Queue up an async operation since the package installation may take a little while. 14954 mHandler.post(new Runnable() { 14955 public void run() { 14956 mHandler.removeCallbacks(this); 14957 // Result object to be returned 14958 PackageInstalledInfo res = new PackageInstalledInfo(); 14959 res.setReturnCode(currentStatus); 14960 res.uid = -1; 14961 res.pkg = null; 14962 res.removedInfo = null; 14963 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14964 args.doPreInstall(res.returnCode); 14965 synchronized (mInstallLock) { 14966 installPackageTracedLI(args, res); 14967 } 14968 args.doPostInstall(res.returnCode, res.uid); 14969 } 14970 14971 // A restore should be performed at this point if (a) the install 14972 // succeeded, (b) the operation is not an update, and (c) the new 14973 // package has not opted out of backup participation. 14974 final boolean update = res.removedInfo != null 14975 && res.removedInfo.removedPackage != null; 14976 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 14977 boolean doRestore = !update 14978 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 14979 14980 // Set up the post-install work request bookkeeping. This will be used 14981 // and cleaned up by the post-install event handling regardless of whether 14982 // there's a restore pass performed. Token values are >= 1. 14983 int token; 14984 if (mNextInstallToken < 0) mNextInstallToken = 1; 14985 token = mNextInstallToken++; 14986 14987 PostInstallData data = new PostInstallData(args, res); 14988 mRunningInstalls.put(token, data); 14989 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 14990 14991 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 14992 // Pass responsibility to the Backup Manager. It will perform a 14993 // restore if appropriate, then pass responsibility back to the 14994 // Package Manager to run the post-install observer callbacks 14995 // and broadcasts. 14996 IBackupManager bm = IBackupManager.Stub.asInterface( 14997 ServiceManager.getService(Context.BACKUP_SERVICE)); 14998 if (bm != null) { 14999 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 15000 + " to BM for possible restore"); 15001 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 15002 try { 15003 // TODO: http://b/22388012 15004 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 15005 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 15006 } else { 15007 doRestore = false; 15008 } 15009 } catch (RemoteException e) { 15010 // can't happen; the backup manager is local 15011 } catch (Exception e) { 15012 Slog.e(TAG, "Exception trying to enqueue restore", e); 15013 doRestore = false; 15014 } 15015 } else { 15016 Slog.e(TAG, "Backup Manager not found!"); 15017 doRestore = false; 15018 } 15019 } 15020 15021 if (!doRestore) { 15022 // No restore possible, or the Backup Manager was mysteriously not 15023 // available -- just fire the post-install work request directly. 15024 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 15025 15026 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 15027 15028 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 15029 mHandler.sendMessage(msg); 15030 } 15031 } 15032 }); 15033 } 15034 15035 /** 15036 * Callback from PackageSettings whenever an app is first transitioned out of the 15037 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 15038 * the app was "launched" for a restoreAtInstall operation. Therefore we check 15039 * here whether the app is the target of an ongoing install, and only send the 15040 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 15041 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 15042 * handling. 15043 */ 15044 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 15045 // Serialize this with the rest of the install-process message chain. In the 15046 // restore-at-install case, this Runnable will necessarily run before the 15047 // POST_INSTALL message is processed, so the contents of mRunningInstalls 15048 // are coherent. In the non-restore case, the app has already completed install 15049 // and been launched through some other means, so it is not in a problematic 15050 // state for observers to see the FIRST_LAUNCH signal. 15051 mHandler.post(new Runnable() { 15052 @Override 15053 public void run() { 15054 for (int i = 0; i < mRunningInstalls.size(); i++) { 15055 final PostInstallData data = mRunningInstalls.valueAt(i); 15056 if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 15057 continue; 15058 } 15059 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 15060 // right package; but is it for the right user? 15061 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 15062 if (userId == data.res.newUsers[uIndex]) { 15063 if (DEBUG_BACKUP) { 15064 Slog.i(TAG, "Package " + pkgName 15065 + " being restored so deferring FIRST_LAUNCH"); 15066 } 15067 return; 15068 } 15069 } 15070 } 15071 } 15072 // didn't find it, so not being restored 15073 if (DEBUG_BACKUP) { 15074 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 15075 } 15076 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 15077 } 15078 }); 15079 } 15080 15081 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 15082 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 15083 installerPkg, null, userIds); 15084 } 15085 15086 private abstract class HandlerParams { 15087 private static final int MAX_RETRIES = 4; 15088 15089 /** 15090 * Number of times startCopy() has been attempted and had a non-fatal 15091 * error. 15092 */ 15093 private int mRetries = 0; 15094 15095 /** User handle for the user requesting the information or installation. */ 15096 private final UserHandle mUser; 15097 String traceMethod; 15098 int traceCookie; 15099 15100 HandlerParams(UserHandle user) { 15101 mUser = user; 15102 } 15103 15104 UserHandle getUser() { 15105 return mUser; 15106 } 15107 15108 HandlerParams setTraceMethod(String traceMethod) { 15109 this.traceMethod = traceMethod; 15110 return this; 15111 } 15112 15113 HandlerParams setTraceCookie(int traceCookie) { 15114 this.traceCookie = traceCookie; 15115 return this; 15116 } 15117 15118 final boolean startCopy() { 15119 boolean res; 15120 try { 15121 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 15122 15123 if (++mRetries > MAX_RETRIES) { 15124 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 15125 mHandler.sendEmptyMessage(MCS_GIVE_UP); 15126 handleServiceError(); 15127 return false; 15128 } else { 15129 handleStartCopy(); 15130 res = true; 15131 } 15132 } catch (RemoteException e) { 15133 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 15134 mHandler.sendEmptyMessage(MCS_RECONNECT); 15135 res = false; 15136 } 15137 handleReturnCode(); 15138 return res; 15139 } 15140 15141 final void serviceError() { 15142 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 15143 handleServiceError(); 15144 handleReturnCode(); 15145 } 15146 15147 abstract void handleStartCopy() throws RemoteException; 15148 abstract void handleServiceError(); 15149 abstract void handleReturnCode(); 15150 } 15151 15152 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 15153 for (File path : paths) { 15154 try { 15155 mcs.clearDirectory(path.getAbsolutePath()); 15156 } catch (RemoteException e) { 15157 } 15158 } 15159 } 15160 15161 static class OriginInfo { 15162 /** 15163 * Location where install is coming from, before it has been 15164 * copied/renamed into place. This could be a single monolithic APK 15165 * file, or a cluster directory. This location may be untrusted. 15166 */ 15167 final File file; 15168 final String cid; 15169 15170 /** 15171 * Flag indicating that {@link #file} or {@link #cid} has already been 15172 * staged, meaning downstream users don't need to defensively copy the 15173 * contents. 15174 */ 15175 final boolean staged; 15176 15177 /** 15178 * Flag indicating that {@link #file} or {@link #cid} is an already 15179 * installed app that is being moved. 15180 */ 15181 final boolean existing; 15182 15183 final String resolvedPath; 15184 final File resolvedFile; 15185 15186 static OriginInfo fromNothing() { 15187 return new OriginInfo(null, null, false, false); 15188 } 15189 15190 static OriginInfo fromUntrustedFile(File file) { 15191 return new OriginInfo(file, null, false, false); 15192 } 15193 15194 static OriginInfo fromExistingFile(File file) { 15195 return new OriginInfo(file, null, false, true); 15196 } 15197 15198 static OriginInfo fromStagedFile(File file) { 15199 return new OriginInfo(file, null, true, false); 15200 } 15201 15202 static OriginInfo fromStagedContainer(String cid) { 15203 return new OriginInfo(null, cid, true, false); 15204 } 15205 15206 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 15207 this.file = file; 15208 this.cid = cid; 15209 this.staged = staged; 15210 this.existing = existing; 15211 15212 if (cid != null) { 15213 resolvedPath = PackageHelper.getSdDir(cid); 15214 resolvedFile = new File(resolvedPath); 15215 } else if (file != null) { 15216 resolvedPath = file.getAbsolutePath(); 15217 resolvedFile = file; 15218 } else { 15219 resolvedPath = null; 15220 resolvedFile = null; 15221 } 15222 } 15223 } 15224 15225 static class MoveInfo { 15226 final int moveId; 15227 final String fromUuid; 15228 final String toUuid; 15229 final String packageName; 15230 final String dataAppName; 15231 final int appId; 15232 final String seinfo; 15233 final int targetSdkVersion; 15234 15235 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 15236 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 15237 this.moveId = moveId; 15238 this.fromUuid = fromUuid; 15239 this.toUuid = toUuid; 15240 this.packageName = packageName; 15241 this.dataAppName = dataAppName; 15242 this.appId = appId; 15243 this.seinfo = seinfo; 15244 this.targetSdkVersion = targetSdkVersion; 15245 } 15246 } 15247 15248 static class VerificationInfo { 15249 /** A constant used to indicate that a uid value is not present. */ 15250 public static final int NO_UID = -1; 15251 15252 /** URI referencing where the package was downloaded from. */ 15253 final Uri originatingUri; 15254 15255 /** HTTP referrer URI associated with the originatingURI. */ 15256 final Uri referrer; 15257 15258 /** UID of the application that the install request originated from. */ 15259 final int originatingUid; 15260 15261 /** UID of application requesting the install */ 15262 final int installerUid; 15263 15264 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 15265 this.originatingUri = originatingUri; 15266 this.referrer = referrer; 15267 this.originatingUid = originatingUid; 15268 this.installerUid = installerUid; 15269 } 15270 } 15271 15272 class InstallParams extends HandlerParams { 15273 final OriginInfo origin; 15274 final MoveInfo move; 15275 final IPackageInstallObserver2 observer; 15276 int installFlags; 15277 final String installerPackageName; 15278 final String volumeUuid; 15279 private InstallArgs mArgs; 15280 private int mRet; 15281 final String packageAbiOverride; 15282 final String[] grantedRuntimePermissions; 15283 final VerificationInfo verificationInfo; 15284 final Certificate[][] certificates; 15285 final int installReason; 15286 15287 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 15288 int installFlags, String installerPackageName, String volumeUuid, 15289 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 15290 String[] grantedPermissions, Certificate[][] certificates, int installReason) { 15291 super(user); 15292 this.origin = origin; 15293 this.move = move; 15294 this.observer = observer; 15295 this.installFlags = installFlags; 15296 this.installerPackageName = installerPackageName; 15297 this.volumeUuid = volumeUuid; 15298 this.verificationInfo = verificationInfo; 15299 this.packageAbiOverride = packageAbiOverride; 15300 this.grantedRuntimePermissions = grantedPermissions; 15301 this.certificates = certificates; 15302 this.installReason = installReason; 15303 } 15304 15305 @Override 15306 public String toString() { 15307 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 15308 + " file=" + origin.file + " cid=" + origin.cid + "}"; 15309 } 15310 15311 private int installLocationPolicy(PackageInfoLite pkgLite) { 15312 String packageName = pkgLite.packageName; 15313 int installLocation = pkgLite.installLocation; 15314 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 15315 // reader 15316 synchronized (mPackages) { 15317 // Currently installed package which the new package is attempting to replace or 15318 // null if no such package is installed. 15319 PackageParser.Package installedPkg = mPackages.get(packageName); 15320 // Package which currently owns the data which the new package will own if installed. 15321 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 15322 // will be null whereas dataOwnerPkg will contain information about the package 15323 // which was uninstalled while keeping its data. 15324 PackageParser.Package dataOwnerPkg = installedPkg; 15325 if (dataOwnerPkg == null) { 15326 PackageSetting ps = mSettings.mPackages.get(packageName); 15327 if (ps != null) { 15328 dataOwnerPkg = ps.pkg; 15329 } 15330 } 15331 15332 if (dataOwnerPkg != null) { 15333 // If installed, the package will get access to data left on the device by its 15334 // predecessor. As a security measure, this is permited only if this is not a 15335 // version downgrade or if the predecessor package is marked as debuggable and 15336 // a downgrade is explicitly requested. 15337 // 15338 // On debuggable platform builds, downgrades are permitted even for 15339 // non-debuggable packages to make testing easier. Debuggable platform builds do 15340 // not offer security guarantees and thus it's OK to disable some security 15341 // mechanisms to make debugging/testing easier on those builds. However, even on 15342 // debuggable builds downgrades of packages are permitted only if requested via 15343 // installFlags. This is because we aim to keep the behavior of debuggable 15344 // platform builds as close as possible to the behavior of non-debuggable 15345 // platform builds. 15346 final boolean downgradeRequested = 15347 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 15348 final boolean packageDebuggable = 15349 (dataOwnerPkg.applicationInfo.flags 15350 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 15351 final boolean downgradePermitted = 15352 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 15353 if (!downgradePermitted) { 15354 try { 15355 checkDowngrade(dataOwnerPkg, pkgLite); 15356 } catch (PackageManagerException e) { 15357 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 15358 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 15359 } 15360 } 15361 } 15362 15363 if (installedPkg != null) { 15364 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 15365 // Check for updated system application. 15366 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 15367 if (onSd) { 15368 Slog.w(TAG, "Cannot install update to system app on sdcard"); 15369 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 15370 } 15371 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 15372 } else { 15373 if (onSd) { 15374 // Install flag overrides everything. 15375 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 15376 } 15377 // If current upgrade specifies particular preference 15378 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 15379 // Application explicitly specified internal. 15380 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 15381 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 15382 // App explictly prefers external. Let policy decide 15383 } else { 15384 // Prefer previous location 15385 if (isExternal(installedPkg)) { 15386 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 15387 } 15388 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 15389 } 15390 } 15391 } else { 15392 // Invalid install. Return error code 15393 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 15394 } 15395 } 15396 } 15397 // All the special cases have been taken care of. 15398 // Return result based on recommended install location. 15399 if (onSd) { 15400 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 15401 } 15402 return pkgLite.recommendedInstallLocation; 15403 } 15404 15405 /* 15406 * Invoke remote method to get package information and install 15407 * location values. Override install location based on default 15408 * policy if needed and then create install arguments based 15409 * on the install location. 15410 */ 15411 public void handleStartCopy() throws RemoteException { 15412 int ret = PackageManager.INSTALL_SUCCEEDED; 15413 15414 // If we're already staged, we've firmly committed to an install location 15415 if (origin.staged) { 15416 if (origin.file != null) { 15417 installFlags |= PackageManager.INSTALL_INTERNAL; 15418 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 15419 } else if (origin.cid != null) { 15420 installFlags |= PackageManager.INSTALL_EXTERNAL; 15421 installFlags &= ~PackageManager.INSTALL_INTERNAL; 15422 } else { 15423 throw new IllegalStateException("Invalid stage location"); 15424 } 15425 } 15426 15427 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 15428 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 15429 final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 15430 PackageInfoLite pkgLite = null; 15431 15432 if (onInt && onSd) { 15433 // Check if both bits are set. 15434 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 15435 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 15436 } else if (onSd && ephemeral) { 15437 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 15438 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 15439 } else { 15440 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 15441 packageAbiOverride); 15442 15443 if (DEBUG_EPHEMERAL && ephemeral) { 15444 Slog.v(TAG, "pkgLite for install: " + pkgLite); 15445 } 15446 15447 /* 15448 * If we have too little free space, try to free cache 15449 * before giving up. 15450 */ 15451 if (!origin.staged && pkgLite.recommendedInstallLocation 15452 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 15453 // TODO: focus freeing disk space on the target device 15454 final StorageManager storage = StorageManager.from(mContext); 15455 final long lowThreshold = storage.getStorageLowBytes( 15456 Environment.getDataDirectory()); 15457 15458 final long sizeBytes = mContainerService.calculateInstalledSize( 15459 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 15460 15461 try { 15462 mInstaller.freeCache(null, sizeBytes + lowThreshold, 0); 15463 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 15464 installFlags, packageAbiOverride); 15465 } catch (InstallerException e) { 15466 Slog.w(TAG, "Failed to free cache", e); 15467 } 15468 15469 /* 15470 * The cache free must have deleted the file we 15471 * downloaded to install. 15472 * 15473 * TODO: fix the "freeCache" call to not delete 15474 * the file we care about. 15475 */ 15476 if (pkgLite.recommendedInstallLocation 15477 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 15478 pkgLite.recommendedInstallLocation 15479 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 15480 } 15481 } 15482 } 15483 15484 if (ret == PackageManager.INSTALL_SUCCEEDED) { 15485 int loc = pkgLite.recommendedInstallLocation; 15486 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 15487 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 15488 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 15489 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 15490 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 15491 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 15492 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 15493 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 15494 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 15495 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 15496 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 15497 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 15498 } else { 15499 // Override with defaults if needed. 15500 loc = installLocationPolicy(pkgLite); 15501 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 15502 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 15503 } else if (!onSd && !onInt) { 15504 // Override install location with flags 15505 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 15506 // Set the flag to install on external media. 15507 installFlags |= PackageManager.INSTALL_EXTERNAL; 15508 installFlags &= ~PackageManager.INSTALL_INTERNAL; 15509 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 15510 if (DEBUG_EPHEMERAL) { 15511 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 15512 } 15513 installFlags |= PackageManager.INSTALL_INSTANT_APP; 15514 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 15515 |PackageManager.INSTALL_INTERNAL); 15516 } else { 15517 // Make sure the flag for installing on external 15518 // media is unset 15519 installFlags |= PackageManager.INSTALL_INTERNAL; 15520 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 15521 } 15522 } 15523 } 15524 } 15525 15526 final InstallArgs args = createInstallArgs(this); 15527 mArgs = args; 15528 15529 if (ret == PackageManager.INSTALL_SUCCEEDED) { 15530 // TODO: http://b/22976637 15531 // Apps installed for "all" users use the device owner to verify the app 15532 UserHandle verifierUser = getUser(); 15533 if (verifierUser == UserHandle.ALL) { 15534 verifierUser = UserHandle.SYSTEM; 15535 } 15536 15537 /* 15538 * Determine if we have any installed package verifiers. If we 15539 * do, then we'll defer to them to verify the packages. 15540 */ 15541 final int requiredUid = mRequiredVerifierPackage == null ? -1 15542 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 15543 verifierUser.getIdentifier()); 15544 if (!origin.existing && requiredUid != -1 15545 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 15546 final Intent verification = new Intent( 15547 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 15548 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 15549 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 15550 PACKAGE_MIME_TYPE); 15551 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 15552 15553 // Query all live verifiers based on current user state 15554 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 15555 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 15556 15557 if (DEBUG_VERIFY) { 15558 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 15559 + verification.toString() + " with " + pkgLite.verifiers.length 15560 + " optional verifiers"); 15561 } 15562 15563 final int verificationId = mPendingVerificationToken++; 15564 15565 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 15566 15567 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 15568 installerPackageName); 15569 15570 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 15571 installFlags); 15572 15573 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 15574 pkgLite.packageName); 15575 15576 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 15577 pkgLite.versionCode); 15578 15579 if (verificationInfo != null) { 15580 if (verificationInfo.originatingUri != null) { 15581 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 15582 verificationInfo.originatingUri); 15583 } 15584 if (verificationInfo.referrer != null) { 15585 verification.putExtra(Intent.EXTRA_REFERRER, 15586 verificationInfo.referrer); 15587 } 15588 if (verificationInfo.originatingUid >= 0) { 15589 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 15590 verificationInfo.originatingUid); 15591 } 15592 if (verificationInfo.installerUid >= 0) { 15593 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 15594 verificationInfo.installerUid); 15595 } 15596 } 15597 15598 final PackageVerificationState verificationState = new PackageVerificationState( 15599 requiredUid, args); 15600 15601 mPendingVerification.append(verificationId, verificationState); 15602 15603 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 15604 receivers, verificationState); 15605 15606 DeviceIdleController.LocalService idleController = getDeviceIdleController(); 15607 final long idleDuration = getVerificationTimeout(); 15608 15609 /* 15610 * If any sufficient verifiers were listed in the package 15611 * manifest, attempt to ask them. 15612 */ 15613 if (sufficientVerifiers != null) { 15614 final int N = sufficientVerifiers.size(); 15615 if (N == 0) { 15616 Slog.i(TAG, "Additional verifiers required, but none installed."); 15617 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 15618 } else { 15619 for (int i = 0; i < N; i++) { 15620 final ComponentName verifierComponent = sufficientVerifiers.get(i); 15621 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 15622 verifierComponent.getPackageName(), idleDuration, 15623 verifierUser.getIdentifier(), false, "package verifier"); 15624 15625 final Intent sufficientIntent = new Intent(verification); 15626 sufficientIntent.setComponent(verifierComponent); 15627 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 15628 } 15629 } 15630 } 15631 15632 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 15633 mRequiredVerifierPackage, receivers); 15634 if (ret == PackageManager.INSTALL_SUCCEEDED 15635 && mRequiredVerifierPackage != null) { 15636 Trace.asyncTraceBegin( 15637 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 15638 /* 15639 * Send the intent to the required verification agent, 15640 * but only start the verification timeout after the 15641 * target BroadcastReceivers have run. 15642 */ 15643 verification.setComponent(requiredVerifierComponent); 15644 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 15645 mRequiredVerifierPackage, idleDuration, 15646 verifierUser.getIdentifier(), false, "package verifier"); 15647 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 15648 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 15649 new BroadcastReceiver() { 15650 @Override 15651 public void onReceive(Context context, Intent intent) { 15652 final Message msg = mHandler 15653 .obtainMessage(CHECK_PENDING_VERIFICATION); 15654 msg.arg1 = verificationId; 15655 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 15656 } 15657 }, null, 0, null, null); 15658 15659 /* 15660 * We don't want the copy to proceed until verification 15661 * succeeds, so null out this field. 15662 */ 15663 mArgs = null; 15664 } 15665 } else { 15666 /* 15667 * No package verification is enabled, so immediately start 15668 * the remote call to initiate copy using temporary file. 15669 */ 15670 ret = args.copyApk(mContainerService, true); 15671 } 15672 } 15673 15674 mRet = ret; 15675 } 15676 15677 @Override 15678 void handleReturnCode() { 15679 // If mArgs is null, then MCS couldn't be reached. When it 15680 // reconnects, it will try again to install. At that point, this 15681 // will succeed. 15682 if (mArgs != null) { 15683 processPendingInstall(mArgs, mRet); 15684 } 15685 } 15686 15687 @Override 15688 void handleServiceError() { 15689 mArgs = createInstallArgs(this); 15690 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15691 } 15692 15693 public boolean isForwardLocked() { 15694 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 15695 } 15696 } 15697 15698 /** 15699 * Used during creation of InstallArgs 15700 * 15701 * @param installFlags package installation flags 15702 * @return true if should be installed on external storage 15703 */ 15704 private static boolean installOnExternalAsec(int installFlags) { 15705 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 15706 return false; 15707 } 15708 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 15709 return true; 15710 } 15711 return false; 15712 } 15713 15714 /** 15715 * Used during creation of InstallArgs 15716 * 15717 * @param installFlags package installation flags 15718 * @return true if should be installed as forward locked 15719 */ 15720 private static boolean installForwardLocked(int installFlags) { 15721 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 15722 } 15723 15724 private InstallArgs createInstallArgs(InstallParams params) { 15725 if (params.move != null) { 15726 return new MoveInstallArgs(params); 15727 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 15728 return new AsecInstallArgs(params); 15729 } else { 15730 return new FileInstallArgs(params); 15731 } 15732 } 15733 15734 /** 15735 * Create args that describe an existing installed package. Typically used 15736 * when cleaning up old installs, or used as a move source. 15737 */ 15738 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 15739 String resourcePath, String[] instructionSets) { 15740 final boolean isInAsec; 15741 if (installOnExternalAsec(installFlags)) { 15742 /* Apps on SD card are always in ASEC containers. */ 15743 isInAsec = true; 15744 } else if (installForwardLocked(installFlags) 15745 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 15746 /* 15747 * Forward-locked apps are only in ASEC containers if they're the 15748 * new style 15749 */ 15750 isInAsec = true; 15751 } else { 15752 isInAsec = false; 15753 } 15754 15755 if (isInAsec) { 15756 return new AsecInstallArgs(codePath, instructionSets, 15757 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 15758 } else { 15759 return new FileInstallArgs(codePath, resourcePath, instructionSets); 15760 } 15761 } 15762 15763 static abstract class InstallArgs { 15764 /** @see InstallParams#origin */ 15765 final OriginInfo origin; 15766 /** @see InstallParams#move */ 15767 final MoveInfo move; 15768 15769 final IPackageInstallObserver2 observer; 15770 // Always refers to PackageManager flags only 15771 final int installFlags; 15772 final String installerPackageName; 15773 final String volumeUuid; 15774 final UserHandle user; 15775 final String abiOverride; 15776 final String[] installGrantPermissions; 15777 /** If non-null, drop an async trace when the install completes */ 15778 final String traceMethod; 15779 final int traceCookie; 15780 final Certificate[][] certificates; 15781 final int installReason; 15782 15783 // The list of instruction sets supported by this app. This is currently 15784 // only used during the rmdex() phase to clean up resources. We can get rid of this 15785 // if we move dex files under the common app path. 15786 /* nullable */ String[] instructionSets; 15787 15788 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 15789 int installFlags, String installerPackageName, String volumeUuid, 15790 UserHandle user, String[] instructionSets, 15791 String abiOverride, String[] installGrantPermissions, 15792 String traceMethod, int traceCookie, Certificate[][] certificates, 15793 int installReason) { 15794 this.origin = origin; 15795 this.move = move; 15796 this.installFlags = installFlags; 15797 this.observer = observer; 15798 this.installerPackageName = installerPackageName; 15799 this.volumeUuid = volumeUuid; 15800 this.user = user; 15801 this.instructionSets = instructionSets; 15802 this.abiOverride = abiOverride; 15803 this.installGrantPermissions = installGrantPermissions; 15804 this.traceMethod = traceMethod; 15805 this.traceCookie = traceCookie; 15806 this.certificates = certificates; 15807 this.installReason = installReason; 15808 } 15809 15810 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 15811 abstract int doPreInstall(int status); 15812 15813 /** 15814 * Rename package into final resting place. All paths on the given 15815 * scanned package should be updated to reflect the rename. 15816 */ 15817 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 15818 abstract int doPostInstall(int status, int uid); 15819 15820 /** @see PackageSettingBase#codePathString */ 15821 abstract String getCodePath(); 15822 /** @see PackageSettingBase#resourcePathString */ 15823 abstract String getResourcePath(); 15824 15825 // Need installer lock especially for dex file removal. 15826 abstract void cleanUpResourcesLI(); 15827 abstract boolean doPostDeleteLI(boolean delete); 15828 15829 /** 15830 * Called before the source arguments are copied. This is used mostly 15831 * for MoveParams when it needs to read the source file to put it in the 15832 * destination. 15833 */ 15834 int doPreCopy() { 15835 return PackageManager.INSTALL_SUCCEEDED; 15836 } 15837 15838 /** 15839 * Called after the source arguments are copied. This is used mostly for 15840 * MoveParams when it needs to read the source file to put it in the 15841 * destination. 15842 */ 15843 int doPostCopy(int uid) { 15844 return PackageManager.INSTALL_SUCCEEDED; 15845 } 15846 15847 protected boolean isFwdLocked() { 15848 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 15849 } 15850 15851 protected boolean isExternalAsec() { 15852 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 15853 } 15854 15855 protected boolean isEphemeral() { 15856 return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 15857 } 15858 15859 UserHandle getUser() { 15860 return user; 15861 } 15862 } 15863 15864 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 15865 if (!allCodePaths.isEmpty()) { 15866 if (instructionSets == null) { 15867 throw new IllegalStateException("instructionSet == null"); 15868 } 15869 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 15870 for (String codePath : allCodePaths) { 15871 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 15872 try { 15873 mInstaller.rmdex(codePath, dexCodeInstructionSet); 15874 } catch (InstallerException ignored) { 15875 } 15876 } 15877 } 15878 } 15879 } 15880 15881 /** 15882 * Logic to handle installation of non-ASEC applications, including copying 15883 * and renaming logic. 15884 */ 15885 class FileInstallArgs extends InstallArgs { 15886 private File codeFile; 15887 private File resourceFile; 15888 15889 // Example topology: 15890 // /data/app/com.example/base.apk 15891 // /data/app/com.example/split_foo.apk 15892 // /data/app/com.example/lib/arm/libfoo.so 15893 // /data/app/com.example/lib/arm64/libfoo.so 15894 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 15895 15896 /** New install */ 15897 FileInstallArgs(InstallParams params) { 15898 super(params.origin, params.move, params.observer, params.installFlags, 15899 params.installerPackageName, params.volumeUuid, 15900 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 15901 params.grantedRuntimePermissions, 15902 params.traceMethod, params.traceCookie, params.certificates, 15903 params.installReason); 15904 if (isFwdLocked()) { 15905 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 15906 } 15907 } 15908 15909 /** Existing install */ 15910 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 15911 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 15912 null, null, null, 0, null /*certificates*/, 15913 PackageManager.INSTALL_REASON_UNKNOWN); 15914 this.codeFile = (codePath != null) ? new File(codePath) : null; 15915 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 15916 } 15917 15918 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 15919 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 15920 try { 15921 return doCopyApk(imcs, temp); 15922 } finally { 15923 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15924 } 15925 } 15926 15927 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 15928 if (origin.staged) { 15929 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 15930 codeFile = origin.file; 15931 resourceFile = origin.file; 15932 return PackageManager.INSTALL_SUCCEEDED; 15933 } 15934 15935 try { 15936 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 15937 final File tempDir = 15938 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 15939 codeFile = tempDir; 15940 resourceFile = tempDir; 15941 } catch (IOException e) { 15942 Slog.w(TAG, "Failed to create copy file: " + e); 15943 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 15944 } 15945 15946 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 15947 @Override 15948 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 15949 if (!FileUtils.isValidExtFilename(name)) { 15950 throw new IllegalArgumentException("Invalid filename: " + name); 15951 } 15952 try { 15953 final File file = new File(codeFile, name); 15954 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 15955 O_RDWR | O_CREAT, 0644); 15956 Os.chmod(file.getAbsolutePath(), 0644); 15957 return new ParcelFileDescriptor(fd); 15958 } catch (ErrnoException e) { 15959 throw new RemoteException("Failed to open: " + e.getMessage()); 15960 } 15961 } 15962 }; 15963 15964 int ret = PackageManager.INSTALL_SUCCEEDED; 15965 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 15966 if (ret != PackageManager.INSTALL_SUCCEEDED) { 15967 Slog.e(TAG, "Failed to copy package"); 15968 return ret; 15969 } 15970 15971 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 15972 NativeLibraryHelper.Handle handle = null; 15973 try { 15974 handle = NativeLibraryHelper.Handle.create(codeFile); 15975 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 15976 abiOverride); 15977 } catch (IOException e) { 15978 Slog.e(TAG, "Copying native libraries failed", e); 15979 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15980 } finally { 15981 IoUtils.closeQuietly(handle); 15982 } 15983 15984 return ret; 15985 } 15986 15987 int doPreInstall(int status) { 15988 if (status != PackageManager.INSTALL_SUCCEEDED) { 15989 cleanUp(); 15990 } 15991 return status; 15992 } 15993 15994 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15995 if (status != PackageManager.INSTALL_SUCCEEDED) { 15996 cleanUp(); 15997 return false; 15998 } 15999 16000 final File targetDir = codeFile.getParentFile(); 16001 final File beforeCodeFile = codeFile; 16002 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 16003 16004 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 16005 try { 16006 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 16007 } catch (ErrnoException e) { 16008 Slog.w(TAG, "Failed to rename", e); 16009 return false; 16010 } 16011 16012 if (!SELinux.restoreconRecursive(afterCodeFile)) { 16013 Slog.w(TAG, "Failed to restorecon"); 16014 return false; 16015 } 16016 16017 // Reflect the rename internally 16018 codeFile = afterCodeFile; 16019 resourceFile = afterCodeFile; 16020 16021 // Reflect the rename in scanned details 16022 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 16023 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 16024 afterCodeFile, pkg.baseCodePath)); 16025 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 16026 afterCodeFile, pkg.splitCodePaths)); 16027 16028 // Reflect the rename in app info 16029 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 16030 pkg.setApplicationInfoCodePath(pkg.codePath); 16031 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 16032 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 16033 pkg.setApplicationInfoResourcePath(pkg.codePath); 16034 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 16035 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 16036 16037 return true; 16038 } 16039 16040 int doPostInstall(int status, int uid) { 16041 if (status != PackageManager.INSTALL_SUCCEEDED) { 16042 cleanUp(); 16043 } 16044 return status; 16045 } 16046 16047 @Override 16048 String getCodePath() { 16049 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 16050 } 16051 16052 @Override 16053 String getResourcePath() { 16054 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 16055 } 16056 16057 private boolean cleanUp() { 16058 if (codeFile == null || !codeFile.exists()) { 16059 return false; 16060 } 16061 16062 removeCodePathLI(codeFile); 16063 16064 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 16065 resourceFile.delete(); 16066 } 16067 16068 return true; 16069 } 16070 16071 void cleanUpResourcesLI() { 16072 // Try enumerating all code paths before deleting 16073 List<String> allCodePaths = Collections.EMPTY_LIST; 16074 if (codeFile != null && codeFile.exists()) { 16075 try { 16076 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 16077 allCodePaths = pkg.getAllCodePaths(); 16078 } catch (PackageParserException e) { 16079 // Ignored; we tried our best 16080 } 16081 } 16082 16083 cleanUp(); 16084 removeDexFiles(allCodePaths, instructionSets); 16085 } 16086 16087 boolean doPostDeleteLI(boolean delete) { 16088 // XXX err, shouldn't we respect the delete flag? 16089 cleanUpResourcesLI(); 16090 return true; 16091 } 16092 } 16093 16094 private boolean isAsecExternal(String cid) { 16095 final String asecPath = PackageHelper.getSdFilesystem(cid); 16096 return !asecPath.startsWith(mAsecInternalPath); 16097 } 16098 16099 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 16100 PackageManagerException { 16101 if (copyRet < 0) { 16102 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 16103 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 16104 throw new PackageManagerException(copyRet, message); 16105 } 16106 } 16107 } 16108 16109 /** 16110 * Extract the StorageManagerService "container ID" from the full code path of an 16111 * .apk. 16112 */ 16113 static String cidFromCodePath(String fullCodePath) { 16114 int eidx = fullCodePath.lastIndexOf("/"); 16115 String subStr1 = fullCodePath.substring(0, eidx); 16116 int sidx = subStr1.lastIndexOf("/"); 16117 return subStr1.substring(sidx+1, eidx); 16118 } 16119 16120 /** 16121 * Logic to handle installation of ASEC applications, including copying and 16122 * renaming logic. 16123 */ 16124 class AsecInstallArgs extends InstallArgs { 16125 static final String RES_FILE_NAME = "pkg.apk"; 16126 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 16127 16128 String cid; 16129 String packagePath; 16130 String resourcePath; 16131 16132 /** New install */ 16133 AsecInstallArgs(InstallParams params) { 16134 super(params.origin, params.move, params.observer, params.installFlags, 16135 params.installerPackageName, params.volumeUuid, 16136 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 16137 params.grantedRuntimePermissions, 16138 params.traceMethod, params.traceCookie, params.certificates, 16139 params.installReason); 16140 } 16141 16142 /** Existing install */ 16143 AsecInstallArgs(String fullCodePath, String[] instructionSets, 16144 boolean isExternal, boolean isForwardLocked) { 16145 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 16146 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 16147 instructionSets, null, null, null, 0, null /*certificates*/, 16148 PackageManager.INSTALL_REASON_UNKNOWN); 16149 // Hackily pretend we're still looking at a full code path 16150 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 16151 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 16152 } 16153 16154 // Extract cid from fullCodePath 16155 int eidx = fullCodePath.lastIndexOf("/"); 16156 String subStr1 = fullCodePath.substring(0, eidx); 16157 int sidx = subStr1.lastIndexOf("/"); 16158 cid = subStr1.substring(sidx+1, eidx); 16159 setMountPath(subStr1); 16160 } 16161 16162 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 16163 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 16164 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 16165 instructionSets, null, null, null, 0, null /*certificates*/, 16166 PackageManager.INSTALL_REASON_UNKNOWN); 16167 this.cid = cid; 16168 setMountPath(PackageHelper.getSdDir(cid)); 16169 } 16170 16171 void createCopyFile() { 16172 cid = mInstallerService.allocateExternalStageCidLegacy(); 16173 } 16174 16175 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 16176 if (origin.staged && origin.cid != null) { 16177 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 16178 cid = origin.cid; 16179 setMountPath(PackageHelper.getSdDir(cid)); 16180 return PackageManager.INSTALL_SUCCEEDED; 16181 } 16182 16183 if (temp) { 16184 createCopyFile(); 16185 } else { 16186 /* 16187 * Pre-emptively destroy the container since it's destroyed if 16188 * copying fails due to it existing anyway. 16189 */ 16190 PackageHelper.destroySdDir(cid); 16191 } 16192 16193 final String newMountPath = imcs.copyPackageToContainer( 16194 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 16195 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 16196 16197 if (newMountPath != null) { 16198 setMountPath(newMountPath); 16199 return PackageManager.INSTALL_SUCCEEDED; 16200 } else { 16201 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 16202 } 16203 } 16204 16205 @Override 16206 String getCodePath() { 16207 return packagePath; 16208 } 16209 16210 @Override 16211 String getResourcePath() { 16212 return resourcePath; 16213 } 16214 16215 int doPreInstall(int status) { 16216 if (status != PackageManager.INSTALL_SUCCEEDED) { 16217 // Destroy container 16218 PackageHelper.destroySdDir(cid); 16219 } else { 16220 boolean mounted = PackageHelper.isContainerMounted(cid); 16221 if (!mounted) { 16222 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 16223 Process.SYSTEM_UID); 16224 if (newMountPath != null) { 16225 setMountPath(newMountPath); 16226 } else { 16227 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 16228 } 16229 } 16230 } 16231 return status; 16232 } 16233 16234 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 16235 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 16236 String newMountPath = null; 16237 if (PackageHelper.isContainerMounted(cid)) { 16238 // Unmount the container 16239 if (!PackageHelper.unMountSdDir(cid)) { 16240 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 16241 return false; 16242 } 16243 } 16244 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 16245 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 16246 " which might be stale. Will try to clean up."); 16247 // Clean up the stale container and proceed to recreate. 16248 if (!PackageHelper.destroySdDir(newCacheId)) { 16249 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 16250 return false; 16251 } 16252 // Successfully cleaned up stale container. Try to rename again. 16253 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 16254 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 16255 + " inspite of cleaning it up."); 16256 return false; 16257 } 16258 } 16259 if (!PackageHelper.isContainerMounted(newCacheId)) { 16260 Slog.w(TAG, "Mounting container " + newCacheId); 16261 newMountPath = PackageHelper.mountSdDir(newCacheId, 16262 getEncryptKey(), Process.SYSTEM_UID); 16263 } else { 16264 newMountPath = PackageHelper.getSdDir(newCacheId); 16265 } 16266 if (newMountPath == null) { 16267 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 16268 return false; 16269 } 16270 Log.i(TAG, "Succesfully renamed " + cid + 16271 " to " + newCacheId + 16272 " at new path: " + newMountPath); 16273 cid = newCacheId; 16274 16275 final File beforeCodeFile = new File(packagePath); 16276 setMountPath(newMountPath); 16277 final File afterCodeFile = new File(packagePath); 16278 16279 // Reflect the rename in scanned details 16280 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 16281 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 16282 afterCodeFile, pkg.baseCodePath)); 16283 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 16284 afterCodeFile, pkg.splitCodePaths)); 16285 16286 // Reflect the rename in app info 16287 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 16288 pkg.setApplicationInfoCodePath(pkg.codePath); 16289 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 16290 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 16291 pkg.setApplicationInfoResourcePath(pkg.codePath); 16292 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 16293 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 16294 16295 return true; 16296 } 16297 16298 private void setMountPath(String mountPath) { 16299 final File mountFile = new File(mountPath); 16300 16301 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 16302 if (monolithicFile.exists()) { 16303 packagePath = monolithicFile.getAbsolutePath(); 16304 if (isFwdLocked()) { 16305 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 16306 } else { 16307 resourcePath = packagePath; 16308 } 16309 } else { 16310 packagePath = mountFile.getAbsolutePath(); 16311 resourcePath = packagePath; 16312 } 16313 } 16314 16315 int doPostInstall(int status, int uid) { 16316 if (status != PackageManager.INSTALL_SUCCEEDED) { 16317 cleanUp(); 16318 } else { 16319 final int groupOwner; 16320 final String protectedFile; 16321 if (isFwdLocked()) { 16322 groupOwner = UserHandle.getSharedAppGid(uid); 16323 protectedFile = RES_FILE_NAME; 16324 } else { 16325 groupOwner = -1; 16326 protectedFile = null; 16327 } 16328 16329 if (uid < Process.FIRST_APPLICATION_UID 16330 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 16331 Slog.e(TAG, "Failed to finalize " + cid); 16332 PackageHelper.destroySdDir(cid); 16333 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 16334 } 16335 16336 boolean mounted = PackageHelper.isContainerMounted(cid); 16337 if (!mounted) { 16338 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 16339 } 16340 } 16341 return status; 16342 } 16343 16344 private void cleanUp() { 16345 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 16346 16347 // Destroy secure container 16348 PackageHelper.destroySdDir(cid); 16349 } 16350 16351 private List<String> getAllCodePaths() { 16352 final File codeFile = new File(getCodePath()); 16353 if (codeFile != null && codeFile.exists()) { 16354 try { 16355 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 16356 return pkg.getAllCodePaths(); 16357 } catch (PackageParserException e) { 16358 // Ignored; we tried our best 16359 } 16360 } 16361 return Collections.EMPTY_LIST; 16362 } 16363 16364 void cleanUpResourcesLI() { 16365 // Enumerate all code paths before deleting 16366 cleanUpResourcesLI(getAllCodePaths()); 16367 } 16368 16369 private void cleanUpResourcesLI(List<String> allCodePaths) { 16370 cleanUp(); 16371 removeDexFiles(allCodePaths, instructionSets); 16372 } 16373 16374 String getPackageName() { 16375 return getAsecPackageName(cid); 16376 } 16377 16378 boolean doPostDeleteLI(boolean delete) { 16379 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 16380 final List<String> allCodePaths = getAllCodePaths(); 16381 boolean mounted = PackageHelper.isContainerMounted(cid); 16382 if (mounted) { 16383 // Unmount first 16384 if (PackageHelper.unMountSdDir(cid)) { 16385 mounted = false; 16386 } 16387 } 16388 if (!mounted && delete) { 16389 cleanUpResourcesLI(allCodePaths); 16390 } 16391 return !mounted; 16392 } 16393 16394 @Override 16395 int doPreCopy() { 16396 if (isFwdLocked()) { 16397 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 16398 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 16399 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 16400 } 16401 } 16402 16403 return PackageManager.INSTALL_SUCCEEDED; 16404 } 16405 16406 @Override 16407 int doPostCopy(int uid) { 16408 if (isFwdLocked()) { 16409 if (uid < Process.FIRST_APPLICATION_UID 16410 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 16411 RES_FILE_NAME)) { 16412 Slog.e(TAG, "Failed to finalize " + cid); 16413 PackageHelper.destroySdDir(cid); 16414 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 16415 } 16416 } 16417 16418 return PackageManager.INSTALL_SUCCEEDED; 16419 } 16420 } 16421 16422 /** 16423 * Logic to handle movement of existing installed applications. 16424 */ 16425 class MoveInstallArgs extends InstallArgs { 16426 private File codeFile; 16427 private File resourceFile; 16428 16429 /** New install */ 16430 MoveInstallArgs(InstallParams params) { 16431 super(params.origin, params.move, params.observer, params.installFlags, 16432 params.installerPackageName, params.volumeUuid, 16433 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 16434 params.grantedRuntimePermissions, 16435 params.traceMethod, params.traceCookie, params.certificates, 16436 params.installReason); 16437 } 16438 16439 int copyApk(IMediaContainerService imcs, boolean temp) { 16440 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 16441 + move.fromUuid + " to " + move.toUuid); 16442 synchronized (mInstaller) { 16443 try { 16444 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 16445 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 16446 } catch (InstallerException e) { 16447 Slog.w(TAG, "Failed to move app", e); 16448 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 16449 } 16450 } 16451 16452 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 16453 resourceFile = codeFile; 16454 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 16455 16456 return PackageManager.INSTALL_SUCCEEDED; 16457 } 16458 16459 int doPreInstall(int status) { 16460 if (status != PackageManager.INSTALL_SUCCEEDED) { 16461 cleanUp(move.toUuid); 16462 } 16463 return status; 16464 } 16465 16466 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 16467 if (status != PackageManager.INSTALL_SUCCEEDED) { 16468 cleanUp(move.toUuid); 16469 return false; 16470 } 16471 16472 // Reflect the move in app info 16473 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 16474 pkg.setApplicationInfoCodePath(pkg.codePath); 16475 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 16476 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 16477 pkg.setApplicationInfoResourcePath(pkg.codePath); 16478 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 16479 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 16480 16481 return true; 16482 } 16483 16484 int doPostInstall(int status, int uid) { 16485 if (status == PackageManager.INSTALL_SUCCEEDED) { 16486 cleanUp(move.fromUuid); 16487 } else { 16488 cleanUp(move.toUuid); 16489 } 16490 return status; 16491 } 16492 16493 @Override 16494 String getCodePath() { 16495 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 16496 } 16497 16498 @Override 16499 String getResourcePath() { 16500 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 16501 } 16502 16503 private boolean cleanUp(String volumeUuid) { 16504 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 16505 move.dataAppName); 16506 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 16507 final int[] userIds = sUserManager.getUserIds(); 16508 synchronized (mInstallLock) { 16509 // Clean up both app data and code 16510 // All package moves are frozen until finished 16511 for (int userId : userIds) { 16512 try { 16513 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 16514 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 16515 } catch (InstallerException e) { 16516 Slog.w(TAG, String.valueOf(e)); 16517 } 16518 } 16519 removeCodePathLI(codeFile); 16520 } 16521 return true; 16522 } 16523 16524 void cleanUpResourcesLI() { 16525 throw new UnsupportedOperationException(); 16526 } 16527 16528 boolean doPostDeleteLI(boolean delete) { 16529 throw new UnsupportedOperationException(); 16530 } 16531 } 16532 16533 static String getAsecPackageName(String packageCid) { 16534 int idx = packageCid.lastIndexOf("-"); 16535 if (idx == -1) { 16536 return packageCid; 16537 } 16538 return packageCid.substring(0, idx); 16539 } 16540 16541 // Utility method used to create code paths based on package name and available index. 16542 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 16543 String idxStr = ""; 16544 int idx = 1; 16545 // Fall back to default value of idx=1 if prefix is not 16546 // part of oldCodePath 16547 if (oldCodePath != null) { 16548 String subStr = oldCodePath; 16549 // Drop the suffix right away 16550 if (suffix != null && subStr.endsWith(suffix)) { 16551 subStr = subStr.substring(0, subStr.length() - suffix.length()); 16552 } 16553 // If oldCodePath already contains prefix find out the 16554 // ending index to either increment or decrement. 16555 int sidx = subStr.lastIndexOf(prefix); 16556 if (sidx != -1) { 16557 subStr = subStr.substring(sidx + prefix.length()); 16558 if (subStr != null) { 16559 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 16560 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 16561 } 16562 try { 16563 idx = Integer.parseInt(subStr); 16564 if (idx <= 1) { 16565 idx++; 16566 } else { 16567 idx--; 16568 } 16569 } catch(NumberFormatException e) { 16570 } 16571 } 16572 } 16573 } 16574 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 16575 return prefix + idxStr; 16576 } 16577 16578 private File getNextCodePath(File targetDir, String packageName) { 16579 File result; 16580 SecureRandom random = new SecureRandom(); 16581 byte[] bytes = new byte[16]; 16582 do { 16583 random.nextBytes(bytes); 16584 String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP); 16585 result = new File(targetDir, packageName + "-" + suffix); 16586 } while (result.exists()); 16587 return result; 16588 } 16589 16590 // Utility method that returns the relative package path with respect 16591 // to the installation directory. Like say for /data/data/com.test-1.apk 16592 // string com.test-1 is returned. 16593 static String deriveCodePathName(String codePath) { 16594 if (codePath == null) { 16595 return null; 16596 } 16597 final File codeFile = new File(codePath); 16598 final String name = codeFile.getName(); 16599 if (codeFile.isDirectory()) { 16600 return name; 16601 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 16602 final int lastDot = name.lastIndexOf('.'); 16603 return name.substring(0, lastDot); 16604 } else { 16605 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 16606 return null; 16607 } 16608 } 16609 16610 static class PackageInstalledInfo { 16611 String name; 16612 int uid; 16613 // The set of users that originally had this package installed. 16614 int[] origUsers; 16615 // The set of users that now have this package installed. 16616 int[] newUsers; 16617 PackageParser.Package pkg; 16618 int returnCode; 16619 String returnMsg; 16620 PackageRemovedInfo removedInfo; 16621 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 16622 16623 public void setError(int code, String msg) { 16624 setReturnCode(code); 16625 setReturnMessage(msg); 16626 Slog.w(TAG, msg); 16627 } 16628 16629 public void setError(String msg, PackageParserException e) { 16630 setReturnCode(e.error); 16631 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 16632 Slog.w(TAG, msg, e); 16633 } 16634 16635 public void setError(String msg, PackageManagerException e) { 16636 returnCode = e.error; 16637 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 16638 Slog.w(TAG, msg, e); 16639 } 16640 16641 public void setReturnCode(int returnCode) { 16642 this.returnCode = returnCode; 16643 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 16644 for (int i = 0; i < childCount; i++) { 16645 addedChildPackages.valueAt(i).returnCode = returnCode; 16646 } 16647 } 16648 16649 private void setReturnMessage(String returnMsg) { 16650 this.returnMsg = returnMsg; 16651 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 16652 for (int i = 0; i < childCount; i++) { 16653 addedChildPackages.valueAt(i).returnMsg = returnMsg; 16654 } 16655 } 16656 16657 // In some error cases we want to convey more info back to the observer 16658 String origPackage; 16659 String origPermission; 16660 } 16661 16662 /* 16663 * Install a non-existing package. 16664 */ 16665 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 16666 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 16667 PackageInstalledInfo res, int installReason) { 16668 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 16669 16670 // Remember this for later, in case we need to rollback this install 16671 String pkgName = pkg.packageName; 16672 16673 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 16674 16675 synchronized(mPackages) { 16676 final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName); 16677 if (renamedPackage != null) { 16678 // A package with the same name is already installed, though 16679 // it has been renamed to an older name. The package we 16680 // are trying to install should be installed as an update to 16681 // the existing one, but that has not been requested, so bail. 16682 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 16683 + " without first uninstalling package running as " 16684 + renamedPackage); 16685 return; 16686 } 16687 if (mPackages.containsKey(pkgName)) { 16688 // Don't allow installation over an existing package with the same name. 16689 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 16690 + " without first uninstalling."); 16691 return; 16692 } 16693 } 16694 16695 try { 16696 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 16697 System.currentTimeMillis(), user); 16698 16699 updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason); 16700 16701 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 16702 prepareAppDataAfterInstallLIF(newPackage); 16703 16704 } else { 16705 // Remove package from internal structures, but keep around any 16706 // data that might have already existed 16707 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 16708 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 16709 } 16710 } catch (PackageManagerException e) { 16711 res.setError("Package couldn't be installed in " + pkg.codePath, e); 16712 } 16713 16714 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16715 } 16716 16717 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 16718 // Can't rotate keys during boot or if sharedUser. 16719 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 16720 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 16721 return false; 16722 } 16723 // app is using upgradeKeySets; make sure all are valid 16724 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16725 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 16726 for (int i = 0; i < upgradeKeySets.length; i++) { 16727 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 16728 Slog.wtf(TAG, "Package " 16729 + (oldPs.name != null ? oldPs.name : "<null>") 16730 + " contains upgrade-key-set reference to unknown key-set: " 16731 + upgradeKeySets[i] 16732 + " reverting to signatures check."); 16733 return false; 16734 } 16735 } 16736 return true; 16737 } 16738 16739 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 16740 // Upgrade keysets are being used. Determine if new package has a superset of the 16741 // required keys. 16742 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 16743 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16744 for (int i = 0; i < upgradeKeySets.length; i++) { 16745 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 16746 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 16747 return true; 16748 } 16749 } 16750 return false; 16751 } 16752 16753 private static void updateDigest(MessageDigest digest, File file) throws IOException { 16754 try (DigestInputStream digestStream = 16755 new DigestInputStream(new FileInputStream(file), digest)) { 16756 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 16757 } 16758 } 16759 16760 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 16761 UserHandle user, String installerPackageName, PackageInstalledInfo res, 16762 int installReason) { 16763 final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 16764 16765 final PackageParser.Package oldPackage; 16766 final PackageSetting ps; 16767 final String pkgName = pkg.packageName; 16768 final int[] allUsers; 16769 final int[] installedUsers; 16770 16771 synchronized(mPackages) { 16772 oldPackage = mPackages.get(pkgName); 16773 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 16774 16775 // don't allow upgrade to target a release SDK from a pre-release SDK 16776 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 16777 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 16778 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 16779 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 16780 if (oldTargetsPreRelease 16781 && !newTargetsPreRelease 16782 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 16783 Slog.w(TAG, "Can't install package targeting released sdk"); 16784 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 16785 return; 16786 } 16787 16788 ps = mSettings.mPackages.get(pkgName); 16789 16790 // verify signatures are valid 16791 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 16792 if (!checkUpgradeKeySetLP(ps, pkg)) { 16793 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 16794 "New package not signed by keys specified by upgrade-keysets: " 16795 + pkgName); 16796 return; 16797 } 16798 } else { 16799 // default to original signature matching 16800 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 16801 != PackageManager.SIGNATURE_MATCH) { 16802 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 16803 "New package has a different signature: " + pkgName); 16804 return; 16805 } 16806 } 16807 16808 // don't allow a system upgrade unless the upgrade hash matches 16809 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 16810 byte[] digestBytes = null; 16811 try { 16812 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 16813 updateDigest(digest, new File(pkg.baseCodePath)); 16814 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 16815 for (String path : pkg.splitCodePaths) { 16816 updateDigest(digest, new File(path)); 16817 } 16818 } 16819 digestBytes = digest.digest(); 16820 } catch (NoSuchAlgorithmException | IOException e) { 16821 res.setError(INSTALL_FAILED_INVALID_APK, 16822 "Could not compute hash: " + pkgName); 16823 return; 16824 } 16825 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 16826 res.setError(INSTALL_FAILED_INVALID_APK, 16827 "New package fails restrict-update check: " + pkgName); 16828 return; 16829 } 16830 // retain upgrade restriction 16831 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 16832 } 16833 16834 // Check for shared user id changes 16835 String invalidPackageName = 16836 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 16837 if (invalidPackageName != null) { 16838 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 16839 "Package " + invalidPackageName + " tried to change user " 16840 + oldPackage.mSharedUserId); 16841 return; 16842 } 16843 16844 // In case of rollback, remember per-user/profile install state 16845 allUsers = sUserManager.getUserIds(); 16846 installedUsers = ps.queryInstalledUsers(allUsers, true); 16847 16848 // don't allow an upgrade from full to ephemeral 16849 if (isInstantApp) { 16850 if (user == null || user.getIdentifier() == UserHandle.USER_ALL) { 16851 for (int currentUser : allUsers) { 16852 if (!ps.getInstantApp(currentUser)) { 16853 // can't downgrade from full to instant 16854 Slog.w(TAG, "Can't replace full app with instant app: " + pkgName 16855 + " for user: " + currentUser); 16856 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 16857 return; 16858 } 16859 } 16860 } else if (!ps.getInstantApp(user.getIdentifier())) { 16861 // can't downgrade from full to instant 16862 Slog.w(TAG, "Can't replace full app with instant app: " + pkgName 16863 + " for user: " + user.getIdentifier()); 16864 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 16865 return; 16866 } 16867 } 16868 } 16869 16870 // Update what is removed 16871 res.removedInfo = new PackageRemovedInfo(this); 16872 res.removedInfo.uid = oldPackage.applicationInfo.uid; 16873 res.removedInfo.removedPackage = oldPackage.packageName; 16874 res.removedInfo.installerPackageName = ps.installerPackageName; 16875 res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null; 16876 res.removedInfo.isUpdate = true; 16877 res.removedInfo.origUsers = installedUsers; 16878 res.removedInfo.installReasons = new SparseArray<>(installedUsers.length); 16879 for (int i = 0; i < installedUsers.length; i++) { 16880 final int userId = installedUsers[i]; 16881 res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId)); 16882 } 16883 16884 final int childCount = (oldPackage.childPackages != null) 16885 ? oldPackage.childPackages.size() : 0; 16886 for (int i = 0; i < childCount; i++) { 16887 boolean childPackageUpdated = false; 16888 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 16889 final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 16890 if (res.addedChildPackages != null) { 16891 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 16892 if (childRes != null) { 16893 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 16894 childRes.removedInfo.removedPackage = childPkg.packageName; 16895 if (childPs != null) { 16896 childRes.removedInfo.installerPackageName = childPs.installerPackageName; 16897 } 16898 childRes.removedInfo.isUpdate = true; 16899 childRes.removedInfo.installReasons = res.removedInfo.installReasons; 16900 childPackageUpdated = true; 16901 } 16902 } 16903 if (!childPackageUpdated) { 16904 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this); 16905 childRemovedRes.removedPackage = childPkg.packageName; 16906 if (childPs != null) { 16907 childRemovedRes.installerPackageName = childPs.installerPackageName; 16908 } 16909 childRemovedRes.isUpdate = false; 16910 childRemovedRes.dataRemoved = true; 16911 synchronized (mPackages) { 16912 if (childPs != null) { 16913 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 16914 } 16915 } 16916 if (res.removedInfo.removedChildPackages == null) { 16917 res.removedInfo.removedChildPackages = new ArrayMap<>(); 16918 } 16919 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 16920 } 16921 } 16922 16923 boolean sysPkg = (isSystemApp(oldPackage)); 16924 if (sysPkg) { 16925 // Set the system/privileged flags as needed 16926 final boolean privileged = 16927 (oldPackage.applicationInfo.privateFlags 16928 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 16929 final int systemPolicyFlags = policyFlags 16930 | PackageParser.PARSE_IS_SYSTEM 16931 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 16932 16933 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 16934 user, allUsers, installerPackageName, res, installReason); 16935 } else { 16936 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 16937 user, allUsers, installerPackageName, res, installReason); 16938 } 16939 } 16940 16941 @Override 16942 public List<String> getPreviousCodePaths(String packageName) { 16943 final List<String> result = new ArrayList<>(); 16944 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 16945 return result; 16946 } 16947 final PackageSetting ps = mSettings.mPackages.get(packageName); 16948 if (ps != null && ps.oldCodePaths != null) { 16949 result.addAll(ps.oldCodePaths); 16950 } 16951 return result; 16952 } 16953 16954 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 16955 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 16956 int[] allUsers, String installerPackageName, PackageInstalledInfo res, 16957 int installReason) { 16958 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 16959 + deletedPackage); 16960 16961 String pkgName = deletedPackage.packageName; 16962 boolean deletedPkg = true; 16963 boolean addedPkg = false; 16964 boolean updatedSettings = false; 16965 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 16966 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 16967 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 16968 16969 final long origUpdateTime = (pkg.mExtras != null) 16970 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 16971 16972 // First delete the existing package while retaining the data directory 16973 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 16974 res.removedInfo, true, pkg)) { 16975 // If the existing package wasn't successfully deleted 16976 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 16977 deletedPkg = false; 16978 } else { 16979 // Successfully deleted the old package; proceed with replace. 16980 16981 // If deleted package lived in a container, give users a chance to 16982 // relinquish resources before killing. 16983 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 16984 if (DEBUG_INSTALL) { 16985 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 16986 } 16987 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 16988 final ArrayList<String> pkgList = new ArrayList<String>(1); 16989 pkgList.add(deletedPackage.applicationInfo.packageName); 16990 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 16991 } 16992 16993 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 16994 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16995 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 16996 16997 try { 16998 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 16999 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 17000 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 17001 installReason); 17002 17003 // Update the in-memory copy of the previous code paths. 17004 PackageSetting ps = mSettings.mPackages.get(pkgName); 17005 if (!killApp) { 17006 if (ps.oldCodePaths == null) { 17007 ps.oldCodePaths = new ArraySet<>(); 17008 } 17009 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 17010 if (deletedPackage.splitCodePaths != null) { 17011 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 17012 } 17013 } else { 17014 ps.oldCodePaths = null; 17015 } 17016 if (ps.childPackageNames != null) { 17017 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 17018 final String childPkgName = ps.childPackageNames.get(i); 17019 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 17020 childPs.oldCodePaths = ps.oldCodePaths; 17021 } 17022 } 17023 // set instant app status, but, only if it's explicitly specified 17024 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 17025 final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0; 17026 setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp); 17027 prepareAppDataAfterInstallLIF(newPackage); 17028 addedPkg = true; 17029 mDexManager.notifyPackageUpdated(newPackage.packageName, 17030 newPackage.baseCodePath, newPackage.splitCodePaths); 17031 } catch (PackageManagerException e) { 17032 res.setError("Package couldn't be installed in " + pkg.codePath, e); 17033 } 17034 } 17035 17036 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 17037 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 17038 17039 // Revert all internal state mutations and added folders for the failed install 17040 if (addedPkg) { 17041 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 17042 res.removedInfo, true, null); 17043 } 17044 17045 // Restore the old package 17046 if (deletedPkg) { 17047 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 17048 File restoreFile = new File(deletedPackage.codePath); 17049 // Parse old package 17050 boolean oldExternal = isExternal(deletedPackage); 17051 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 17052 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 17053 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 17054 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 17055 try { 17056 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 17057 null); 17058 } catch (PackageManagerException e) { 17059 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 17060 + e.getMessage()); 17061 return; 17062 } 17063 17064 synchronized (mPackages) { 17065 // Ensure the installer package name up to date 17066 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 17067 17068 // Update permissions for restored package 17069 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 17070 17071 mSettings.writeLPr(); 17072 } 17073 17074 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 17075 } 17076 } else { 17077 synchronized (mPackages) { 17078 PackageSetting ps = mSettings.getPackageLPr(pkg.packageName); 17079 if (ps != null) { 17080 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 17081 if (res.removedInfo.removedChildPackages != null) { 17082 final int childCount = res.removedInfo.removedChildPackages.size(); 17083 // Iterate in reverse as we may modify the collection 17084 for (int i = childCount - 1; i >= 0; i--) { 17085 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 17086 if (res.addedChildPackages.containsKey(childPackageName)) { 17087 res.removedInfo.removedChildPackages.removeAt(i); 17088 } else { 17089 PackageRemovedInfo childInfo = res.removedInfo 17090 .removedChildPackages.valueAt(i); 17091 childInfo.removedForAllUsers = mPackages.get( 17092 childInfo.removedPackage) == null; 17093 } 17094 } 17095 } 17096 } 17097 } 17098 } 17099 } 17100 17101 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 17102 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 17103 int[] allUsers, String installerPackageName, PackageInstalledInfo res, 17104 int installReason) { 17105 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 17106 + ", old=" + deletedPackage); 17107 17108 final boolean disabledSystem; 17109 17110 // Remove existing system package 17111 removePackageLI(deletedPackage, true); 17112 17113 synchronized (mPackages) { 17114 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 17115 } 17116 if (!disabledSystem) { 17117 // We didn't need to disable the .apk as a current system package, 17118 // which means we are replacing another update that is already 17119 // installed. We need to make sure to delete the older one's .apk. 17120 res.removedInfo.args = createInstallArgsForExisting(0, 17121 deletedPackage.applicationInfo.getCodePath(), 17122 deletedPackage.applicationInfo.getResourcePath(), 17123 getAppDexInstructionSets(deletedPackage.applicationInfo)); 17124 } else { 17125 res.removedInfo.args = null; 17126 } 17127 17128 // Successfully disabled the old package. Now proceed with re-installation 17129 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 17130 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 17131 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 17132 17133 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 17134 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 17135 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 17136 17137 PackageParser.Package newPackage = null; 17138 try { 17139 // Add the package to the internal data structures 17140 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 17141 17142 // Set the update and install times 17143 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 17144 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 17145 System.currentTimeMillis()); 17146 17147 // Update the package dynamic state if succeeded 17148 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 17149 // Now that the install succeeded make sure we remove data 17150 // directories for any child package the update removed. 17151 final int deletedChildCount = (deletedPackage.childPackages != null) 17152 ? deletedPackage.childPackages.size() : 0; 17153 final int newChildCount = (newPackage.childPackages != null) 17154 ? newPackage.childPackages.size() : 0; 17155 for (int i = 0; i < deletedChildCount; i++) { 17156 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 17157 boolean childPackageDeleted = true; 17158 for (int j = 0; j < newChildCount; j++) { 17159 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 17160 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 17161 childPackageDeleted = false; 17162 break; 17163 } 17164 } 17165 if (childPackageDeleted) { 17166 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 17167 deletedChildPkg.packageName); 17168 if (ps != null && res.removedInfo.removedChildPackages != null) { 17169 PackageRemovedInfo removedChildRes = res.removedInfo 17170 .removedChildPackages.get(deletedChildPkg.packageName); 17171 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 17172 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 17173 } 17174 } 17175 } 17176 17177 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 17178 installReason); 17179 prepareAppDataAfterInstallLIF(newPackage); 17180 17181 mDexManager.notifyPackageUpdated(newPackage.packageName, 17182 newPackage.baseCodePath, newPackage.splitCodePaths); 17183 } 17184 } catch (PackageManagerException e) { 17185 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 17186 res.setError("Package couldn't be installed in " + pkg.codePath, e); 17187 } 17188 17189 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 17190 // Re installation failed. Restore old information 17191 // Remove new pkg information 17192 if (newPackage != null) { 17193 removeInstalledPackageLI(newPackage, true); 17194 } 17195 // Add back the old system package 17196 try { 17197 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 17198 } catch (PackageManagerException e) { 17199 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 17200 } 17201 17202 synchronized (mPackages) { 17203 if (disabledSystem) { 17204 enableSystemPackageLPw(deletedPackage); 17205 } 17206 17207 // Ensure the installer package name up to date 17208 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 17209 17210 // Update permissions for restored package 17211 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 17212 17213 mSettings.writeLPr(); 17214 } 17215 17216 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 17217 + " after failed upgrade"); 17218 } 17219 } 17220 17221 /** 17222 * Checks whether the parent or any of the child packages have a change shared 17223 * user. For a package to be a valid update the shred users of the parent and 17224 * the children should match. We may later support changing child shared users. 17225 * @param oldPkg The updated package. 17226 * @param newPkg The update package. 17227 * @return The shared user that change between the versions. 17228 */ 17229 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 17230 PackageParser.Package newPkg) { 17231 // Check parent shared user 17232 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 17233 return newPkg.packageName; 17234 } 17235 // Check child shared users 17236 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 17237 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 17238 for (int i = 0; i < newChildCount; i++) { 17239 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 17240 // If this child was present, did it have the same shared user? 17241 for (int j = 0; j < oldChildCount; j++) { 17242 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 17243 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 17244 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 17245 return newChildPkg.packageName; 17246 } 17247 } 17248 } 17249 return null; 17250 } 17251 17252 private void removeNativeBinariesLI(PackageSetting ps) { 17253 // Remove the lib path for the parent package 17254 if (ps != null) { 17255 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 17256 // Remove the lib path for the child packages 17257 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 17258 for (int i = 0; i < childCount; i++) { 17259 PackageSetting childPs = null; 17260 synchronized (mPackages) { 17261 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 17262 } 17263 if (childPs != null) { 17264 NativeLibraryHelper.removeNativeBinariesLI(childPs 17265 .legacyNativeLibraryPathString); 17266 } 17267 } 17268 } 17269 } 17270 17271 private void enableSystemPackageLPw(PackageParser.Package pkg) { 17272 // Enable the parent package 17273 mSettings.enableSystemPackageLPw(pkg.packageName); 17274 // Enable the child packages 17275 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 17276 for (int i = 0; i < childCount; i++) { 17277 PackageParser.Package childPkg = pkg.childPackages.get(i); 17278 mSettings.enableSystemPackageLPw(childPkg.packageName); 17279 } 17280 } 17281 17282 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 17283 PackageParser.Package newPkg) { 17284 // Disable the parent package (parent always replaced) 17285 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 17286 // Disable the child packages 17287 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 17288 for (int i = 0; i < childCount; i++) { 17289 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 17290 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 17291 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 17292 } 17293 return disabled; 17294 } 17295 17296 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 17297 String installerPackageName) { 17298 // Enable the parent package 17299 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 17300 // Enable the child packages 17301 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 17302 for (int i = 0; i < childCount; i++) { 17303 PackageParser.Package childPkg = pkg.childPackages.get(i); 17304 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 17305 } 17306 } 17307 17308 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 17309 // Collect all used permissions in the UID 17310 ArraySet<String> usedPermissions = new ArraySet<>(); 17311 final int packageCount = su.packages.size(); 17312 for (int i = 0; i < packageCount; i++) { 17313 PackageSetting ps = su.packages.valueAt(i); 17314 if (ps.pkg == null) { 17315 continue; 17316 } 17317 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 17318 for (int j = 0; j < requestedPermCount; j++) { 17319 String permission = ps.pkg.requestedPermissions.get(j); 17320 BasePermission bp = mSettings.mPermissions.get(permission); 17321 if (bp != null) { 17322 usedPermissions.add(permission); 17323 } 17324 } 17325 } 17326 17327 PermissionsState permissionsState = su.getPermissionsState(); 17328 // Prune install permissions 17329 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 17330 final int installPermCount = installPermStates.size(); 17331 for (int i = installPermCount - 1; i >= 0; i--) { 17332 PermissionState permissionState = installPermStates.get(i); 17333 if (!usedPermissions.contains(permissionState.getName())) { 17334 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 17335 if (bp != null) { 17336 permissionsState.revokeInstallPermission(bp); 17337 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 17338 PackageManager.MASK_PERMISSION_FLAGS, 0); 17339 } 17340 } 17341 } 17342 17343 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 17344 17345 // Prune runtime permissions 17346 for (int userId : allUserIds) { 17347 List<PermissionState> runtimePermStates = permissionsState 17348 .getRuntimePermissionStates(userId); 17349 final int runtimePermCount = runtimePermStates.size(); 17350 for (int i = runtimePermCount - 1; i >= 0; i--) { 17351 PermissionState permissionState = runtimePermStates.get(i); 17352 if (!usedPermissions.contains(permissionState.getName())) { 17353 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 17354 if (bp != null) { 17355 permissionsState.revokeRuntimePermission(bp, userId); 17356 permissionsState.updatePermissionFlags(bp, userId, 17357 PackageManager.MASK_PERMISSION_FLAGS, 0); 17358 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 17359 runtimePermissionChangedUserIds, userId); 17360 } 17361 } 17362 } 17363 } 17364 17365 return runtimePermissionChangedUserIds; 17366 } 17367 17368 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 17369 int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) { 17370 // Update the parent package setting 17371 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 17372 res, user, installReason); 17373 // Update the child packages setting 17374 final int childCount = (newPackage.childPackages != null) 17375 ? newPackage.childPackages.size() : 0; 17376 for (int i = 0; i < childCount; i++) { 17377 PackageParser.Package childPackage = newPackage.childPackages.get(i); 17378 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 17379 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 17380 childRes.origUsers, childRes, user, installReason); 17381 } 17382 } 17383 17384 private void updateSettingsInternalLI(PackageParser.Package newPackage, 17385 String installerPackageName, int[] allUsers, int[] installedForUsers, 17386 PackageInstalledInfo res, UserHandle user, int installReason) { 17387 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 17388 17389 String pkgName = newPackage.packageName; 17390 synchronized (mPackages) { 17391 //write settings. the installStatus will be incomplete at this stage. 17392 //note that the new package setting would have already been 17393 //added to mPackages. It hasn't been persisted yet. 17394 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 17395 // TODO: Remove this write? It's also written at the end of this method 17396 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 17397 mSettings.writeLPr(); 17398 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 17399 } 17400 17401 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 17402 synchronized (mPackages) { 17403 updatePermissionsLPw(newPackage.packageName, newPackage, 17404 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 17405 ? UPDATE_PERMISSIONS_ALL : 0)); 17406 // For system-bundled packages, we assume that installing an upgraded version 17407 // of the package implies that the user actually wants to run that new code, 17408 // so we enable the package. 17409 PackageSetting ps = mSettings.mPackages.get(pkgName); 17410 final int userId = user.getIdentifier(); 17411 if (ps != null) { 17412 if (isSystemApp(newPackage)) { 17413 if (DEBUG_INSTALL) { 17414 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 17415 } 17416 // Enable system package for requested users 17417 if (res.origUsers != null) { 17418 for (int origUserId : res.origUsers) { 17419 if (userId == UserHandle.USER_ALL || userId == origUserId) { 17420 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 17421 origUserId, installerPackageName); 17422 } 17423 } 17424 } 17425 // Also convey the prior install/uninstall state 17426 if (allUsers != null && installedForUsers != null) { 17427 for (int currentUserId : allUsers) { 17428 final boolean installed = ArrayUtils.contains( 17429 installedForUsers, currentUserId); 17430 if (DEBUG_INSTALL) { 17431 Slog.d(TAG, " user " + currentUserId + " => " + installed); 17432 } 17433 ps.setInstalled(installed, currentUserId); 17434 } 17435 // these install state changes will be persisted in the 17436 // upcoming call to mSettings.writeLPr(). 17437 } 17438 } 17439 // It's implied that when a user requests installation, they want the app to be 17440 // installed and enabled. 17441 if (userId != UserHandle.USER_ALL) { 17442 ps.setInstalled(true, userId); 17443 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 17444 } 17445 17446 // When replacing an existing package, preserve the original install reason for all 17447 // users that had the package installed before. 17448 final Set<Integer> previousUserIds = new ArraySet<>(); 17449 if (res.removedInfo != null && res.removedInfo.installReasons != null) { 17450 final int installReasonCount = res.removedInfo.installReasons.size(); 17451 for (int i = 0; i < installReasonCount; i++) { 17452 final int previousUserId = res.removedInfo.installReasons.keyAt(i); 17453 final int previousInstallReason = res.removedInfo.installReasons.valueAt(i); 17454 ps.setInstallReason(previousInstallReason, previousUserId); 17455 previousUserIds.add(previousUserId); 17456 } 17457 } 17458 17459 // Set install reason for users that are having the package newly installed. 17460 if (userId == UserHandle.USER_ALL) { 17461 for (int currentUserId : sUserManager.getUserIds()) { 17462 if (!previousUserIds.contains(currentUserId)) { 17463 ps.setInstallReason(installReason, currentUserId); 17464 } 17465 } 17466 } else if (!previousUserIds.contains(userId)) { 17467 ps.setInstallReason(installReason, userId); 17468 } 17469 mSettings.writeKernelMappingLPr(ps); 17470 } 17471 res.name = pkgName; 17472 res.uid = newPackage.applicationInfo.uid; 17473 res.pkg = newPackage; 17474 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 17475 mSettings.setInstallerPackageName(pkgName, installerPackageName); 17476 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 17477 //to update install status 17478 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 17479 mSettings.writeLPr(); 17480 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 17481 } 17482 17483 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 17484 } 17485 17486 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 17487 try { 17488 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 17489 installPackageLI(args, res); 17490 } finally { 17491 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 17492 } 17493 } 17494 17495 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 17496 final int installFlags = args.installFlags; 17497 final String installerPackageName = args.installerPackageName; 17498 final String volumeUuid = args.volumeUuid; 17499 final File tmpPackageFile = new File(args.getCodePath()); 17500 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 17501 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 17502 || (args.volumeUuid != null)); 17503 final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0); 17504 final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0); 17505 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 17506 boolean replace = false; 17507 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 17508 if (args.move != null) { 17509 // moving a complete application; perform an initial scan on the new install location 17510 scanFlags |= SCAN_INITIAL; 17511 } 17512 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 17513 scanFlags |= SCAN_DONT_KILL_APP; 17514 } 17515 if (instantApp) { 17516 scanFlags |= SCAN_AS_INSTANT_APP; 17517 } 17518 if (fullApp) { 17519 scanFlags |= SCAN_AS_FULL_APP; 17520 } 17521 17522 // Result object to be returned 17523 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 17524 17525 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 17526 17527 // Sanity check 17528 if (instantApp && (forwardLocked || onExternal)) { 17529 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 17530 + " external=" + onExternal); 17531 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 17532 return; 17533 } 17534 17535 // Retrieve PackageSettings and parse package 17536 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 17537 | PackageParser.PARSE_ENFORCE_CODE 17538 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 17539 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 17540 | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0) 17541 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 17542 PackageParser pp = new PackageParser(); 17543 pp.setSeparateProcesses(mSeparateProcesses); 17544 pp.setDisplayMetrics(mMetrics); 17545 pp.setCallback(mPackageParserCallback); 17546 17547 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 17548 final PackageParser.Package pkg; 17549 try { 17550 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 17551 } catch (PackageParserException e) { 17552 res.setError("Failed parse during installPackageLI", e); 17553 return; 17554 } finally { 17555 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 17556 } 17557 17558 // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2 17559 if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) { 17560 Slog.w(TAG, "Instant app package " + pkg.packageName 17561 + " does not target O, this will be a fatal error."); 17562 // STOPSHIP: Make this a fatal error 17563 pkg.applicationInfo.targetSdkVersion = Build.VERSION_CODES.O; 17564 } 17565 if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) { 17566 Slog.w(TAG, "Instant app package " + pkg.packageName 17567 + " does not target targetSandboxVersion 2, this will be a fatal error."); 17568 // STOPSHIP: Make this a fatal error 17569 pkg.applicationInfo.targetSandboxVersion = 2; 17570 } 17571 17572 if (pkg.applicationInfo.isStaticSharedLibrary()) { 17573 // Static shared libraries have synthetic package names 17574 renameStaticSharedLibraryPackage(pkg); 17575 17576 // No static shared libs on external storage 17577 if (onExternal) { 17578 Slog.i(TAG, "Static shared libs can only be installed on internal storage."); 17579 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 17580 "Packages declaring static-shared libs cannot be updated"); 17581 return; 17582 } 17583 } 17584 17585 // If we are installing a clustered package add results for the children 17586 if (pkg.childPackages != null) { 17587 synchronized (mPackages) { 17588 final int childCount = pkg.childPackages.size(); 17589 for (int i = 0; i < childCount; i++) { 17590 PackageParser.Package childPkg = pkg.childPackages.get(i); 17591 PackageInstalledInfo childRes = new PackageInstalledInfo(); 17592 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 17593 childRes.pkg = childPkg; 17594 childRes.name = childPkg.packageName; 17595 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 17596 if (childPs != null) { 17597 childRes.origUsers = childPs.queryInstalledUsers( 17598 sUserManager.getUserIds(), true); 17599 } 17600 if ((mPackages.containsKey(childPkg.packageName))) { 17601 childRes.removedInfo = new PackageRemovedInfo(this); 17602 childRes.removedInfo.removedPackage = childPkg.packageName; 17603 childRes.removedInfo.installerPackageName = childPs.installerPackageName; 17604 } 17605 if (res.addedChildPackages == null) { 17606 res.addedChildPackages = new ArrayMap<>(); 17607 } 17608 res.addedChildPackages.put(childPkg.packageName, childRes); 17609 } 17610 } 17611 } 17612 17613 // If package doesn't declare API override, mark that we have an install 17614 // time CPU ABI override. 17615 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 17616 pkg.cpuAbiOverride = args.abiOverride; 17617 } 17618 17619 String pkgName = res.name = pkg.packageName; 17620 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 17621 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 17622 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 17623 return; 17624 } 17625 } 17626 17627 try { 17628 // either use what we've been given or parse directly from the APK 17629 if (args.certificates != null) { 17630 try { 17631 PackageParser.populateCertificates(pkg, args.certificates); 17632 } catch (PackageParserException e) { 17633 // there was something wrong with the certificates we were given; 17634 // try to pull them from the APK 17635 PackageParser.collectCertificates(pkg, parseFlags); 17636 } 17637 } else { 17638 PackageParser.collectCertificates(pkg, parseFlags); 17639 } 17640 } catch (PackageParserException e) { 17641 res.setError("Failed collect during installPackageLI", e); 17642 return; 17643 } 17644 17645 // Get rid of all references to package scan path via parser. 17646 pp = null; 17647 String oldCodePath = null; 17648 boolean systemApp = false; 17649 synchronized (mPackages) { 17650 // Check if installing already existing package 17651 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 17652 String oldName = mSettings.getRenamedPackageLPr(pkgName); 17653 if (pkg.mOriginalPackages != null 17654 && pkg.mOriginalPackages.contains(oldName) 17655 && mPackages.containsKey(oldName)) { 17656 // This package is derived from an original package, 17657 // and this device has been updating from that original 17658 // name. We must continue using the original name, so 17659 // rename the new package here. 17660 pkg.setPackageName(oldName); 17661 pkgName = pkg.packageName; 17662 replace = true; 17663 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 17664 + oldName + " pkgName=" + pkgName); 17665 } else if (mPackages.containsKey(pkgName)) { 17666 // This package, under its official name, already exists 17667 // on the device; we should replace it. 17668 replace = true; 17669 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 17670 } 17671 17672 // Child packages are installed through the parent package 17673 if (pkg.parentPackage != null) { 17674 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 17675 "Package " + pkg.packageName + " is child of package " 17676 + pkg.parentPackage.parentPackage + ". Child packages " 17677 + "can be updated only through the parent package."); 17678 return; 17679 } 17680 17681 if (replace) { 17682 // Prevent apps opting out from runtime permissions 17683 PackageParser.Package oldPackage = mPackages.get(pkgName); 17684 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 17685 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 17686 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 17687 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 17688 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 17689 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 17690 + " doesn't support runtime permissions but the old" 17691 + " target SDK " + oldTargetSdk + " does."); 17692 return; 17693 } 17694 // Prevent apps from downgrading their targetSandbox. 17695 final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion; 17696 final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion; 17697 if (oldTargetSandbox == 2 && newTargetSandbox != 2) { 17698 res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE, 17699 "Package " + pkg.packageName + " new target sandbox " 17700 + newTargetSandbox + " is incompatible with the previous value of" 17701 + oldTargetSandbox + "."); 17702 return; 17703 } 17704 17705 // Prevent installing of child packages 17706 if (oldPackage.parentPackage != null) { 17707 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 17708 "Package " + pkg.packageName + " is child of package " 17709 + oldPackage.parentPackage + ". Child packages " 17710 + "can be updated only through the parent package."); 17711 return; 17712 } 17713 } 17714 } 17715 17716 PackageSetting ps = mSettings.mPackages.get(pkgName); 17717 if (ps != null) { 17718 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 17719 17720 // Static shared libs have same package with different versions where 17721 // we internally use a synthetic package name to allow multiple versions 17722 // of the same package, therefore we need to compare signatures against 17723 // the package setting for the latest library version. 17724 PackageSetting signatureCheckPs = ps; 17725 if (pkg.applicationInfo.isStaticSharedLibrary()) { 17726 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg); 17727 if (libraryEntry != null) { 17728 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk); 17729 } 17730 } 17731 17732 // Quick sanity check that we're signed correctly if updating; 17733 // we'll check this again later when scanning, but we want to 17734 // bail early here before tripping over redefined permissions. 17735 if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) { 17736 if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) { 17737 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 17738 + pkg.packageName + " upgrade keys do not match the " 17739 + "previously installed version"); 17740 return; 17741 } 17742 } else { 17743 try { 17744 verifySignaturesLP(signatureCheckPs, pkg); 17745 } catch (PackageManagerException e) { 17746 res.setError(e.error, e.getMessage()); 17747 return; 17748 } 17749 } 17750 17751 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 17752 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 17753 systemApp = (ps.pkg.applicationInfo.flags & 17754 ApplicationInfo.FLAG_SYSTEM) != 0; 17755 } 17756 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 17757 } 17758 17759 int N = pkg.permissions.size(); 17760 for (int i = N-1; i >= 0; i--) { 17761 PackageParser.Permission perm = pkg.permissions.get(i); 17762 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 17763 17764 // Don't allow anyone but the system to define ephemeral permissions. 17765 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_EPHEMERAL) != 0 17766 && !systemApp) { 17767 Slog.w(TAG, "Non-System package " + pkg.packageName 17768 + " attempting to delcare ephemeral permission " 17769 + perm.info.name + "; Removing ephemeral."); 17770 perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_EPHEMERAL; 17771 } 17772 // Check whether the newly-scanned package wants to define an already-defined perm 17773 if (bp != null) { 17774 // If the defining package is signed with our cert, it's okay. This 17775 // also includes the "updating the same package" case, of course. 17776 // "updating same package" could also involve key-rotation. 17777 final boolean sigsOk; 17778 if (bp.sourcePackage.equals(pkg.packageName) 17779 && (bp.packageSetting instanceof PackageSetting) 17780 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 17781 scanFlags))) { 17782 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 17783 } else { 17784 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 17785 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 17786 } 17787 if (!sigsOk) { 17788 // If the owning package is the system itself, we log but allow 17789 // install to proceed; we fail the install on all other permission 17790 // redefinitions. 17791 if (!bp.sourcePackage.equals("android")) { 17792 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 17793 + pkg.packageName + " attempting to redeclare permission " 17794 + perm.info.name + " already owned by " + bp.sourcePackage); 17795 res.origPermission = perm.info.name; 17796 res.origPackage = bp.sourcePackage; 17797 return; 17798 } else { 17799 Slog.w(TAG, "Package " + pkg.packageName 17800 + " attempting to redeclare system permission " 17801 + perm.info.name + "; ignoring new declaration"); 17802 pkg.permissions.remove(i); 17803 } 17804 } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) { 17805 // Prevent apps to change protection level to dangerous from any other 17806 // type as this would allow a privilege escalation where an app adds a 17807 // normal/signature permission in other app's group and later redefines 17808 // it as dangerous leading to the group auto-grant. 17809 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE) 17810 == PermissionInfo.PROTECTION_DANGEROUS) { 17811 if (bp != null && !bp.isRuntime()) { 17812 Slog.w(TAG, "Package " + pkg.packageName + " trying to change a " 17813 + "non-runtime permission " + perm.info.name 17814 + " to runtime; keeping old protection level"); 17815 perm.info.protectionLevel = bp.protectionLevel; 17816 } 17817 } 17818 } 17819 } 17820 } 17821 } 17822 17823 if (systemApp) { 17824 if (onExternal) { 17825 // Abort update; system app can't be replaced with app on sdcard 17826 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 17827 "Cannot install updates to system apps on sdcard"); 17828 return; 17829 } else if (instantApp) { 17830 // Abort update; system app can't be replaced with an instant app 17831 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID, 17832 "Cannot update a system app with an instant app"); 17833 return; 17834 } 17835 } 17836 17837 if (args.move != null) { 17838 // We did an in-place move, so dex is ready to roll 17839 scanFlags |= SCAN_NO_DEX; 17840 scanFlags |= SCAN_MOVE; 17841 17842 synchronized (mPackages) { 17843 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17844 if (ps == null) { 17845 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 17846 "Missing settings for moved package " + pkgName); 17847 } 17848 17849 // We moved the entire application as-is, so bring over the 17850 // previously derived ABI information. 17851 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 17852 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 17853 } 17854 17855 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 17856 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 17857 scanFlags |= SCAN_NO_DEX; 17858 17859 try { 17860 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 17861 args.abiOverride : pkg.cpuAbiOverride); 17862 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 17863 true /*extractLibs*/, mAppLib32InstallDir); 17864 } catch (PackageManagerException pme) { 17865 Slog.e(TAG, "Error deriving application ABI", pme); 17866 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 17867 return; 17868 } 17869 17870 // Shared libraries for the package need to be updated. 17871 synchronized (mPackages) { 17872 try { 17873 updateSharedLibrariesLPr(pkg, null); 17874 } catch (PackageManagerException e) { 17875 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 17876 } 17877 } 17878 17879 // dexopt can take some time to complete, so, for instant apps, we skip this 17880 // step during installation. Instead, we'll take extra time the first time the 17881 // instant app starts. It's preferred to do it this way to provide continuous 17882 // progress to the user instead of mysteriously blocking somewhere in the 17883 // middle of running an instant app. 17884 if (!instantApp) { 17885 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 17886 // Do not run PackageDexOptimizer through the local performDexOpt 17887 // method because `pkg` may not be in `mPackages` yet. 17888 // 17889 // Also, don't fail application installs if the dexopt step fails. 17890 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 17891 null /* instructionSets */, false /* checkProfiles */, 17892 getCompilerFilterForReason(REASON_INSTALL), 17893 getOrCreateCompilerPackageStats(pkg), 17894 mDexManager.isUsedByOtherApps(pkg.packageName)); 17895 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 17896 } 17897 17898 // Notify BackgroundDexOptService that the package has been changed. 17899 // If this is an update of a package which used to fail to compile, 17900 // BDOS will remove it from its blacklist. 17901 // TODO: Layering violation 17902 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 17903 } 17904 17905 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 17906 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 17907 return; 17908 } 17909 17910 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 17911 17912 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 17913 "installPackageLI")) { 17914 if (replace) { 17915 if (pkg.applicationInfo.isStaticSharedLibrary()) { 17916 // Static libs have a synthetic package name containing the version 17917 // and cannot be updated as an update would get a new package name, 17918 // unless this is the exact same version code which is useful for 17919 // development. 17920 PackageParser.Package existingPkg = mPackages.get(pkg.packageName); 17921 if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) { 17922 res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring " 17923 + "static-shared libs cannot be updated"); 17924 return; 17925 } 17926 } 17927 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 17928 installerPackageName, res, args.installReason); 17929 } else { 17930 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 17931 args.user, installerPackageName, volumeUuid, res, args.installReason); 17932 } 17933 } 17934 17935 synchronized (mPackages) { 17936 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17937 if (ps != null) { 17938 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 17939 ps.setUpdateAvailable(false /*updateAvailable*/); 17940 } 17941 17942 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 17943 for (int i = 0; i < childCount; i++) { 17944 PackageParser.Package childPkg = pkg.childPackages.get(i); 17945 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 17946 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 17947 if (childPs != null) { 17948 childRes.newUsers = childPs.queryInstalledUsers( 17949 sUserManager.getUserIds(), true); 17950 } 17951 } 17952 17953 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 17954 updateSequenceNumberLP(pkgName, res.newUsers); 17955 updateInstantAppInstallerLocked(pkgName); 17956 } 17957 } 17958 } 17959 17960 private void startIntentFilterVerifications(int userId, boolean replacing, 17961 PackageParser.Package pkg) { 17962 if (mIntentFilterVerifierComponent == null) { 17963 Slog.w(TAG, "No IntentFilter verification will not be done as " 17964 + "there is no IntentFilterVerifier available!"); 17965 return; 17966 } 17967 17968 final int verifierUid = getPackageUid( 17969 mIntentFilterVerifierComponent.getPackageName(), 17970 MATCH_DEBUG_TRIAGED_MISSING, 17971 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 17972 17973 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 17974 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 17975 mHandler.sendMessage(msg); 17976 17977 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 17978 for (int i = 0; i < childCount; i++) { 17979 PackageParser.Package childPkg = pkg.childPackages.get(i); 17980 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 17981 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 17982 mHandler.sendMessage(msg); 17983 } 17984 } 17985 17986 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 17987 PackageParser.Package pkg) { 17988 int size = pkg.activities.size(); 17989 if (size == 0) { 17990 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17991 "No activity, so no need to verify any IntentFilter!"); 17992 return; 17993 } 17994 17995 final boolean hasDomainURLs = hasDomainURLs(pkg); 17996 if (!hasDomainURLs) { 17997 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17998 "No domain URLs, so no need to verify any IntentFilter!"); 17999 return; 18000 } 18001 18002 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 18003 + " if any IntentFilter from the " + size 18004 + " Activities needs verification ..."); 18005 18006 int count = 0; 18007 final String packageName = pkg.packageName; 18008 18009 synchronized (mPackages) { 18010 // If this is a new install and we see that we've already run verification for this 18011 // package, we have nothing to do: it means the state was restored from backup. 18012 if (!replacing) { 18013 IntentFilterVerificationInfo ivi = 18014 mSettings.getIntentFilterVerificationLPr(packageName); 18015 if (ivi != null) { 18016 if (DEBUG_DOMAIN_VERIFICATION) { 18017 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 18018 + ivi.getStatusString()); 18019 } 18020 return; 18021 } 18022 } 18023 18024 // If any filters need to be verified, then all need to be. 18025 boolean needToVerify = false; 18026 for (PackageParser.Activity a : pkg.activities) { 18027 for (ActivityIntentInfo filter : a.intents) { 18028 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 18029 if (DEBUG_DOMAIN_VERIFICATION) { 18030 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 18031 } 18032 needToVerify = true; 18033 break; 18034 } 18035 } 18036 } 18037 18038 if (needToVerify) { 18039 final int verificationId = mIntentFilterVerificationToken++; 18040 for (PackageParser.Activity a : pkg.activities) { 18041 for (ActivityIntentInfo filter : a.intents) { 18042 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 18043 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 18044 "Verification needed for IntentFilter:" + filter.toString()); 18045 mIntentFilterVerifier.addOneIntentFilterVerification( 18046 verifierUid, userId, verificationId, filter, packageName); 18047 count++; 18048 } 18049 } 18050 } 18051 } 18052 } 18053 18054 if (count > 0) { 18055 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 18056 + " IntentFilter verification" + (count > 1 ? "s" : "") 18057 + " for userId:" + userId); 18058 mIntentFilterVerifier.startVerifications(userId); 18059 } else { 18060 if (DEBUG_DOMAIN_VERIFICATION) { 18061 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 18062 } 18063 } 18064 } 18065 18066 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 18067 final ComponentName cn = filter.activity.getComponentName(); 18068 final String packageName = cn.getPackageName(); 18069 18070 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 18071 packageName); 18072 if (ivi == null) { 18073 return true; 18074 } 18075 int status = ivi.getStatus(); 18076 switch (status) { 18077 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 18078 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 18079 return true; 18080 18081 default: 18082 // Nothing to do 18083 return false; 18084 } 18085 } 18086 18087 private static boolean isMultiArch(ApplicationInfo info) { 18088 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 18089 } 18090 18091 private static boolean isExternal(PackageParser.Package pkg) { 18092 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 18093 } 18094 18095 private static boolean isExternal(PackageSetting ps) { 18096 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 18097 } 18098 18099 private static boolean isSystemApp(PackageParser.Package pkg) { 18100 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 18101 } 18102 18103 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 18104 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 18105 } 18106 18107 private static boolean hasDomainURLs(PackageParser.Package pkg) { 18108 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 18109 } 18110 18111 private static boolean isSystemApp(PackageSetting ps) { 18112 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 18113 } 18114 18115 private static boolean isUpdatedSystemApp(PackageSetting ps) { 18116 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 18117 } 18118 18119 private int packageFlagsToInstallFlags(PackageSetting ps) { 18120 int installFlags = 0; 18121 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 18122 // This existing package was an external ASEC install when we have 18123 // the external flag without a UUID 18124 installFlags |= PackageManager.INSTALL_EXTERNAL; 18125 } 18126 if (ps.isForwardLocked()) { 18127 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 18128 } 18129 return installFlags; 18130 } 18131 18132 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 18133 if (isExternal(pkg)) { 18134 if (TextUtils.isEmpty(pkg.volumeUuid)) { 18135 return StorageManager.UUID_PRIMARY_PHYSICAL; 18136 } else { 18137 return pkg.volumeUuid; 18138 } 18139 } else { 18140 return StorageManager.UUID_PRIVATE_INTERNAL; 18141 } 18142 } 18143 18144 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 18145 if (isExternal(pkg)) { 18146 if (TextUtils.isEmpty(pkg.volumeUuid)) { 18147 return mSettings.getExternalVersion(); 18148 } else { 18149 return mSettings.findOrCreateVersion(pkg.volumeUuid); 18150 } 18151 } else { 18152 return mSettings.getInternalVersion(); 18153 } 18154 } 18155 18156 private void deleteTempPackageFiles() { 18157 final FilenameFilter filter = new FilenameFilter() { 18158 public boolean accept(File dir, String name) { 18159 return name.startsWith("vmdl") && name.endsWith(".tmp"); 18160 } 18161 }; 18162 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 18163 file.delete(); 18164 } 18165 } 18166 18167 @Override 18168 public void deletePackageAsUser(String packageName, int versionCode, 18169 IPackageDeleteObserver observer, int userId, int flags) { 18170 deletePackageVersioned(new VersionedPackage(packageName, versionCode), 18171 new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags); 18172 } 18173 18174 @Override 18175 public void deletePackageVersioned(VersionedPackage versionedPackage, 18176 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 18177 mContext.enforceCallingOrSelfPermission( 18178 android.Manifest.permission.DELETE_PACKAGES, null); 18179 Preconditions.checkNotNull(versionedPackage); 18180 Preconditions.checkNotNull(observer); 18181 Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(), 18182 PackageManager.VERSION_CODE_HIGHEST, 18183 Integer.MAX_VALUE, "versionCode must be >= -1"); 18184 18185 final String packageName = versionedPackage.getPackageName(); 18186 final int versionCode = versionedPackage.getVersionCode(); 18187 final String internalPackageName; 18188 synchronized (mPackages) { 18189 // Normalize package name to handle renamed packages and static libs 18190 internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(), 18191 versionedPackage.getVersionCode()); 18192 } 18193 18194 final int uid = Binder.getCallingUid(); 18195 if (!isOrphaned(internalPackageName) 18196 && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) { 18197 try { 18198 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 18199 intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null)); 18200 intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder()); 18201 observer.onUserActionRequired(intent); 18202 } catch (RemoteException re) { 18203 } 18204 return; 18205 } 18206 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 18207 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 18208 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 18209 mContext.enforceCallingOrSelfPermission( 18210 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 18211 "deletePackage for user " + userId); 18212 } 18213 18214 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 18215 try { 18216 observer.onPackageDeleted(packageName, 18217 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 18218 } catch (RemoteException re) { 18219 } 18220 return; 18221 } 18222 18223 if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) { 18224 try { 18225 observer.onPackageDeleted(packageName, 18226 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 18227 } catch (RemoteException re) { 18228 } 18229 return; 18230 } 18231 18232 if (DEBUG_REMOVE) { 18233 Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId 18234 + " deleteAllUsers: " + deleteAllUsers + " version=" 18235 + (versionCode == PackageManager.VERSION_CODE_HIGHEST 18236 ? "VERSION_CODE_HIGHEST" : versionCode)); 18237 } 18238 // Queue up an async operation since the package deletion may take a little while. 18239 mHandler.post(new Runnable() { 18240 public void run() { 18241 mHandler.removeCallbacks(this); 18242 int returnCode; 18243 if (!deleteAllUsers) { 18244 returnCode = deletePackageX(internalPackageName, versionCode, 18245 userId, deleteFlags); 18246 } else { 18247 int[] blockUninstallUserIds = getBlockUninstallForUsers( 18248 internalPackageName, users); 18249 // If nobody is blocking uninstall, proceed with delete for all users 18250 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 18251 returnCode = deletePackageX(internalPackageName, versionCode, 18252 userId, deleteFlags); 18253 } else { 18254 // Otherwise uninstall individually for users with blockUninstalls=false 18255 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 18256 for (int userId : users) { 18257 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 18258 returnCode = deletePackageX(internalPackageName, versionCode, 18259 userId, userFlags); 18260 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 18261 Slog.w(TAG, "Package delete failed for user " + userId 18262 + ", returnCode " + returnCode); 18263 } 18264 } 18265 } 18266 // The app has only been marked uninstalled for certain users. 18267 // We still need to report that delete was blocked 18268 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 18269 } 18270 } 18271 try { 18272 observer.onPackageDeleted(packageName, returnCode, null); 18273 } catch (RemoteException e) { 18274 Log.i(TAG, "Observer no longer exists."); 18275 } //end catch 18276 } //end run 18277 }); 18278 } 18279 18280 private String resolveExternalPackageNameLPr(PackageParser.Package pkg) { 18281 if (pkg.staticSharedLibName != null) { 18282 return pkg.manifestPackageName; 18283 } 18284 return pkg.packageName; 18285 } 18286 18287 private String resolveInternalPackageNameLPr(String packageName, int versionCode) { 18288 // Handle renamed packages 18289 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 18290 packageName = normalizedPackageName != null ? normalizedPackageName : packageName; 18291 18292 // Is this a static library? 18293 SparseArray<SharedLibraryEntry> versionedLib = 18294 mStaticLibsByDeclaringPackage.get(packageName); 18295 if (versionedLib == null || versionedLib.size() <= 0) { 18296 return packageName; 18297 } 18298 18299 // Figure out which lib versions the caller can see 18300 SparseIntArray versionsCallerCanSee = null; 18301 final int callingAppId = UserHandle.getAppId(Binder.getCallingUid()); 18302 if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID 18303 && callingAppId != Process.ROOT_UID) { 18304 versionsCallerCanSee = new SparseIntArray(); 18305 String libName = versionedLib.valueAt(0).info.getName(); 18306 String[] uidPackages = getPackagesForUid(Binder.getCallingUid()); 18307 if (uidPackages != null) { 18308 for (String uidPackage : uidPackages) { 18309 PackageSetting ps = mSettings.getPackageLPr(uidPackage); 18310 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 18311 if (libIdx >= 0) { 18312 final int libVersion = ps.usesStaticLibrariesVersions[libIdx]; 18313 versionsCallerCanSee.append(libVersion, libVersion); 18314 } 18315 } 18316 } 18317 } 18318 18319 // Caller can see nothing - done 18320 if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) { 18321 return packageName; 18322 } 18323 18324 // Find the version the caller can see and the app version code 18325 SharedLibraryEntry highestVersion = null; 18326 final int versionCount = versionedLib.size(); 18327 for (int i = 0; i < versionCount; i++) { 18328 SharedLibraryEntry libEntry = versionedLib.valueAt(i); 18329 if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey( 18330 libEntry.info.getVersion()) < 0) { 18331 continue; 18332 } 18333 final int libVersionCode = libEntry.info.getDeclaringPackage().getVersionCode(); 18334 if (versionCode != PackageManager.VERSION_CODE_HIGHEST) { 18335 if (libVersionCode == versionCode) { 18336 return libEntry.apk; 18337 } 18338 } else if (highestVersion == null) { 18339 highestVersion = libEntry; 18340 } else if (libVersionCode > highestVersion.info 18341 .getDeclaringPackage().getVersionCode()) { 18342 highestVersion = libEntry; 18343 } 18344 } 18345 18346 if (highestVersion != null) { 18347 return highestVersion.apk; 18348 } 18349 18350 return packageName; 18351 } 18352 18353 private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) { 18354 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID 18355 || callingUid == Process.SYSTEM_UID) { 18356 return true; 18357 } 18358 final int callingUserId = UserHandle.getUserId(callingUid); 18359 // If the caller installed the pkgName, then allow it to silently uninstall. 18360 if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) { 18361 return true; 18362 } 18363 18364 // Allow package verifier to silently uninstall. 18365 if (mRequiredVerifierPackage != null && 18366 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) { 18367 return true; 18368 } 18369 18370 // Allow package uninstaller to silently uninstall. 18371 if (mRequiredUninstallerPackage != null && 18372 callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) { 18373 return true; 18374 } 18375 18376 // Allow storage manager to silently uninstall. 18377 if (mStorageManagerPackage != null && 18378 callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) { 18379 return true; 18380 } 18381 return false; 18382 } 18383 18384 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 18385 int[] result = EMPTY_INT_ARRAY; 18386 for (int userId : userIds) { 18387 if (getBlockUninstallForUser(packageName, userId)) { 18388 result = ArrayUtils.appendInt(result, userId); 18389 } 18390 } 18391 return result; 18392 } 18393 18394 @Override 18395 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 18396 final int callingUid = Binder.getCallingUid(); 18397 if (getInstantAppPackageName(callingUid) != null 18398 && !isCallerSameApp(packageName, callingUid)) { 18399 return false; 18400 } 18401 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 18402 } 18403 18404 private boolean isPackageDeviceAdmin(String packageName, int userId) { 18405 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 18406 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 18407 try { 18408 if (dpm != null) { 18409 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 18410 /* callingUserOnly =*/ false); 18411 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 18412 : deviceOwnerComponentName.getPackageName(); 18413 // Does the package contains the device owner? 18414 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 18415 // this check is probably not needed, since DO should be registered as a device 18416 // admin on some user too. (Original bug for this: b/17657954) 18417 if (packageName.equals(deviceOwnerPackageName)) { 18418 return true; 18419 } 18420 // Does it contain a device admin for any user? 18421 int[] users; 18422 if (userId == UserHandle.USER_ALL) { 18423 users = sUserManager.getUserIds(); 18424 } else { 18425 users = new int[]{userId}; 18426 } 18427 for (int i = 0; i < users.length; ++i) { 18428 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 18429 return true; 18430 } 18431 } 18432 } 18433 } catch (RemoteException e) { 18434 } 18435 return false; 18436 } 18437 18438 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 18439 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 18440 } 18441 18442 /** 18443 * This method is an internal method that could be get invoked either 18444 * to delete an installed package or to clean up a failed installation. 18445 * After deleting an installed package, a broadcast is sent to notify any 18446 * listeners that the package has been removed. For cleaning up a failed 18447 * installation, the broadcast is not necessary since the package's 18448 * installation wouldn't have sent the initial broadcast either 18449 * The key steps in deleting a package are 18450 * deleting the package information in internal structures like mPackages, 18451 * deleting the packages base directories through installd 18452 * updating mSettings to reflect current status 18453 * persisting settings for later use 18454 * sending a broadcast if necessary 18455 */ 18456 private int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) { 18457 final PackageRemovedInfo info = new PackageRemovedInfo(this); 18458 final boolean res; 18459 18460 final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 18461 ? UserHandle.USER_ALL : userId; 18462 18463 if (isPackageDeviceAdmin(packageName, removeUser)) { 18464 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 18465 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 18466 } 18467 18468 PackageSetting uninstalledPs = null; 18469 PackageParser.Package pkg = null; 18470 18471 // for the uninstall-updates case and restricted profiles, remember the per- 18472 // user handle installed state 18473 int[] allUsers; 18474 synchronized (mPackages) { 18475 uninstalledPs = mSettings.mPackages.get(packageName); 18476 if (uninstalledPs == null) { 18477 Slog.w(TAG, "Not removing non-existent package " + packageName); 18478 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 18479 } 18480 18481 if (versionCode != PackageManager.VERSION_CODE_HIGHEST 18482 && uninstalledPs.versionCode != versionCode) { 18483 Slog.w(TAG, "Not removing package " + packageName + " with versionCode " 18484 + uninstalledPs.versionCode + " != " + versionCode); 18485 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 18486 } 18487 18488 // Static shared libs can be declared by any package, so let us not 18489 // allow removing a package if it provides a lib others depend on. 18490 pkg = mPackages.get(packageName); 18491 18492 allUsers = sUserManager.getUserIds(); 18493 18494 if (pkg != null && pkg.staticSharedLibName != null) { 18495 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName, 18496 pkg.staticSharedLibVersion); 18497 if (libEntry != null) { 18498 for (int currUserId : allUsers) { 18499 if (userId != UserHandle.USER_ALL && userId != currUserId) { 18500 continue; 18501 } 18502 List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr( 18503 libEntry.info, 0, currUserId); 18504 if (!ArrayUtils.isEmpty(libClientPackages)) { 18505 Slog.w(TAG, "Not removing package " + pkg.manifestPackageName 18506 + " hosting lib " + libEntry.info.getName() + " version " 18507 + libEntry.info.getVersion() + " used by " + libClientPackages 18508 + " for user " + currUserId); 18509 return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY; 18510 } 18511 } 18512 } 18513 } 18514 18515 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 18516 } 18517 18518 final int freezeUser; 18519 if (isUpdatedSystemApp(uninstalledPs) 18520 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) { 18521 // We're downgrading a system app, which will apply to all users, so 18522 // freeze them all during the downgrade 18523 freezeUser = UserHandle.USER_ALL; 18524 } else { 18525 freezeUser = removeUser; 18526 } 18527 18528 synchronized (mInstallLock) { 18529 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 18530 try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser, 18531 deleteFlags, "deletePackageX")) { 18532 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers, 18533 deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null); 18534 } 18535 synchronized (mPackages) { 18536 if (res) { 18537 if (pkg != null) { 18538 mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers); 18539 } 18540 updateSequenceNumberLP(packageName, info.removedUsers); 18541 updateInstantAppInstallerLocked(packageName); 18542 } 18543 } 18544 } 18545 18546 if (res) { 18547 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 18548 info.sendPackageRemovedBroadcasts(killApp); 18549 info.sendSystemPackageUpdatedBroadcasts(); 18550 info.sendSystemPackageAppearedBroadcasts(); 18551 } 18552 // Force a gc here. 18553 Runtime.getRuntime().gc(); 18554 // Delete the resources here after sending the broadcast to let 18555 // other processes clean up before deleting resources. 18556 if (info.args != null) { 18557 synchronized (mInstallLock) { 18558 info.args.doPostDeleteLI(true); 18559 } 18560 } 18561 18562 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 18563 } 18564 18565 static class PackageRemovedInfo { 18566 final PackageSender packageSender; 18567 String removedPackage; 18568 String installerPackageName; 18569 int uid = -1; 18570 int removedAppId = -1; 18571 int[] origUsers; 18572 int[] removedUsers = null; 18573 int[] broadcastUsers = null; 18574 SparseArray<Integer> installReasons; 18575 boolean isRemovedPackageSystemUpdate = false; 18576 boolean isUpdate; 18577 boolean dataRemoved; 18578 boolean removedForAllUsers; 18579 boolean isStaticSharedLib; 18580 // Clean up resources deleted packages. 18581 InstallArgs args = null; 18582 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 18583 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 18584 18585 PackageRemovedInfo(PackageSender packageSender) { 18586 this.packageSender = packageSender; 18587 } 18588 18589 void sendPackageRemovedBroadcasts(boolean killApp) { 18590 sendPackageRemovedBroadcastInternal(killApp); 18591 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 18592 for (int i = 0; i < childCount; i++) { 18593 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 18594 childInfo.sendPackageRemovedBroadcastInternal(killApp); 18595 } 18596 } 18597 18598 void sendSystemPackageUpdatedBroadcasts() { 18599 if (isRemovedPackageSystemUpdate) { 18600 sendSystemPackageUpdatedBroadcastsInternal(); 18601 final int childCount = (removedChildPackages != null) 18602 ? removedChildPackages.size() : 0; 18603 for (int i = 0; i < childCount; i++) { 18604 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 18605 if (childInfo.isRemovedPackageSystemUpdate) { 18606 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 18607 } 18608 } 18609 } 18610 } 18611 18612 void sendSystemPackageAppearedBroadcasts() { 18613 final int packageCount = (appearedChildPackages != null) 18614 ? appearedChildPackages.size() : 0; 18615 for (int i = 0; i < packageCount; i++) { 18616 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 18617 packageSender.sendPackageAddedForNewUsers(installedInfo.name, 18618 true, UserHandle.getAppId(installedInfo.uid), 18619 installedInfo.newUsers); 18620 } 18621 } 18622 18623 private void sendSystemPackageUpdatedBroadcastsInternal() { 18624 Bundle extras = new Bundle(2); 18625 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 18626 extras.putBoolean(Intent.EXTRA_REPLACING, true); 18627 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 18628 removedPackage, extras, 0, null /*targetPackage*/, null, null); 18629 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 18630 removedPackage, extras, 0, null /*targetPackage*/, null, null); 18631 packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 18632 null, null, 0, removedPackage, null, null); 18633 if (installerPackageName != null) { 18634 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 18635 removedPackage, extras, 0 /*flags*/, 18636 installerPackageName, null, null); 18637 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 18638 removedPackage, extras, 0 /*flags*/, 18639 installerPackageName, null, null); 18640 } 18641 } 18642 18643 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 18644 // Don't send static shared library removal broadcasts as these 18645 // libs are visible only the the apps that depend on them an one 18646 // cannot remove the library if it has a dependency. 18647 if (isStaticSharedLib) { 18648 return; 18649 } 18650 Bundle extras = new Bundle(2); 18651 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 18652 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 18653 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 18654 if (isUpdate || isRemovedPackageSystemUpdate) { 18655 extras.putBoolean(Intent.EXTRA_REPLACING, true); 18656 } 18657 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 18658 if (removedPackage != null) { 18659 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, 18660 removedPackage, extras, 0, null /*targetPackage*/, null, broadcastUsers); 18661 if (installerPackageName != null) { 18662 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, 18663 removedPackage, extras, 0 /*flags*/, 18664 installerPackageName, null, broadcastUsers); 18665 } 18666 if (dataRemoved && !isRemovedPackageSystemUpdate) { 18667 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 18668 removedPackage, extras, 18669 Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, 18670 null, null, broadcastUsers); 18671 } 18672 } 18673 if (removedAppId >= 0) { 18674 packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 18675 Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, null, null, broadcastUsers); 18676 } 18677 } 18678 18679 void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) { 18680 removedUsers = userIds; 18681 if (removedUsers == null) { 18682 broadcastUsers = null; 18683 return; 18684 } 18685 18686 broadcastUsers = EMPTY_INT_ARRAY; 18687 for (int i = userIds.length - 1; i >= 0; --i) { 18688 final int userId = userIds[i]; 18689 if (deletedPackageSetting.getInstantApp(userId)) { 18690 continue; 18691 } 18692 broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId); 18693 } 18694 } 18695 } 18696 18697 /* 18698 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 18699 * flag is not set, the data directory is removed as well. 18700 * make sure this flag is set for partially installed apps. If not its meaningless to 18701 * delete a partially installed application. 18702 */ 18703 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 18704 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 18705 String packageName = ps.name; 18706 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 18707 // Retrieve object to delete permissions for shared user later on 18708 final PackageParser.Package deletedPkg; 18709 final PackageSetting deletedPs; 18710 // reader 18711 synchronized (mPackages) { 18712 deletedPkg = mPackages.get(packageName); 18713 deletedPs = mSettings.mPackages.get(packageName); 18714 if (outInfo != null) { 18715 outInfo.removedPackage = packageName; 18716 outInfo.installerPackageName = ps.installerPackageName; 18717 outInfo.isStaticSharedLib = deletedPkg != null 18718 && deletedPkg.staticSharedLibName != null; 18719 outInfo.populateUsers(deletedPs == null ? null 18720 : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs); 18721 } 18722 } 18723 18724 removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0); 18725 18726 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 18727 final PackageParser.Package resolvedPkg; 18728 if (deletedPkg != null) { 18729 resolvedPkg = deletedPkg; 18730 } else { 18731 // We don't have a parsed package when it lives on an ejected 18732 // adopted storage device, so fake something together 18733 resolvedPkg = new PackageParser.Package(ps.name); 18734 resolvedPkg.setVolumeUuid(ps.volumeUuid); 18735 } 18736 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 18737 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18738 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 18739 if (outInfo != null) { 18740 outInfo.dataRemoved = true; 18741 } 18742 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 18743 } 18744 18745 int removedAppId = -1; 18746 18747 // writer 18748 synchronized (mPackages) { 18749 boolean installedStateChanged = false; 18750 if (deletedPs != null) { 18751 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 18752 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 18753 clearDefaultBrowserIfNeeded(packageName); 18754 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 18755 removedAppId = mSettings.removePackageLPw(packageName); 18756 if (outInfo != null) { 18757 outInfo.removedAppId = removedAppId; 18758 } 18759 updatePermissionsLPw(deletedPs.name, null, 0); 18760 if (deletedPs.sharedUser != null) { 18761 // Remove permissions associated with package. Since runtime 18762 // permissions are per user we have to kill the removed package 18763 // or packages running under the shared user of the removed 18764 // package if revoking the permissions requested only by the removed 18765 // package is successful and this causes a change in gids. 18766 for (int userId : UserManagerService.getInstance().getUserIds()) { 18767 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 18768 userId); 18769 if (userIdToKill == UserHandle.USER_ALL 18770 || userIdToKill >= UserHandle.USER_SYSTEM) { 18771 // If gids changed for this user, kill all affected packages. 18772 mHandler.post(new Runnable() { 18773 @Override 18774 public void run() { 18775 // This has to happen with no lock held. 18776 killApplication(deletedPs.name, deletedPs.appId, 18777 KILL_APP_REASON_GIDS_CHANGED); 18778 } 18779 }); 18780 break; 18781 } 18782 } 18783 } 18784 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 18785 } 18786 // make sure to preserve per-user disabled state if this removal was just 18787 // a downgrade of a system app to the factory package 18788 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 18789 if (DEBUG_REMOVE) { 18790 Slog.d(TAG, "Propagating install state across downgrade"); 18791 } 18792 for (int userId : allUserHandles) { 18793 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 18794 if (DEBUG_REMOVE) { 18795 Slog.d(TAG, " user " + userId + " => " + installed); 18796 } 18797 if (installed != ps.getInstalled(userId)) { 18798 installedStateChanged = true; 18799 } 18800 ps.setInstalled(installed, userId); 18801 } 18802 } 18803 } 18804 // can downgrade to reader 18805 if (writeSettings) { 18806 // Save settings now 18807 mSettings.writeLPr(); 18808 } 18809 if (installedStateChanged) { 18810 mSettings.writeKernelMappingLPr(ps); 18811 } 18812 } 18813 if (removedAppId != -1) { 18814 // A user ID was deleted here. Go through all users and remove it 18815 // from KeyStore. 18816 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId); 18817 } 18818 } 18819 18820 static boolean locationIsPrivileged(File path) { 18821 try { 18822 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 18823 .getCanonicalPath(); 18824 return path.getCanonicalPath().startsWith(privilegedAppDir); 18825 } catch (IOException e) { 18826 Slog.e(TAG, "Unable to access code path " + path); 18827 } 18828 return false; 18829 } 18830 18831 /* 18832 * Tries to delete system package. 18833 */ 18834 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 18835 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 18836 boolean writeSettings) { 18837 if (deletedPs.parentPackageName != null) { 18838 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 18839 return false; 18840 } 18841 18842 final boolean applyUserRestrictions 18843 = (allUserHandles != null) && (outInfo.origUsers != null); 18844 final PackageSetting disabledPs; 18845 // Confirm if the system package has been updated 18846 // An updated system app can be deleted. This will also have to restore 18847 // the system pkg from system partition 18848 // reader 18849 synchronized (mPackages) { 18850 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 18851 } 18852 18853 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 18854 + " disabledPs=" + disabledPs); 18855 18856 if (disabledPs == null) { 18857 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 18858 return false; 18859 } else if (DEBUG_REMOVE) { 18860 Slog.d(TAG, "Deleting system pkg from data partition"); 18861 } 18862 18863 if (DEBUG_REMOVE) { 18864 if (applyUserRestrictions) { 18865 Slog.d(TAG, "Remembering install states:"); 18866 for (int userId : allUserHandles) { 18867 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 18868 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 18869 } 18870 } 18871 } 18872 18873 // Delete the updated package 18874 outInfo.isRemovedPackageSystemUpdate = true; 18875 if (outInfo.removedChildPackages != null) { 18876 final int childCount = (deletedPs.childPackageNames != null) 18877 ? deletedPs.childPackageNames.size() : 0; 18878 for (int i = 0; i < childCount; i++) { 18879 String childPackageName = deletedPs.childPackageNames.get(i); 18880 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 18881 .contains(childPackageName)) { 18882 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 18883 childPackageName); 18884 if (childInfo != null) { 18885 childInfo.isRemovedPackageSystemUpdate = true; 18886 } 18887 } 18888 } 18889 } 18890 18891 if (disabledPs.versionCode < deletedPs.versionCode) { 18892 // Delete data for downgrades 18893 flags &= ~PackageManager.DELETE_KEEP_DATA; 18894 } else { 18895 // Preserve data by setting flag 18896 flags |= PackageManager.DELETE_KEEP_DATA; 18897 } 18898 18899 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 18900 outInfo, writeSettings, disabledPs.pkg); 18901 if (!ret) { 18902 return false; 18903 } 18904 18905 // writer 18906 synchronized (mPackages) { 18907 // Reinstate the old system package 18908 enableSystemPackageLPw(disabledPs.pkg); 18909 // Remove any native libraries from the upgraded package. 18910 removeNativeBinariesLI(deletedPs); 18911 } 18912 18913 // Install the system package 18914 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 18915 int parseFlags = mDefParseFlags 18916 | PackageParser.PARSE_MUST_BE_APK 18917 | PackageParser.PARSE_IS_SYSTEM 18918 | PackageParser.PARSE_IS_SYSTEM_DIR; 18919 if (locationIsPrivileged(disabledPs.codePath)) { 18920 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 18921 } 18922 18923 final PackageParser.Package newPkg; 18924 try { 18925 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */, 18926 0 /* currentTime */, null); 18927 } catch (PackageManagerException e) { 18928 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 18929 + e.getMessage()); 18930 return false; 18931 } 18932 18933 try { 18934 // update shared libraries for the newly re-installed system package 18935 updateSharedLibrariesLPr(newPkg, null); 18936 } catch (PackageManagerException e) { 18937 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 18938 } 18939 18940 prepareAppDataAfterInstallLIF(newPkg); 18941 18942 // writer 18943 synchronized (mPackages) { 18944 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 18945 18946 // Propagate the permissions state as we do not want to drop on the floor 18947 // runtime permissions. The update permissions method below will take 18948 // care of removing obsolete permissions and grant install permissions. 18949 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 18950 updatePermissionsLPw(newPkg.packageName, newPkg, 18951 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 18952 18953 if (applyUserRestrictions) { 18954 boolean installedStateChanged = false; 18955 if (DEBUG_REMOVE) { 18956 Slog.d(TAG, "Propagating install state across reinstall"); 18957 } 18958 for (int userId : allUserHandles) { 18959 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 18960 if (DEBUG_REMOVE) { 18961 Slog.d(TAG, " user " + userId + " => " + installed); 18962 } 18963 if (installed != ps.getInstalled(userId)) { 18964 installedStateChanged = true; 18965 } 18966 ps.setInstalled(installed, userId); 18967 18968 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 18969 } 18970 // Regardless of writeSettings we need to ensure that this restriction 18971 // state propagation is persisted 18972 mSettings.writeAllUsersPackageRestrictionsLPr(); 18973 if (installedStateChanged) { 18974 mSettings.writeKernelMappingLPr(ps); 18975 } 18976 } 18977 // can downgrade to reader here 18978 if (writeSettings) { 18979 mSettings.writeLPr(); 18980 } 18981 } 18982 return true; 18983 } 18984 18985 private boolean deleteInstalledPackageLIF(PackageSetting ps, 18986 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 18987 PackageRemovedInfo outInfo, boolean writeSettings, 18988 PackageParser.Package replacingPackage) { 18989 synchronized (mPackages) { 18990 if (outInfo != null) { 18991 outInfo.uid = ps.appId; 18992 } 18993 18994 if (outInfo != null && outInfo.removedChildPackages != null) { 18995 final int childCount = (ps.childPackageNames != null) 18996 ? ps.childPackageNames.size() : 0; 18997 for (int i = 0; i < childCount; i++) { 18998 String childPackageName = ps.childPackageNames.get(i); 18999 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 19000 if (childPs == null) { 19001 return false; 19002 } 19003 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 19004 childPackageName); 19005 if (childInfo != null) { 19006 childInfo.uid = childPs.appId; 19007 } 19008 } 19009 } 19010 } 19011 19012 // Delete package data from internal structures and also remove data if flag is set 19013 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 19014 19015 // Delete the child packages data 19016 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 19017 for (int i = 0; i < childCount; i++) { 19018 PackageSetting childPs; 19019 synchronized (mPackages) { 19020 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 19021 } 19022 if (childPs != null) { 19023 PackageRemovedInfo childOutInfo = (outInfo != null 19024 && outInfo.removedChildPackages != null) 19025 ? outInfo.removedChildPackages.get(childPs.name) : null; 19026 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 19027 && (replacingPackage != null 19028 && !replacingPackage.hasChildPackage(childPs.name)) 19029 ? flags & ~DELETE_KEEP_DATA : flags; 19030 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 19031 deleteFlags, writeSettings); 19032 } 19033 } 19034 19035 // Delete application code and resources only for parent packages 19036 if (ps.parentPackageName == null) { 19037 if (deleteCodeAndResources && (outInfo != null)) { 19038 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 19039 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 19040 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 19041 } 19042 } 19043 19044 return true; 19045 } 19046 19047 @Override 19048 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 19049 int userId) { 19050 mContext.enforceCallingOrSelfPermission( 19051 android.Manifest.permission.DELETE_PACKAGES, null); 19052 synchronized (mPackages) { 19053 // Cannot block uninstall of static shared libs as they are 19054 // considered a part of the using app (emulating static linking). 19055 // Also static libs are installed always on internal storage. 19056 PackageParser.Package pkg = mPackages.get(packageName); 19057 if (pkg != null && pkg.staticSharedLibName != null) { 19058 Slog.w(TAG, "Cannot block uninstall of package: " + packageName 19059 + " providing static shared library: " + pkg.staticSharedLibName); 19060 return false; 19061 } 19062 mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall); 19063 mSettings.writePackageRestrictionsLPr(userId); 19064 } 19065 return true; 19066 } 19067 19068 @Override 19069 public boolean getBlockUninstallForUser(String packageName, int userId) { 19070 synchronized (mPackages) { 19071 return mSettings.getBlockUninstallLPr(userId, packageName); 19072 } 19073 } 19074 19075 @Override 19076 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 19077 enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root"); 19078 synchronized (mPackages) { 19079 PackageSetting ps = mSettings.mPackages.get(packageName); 19080 if (ps == null) { 19081 Log.w(TAG, "Package doesn't exist: " + packageName); 19082 return false; 19083 } 19084 if (systemUserApp) { 19085 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 19086 } else { 19087 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 19088 } 19089 mSettings.writeLPr(); 19090 } 19091 return true; 19092 } 19093 19094 /* 19095 * This method handles package deletion in general 19096 */ 19097 private boolean deletePackageLIF(String packageName, UserHandle user, 19098 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 19099 PackageRemovedInfo outInfo, boolean writeSettings, 19100 PackageParser.Package replacingPackage) { 19101 if (packageName == null) { 19102 Slog.w(TAG, "Attempt to delete null packageName."); 19103 return false; 19104 } 19105 19106 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 19107 19108 PackageSetting ps; 19109 synchronized (mPackages) { 19110 ps = mSettings.mPackages.get(packageName); 19111 if (ps == null) { 19112 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 19113 return false; 19114 } 19115 19116 if (ps.parentPackageName != null && (!isSystemApp(ps) 19117 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 19118 if (DEBUG_REMOVE) { 19119 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 19120 + ((user == null) ? UserHandle.USER_ALL : user)); 19121 } 19122 final int removedUserId = (user != null) ? user.getIdentifier() 19123 : UserHandle.USER_ALL; 19124 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 19125 return false; 19126 } 19127 markPackageUninstalledForUserLPw(ps, user); 19128 scheduleWritePackageRestrictionsLocked(user); 19129 return true; 19130 } 19131 } 19132 19133 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 19134 && user.getIdentifier() != UserHandle.USER_ALL)) { 19135 // The caller is asking that the package only be deleted for a single 19136 // user. To do this, we just mark its uninstalled state and delete 19137 // its data. If this is a system app, we only allow this to happen if 19138 // they have set the special DELETE_SYSTEM_APP which requests different 19139 // semantics than normal for uninstalling system apps. 19140 markPackageUninstalledForUserLPw(ps, user); 19141 19142 if (!isSystemApp(ps)) { 19143 // Do not uninstall the APK if an app should be cached 19144 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 19145 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 19146 // Other user still have this package installed, so all 19147 // we need to do is clear this user's data and save that 19148 // it is uninstalled. 19149 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 19150 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 19151 return false; 19152 } 19153 scheduleWritePackageRestrictionsLocked(user); 19154 return true; 19155 } else { 19156 // We need to set it back to 'installed' so the uninstall 19157 // broadcasts will be sent correctly. 19158 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 19159 ps.setInstalled(true, user.getIdentifier()); 19160 mSettings.writeKernelMappingLPr(ps); 19161 } 19162 } else { 19163 // This is a system app, so we assume that the 19164 // other users still have this package installed, so all 19165 // we need to do is clear this user's data and save that 19166 // it is uninstalled. 19167 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 19168 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 19169 return false; 19170 } 19171 scheduleWritePackageRestrictionsLocked(user); 19172 return true; 19173 } 19174 } 19175 19176 // If we are deleting a composite package for all users, keep track 19177 // of result for each child. 19178 if (ps.childPackageNames != null && outInfo != null) { 19179 synchronized (mPackages) { 19180 final int childCount = ps.childPackageNames.size(); 19181 outInfo.removedChildPackages = new ArrayMap<>(childCount); 19182 for (int i = 0; i < childCount; i++) { 19183 String childPackageName = ps.childPackageNames.get(i); 19184 PackageRemovedInfo childInfo = new PackageRemovedInfo(this); 19185 childInfo.removedPackage = childPackageName; 19186 childInfo.installerPackageName = ps.installerPackageName; 19187 outInfo.removedChildPackages.put(childPackageName, childInfo); 19188 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 19189 if (childPs != null) { 19190 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 19191 } 19192 } 19193 } 19194 } 19195 19196 boolean ret = false; 19197 if (isSystemApp(ps)) { 19198 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 19199 // When an updated system application is deleted we delete the existing resources 19200 // as well and fall back to existing code in system partition 19201 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 19202 } else { 19203 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 19204 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 19205 outInfo, writeSettings, replacingPackage); 19206 } 19207 19208 // Take a note whether we deleted the package for all users 19209 if (outInfo != null) { 19210 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 19211 if (outInfo.removedChildPackages != null) { 19212 synchronized (mPackages) { 19213 final int childCount = outInfo.removedChildPackages.size(); 19214 for (int i = 0; i < childCount; i++) { 19215 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 19216 if (childInfo != null) { 19217 childInfo.removedForAllUsers = mPackages.get( 19218 childInfo.removedPackage) == null; 19219 } 19220 } 19221 } 19222 } 19223 // If we uninstalled an update to a system app there may be some 19224 // child packages that appeared as they are declared in the system 19225 // app but were not declared in the update. 19226 if (isSystemApp(ps)) { 19227 synchronized (mPackages) { 19228 PackageSetting updatedPs = mSettings.getPackageLPr(ps.name); 19229 final int childCount = (updatedPs.childPackageNames != null) 19230 ? updatedPs.childPackageNames.size() : 0; 19231 for (int i = 0; i < childCount; i++) { 19232 String childPackageName = updatedPs.childPackageNames.get(i); 19233 if (outInfo.removedChildPackages == null 19234 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 19235 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 19236 if (childPs == null) { 19237 continue; 19238 } 19239 PackageInstalledInfo installRes = new PackageInstalledInfo(); 19240 installRes.name = childPackageName; 19241 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 19242 installRes.pkg = mPackages.get(childPackageName); 19243 installRes.uid = childPs.pkg.applicationInfo.uid; 19244 if (outInfo.appearedChildPackages == null) { 19245 outInfo.appearedChildPackages = new ArrayMap<>(); 19246 } 19247 outInfo.appearedChildPackages.put(childPackageName, installRes); 19248 } 19249 } 19250 } 19251 } 19252 } 19253 19254 return ret; 19255 } 19256 19257 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 19258 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 19259 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 19260 for (int nextUserId : userIds) { 19261 if (DEBUG_REMOVE) { 19262 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 19263 } 19264 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 19265 false /*installed*/, 19266 true /*stopped*/, 19267 true /*notLaunched*/, 19268 false /*hidden*/, 19269 false /*suspended*/, 19270 false /*instantApp*/, 19271 null /*lastDisableAppCaller*/, 19272 null /*enabledComponents*/, 19273 null /*disabledComponents*/, 19274 ps.readUserState(nextUserId).domainVerificationStatus, 19275 0, PackageManager.INSTALL_REASON_UNKNOWN); 19276 } 19277 mSettings.writeKernelMappingLPr(ps); 19278 } 19279 19280 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 19281 PackageRemovedInfo outInfo) { 19282 final PackageParser.Package pkg; 19283 synchronized (mPackages) { 19284 pkg = mPackages.get(ps.name); 19285 } 19286 19287 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 19288 : new int[] {userId}; 19289 for (int nextUserId : userIds) { 19290 if (DEBUG_REMOVE) { 19291 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 19292 + nextUserId); 19293 } 19294 19295 destroyAppDataLIF(pkg, userId, 19296 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19297 destroyAppProfilesLIF(pkg, userId); 19298 clearDefaultBrowserIfNeededForUser(ps.name, userId); 19299 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 19300 schedulePackageCleaning(ps.name, nextUserId, false); 19301 synchronized (mPackages) { 19302 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 19303 scheduleWritePackageRestrictionsLocked(nextUserId); 19304 } 19305 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 19306 } 19307 } 19308 19309 if (outInfo != null) { 19310 outInfo.removedPackage = ps.name; 19311 outInfo.installerPackageName = ps.installerPackageName; 19312 outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null; 19313 outInfo.removedAppId = ps.appId; 19314 outInfo.removedUsers = userIds; 19315 outInfo.broadcastUsers = userIds; 19316 } 19317 19318 return true; 19319 } 19320 19321 private final class ClearStorageConnection implements ServiceConnection { 19322 IMediaContainerService mContainerService; 19323 19324 @Override 19325 public void onServiceConnected(ComponentName name, IBinder service) { 19326 synchronized (this) { 19327 mContainerService = IMediaContainerService.Stub 19328 .asInterface(Binder.allowBlocking(service)); 19329 notifyAll(); 19330 } 19331 } 19332 19333 @Override 19334 public void onServiceDisconnected(ComponentName name) { 19335 } 19336 } 19337 19338 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 19339 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 19340 19341 final boolean mounted; 19342 if (Environment.isExternalStorageEmulated()) { 19343 mounted = true; 19344 } else { 19345 final String status = Environment.getExternalStorageState(); 19346 19347 mounted = status.equals(Environment.MEDIA_MOUNTED) 19348 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 19349 } 19350 19351 if (!mounted) { 19352 return; 19353 } 19354 19355 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 19356 int[] users; 19357 if (userId == UserHandle.USER_ALL) { 19358 users = sUserManager.getUserIds(); 19359 } else { 19360 users = new int[] { userId }; 19361 } 19362 final ClearStorageConnection conn = new ClearStorageConnection(); 19363 if (mContext.bindServiceAsUser( 19364 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 19365 try { 19366 for (int curUser : users) { 19367 long timeout = SystemClock.uptimeMillis() + 5000; 19368 synchronized (conn) { 19369 long now; 19370 while (conn.mContainerService == null && 19371 (now = SystemClock.uptimeMillis()) < timeout) { 19372 try { 19373 conn.wait(timeout - now); 19374 } catch (InterruptedException e) { 19375 } 19376 } 19377 } 19378 if (conn.mContainerService == null) { 19379 return; 19380 } 19381 19382 final UserEnvironment userEnv = new UserEnvironment(curUser); 19383 clearDirectory(conn.mContainerService, 19384 userEnv.buildExternalStorageAppCacheDirs(packageName)); 19385 if (allData) { 19386 clearDirectory(conn.mContainerService, 19387 userEnv.buildExternalStorageAppDataDirs(packageName)); 19388 clearDirectory(conn.mContainerService, 19389 userEnv.buildExternalStorageAppMediaDirs(packageName)); 19390 } 19391 } 19392 } finally { 19393 mContext.unbindService(conn); 19394 } 19395 } 19396 } 19397 19398 @Override 19399 public void clearApplicationProfileData(String packageName) { 19400 enforceSystemOrRoot("Only the system can clear all profile data"); 19401 19402 final PackageParser.Package pkg; 19403 synchronized (mPackages) { 19404 pkg = mPackages.get(packageName); 19405 } 19406 19407 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 19408 synchronized (mInstallLock) { 19409 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 19410 } 19411 } 19412 } 19413 19414 @Override 19415 public void clearApplicationUserData(final String packageName, 19416 final IPackageDataObserver observer, final int userId) { 19417 mContext.enforceCallingOrSelfPermission( 19418 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 19419 19420 enforceCrossUserPermission(Binder.getCallingUid(), userId, 19421 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 19422 19423 if (mProtectedPackages.isPackageDataProtected(userId, packageName)) { 19424 throw new SecurityException("Cannot clear data for a protected package: " 19425 + packageName); 19426 } 19427 // Queue up an async operation since the package deletion may take a little while. 19428 mHandler.post(new Runnable() { 19429 public void run() { 19430 mHandler.removeCallbacks(this); 19431 final boolean succeeded; 19432 try (PackageFreezer freezer = freezePackage(packageName, 19433 "clearApplicationUserData")) { 19434 synchronized (mInstallLock) { 19435 succeeded = clearApplicationUserDataLIF(packageName, userId); 19436 } 19437 clearExternalStorageDataSync(packageName, userId, true); 19438 synchronized (mPackages) { 19439 mInstantAppRegistry.deleteInstantApplicationMetadataLPw( 19440 packageName, userId); 19441 } 19442 } 19443 if (succeeded) { 19444 // invoke DeviceStorageMonitor's update method to clear any notifications 19445 DeviceStorageMonitorInternal dsm = LocalServices 19446 .getService(DeviceStorageMonitorInternal.class); 19447 if (dsm != null) { 19448 dsm.checkMemory(); 19449 } 19450 } 19451 if(observer != null) { 19452 try { 19453 observer.onRemoveCompleted(packageName, succeeded); 19454 } catch (RemoteException e) { 19455 Log.i(TAG, "Observer no longer exists."); 19456 } 19457 } //end if observer 19458 } //end run 19459 }); 19460 } 19461 19462 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 19463 if (packageName == null) { 19464 Slog.w(TAG, "Attempt to delete null packageName."); 19465 return false; 19466 } 19467 19468 // Try finding details about the requested package 19469 PackageParser.Package pkg; 19470 synchronized (mPackages) { 19471 pkg = mPackages.get(packageName); 19472 if (pkg == null) { 19473 final PackageSetting ps = mSettings.mPackages.get(packageName); 19474 if (ps != null) { 19475 pkg = ps.pkg; 19476 } 19477 } 19478 19479 if (pkg == null) { 19480 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 19481 return false; 19482 } 19483 19484 PackageSetting ps = (PackageSetting) pkg.mExtras; 19485 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 19486 } 19487 19488 clearAppDataLIF(pkg, userId, 19489 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19490 19491 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 19492 removeKeystoreDataIfNeeded(userId, appId); 19493 19494 UserManagerInternal umInternal = getUserManagerInternal(); 19495 final int flags; 19496 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 19497 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19498 } else if (umInternal.isUserRunning(userId)) { 19499 flags = StorageManager.FLAG_STORAGE_DE; 19500 } else { 19501 flags = 0; 19502 } 19503 prepareAppDataContentsLIF(pkg, userId, flags); 19504 19505 return true; 19506 } 19507 19508 /** 19509 * Reverts user permission state changes (permissions and flags) in 19510 * all packages for a given user. 19511 * 19512 * @param userId The device user for which to do a reset. 19513 */ 19514 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 19515 final int packageCount = mPackages.size(); 19516 for (int i = 0; i < packageCount; i++) { 19517 PackageParser.Package pkg = mPackages.valueAt(i); 19518 PackageSetting ps = (PackageSetting) pkg.mExtras; 19519 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 19520 } 19521 } 19522 19523 private void resetNetworkPolicies(int userId) { 19524 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 19525 } 19526 19527 /** 19528 * Reverts user permission state changes (permissions and flags). 19529 * 19530 * @param ps The package for which to reset. 19531 * @param userId The device user for which to do a reset. 19532 */ 19533 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 19534 final PackageSetting ps, final int userId) { 19535 if (ps.pkg == null) { 19536 return; 19537 } 19538 19539 // These are flags that can change base on user actions. 19540 final int userSettableMask = FLAG_PERMISSION_USER_SET 19541 | FLAG_PERMISSION_USER_FIXED 19542 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 19543 | FLAG_PERMISSION_REVIEW_REQUIRED; 19544 19545 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 19546 | FLAG_PERMISSION_POLICY_FIXED; 19547 19548 boolean writeInstallPermissions = false; 19549 boolean writeRuntimePermissions = false; 19550 19551 final int permissionCount = ps.pkg.requestedPermissions.size(); 19552 for (int i = 0; i < permissionCount; i++) { 19553 String permission = ps.pkg.requestedPermissions.get(i); 19554 19555 BasePermission bp = mSettings.mPermissions.get(permission); 19556 if (bp == null) { 19557 continue; 19558 } 19559 19560 // If shared user we just reset the state to which only this app contributed. 19561 if (ps.sharedUser != null) { 19562 boolean used = false; 19563 final int packageCount = ps.sharedUser.packages.size(); 19564 for (int j = 0; j < packageCount; j++) { 19565 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 19566 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 19567 && pkg.pkg.requestedPermissions.contains(permission)) { 19568 used = true; 19569 break; 19570 } 19571 } 19572 if (used) { 19573 continue; 19574 } 19575 } 19576 19577 PermissionsState permissionsState = ps.getPermissionsState(); 19578 19579 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 19580 19581 // Always clear the user settable flags. 19582 final boolean hasInstallState = permissionsState.getInstallPermissionState( 19583 bp.name) != null; 19584 // If permission review is enabled and this is a legacy app, mark the 19585 // permission as requiring a review as this is the initial state. 19586 int flags = 0; 19587 if (mPermissionReviewRequired 19588 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 19589 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 19590 } 19591 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 19592 if (hasInstallState) { 19593 writeInstallPermissions = true; 19594 } else { 19595 writeRuntimePermissions = true; 19596 } 19597 } 19598 19599 // Below is only runtime permission handling. 19600 if (!bp.isRuntime()) { 19601 continue; 19602 } 19603 19604 // Never clobber system or policy. 19605 if ((oldFlags & policyOrSystemFlags) != 0) { 19606 continue; 19607 } 19608 19609 // If this permission was granted by default, make sure it is. 19610 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 19611 if (permissionsState.grantRuntimePermission(bp, userId) 19612 != PERMISSION_OPERATION_FAILURE) { 19613 writeRuntimePermissions = true; 19614 } 19615 // If permission review is enabled the permissions for a legacy apps 19616 // are represented as constantly granted runtime ones, so don't revoke. 19617 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 19618 // Otherwise, reset the permission. 19619 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 19620 switch (revokeResult) { 19621 case PERMISSION_OPERATION_SUCCESS: 19622 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 19623 writeRuntimePermissions = true; 19624 final int appId = ps.appId; 19625 mHandler.post(new Runnable() { 19626 @Override 19627 public void run() { 19628 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 19629 } 19630 }); 19631 } break; 19632 } 19633 } 19634 } 19635 19636 // Synchronously write as we are taking permissions away. 19637 if (writeRuntimePermissions) { 19638 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 19639 } 19640 19641 // Synchronously write as we are taking permissions away. 19642 if (writeInstallPermissions) { 19643 mSettings.writeLPr(); 19644 } 19645 } 19646 19647 /** 19648 * Remove entries from the keystore daemon. Will only remove it if the 19649 * {@code appId} is valid. 19650 */ 19651 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 19652 if (appId < 0) { 19653 return; 19654 } 19655 19656 final KeyStore keyStore = KeyStore.getInstance(); 19657 if (keyStore != null) { 19658 if (userId == UserHandle.USER_ALL) { 19659 for (final int individual : sUserManager.getUserIds()) { 19660 keyStore.clearUid(UserHandle.getUid(individual, appId)); 19661 } 19662 } else { 19663 keyStore.clearUid(UserHandle.getUid(userId, appId)); 19664 } 19665 } else { 19666 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 19667 } 19668 } 19669 19670 @Override 19671 public void deleteApplicationCacheFiles(final String packageName, 19672 final IPackageDataObserver observer) { 19673 final int userId = UserHandle.getCallingUserId(); 19674 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 19675 } 19676 19677 @Override 19678 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 19679 final IPackageDataObserver observer) { 19680 mContext.enforceCallingOrSelfPermission( 19681 android.Manifest.permission.DELETE_CACHE_FILES, null); 19682 enforceCrossUserPermission(Binder.getCallingUid(), userId, 19683 /* requireFullPermission= */ true, /* checkShell= */ false, 19684 "delete application cache files"); 19685 19686 final PackageParser.Package pkg; 19687 synchronized (mPackages) { 19688 pkg = mPackages.get(packageName); 19689 } 19690 19691 // Queue up an async operation since the package deletion may take a little while. 19692 mHandler.post(new Runnable() { 19693 public void run() { 19694 synchronized (mInstallLock) { 19695 final int flags = StorageManager.FLAG_STORAGE_DE 19696 | StorageManager.FLAG_STORAGE_CE; 19697 // We're only clearing cache files, so we don't care if the 19698 // app is unfrozen and still able to run 19699 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 19700 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 19701 } 19702 clearExternalStorageDataSync(packageName, userId, false); 19703 if (observer != null) { 19704 try { 19705 observer.onRemoveCompleted(packageName, true); 19706 } catch (RemoteException e) { 19707 Log.i(TAG, "Observer no longer exists."); 19708 } 19709 } 19710 } 19711 }); 19712 } 19713 19714 @Override 19715 public void getPackageSizeInfo(final String packageName, int userHandle, 19716 final IPackageStatsObserver observer) { 19717 throw new UnsupportedOperationException( 19718 "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!"); 19719 } 19720 19721 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 19722 final PackageSetting ps; 19723 synchronized (mPackages) { 19724 ps = mSettings.mPackages.get(packageName); 19725 if (ps == null) { 19726 Slog.w(TAG, "Failed to find settings for " + packageName); 19727 return false; 19728 } 19729 } 19730 19731 final String[] packageNames = { packageName }; 19732 final long[] ceDataInodes = { ps.getCeDataInode(userId) }; 19733 final String[] codePaths = { ps.codePathString }; 19734 19735 try { 19736 mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0, 19737 ps.appId, ceDataInodes, codePaths, stats); 19738 19739 // For now, ignore code size of packages on system partition 19740 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 19741 stats.codeSize = 0; 19742 } 19743 19744 // External clients expect these to be tracked separately 19745 stats.dataSize -= stats.cacheSize; 19746 19747 } catch (InstallerException e) { 19748 Slog.w(TAG, String.valueOf(e)); 19749 return false; 19750 } 19751 19752 return true; 19753 } 19754 19755 private int getUidTargetSdkVersionLockedLPr(int uid) { 19756 Object obj = mSettings.getUserIdLPr(uid); 19757 if (obj instanceof SharedUserSetting) { 19758 final SharedUserSetting sus = (SharedUserSetting) obj; 19759 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 19760 final Iterator<PackageSetting> it = sus.packages.iterator(); 19761 while (it.hasNext()) { 19762 final PackageSetting ps = it.next(); 19763 if (ps.pkg != null) { 19764 int v = ps.pkg.applicationInfo.targetSdkVersion; 19765 if (v < vers) vers = v; 19766 } 19767 } 19768 return vers; 19769 } else if (obj instanceof PackageSetting) { 19770 final PackageSetting ps = (PackageSetting) obj; 19771 if (ps.pkg != null) { 19772 return ps.pkg.applicationInfo.targetSdkVersion; 19773 } 19774 } 19775 return Build.VERSION_CODES.CUR_DEVELOPMENT; 19776 } 19777 19778 @Override 19779 public void addPreferredActivity(IntentFilter filter, int match, 19780 ComponentName[] set, ComponentName activity, int userId) { 19781 addPreferredActivityInternal(filter, match, set, activity, true, userId, 19782 "Adding preferred"); 19783 } 19784 19785 private void addPreferredActivityInternal(IntentFilter filter, int match, 19786 ComponentName[] set, ComponentName activity, boolean always, int userId, 19787 String opname) { 19788 // writer 19789 int callingUid = Binder.getCallingUid(); 19790 enforceCrossUserPermission(callingUid, userId, 19791 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 19792 if (filter.countActions() == 0) { 19793 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 19794 return; 19795 } 19796 synchronized (mPackages) { 19797 if (mContext.checkCallingOrSelfPermission( 19798 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 19799 != PackageManager.PERMISSION_GRANTED) { 19800 if (getUidTargetSdkVersionLockedLPr(callingUid) 19801 < Build.VERSION_CODES.FROYO) { 19802 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 19803 + callingUid); 19804 return; 19805 } 19806 mContext.enforceCallingOrSelfPermission( 19807 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 19808 } 19809 19810 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 19811 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 19812 + userId + ":"); 19813 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19814 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 19815 scheduleWritePackageRestrictionsLocked(userId); 19816 postPreferredActivityChangedBroadcast(userId); 19817 } 19818 } 19819 19820 private void postPreferredActivityChangedBroadcast(int userId) { 19821 mHandler.post(() -> { 19822 final IActivityManager am = ActivityManager.getService(); 19823 if (am == null) { 19824 return; 19825 } 19826 19827 final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED); 19828 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 19829 try { 19830 am.broadcastIntent(null, intent, null, null, 19831 0, null, null, null, android.app.AppOpsManager.OP_NONE, 19832 null, false, false, userId); 19833 } catch (RemoteException e) { 19834 } 19835 }); 19836 } 19837 19838 @Override 19839 public void replacePreferredActivity(IntentFilter filter, int match, 19840 ComponentName[] set, ComponentName activity, int userId) { 19841 if (filter.countActions() != 1) { 19842 throw new IllegalArgumentException( 19843 "replacePreferredActivity expects filter to have only 1 action."); 19844 } 19845 if (filter.countDataAuthorities() != 0 19846 || filter.countDataPaths() != 0 19847 || filter.countDataSchemes() > 1 19848 || filter.countDataTypes() != 0) { 19849 throw new IllegalArgumentException( 19850 "replacePreferredActivity expects filter to have no data authorities, " + 19851 "paths, or types; and at most one scheme."); 19852 } 19853 19854 final int callingUid = Binder.getCallingUid(); 19855 enforceCrossUserPermission(callingUid, userId, 19856 true /* requireFullPermission */, false /* checkShell */, 19857 "replace preferred activity"); 19858 synchronized (mPackages) { 19859 if (mContext.checkCallingOrSelfPermission( 19860 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 19861 != PackageManager.PERMISSION_GRANTED) { 19862 if (getUidTargetSdkVersionLockedLPr(callingUid) 19863 < Build.VERSION_CODES.FROYO) { 19864 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 19865 + Binder.getCallingUid()); 19866 return; 19867 } 19868 mContext.enforceCallingOrSelfPermission( 19869 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 19870 } 19871 19872 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 19873 if (pir != null) { 19874 // Get all of the existing entries that exactly match this filter. 19875 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 19876 if (existing != null && existing.size() == 1) { 19877 PreferredActivity cur = existing.get(0); 19878 if (DEBUG_PREFERRED) { 19879 Slog.i(TAG, "Checking replace of preferred:"); 19880 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19881 if (!cur.mPref.mAlways) { 19882 Slog.i(TAG, " -- CUR; not mAlways!"); 19883 } else { 19884 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 19885 Slog.i(TAG, " -- CUR: mSet=" 19886 + Arrays.toString(cur.mPref.mSetComponents)); 19887 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 19888 Slog.i(TAG, " -- NEW: mMatch=" 19889 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 19890 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 19891 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 19892 } 19893 } 19894 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 19895 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 19896 && cur.mPref.sameSet(set)) { 19897 // Setting the preferred activity to what it happens to be already 19898 if (DEBUG_PREFERRED) { 19899 Slog.i(TAG, "Replacing with same preferred activity " 19900 + cur.mPref.mShortComponent + " for user " 19901 + userId + ":"); 19902 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19903 } 19904 return; 19905 } 19906 } 19907 19908 if (existing != null) { 19909 if (DEBUG_PREFERRED) { 19910 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 19911 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19912 } 19913 for (int i = 0; i < existing.size(); i++) { 19914 PreferredActivity pa = existing.get(i); 19915 if (DEBUG_PREFERRED) { 19916 Slog.i(TAG, "Removing existing preferred activity " 19917 + pa.mPref.mComponent + ":"); 19918 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 19919 } 19920 pir.removeFilter(pa); 19921 } 19922 } 19923 } 19924 addPreferredActivityInternal(filter, match, set, activity, true, userId, 19925 "Replacing preferred"); 19926 } 19927 } 19928 19929 @Override 19930 public void clearPackagePreferredActivities(String packageName) { 19931 final int callingUid = Binder.getCallingUid(); 19932 if (getInstantAppPackageName(callingUid) != null) { 19933 return; 19934 } 19935 // writer 19936 synchronized (mPackages) { 19937 PackageParser.Package pkg = mPackages.get(packageName); 19938 if (pkg == null || pkg.applicationInfo.uid != callingUid) { 19939 if (mContext.checkCallingOrSelfPermission( 19940 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 19941 != PackageManager.PERMISSION_GRANTED) { 19942 if (getUidTargetSdkVersionLockedLPr(callingUid) 19943 < Build.VERSION_CODES.FROYO) { 19944 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 19945 + callingUid); 19946 return; 19947 } 19948 mContext.enforceCallingOrSelfPermission( 19949 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 19950 } 19951 } 19952 19953 int user = UserHandle.getCallingUserId(); 19954 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 19955 scheduleWritePackageRestrictionsLocked(user); 19956 } 19957 } 19958 } 19959 19960 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 19961 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 19962 ArrayList<PreferredActivity> removed = null; 19963 boolean changed = false; 19964 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 19965 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 19966 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 19967 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 19968 continue; 19969 } 19970 Iterator<PreferredActivity> it = pir.filterIterator(); 19971 while (it.hasNext()) { 19972 PreferredActivity pa = it.next(); 19973 // Mark entry for removal only if it matches the package name 19974 // and the entry is of type "always". 19975 if (packageName == null || 19976 (pa.mPref.mComponent.getPackageName().equals(packageName) 19977 && pa.mPref.mAlways)) { 19978 if (removed == null) { 19979 removed = new ArrayList<PreferredActivity>(); 19980 } 19981 removed.add(pa); 19982 } 19983 } 19984 if (removed != null) { 19985 for (int j=0; j<removed.size(); j++) { 19986 PreferredActivity pa = removed.get(j); 19987 pir.removeFilter(pa); 19988 } 19989 changed = true; 19990 } 19991 } 19992 if (changed) { 19993 postPreferredActivityChangedBroadcast(userId); 19994 } 19995 return changed; 19996 } 19997 19998 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 19999 private void clearIntentFilterVerificationsLPw(int userId) { 20000 final int packageCount = mPackages.size(); 20001 for (int i = 0; i < packageCount; i++) { 20002 PackageParser.Package pkg = mPackages.valueAt(i); 20003 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 20004 } 20005 } 20006 20007 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 20008 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 20009 if (userId == UserHandle.USER_ALL) { 20010 if (mSettings.removeIntentFilterVerificationLPw(packageName, 20011 sUserManager.getUserIds())) { 20012 for (int oneUserId : sUserManager.getUserIds()) { 20013 scheduleWritePackageRestrictionsLocked(oneUserId); 20014 } 20015 } 20016 } else { 20017 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 20018 scheduleWritePackageRestrictionsLocked(userId); 20019 } 20020 } 20021 } 20022 20023 /** Clears state for all users, and touches intent filter verification policy */ 20024 void clearDefaultBrowserIfNeeded(String packageName) { 20025 for (int oneUserId : sUserManager.getUserIds()) { 20026 clearDefaultBrowserIfNeededForUser(packageName, oneUserId); 20027 } 20028 } 20029 20030 private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) { 20031 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 20032 if (!TextUtils.isEmpty(defaultBrowserPackageName)) { 20033 if (packageName.equals(defaultBrowserPackageName)) { 20034 setDefaultBrowserPackageName(null, userId); 20035 } 20036 } 20037 } 20038 20039 @Override 20040 public void resetApplicationPreferences(int userId) { 20041 mContext.enforceCallingOrSelfPermission( 20042 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 20043 final long identity = Binder.clearCallingIdentity(); 20044 // writer 20045 try { 20046 synchronized (mPackages) { 20047 clearPackagePreferredActivitiesLPw(null, userId); 20048 mSettings.applyDefaultPreferredAppsLPw(this, userId); 20049 // TODO: We have to reset the default SMS and Phone. This requires 20050 // significant refactoring to keep all default apps in the package 20051 // manager (cleaner but more work) or have the services provide 20052 // callbacks to the package manager to request a default app reset. 20053 applyFactoryDefaultBrowserLPw(userId); 20054 clearIntentFilterVerificationsLPw(userId); 20055 primeDomainVerificationsLPw(userId); 20056 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 20057 scheduleWritePackageRestrictionsLocked(userId); 20058 } 20059 resetNetworkPolicies(userId); 20060 } finally { 20061 Binder.restoreCallingIdentity(identity); 20062 } 20063 } 20064 20065 @Override 20066 public int getPreferredActivities(List<IntentFilter> outFilters, 20067 List<ComponentName> outActivities, String packageName) { 20068 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 20069 return 0; 20070 } 20071 int num = 0; 20072 final int userId = UserHandle.getCallingUserId(); 20073 // reader 20074 synchronized (mPackages) { 20075 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 20076 if (pir != null) { 20077 final Iterator<PreferredActivity> it = pir.filterIterator(); 20078 while (it.hasNext()) { 20079 final PreferredActivity pa = it.next(); 20080 if (packageName == null 20081 || (pa.mPref.mComponent.getPackageName().equals(packageName) 20082 && pa.mPref.mAlways)) { 20083 if (outFilters != null) { 20084 outFilters.add(new IntentFilter(pa)); 20085 } 20086 if (outActivities != null) { 20087 outActivities.add(pa.mPref.mComponent); 20088 } 20089 } 20090 } 20091 } 20092 } 20093 20094 return num; 20095 } 20096 20097 @Override 20098 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 20099 int userId) { 20100 int callingUid = Binder.getCallingUid(); 20101 if (callingUid != Process.SYSTEM_UID) { 20102 throw new SecurityException( 20103 "addPersistentPreferredActivity can only be run by the system"); 20104 } 20105 if (filter.countActions() == 0) { 20106 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 20107 return; 20108 } 20109 synchronized (mPackages) { 20110 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 20111 ":"); 20112 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 20113 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 20114 new PersistentPreferredActivity(filter, activity)); 20115 scheduleWritePackageRestrictionsLocked(userId); 20116 postPreferredActivityChangedBroadcast(userId); 20117 } 20118 } 20119 20120 @Override 20121 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 20122 int callingUid = Binder.getCallingUid(); 20123 if (callingUid != Process.SYSTEM_UID) { 20124 throw new SecurityException( 20125 "clearPackagePersistentPreferredActivities can only be run by the system"); 20126 } 20127 ArrayList<PersistentPreferredActivity> removed = null; 20128 boolean changed = false; 20129 synchronized (mPackages) { 20130 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 20131 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 20132 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 20133 .valueAt(i); 20134 if (userId != thisUserId) { 20135 continue; 20136 } 20137 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 20138 while (it.hasNext()) { 20139 PersistentPreferredActivity ppa = it.next(); 20140 // Mark entry for removal only if it matches the package name. 20141 if (ppa.mComponent.getPackageName().equals(packageName)) { 20142 if (removed == null) { 20143 removed = new ArrayList<PersistentPreferredActivity>(); 20144 } 20145 removed.add(ppa); 20146 } 20147 } 20148 if (removed != null) { 20149 for (int j=0; j<removed.size(); j++) { 20150 PersistentPreferredActivity ppa = removed.get(j); 20151 ppir.removeFilter(ppa); 20152 } 20153 changed = true; 20154 } 20155 } 20156 20157 if (changed) { 20158 scheduleWritePackageRestrictionsLocked(userId); 20159 postPreferredActivityChangedBroadcast(userId); 20160 } 20161 } 20162 } 20163 20164 /** 20165 * Common machinery for picking apart a restored XML blob and passing 20166 * it to a caller-supplied functor to be applied to the running system. 20167 */ 20168 private void restoreFromXml(XmlPullParser parser, int userId, 20169 String expectedStartTag, BlobXmlRestorer functor) 20170 throws IOException, XmlPullParserException { 20171 int type; 20172 while ((type = parser.next()) != XmlPullParser.START_TAG 20173 && type != XmlPullParser.END_DOCUMENT) { 20174 } 20175 if (type != XmlPullParser.START_TAG) { 20176 // oops didn't find a start tag?! 20177 if (DEBUG_BACKUP) { 20178 Slog.e(TAG, "Didn't find start tag during restore"); 20179 } 20180 return; 20181 } 20182Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 20183 // this is supposed to be TAG_PREFERRED_BACKUP 20184 if (!expectedStartTag.equals(parser.getName())) { 20185 if (DEBUG_BACKUP) { 20186 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 20187 } 20188 return; 20189 } 20190 20191 // skip interfering stuff, then we're aligned with the backing implementation 20192 while ((type = parser.next()) == XmlPullParser.TEXT) { } 20193Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 20194 functor.apply(parser, userId); 20195 } 20196 20197 private interface BlobXmlRestorer { 20198 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 20199 } 20200 20201 /** 20202 * Non-Binder method, support for the backup/restore mechanism: write the 20203 * full set of preferred activities in its canonical XML format. Returns the 20204 * XML output as a byte array, or null if there is none. 20205 */ 20206 @Override 20207 public byte[] getPreferredActivityBackup(int userId) { 20208 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 20209 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 20210 } 20211 20212 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 20213 try { 20214 final XmlSerializer serializer = new FastXmlSerializer(); 20215 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 20216 serializer.startDocument(null, true); 20217 serializer.startTag(null, TAG_PREFERRED_BACKUP); 20218 20219 synchronized (mPackages) { 20220 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 20221 } 20222 20223 serializer.endTag(null, TAG_PREFERRED_BACKUP); 20224 serializer.endDocument(); 20225 serializer.flush(); 20226 } catch (Exception e) { 20227 if (DEBUG_BACKUP) { 20228 Slog.e(TAG, "Unable to write preferred activities for backup", e); 20229 } 20230 return null; 20231 } 20232 20233 return dataStream.toByteArray(); 20234 } 20235 20236 @Override 20237 public void restorePreferredActivities(byte[] backup, int userId) { 20238 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 20239 throw new SecurityException("Only the system may call restorePreferredActivities()"); 20240 } 20241 20242 try { 20243 final XmlPullParser parser = Xml.newPullParser(); 20244 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 20245 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 20246 new BlobXmlRestorer() { 20247 @Override 20248 public void apply(XmlPullParser parser, int userId) 20249 throws XmlPullParserException, IOException { 20250 synchronized (mPackages) { 20251 mSettings.readPreferredActivitiesLPw(parser, userId); 20252 } 20253 } 20254 } ); 20255 } catch (Exception e) { 20256 if (DEBUG_BACKUP) { 20257 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 20258 } 20259 } 20260 } 20261 20262 /** 20263 * Non-Binder method, support for the backup/restore mechanism: write the 20264 * default browser (etc) settings in its canonical XML format. Returns the default 20265 * browser XML representation as a byte array, or null if there is none. 20266 */ 20267 @Override 20268 public byte[] getDefaultAppsBackup(int userId) { 20269 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 20270 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 20271 } 20272 20273 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 20274 try { 20275 final XmlSerializer serializer = new FastXmlSerializer(); 20276 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 20277 serializer.startDocument(null, true); 20278 serializer.startTag(null, TAG_DEFAULT_APPS); 20279 20280 synchronized (mPackages) { 20281 mSettings.writeDefaultAppsLPr(serializer, userId); 20282 } 20283 20284 serializer.endTag(null, TAG_DEFAULT_APPS); 20285 serializer.endDocument(); 20286 serializer.flush(); 20287 } catch (Exception e) { 20288 if (DEBUG_BACKUP) { 20289 Slog.e(TAG, "Unable to write default apps for backup", e); 20290 } 20291 return null; 20292 } 20293 20294 return dataStream.toByteArray(); 20295 } 20296 20297 @Override 20298 public void restoreDefaultApps(byte[] backup, int userId) { 20299 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 20300 throw new SecurityException("Only the system may call restoreDefaultApps()"); 20301 } 20302 20303 try { 20304 final XmlPullParser parser = Xml.newPullParser(); 20305 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 20306 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 20307 new BlobXmlRestorer() { 20308 @Override 20309 public void apply(XmlPullParser parser, int userId) 20310 throws XmlPullParserException, IOException { 20311 synchronized (mPackages) { 20312 mSettings.readDefaultAppsLPw(parser, userId); 20313 } 20314 } 20315 } ); 20316 } catch (Exception e) { 20317 if (DEBUG_BACKUP) { 20318 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 20319 } 20320 } 20321 } 20322 20323 @Override 20324 public byte[] getIntentFilterVerificationBackup(int userId) { 20325 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 20326 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 20327 } 20328 20329 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 20330 try { 20331 final XmlSerializer serializer = new FastXmlSerializer(); 20332 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 20333 serializer.startDocument(null, true); 20334 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 20335 20336 synchronized (mPackages) { 20337 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 20338 } 20339 20340 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 20341 serializer.endDocument(); 20342 serializer.flush(); 20343 } catch (Exception e) { 20344 if (DEBUG_BACKUP) { 20345 Slog.e(TAG, "Unable to write default apps for backup", e); 20346 } 20347 return null; 20348 } 20349 20350 return dataStream.toByteArray(); 20351 } 20352 20353 @Override 20354 public void restoreIntentFilterVerification(byte[] backup, int userId) { 20355 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 20356 throw new SecurityException("Only the system may call restorePreferredActivities()"); 20357 } 20358 20359 try { 20360 final XmlPullParser parser = Xml.newPullParser(); 20361 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 20362 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 20363 new BlobXmlRestorer() { 20364 @Override 20365 public void apply(XmlPullParser parser, int userId) 20366 throws XmlPullParserException, IOException { 20367 synchronized (mPackages) { 20368 mSettings.readAllDomainVerificationsLPr(parser, userId); 20369 mSettings.writeLPr(); 20370 } 20371 } 20372 } ); 20373 } catch (Exception e) { 20374 if (DEBUG_BACKUP) { 20375 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 20376 } 20377 } 20378 } 20379 20380 @Override 20381 public byte[] getPermissionGrantBackup(int userId) { 20382 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 20383 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 20384 } 20385 20386 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 20387 try { 20388 final XmlSerializer serializer = new FastXmlSerializer(); 20389 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 20390 serializer.startDocument(null, true); 20391 serializer.startTag(null, TAG_PERMISSION_BACKUP); 20392 20393 synchronized (mPackages) { 20394 serializeRuntimePermissionGrantsLPr(serializer, userId); 20395 } 20396 20397 serializer.endTag(null, TAG_PERMISSION_BACKUP); 20398 serializer.endDocument(); 20399 serializer.flush(); 20400 } catch (Exception e) { 20401 if (DEBUG_BACKUP) { 20402 Slog.e(TAG, "Unable to write default apps for backup", e); 20403 } 20404 return null; 20405 } 20406 20407 return dataStream.toByteArray(); 20408 } 20409 20410 @Override 20411 public void restorePermissionGrants(byte[] backup, int userId) { 20412 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 20413 throw new SecurityException("Only the system may call restorePermissionGrants()"); 20414 } 20415 20416 try { 20417 final XmlPullParser parser = Xml.newPullParser(); 20418 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 20419 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 20420 new BlobXmlRestorer() { 20421 @Override 20422 public void apply(XmlPullParser parser, int userId) 20423 throws XmlPullParserException, IOException { 20424 synchronized (mPackages) { 20425 processRestoredPermissionGrantsLPr(parser, userId); 20426 } 20427 } 20428 } ); 20429 } catch (Exception e) { 20430 if (DEBUG_BACKUP) { 20431 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 20432 } 20433 } 20434 } 20435 20436 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 20437 throws IOException { 20438 serializer.startTag(null, TAG_ALL_GRANTS); 20439 20440 final int N = mSettings.mPackages.size(); 20441 for (int i = 0; i < N; i++) { 20442 final PackageSetting ps = mSettings.mPackages.valueAt(i); 20443 boolean pkgGrantsKnown = false; 20444 20445 PermissionsState packagePerms = ps.getPermissionsState(); 20446 20447 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 20448 final int grantFlags = state.getFlags(); 20449 // only look at grants that are not system/policy fixed 20450 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 20451 final boolean isGranted = state.isGranted(); 20452 // And only back up the user-twiddled state bits 20453 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 20454 final String packageName = mSettings.mPackages.keyAt(i); 20455 if (!pkgGrantsKnown) { 20456 serializer.startTag(null, TAG_GRANT); 20457 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 20458 pkgGrantsKnown = true; 20459 } 20460 20461 final boolean userSet = 20462 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 20463 final boolean userFixed = 20464 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 20465 final boolean revoke = 20466 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 20467 20468 serializer.startTag(null, TAG_PERMISSION); 20469 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 20470 if (isGranted) { 20471 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 20472 } 20473 if (userSet) { 20474 serializer.attribute(null, ATTR_USER_SET, "true"); 20475 } 20476 if (userFixed) { 20477 serializer.attribute(null, ATTR_USER_FIXED, "true"); 20478 } 20479 if (revoke) { 20480 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 20481 } 20482 serializer.endTag(null, TAG_PERMISSION); 20483 } 20484 } 20485 } 20486 20487 if (pkgGrantsKnown) { 20488 serializer.endTag(null, TAG_GRANT); 20489 } 20490 } 20491 20492 serializer.endTag(null, TAG_ALL_GRANTS); 20493 } 20494 20495 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 20496 throws XmlPullParserException, IOException { 20497 String pkgName = null; 20498 int outerDepth = parser.getDepth(); 20499 int type; 20500 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 20501 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 20502 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 20503 continue; 20504 } 20505 20506 final String tagName = parser.getName(); 20507 if (tagName.equals(TAG_GRANT)) { 20508 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 20509 if (DEBUG_BACKUP) { 20510 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 20511 } 20512 } else if (tagName.equals(TAG_PERMISSION)) { 20513 20514 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 20515 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 20516 20517 int newFlagSet = 0; 20518 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 20519 newFlagSet |= FLAG_PERMISSION_USER_SET; 20520 } 20521 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 20522 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 20523 } 20524 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 20525 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 20526 } 20527 if (DEBUG_BACKUP) { 20528 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 20529 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 20530 } 20531 final PackageSetting ps = mSettings.mPackages.get(pkgName); 20532 if (ps != null) { 20533 // Already installed so we apply the grant immediately 20534 if (DEBUG_BACKUP) { 20535 Slog.v(TAG, " + already installed; applying"); 20536 } 20537 PermissionsState perms = ps.getPermissionsState(); 20538 BasePermission bp = mSettings.mPermissions.get(permName); 20539 if (bp != null) { 20540 if (isGranted) { 20541 perms.grantRuntimePermission(bp, userId); 20542 } 20543 if (newFlagSet != 0) { 20544 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 20545 } 20546 } 20547 } else { 20548 // Need to wait for post-restore install to apply the grant 20549 if (DEBUG_BACKUP) { 20550 Slog.v(TAG, " - not yet installed; saving for later"); 20551 } 20552 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 20553 isGranted, newFlagSet, userId); 20554 } 20555 } else { 20556 PackageManagerService.reportSettingsProblem(Log.WARN, 20557 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 20558 XmlUtils.skipCurrentTag(parser); 20559 } 20560 } 20561 20562 scheduleWriteSettingsLocked(); 20563 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 20564 } 20565 20566 @Override 20567 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 20568 int sourceUserId, int targetUserId, int flags) { 20569 mContext.enforceCallingOrSelfPermission( 20570 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 20571 int callingUid = Binder.getCallingUid(); 20572 enforceOwnerRights(ownerPackage, callingUid); 20573 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 20574 if (intentFilter.countActions() == 0) { 20575 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 20576 return; 20577 } 20578 synchronized (mPackages) { 20579 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 20580 ownerPackage, targetUserId, flags); 20581 CrossProfileIntentResolver resolver = 20582 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 20583 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 20584 // We have all those whose filter is equal. Now checking if the rest is equal as well. 20585 if (existing != null) { 20586 int size = existing.size(); 20587 for (int i = 0; i < size; i++) { 20588 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 20589 return; 20590 } 20591 } 20592 } 20593 resolver.addFilter(newFilter); 20594 scheduleWritePackageRestrictionsLocked(sourceUserId); 20595 } 20596 } 20597 20598 @Override 20599 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 20600 mContext.enforceCallingOrSelfPermission( 20601 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 20602 int callingUid = Binder.getCallingUid(); 20603 enforceOwnerRights(ownerPackage, callingUid); 20604 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 20605 synchronized (mPackages) { 20606 CrossProfileIntentResolver resolver = 20607 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 20608 ArraySet<CrossProfileIntentFilter> set = 20609 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 20610 for (CrossProfileIntentFilter filter : set) { 20611 if (filter.getOwnerPackage().equals(ownerPackage)) { 20612 resolver.removeFilter(filter); 20613 } 20614 } 20615 scheduleWritePackageRestrictionsLocked(sourceUserId); 20616 } 20617 } 20618 20619 // Enforcing that callingUid is owning pkg on userId 20620 private void enforceOwnerRights(String pkg, int callingUid) { 20621 // The system owns everything. 20622 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 20623 return; 20624 } 20625 int callingUserId = UserHandle.getUserId(callingUid); 20626 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 20627 if (pi == null) { 20628 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 20629 + callingUserId); 20630 } 20631 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 20632 throw new SecurityException("Calling uid " + callingUid 20633 + " does not own package " + pkg); 20634 } 20635 } 20636 20637 @Override 20638 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 20639 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 20640 return null; 20641 } 20642 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 20643 } 20644 20645 public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) { 20646 UserManagerService ums = UserManagerService.getInstance(); 20647 if (ums != null) { 20648 final UserInfo parent = ums.getProfileParent(userId); 20649 final int launcherUid = (parent != null) ? parent.id : userId; 20650 final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid); 20651 if (launcherComponent != null) { 20652 Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED) 20653 .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo) 20654 .putExtra(Intent.EXTRA_USER, UserHandle.of(userId)) 20655 .setPackage(launcherComponent.getPackageName()); 20656 mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid)); 20657 } 20658 } 20659 } 20660 20661 /** 20662 * Report the 'Home' activity which is currently set as "always use this one". If non is set 20663 * then reports the most likely home activity or null if there are more than one. 20664 */ 20665 private ComponentName getDefaultHomeActivity(int userId) { 20666 List<ResolveInfo> allHomeCandidates = new ArrayList<>(); 20667 ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId); 20668 if (cn != null) { 20669 return cn; 20670 } 20671 20672 // Find the launcher with the highest priority and return that component if there are no 20673 // other home activity with the same priority. 20674 int lastPriority = Integer.MIN_VALUE; 20675 ComponentName lastComponent = null; 20676 final int size = allHomeCandidates.size(); 20677 for (int i = 0; i < size; i++) { 20678 final ResolveInfo ri = allHomeCandidates.get(i); 20679 if (ri.priority > lastPriority) { 20680 lastComponent = ri.activityInfo.getComponentName(); 20681 lastPriority = ri.priority; 20682 } else if (ri.priority == lastPriority) { 20683 // Two components found with same priority. 20684 lastComponent = null; 20685 } 20686 } 20687 return lastComponent; 20688 } 20689 20690 private Intent getHomeIntent() { 20691 Intent intent = new Intent(Intent.ACTION_MAIN); 20692 intent.addCategory(Intent.CATEGORY_HOME); 20693 intent.addCategory(Intent.CATEGORY_DEFAULT); 20694 return intent; 20695 } 20696 20697 private IntentFilter getHomeFilter() { 20698 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 20699 filter.addCategory(Intent.CATEGORY_HOME); 20700 filter.addCategory(Intent.CATEGORY_DEFAULT); 20701 return filter; 20702 } 20703 20704 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 20705 int userId) { 20706 Intent intent = getHomeIntent(); 20707 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 20708 PackageManager.GET_META_DATA, userId); 20709 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 20710 true, false, false, userId); 20711 20712 allHomeCandidates.clear(); 20713 if (list != null) { 20714 for (ResolveInfo ri : list) { 20715 allHomeCandidates.add(ri); 20716 } 20717 } 20718 return (preferred == null || preferred.activityInfo == null) 20719 ? null 20720 : new ComponentName(preferred.activityInfo.packageName, 20721 preferred.activityInfo.name); 20722 } 20723 20724 @Override 20725 public void setHomeActivity(ComponentName comp, int userId) { 20726 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 20727 return; 20728 } 20729 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 20730 getHomeActivitiesAsUser(homeActivities, userId); 20731 20732 boolean found = false; 20733 20734 final int size = homeActivities.size(); 20735 final ComponentName[] set = new ComponentName[size]; 20736 for (int i = 0; i < size; i++) { 20737 final ResolveInfo candidate = homeActivities.get(i); 20738 final ActivityInfo info = candidate.activityInfo; 20739 final ComponentName activityName = new ComponentName(info.packageName, info.name); 20740 set[i] = activityName; 20741 if (!found && activityName.equals(comp)) { 20742 found = true; 20743 } 20744 } 20745 if (!found) { 20746 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 20747 + userId); 20748 } 20749 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 20750 set, comp, userId); 20751 } 20752 20753 private @Nullable String getSetupWizardPackageName() { 20754 final Intent intent = new Intent(Intent.ACTION_MAIN); 20755 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 20756 20757 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 20758 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 20759 | MATCH_DISABLED_COMPONENTS, 20760 UserHandle.myUserId()); 20761 if (matches.size() == 1) { 20762 return matches.get(0).getComponentInfo().packageName; 20763 } else { 20764 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 20765 + ": matches=" + matches); 20766 return null; 20767 } 20768 } 20769 20770 private @Nullable String getStorageManagerPackageName() { 20771 final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE); 20772 20773 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 20774 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 20775 | MATCH_DISABLED_COMPONENTS, 20776 UserHandle.myUserId()); 20777 if (matches.size() == 1) { 20778 return matches.get(0).getComponentInfo().packageName; 20779 } else { 20780 Slog.e(TAG, "There should probably be exactly one storage manager; found " 20781 + matches.size() + ": matches=" + matches); 20782 return null; 20783 } 20784 } 20785 20786 @Override 20787 public void setApplicationEnabledSetting(String appPackageName, 20788 int newState, int flags, int userId, String callingPackage) { 20789 if (!sUserManager.exists(userId)) return; 20790 if (callingPackage == null) { 20791 callingPackage = Integer.toString(Binder.getCallingUid()); 20792 } 20793 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 20794 } 20795 20796 @Override 20797 public void setUpdateAvailable(String packageName, boolean updateAvailable) { 20798 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 20799 synchronized (mPackages) { 20800 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 20801 if (pkgSetting != null) { 20802 pkgSetting.setUpdateAvailable(updateAvailable); 20803 } 20804 } 20805 } 20806 20807 @Override 20808 public void setComponentEnabledSetting(ComponentName componentName, 20809 int newState, int flags, int userId) { 20810 if (!sUserManager.exists(userId)) return; 20811 setEnabledSetting(componentName.getPackageName(), 20812 componentName.getClassName(), newState, flags, userId, null); 20813 } 20814 20815 private void setEnabledSetting(final String packageName, String className, int newState, 20816 final int flags, int userId, String callingPackage) { 20817 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 20818 || newState == COMPONENT_ENABLED_STATE_ENABLED 20819 || newState == COMPONENT_ENABLED_STATE_DISABLED 20820 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 20821 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 20822 throw new IllegalArgumentException("Invalid new component state: " 20823 + newState); 20824 } 20825 PackageSetting pkgSetting; 20826 final int callingUid = Binder.getCallingUid(); 20827 final int permission; 20828 if (callingUid == Process.SYSTEM_UID) { 20829 permission = PackageManager.PERMISSION_GRANTED; 20830 } else { 20831 permission = mContext.checkCallingOrSelfPermission( 20832 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 20833 } 20834 enforceCrossUserPermission(callingUid, userId, 20835 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 20836 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 20837 boolean sendNow = false; 20838 boolean isApp = (className == null); 20839 final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null); 20840 String componentName = isApp ? packageName : className; 20841 int packageUid = -1; 20842 ArrayList<String> components; 20843 20844 // reader 20845 synchronized (mPackages) { 20846 pkgSetting = mSettings.mPackages.get(packageName); 20847 if (pkgSetting == null) { 20848 if (!isCallerInstantApp) { 20849 if (className == null) { 20850 throw new IllegalArgumentException("Unknown package: " + packageName); 20851 } 20852 throw new IllegalArgumentException( 20853 "Unknown component: " + packageName + "/" + className); 20854 } else { 20855 // throw SecurityException to prevent leaking package information 20856 throw new SecurityException( 20857 "Attempt to change component state; " 20858 + "pid=" + Binder.getCallingPid() 20859 + ", uid=" + callingUid 20860 + (className == null 20861 ? ", package=" + packageName 20862 : ", component=" + packageName + "/" + className)); 20863 } 20864 } 20865 } 20866 20867 // Limit who can change which apps 20868 if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) { 20869 // Don't allow apps that don't have permission to modify other apps 20870 if (!allowedByPermission) { 20871 throw new SecurityException( 20872 "Attempt to change component state; " 20873 + "pid=" + Binder.getCallingPid() 20874 + ", uid=" + callingUid 20875 + (className == null 20876 ? ", package=" + packageName 20877 : ", component=" + packageName + "/" + className)); 20878 } 20879 // Don't allow changing protected packages. 20880 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 20881 throw new SecurityException("Cannot disable a protected package: " + packageName); 20882 } 20883 } 20884 20885 synchronized (mPackages) { 20886 if (callingUid == Process.SHELL_UID 20887 && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) { 20888 // Shell can only change whole packages between ENABLED and DISABLED_USER states 20889 // unless it is a test package. 20890 int oldState = pkgSetting.getEnabled(userId); 20891 if (className == null 20892 && 20893 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 20894 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 20895 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 20896 && 20897 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 20898 || newState == COMPONENT_ENABLED_STATE_DEFAULT 20899 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 20900 // ok 20901 } else { 20902 throw new SecurityException( 20903 "Shell cannot change component state for " + packageName + "/" 20904 + className + " to " + newState); 20905 } 20906 } 20907 if (className == null) { 20908 // We're dealing with an application/package level state change 20909 if (pkgSetting.getEnabled(userId) == newState) { 20910 // Nothing to do 20911 return; 20912 } 20913 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 20914 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 20915 // Don't care about who enables an app. 20916 callingPackage = null; 20917 } 20918 pkgSetting.setEnabled(newState, userId, callingPackage); 20919 // pkgSetting.pkg.mSetEnabled = newState; 20920 } else { 20921 // We're dealing with a component level state change 20922 // First, verify that this is a valid class name. 20923 PackageParser.Package pkg = pkgSetting.pkg; 20924 if (pkg == null || !pkg.hasComponentClassName(className)) { 20925 if (pkg != null && 20926 pkg.applicationInfo.targetSdkVersion >= 20927 Build.VERSION_CODES.JELLY_BEAN) { 20928 throw new IllegalArgumentException("Component class " + className 20929 + " does not exist in " + packageName); 20930 } else { 20931 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 20932 + className + " does not exist in " + packageName); 20933 } 20934 } 20935 switch (newState) { 20936 case COMPONENT_ENABLED_STATE_ENABLED: 20937 if (!pkgSetting.enableComponentLPw(className, userId)) { 20938 return; 20939 } 20940 break; 20941 case COMPONENT_ENABLED_STATE_DISABLED: 20942 if (!pkgSetting.disableComponentLPw(className, userId)) { 20943 return; 20944 } 20945 break; 20946 case COMPONENT_ENABLED_STATE_DEFAULT: 20947 if (!pkgSetting.restoreComponentLPw(className, userId)) { 20948 return; 20949 } 20950 break; 20951 default: 20952 Slog.e(TAG, "Invalid new component state: " + newState); 20953 return; 20954 } 20955 } 20956 scheduleWritePackageRestrictionsLocked(userId); 20957 updateSequenceNumberLP(packageName, new int[] { userId }); 20958 final long callingId = Binder.clearCallingIdentity(); 20959 try { 20960 updateInstantAppInstallerLocked(packageName); 20961 } finally { 20962 Binder.restoreCallingIdentity(callingId); 20963 } 20964 components = mPendingBroadcasts.get(userId, packageName); 20965 final boolean newPackage = components == null; 20966 if (newPackage) { 20967 components = new ArrayList<String>(); 20968 } 20969 if (!components.contains(componentName)) { 20970 components.add(componentName); 20971 } 20972 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 20973 sendNow = true; 20974 // Purge entry from pending broadcast list if another one exists already 20975 // since we are sending one right away. 20976 mPendingBroadcasts.remove(userId, packageName); 20977 } else { 20978 if (newPackage) { 20979 mPendingBroadcasts.put(userId, packageName, components); 20980 } 20981 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 20982 // Schedule a message 20983 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 20984 } 20985 } 20986 } 20987 20988 long callingId = Binder.clearCallingIdentity(); 20989 try { 20990 if (sendNow) { 20991 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 20992 sendPackageChangedBroadcast(packageName, 20993 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 20994 } 20995 } finally { 20996 Binder.restoreCallingIdentity(callingId); 20997 } 20998 } 20999 21000 @Override 21001 public void flushPackageRestrictionsAsUser(int userId) { 21002 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 21003 return; 21004 } 21005 if (!sUserManager.exists(userId)) { 21006 return; 21007 } 21008 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 21009 false /* checkShell */, "flushPackageRestrictions"); 21010 synchronized (mPackages) { 21011 mSettings.writePackageRestrictionsLPr(userId); 21012 mDirtyUsers.remove(userId); 21013 if (mDirtyUsers.isEmpty()) { 21014 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 21015 } 21016 } 21017 } 21018 21019 private void sendPackageChangedBroadcast(String packageName, 21020 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 21021 if (DEBUG_INSTALL) 21022 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 21023 + componentNames); 21024 Bundle extras = new Bundle(4); 21025 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 21026 String nameList[] = new String[componentNames.size()]; 21027 componentNames.toArray(nameList); 21028 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 21029 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 21030 extras.putInt(Intent.EXTRA_UID, packageUid); 21031 // If this is not reporting a change of the overall package, then only send it 21032 // to registered receivers. We don't want to launch a swath of apps for every 21033 // little component state change. 21034 final int flags = !componentNames.contains(packageName) 21035 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 21036 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 21037 new int[] {UserHandle.getUserId(packageUid)}); 21038 } 21039 21040 @Override 21041 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 21042 if (!sUserManager.exists(userId)) return; 21043 final int callingUid = Binder.getCallingUid(); 21044 if (getInstantAppPackageName(callingUid) != null) { 21045 return; 21046 } 21047 final int permission = mContext.checkCallingOrSelfPermission( 21048 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 21049 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 21050 enforceCrossUserPermission(callingUid, userId, 21051 true /* requireFullPermission */, true /* checkShell */, "stop package"); 21052 // writer 21053 synchronized (mPackages) { 21054 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 21055 allowedByPermission, callingUid, userId)) { 21056 scheduleWritePackageRestrictionsLocked(userId); 21057 } 21058 } 21059 } 21060 21061 @Override 21062 public String getInstallerPackageName(String packageName) { 21063 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 21064 return null; 21065 } 21066 // reader 21067 synchronized (mPackages) { 21068 return mSettings.getInstallerPackageNameLPr(packageName); 21069 } 21070 } 21071 21072 public boolean isOrphaned(String packageName) { 21073 // reader 21074 synchronized (mPackages) { 21075 return mSettings.isOrphaned(packageName); 21076 } 21077 } 21078 21079 @Override 21080 public int getApplicationEnabledSetting(String packageName, int userId) { 21081 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 21082 int callingUid = Binder.getCallingUid(); 21083 enforceCrossUserPermission(callingUid, userId, 21084 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 21085 // reader 21086 synchronized (mPackages) { 21087 if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) { 21088 return COMPONENT_ENABLED_STATE_DISABLED; 21089 } 21090 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 21091 } 21092 } 21093 21094 @Override 21095 public int getComponentEnabledSetting(ComponentName component, int userId) { 21096 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 21097 int callingUid = Binder.getCallingUid(); 21098 enforceCrossUserPermission(callingUid, userId, 21099 false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled"); 21100 synchronized (mPackages) { 21101 if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid, 21102 component, TYPE_UNKNOWN, userId)) { 21103 return COMPONENT_ENABLED_STATE_DISABLED; 21104 } 21105 return mSettings.getComponentEnabledSettingLPr(component, userId); 21106 } 21107 } 21108 21109 @Override 21110 public void enterSafeMode() { 21111 enforceSystemOrRoot("Only the system can request entering safe mode"); 21112 21113 if (!mSystemReady) { 21114 mSafeMode = true; 21115 } 21116 } 21117 21118 @Override 21119 public void systemReady() { 21120 enforceSystemOrRoot("Only the system can claim the system is ready"); 21121 21122 mSystemReady = true; 21123 final ContentResolver resolver = mContext.getContentResolver(); 21124 ContentObserver co = new ContentObserver(mHandler) { 21125 @Override 21126 public void onChange(boolean selfChange) { 21127 mEphemeralAppsDisabled = 21128 (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) || 21129 (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0); 21130 } 21131 }; 21132 mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global 21133 .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE), 21134 false, co, UserHandle.USER_SYSTEM); 21135 mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global 21136 .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM); 21137 co.onChange(true); 21138 21139 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 21140 // disabled after already being started. 21141 CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this, 21142 mContext.getContentResolver(), UserHandle.USER_SYSTEM); 21143 21144 // Read the compatibilty setting when the system is ready. 21145 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 21146 mContext.getContentResolver(), 21147 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 21148 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 21149 if (DEBUG_SETTINGS) { 21150 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 21151 } 21152 21153 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 21154 21155 synchronized (mPackages) { 21156 // Verify that all of the preferred activity components actually 21157 // exist. It is possible for applications to be updated and at 21158 // that point remove a previously declared activity component that 21159 // had been set as a preferred activity. We try to clean this up 21160 // the next time we encounter that preferred activity, but it is 21161 // possible for the user flow to never be able to return to that 21162 // situation so here we do a sanity check to make sure we haven't 21163 // left any junk around. 21164 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 21165 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 21166 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 21167 removed.clear(); 21168 for (PreferredActivity pa : pir.filterSet()) { 21169 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 21170 removed.add(pa); 21171 } 21172 } 21173 if (removed.size() > 0) { 21174 for (int r=0; r<removed.size(); r++) { 21175 PreferredActivity pa = removed.get(r); 21176 Slog.w(TAG, "Removing dangling preferred activity: " 21177 + pa.mPref.mComponent); 21178 pir.removeFilter(pa); 21179 } 21180 mSettings.writePackageRestrictionsLPr( 21181 mSettings.mPreferredActivities.keyAt(i)); 21182 } 21183 } 21184 21185 for (int userId : UserManagerService.getInstance().getUserIds()) { 21186 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 21187 grantPermissionsUserIds = ArrayUtils.appendInt( 21188 grantPermissionsUserIds, userId); 21189 } 21190 } 21191 } 21192 sUserManager.systemReady(); 21193 21194 // If we upgraded grant all default permissions before kicking off. 21195 for (int userId : grantPermissionsUserIds) { 21196 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 21197 } 21198 21199 // If we did not grant default permissions, we preload from this the 21200 // default permission exceptions lazily to ensure we don't hit the 21201 // disk on a new user creation. 21202 if (grantPermissionsUserIds == EMPTY_INT_ARRAY) { 21203 mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions(); 21204 } 21205 21206 // Kick off any messages waiting for system ready 21207 if (mPostSystemReadyMessages != null) { 21208 for (Message msg : mPostSystemReadyMessages) { 21209 msg.sendToTarget(); 21210 } 21211 mPostSystemReadyMessages = null; 21212 } 21213 21214 // Watch for external volumes that come and go over time 21215 final StorageManager storage = mContext.getSystemService(StorageManager.class); 21216 storage.registerListener(mStorageListener); 21217 21218 mInstallerService.systemReady(); 21219 mPackageDexOptimizer.systemReady(); 21220 21221 StorageManagerInternal StorageManagerInternal = LocalServices.getService( 21222 StorageManagerInternal.class); 21223 StorageManagerInternal.addExternalStoragePolicy( 21224 new StorageManagerInternal.ExternalStorageMountPolicy() { 21225 @Override 21226 public int getMountMode(int uid, String packageName) { 21227 if (Process.isIsolated(uid)) { 21228 return Zygote.MOUNT_EXTERNAL_NONE; 21229 } 21230 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 21231 return Zygote.MOUNT_EXTERNAL_DEFAULT; 21232 } 21233 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 21234 return Zygote.MOUNT_EXTERNAL_DEFAULT; 21235 } 21236 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 21237 return Zygote.MOUNT_EXTERNAL_READ; 21238 } 21239 return Zygote.MOUNT_EXTERNAL_WRITE; 21240 } 21241 21242 @Override 21243 public boolean hasExternalStorage(int uid, String packageName) { 21244 return true; 21245 } 21246 }); 21247 21248 // Now that we're mostly running, clean up stale users and apps 21249 sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 21250 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 21251 21252 if (mPrivappPermissionsViolations != null) { 21253 Slog.wtf(TAG,"Signature|privileged permissions not in " 21254 + "privapp-permissions whitelist: " + mPrivappPermissionsViolations); 21255 mPrivappPermissionsViolations = null; 21256 } 21257 } 21258 21259 public void waitForAppDataPrepared() { 21260 if (mPrepareAppDataFuture == null) { 21261 return; 21262 } 21263 ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData"); 21264 mPrepareAppDataFuture = null; 21265 } 21266 21267 @Override 21268 public boolean isSafeMode() { 21269 // allow instant applications 21270 return mSafeMode; 21271 } 21272 21273 @Override 21274 public boolean hasSystemUidErrors() { 21275 // allow instant applications 21276 return mHasSystemUidErrors; 21277 } 21278 21279 static String arrayToString(int[] array) { 21280 StringBuffer buf = new StringBuffer(128); 21281 buf.append('['); 21282 if (array != null) { 21283 for (int i=0; i<array.length; i++) { 21284 if (i > 0) buf.append(", "); 21285 buf.append(array[i]); 21286 } 21287 } 21288 buf.append(']'); 21289 return buf.toString(); 21290 } 21291 21292 static class DumpState { 21293 public static final int DUMP_LIBS = 1 << 0; 21294 public static final int DUMP_FEATURES = 1 << 1; 21295 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 21296 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 21297 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 21298 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 21299 public static final int DUMP_PERMISSIONS = 1 << 6; 21300 public static final int DUMP_PACKAGES = 1 << 7; 21301 public static final int DUMP_SHARED_USERS = 1 << 8; 21302 public static final int DUMP_MESSAGES = 1 << 9; 21303 public static final int DUMP_PROVIDERS = 1 << 10; 21304 public static final int DUMP_VERIFIERS = 1 << 11; 21305 public static final int DUMP_PREFERRED = 1 << 12; 21306 public static final int DUMP_PREFERRED_XML = 1 << 13; 21307 public static final int DUMP_KEYSETS = 1 << 14; 21308 public static final int DUMP_VERSION = 1 << 15; 21309 public static final int DUMP_INSTALLS = 1 << 16; 21310 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 21311 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 21312 public static final int DUMP_FROZEN = 1 << 19; 21313 public static final int DUMP_DEXOPT = 1 << 20; 21314 public static final int DUMP_COMPILER_STATS = 1 << 21; 21315 public static final int DUMP_ENABLED_OVERLAYS = 1 << 22; 21316 public static final int DUMP_CHANGES = 1 << 23; 21317 21318 public static final int OPTION_SHOW_FILTERS = 1 << 0; 21319 21320 private int mTypes; 21321 21322 private int mOptions; 21323 21324 private boolean mTitlePrinted; 21325 21326 private SharedUserSetting mSharedUser; 21327 21328 public boolean isDumping(int type) { 21329 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 21330 return true; 21331 } 21332 21333 return (mTypes & type) != 0; 21334 } 21335 21336 public void setDump(int type) { 21337 mTypes |= type; 21338 } 21339 21340 public boolean isOptionEnabled(int option) { 21341 return (mOptions & option) != 0; 21342 } 21343 21344 public void setOptionEnabled(int option) { 21345 mOptions |= option; 21346 } 21347 21348 public boolean onTitlePrinted() { 21349 final boolean printed = mTitlePrinted; 21350 mTitlePrinted = true; 21351 return printed; 21352 } 21353 21354 public boolean getTitlePrinted() { 21355 return mTitlePrinted; 21356 } 21357 21358 public void setTitlePrinted(boolean enabled) { 21359 mTitlePrinted = enabled; 21360 } 21361 21362 public SharedUserSetting getSharedUser() { 21363 return mSharedUser; 21364 } 21365 21366 public void setSharedUser(SharedUserSetting user) { 21367 mSharedUser = user; 21368 } 21369 } 21370 21371 @Override 21372 public void onShellCommand(FileDescriptor in, FileDescriptor out, 21373 FileDescriptor err, String[] args, ShellCallback callback, 21374 ResultReceiver resultReceiver) { 21375 (new PackageManagerShellCommand(this)).exec( 21376 this, in, out, err, args, callback, resultReceiver); 21377 } 21378 21379 @Override 21380 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 21381 if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return; 21382 21383 DumpState dumpState = new DumpState(); 21384 boolean fullPreferred = false; 21385 boolean checkin = false; 21386 21387 String packageName = null; 21388 ArraySet<String> permissionNames = null; 21389 21390 int opti = 0; 21391 while (opti < args.length) { 21392 String opt = args[opti]; 21393 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 21394 break; 21395 } 21396 opti++; 21397 21398 if ("-a".equals(opt)) { 21399 // Right now we only know how to print all. 21400 } else if ("-h".equals(opt)) { 21401 pw.println("Package manager dump options:"); 21402 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 21403 pw.println(" --checkin: dump for a checkin"); 21404 pw.println(" -f: print details of intent filters"); 21405 pw.println(" -h: print this help"); 21406 pw.println(" cmd may be one of:"); 21407 pw.println(" l[ibraries]: list known shared libraries"); 21408 pw.println(" f[eatures]: list device features"); 21409 pw.println(" k[eysets]: print known keysets"); 21410 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 21411 pw.println(" perm[issions]: dump permissions"); 21412 pw.println(" permission [name ...]: dump declaration and use of given permission"); 21413 pw.println(" pref[erred]: print preferred package settings"); 21414 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 21415 pw.println(" prov[iders]: dump content providers"); 21416 pw.println(" p[ackages]: dump installed packages"); 21417 pw.println(" s[hared-users]: dump shared user IDs"); 21418 pw.println(" m[essages]: print collected runtime messages"); 21419 pw.println(" v[erifiers]: print package verifier info"); 21420 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 21421 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 21422 pw.println(" version: print database version info"); 21423 pw.println(" write: write current settings now"); 21424 pw.println(" installs: details about install sessions"); 21425 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 21426 pw.println(" dexopt: dump dexopt state"); 21427 pw.println(" compiler-stats: dump compiler statistics"); 21428 pw.println(" enabled-overlays: dump list of enabled overlay packages"); 21429 pw.println(" <package.name>: info about given package"); 21430 return; 21431 } else if ("--checkin".equals(opt)) { 21432 checkin = true; 21433 } else if ("-f".equals(opt)) { 21434 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 21435 } else if ("--proto".equals(opt)) { 21436 dumpProto(fd); 21437 return; 21438 } else { 21439 pw.println("Unknown argument: " + opt + "; use -h for help"); 21440 } 21441 } 21442 21443 // Is the caller requesting to dump a particular piece of data? 21444 if (opti < args.length) { 21445 String cmd = args[opti]; 21446 opti++; 21447 // Is this a package name? 21448 if ("android".equals(cmd) || cmd.contains(".")) { 21449 packageName = cmd; 21450 // When dumping a single package, we always dump all of its 21451 // filter information since the amount of data will be reasonable. 21452 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 21453 } else if ("check-permission".equals(cmd)) { 21454 if (opti >= args.length) { 21455 pw.println("Error: check-permission missing permission argument"); 21456 return; 21457 } 21458 String perm = args[opti]; 21459 opti++; 21460 if (opti >= args.length) { 21461 pw.println("Error: check-permission missing package argument"); 21462 return; 21463 } 21464 21465 String pkg = args[opti]; 21466 opti++; 21467 int user = UserHandle.getUserId(Binder.getCallingUid()); 21468 if (opti < args.length) { 21469 try { 21470 user = Integer.parseInt(args[opti]); 21471 } catch (NumberFormatException e) { 21472 pw.println("Error: check-permission user argument is not a number: " 21473 + args[opti]); 21474 return; 21475 } 21476 } 21477 21478 // Normalize package name to handle renamed packages and static libs 21479 pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST); 21480 21481 pw.println(checkPermission(perm, pkg, user)); 21482 return; 21483 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 21484 dumpState.setDump(DumpState.DUMP_LIBS); 21485 } else if ("f".equals(cmd) || "features".equals(cmd)) { 21486 dumpState.setDump(DumpState.DUMP_FEATURES); 21487 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 21488 if (opti >= args.length) { 21489 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 21490 | DumpState.DUMP_SERVICE_RESOLVERS 21491 | DumpState.DUMP_RECEIVER_RESOLVERS 21492 | DumpState.DUMP_CONTENT_RESOLVERS); 21493 } else { 21494 while (opti < args.length) { 21495 String name = args[opti]; 21496 if ("a".equals(name) || "activity".equals(name)) { 21497 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 21498 } else if ("s".equals(name) || "service".equals(name)) { 21499 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 21500 } else if ("r".equals(name) || "receiver".equals(name)) { 21501 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 21502 } else if ("c".equals(name) || "content".equals(name)) { 21503 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 21504 } else { 21505 pw.println("Error: unknown resolver table type: " + name); 21506 return; 21507 } 21508 opti++; 21509 } 21510 } 21511 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 21512 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 21513 } else if ("permission".equals(cmd)) { 21514 if (opti >= args.length) { 21515 pw.println("Error: permission requires permission name"); 21516 return; 21517 } 21518 permissionNames = new ArraySet<>(); 21519 while (opti < args.length) { 21520 permissionNames.add(args[opti]); 21521 opti++; 21522 } 21523 dumpState.setDump(DumpState.DUMP_PERMISSIONS 21524 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 21525 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 21526 dumpState.setDump(DumpState.DUMP_PREFERRED); 21527 } else if ("preferred-xml".equals(cmd)) { 21528 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 21529 if (opti < args.length && "--full".equals(args[opti])) { 21530 fullPreferred = true; 21531 opti++; 21532 } 21533 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 21534 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 21535 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 21536 dumpState.setDump(DumpState.DUMP_PACKAGES); 21537 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 21538 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 21539 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 21540 dumpState.setDump(DumpState.DUMP_PROVIDERS); 21541 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 21542 dumpState.setDump(DumpState.DUMP_MESSAGES); 21543 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 21544 dumpState.setDump(DumpState.DUMP_VERIFIERS); 21545 } else if ("i".equals(cmd) || "ifv".equals(cmd) 21546 || "intent-filter-verifiers".equals(cmd)) { 21547 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 21548 } else if ("version".equals(cmd)) { 21549 dumpState.setDump(DumpState.DUMP_VERSION); 21550 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 21551 dumpState.setDump(DumpState.DUMP_KEYSETS); 21552 } else if ("installs".equals(cmd)) { 21553 dumpState.setDump(DumpState.DUMP_INSTALLS); 21554 } else if ("frozen".equals(cmd)) { 21555 dumpState.setDump(DumpState.DUMP_FROZEN); 21556 } else if ("dexopt".equals(cmd)) { 21557 dumpState.setDump(DumpState.DUMP_DEXOPT); 21558 } else if ("compiler-stats".equals(cmd)) { 21559 dumpState.setDump(DumpState.DUMP_COMPILER_STATS); 21560 } else if ("enabled-overlays".equals(cmd)) { 21561 dumpState.setDump(DumpState.DUMP_ENABLED_OVERLAYS); 21562 } else if ("changes".equals(cmd)) { 21563 dumpState.setDump(DumpState.DUMP_CHANGES); 21564 } else if ("write".equals(cmd)) { 21565 synchronized (mPackages) { 21566 mSettings.writeLPr(); 21567 pw.println("Settings written."); 21568 return; 21569 } 21570 } 21571 } 21572 21573 if (checkin) { 21574 pw.println("vers,1"); 21575 } 21576 21577 // reader 21578 synchronized (mPackages) { 21579 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 21580 if (!checkin) { 21581 if (dumpState.onTitlePrinted()) 21582 pw.println(); 21583 pw.println("Database versions:"); 21584 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 21585 } 21586 } 21587 21588 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 21589 if (!checkin) { 21590 if (dumpState.onTitlePrinted()) 21591 pw.println(); 21592 pw.println("Verifiers:"); 21593 pw.print(" Required: "); 21594 pw.print(mRequiredVerifierPackage); 21595 pw.print(" (uid="); 21596 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 21597 UserHandle.USER_SYSTEM)); 21598 pw.println(")"); 21599 } else if (mRequiredVerifierPackage != null) { 21600 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 21601 pw.print(","); 21602 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 21603 UserHandle.USER_SYSTEM)); 21604 } 21605 } 21606 21607 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 21608 packageName == null) { 21609 if (mIntentFilterVerifierComponent != null) { 21610 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 21611 if (!checkin) { 21612 if (dumpState.onTitlePrinted()) 21613 pw.println(); 21614 pw.println("Intent Filter Verifier:"); 21615 pw.print(" Using: "); 21616 pw.print(verifierPackageName); 21617 pw.print(" (uid="); 21618 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 21619 UserHandle.USER_SYSTEM)); 21620 pw.println(")"); 21621 } else if (verifierPackageName != null) { 21622 pw.print("ifv,"); pw.print(verifierPackageName); 21623 pw.print(","); 21624 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 21625 UserHandle.USER_SYSTEM)); 21626 } 21627 } else { 21628 pw.println(); 21629 pw.println("No Intent Filter Verifier available!"); 21630 } 21631 } 21632 21633 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 21634 boolean printedHeader = false; 21635 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 21636 while (it.hasNext()) { 21637 String libName = it.next(); 21638 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName); 21639 if (versionedLib == null) { 21640 continue; 21641 } 21642 final int versionCount = versionedLib.size(); 21643 for (int i = 0; i < versionCount; i++) { 21644 SharedLibraryEntry libEntry = versionedLib.valueAt(i); 21645 if (!checkin) { 21646 if (!printedHeader) { 21647 if (dumpState.onTitlePrinted()) 21648 pw.println(); 21649 pw.println("Libraries:"); 21650 printedHeader = true; 21651 } 21652 pw.print(" "); 21653 } else { 21654 pw.print("lib,"); 21655 } 21656 pw.print(libEntry.info.getName()); 21657 if (libEntry.info.isStatic()) { 21658 pw.print(" version=" + libEntry.info.getVersion()); 21659 } 21660 if (!checkin) { 21661 pw.print(" -> "); 21662 } 21663 if (libEntry.path != null) { 21664 pw.print(" (jar) "); 21665 pw.print(libEntry.path); 21666 } else { 21667 pw.print(" (apk) "); 21668 pw.print(libEntry.apk); 21669 } 21670 pw.println(); 21671 } 21672 } 21673 } 21674 21675 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 21676 if (dumpState.onTitlePrinted()) 21677 pw.println(); 21678 if (!checkin) { 21679 pw.println("Features:"); 21680 } 21681 21682 synchronized (mAvailableFeatures) { 21683 for (FeatureInfo feat : mAvailableFeatures.values()) { 21684 if (checkin) { 21685 pw.print("feat,"); 21686 pw.print(feat.name); 21687 pw.print(","); 21688 pw.println(feat.version); 21689 } else { 21690 pw.print(" "); 21691 pw.print(feat.name); 21692 if (feat.version > 0) { 21693 pw.print(" version="); 21694 pw.print(feat.version); 21695 } 21696 pw.println(); 21697 } 21698 } 21699 } 21700 } 21701 21702 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 21703 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 21704 : "Activity Resolver Table:", " ", packageName, 21705 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 21706 dumpState.setTitlePrinted(true); 21707 } 21708 } 21709 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 21710 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 21711 : "Receiver Resolver Table:", " ", packageName, 21712 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 21713 dumpState.setTitlePrinted(true); 21714 } 21715 } 21716 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 21717 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 21718 : "Service Resolver Table:", " ", packageName, 21719 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 21720 dumpState.setTitlePrinted(true); 21721 } 21722 } 21723 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 21724 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 21725 : "Provider Resolver Table:", " ", packageName, 21726 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 21727 dumpState.setTitlePrinted(true); 21728 } 21729 } 21730 21731 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 21732 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 21733 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 21734 int user = mSettings.mPreferredActivities.keyAt(i); 21735 if (pir.dump(pw, 21736 dumpState.getTitlePrinted() 21737 ? "\nPreferred Activities User " + user + ":" 21738 : "Preferred Activities User " + user + ":", " ", 21739 packageName, true, false)) { 21740 dumpState.setTitlePrinted(true); 21741 } 21742 } 21743 } 21744 21745 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 21746 pw.flush(); 21747 FileOutputStream fout = new FileOutputStream(fd); 21748 BufferedOutputStream str = new BufferedOutputStream(fout); 21749 XmlSerializer serializer = new FastXmlSerializer(); 21750 try { 21751 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 21752 serializer.startDocument(null, true); 21753 serializer.setFeature( 21754 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 21755 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 21756 serializer.endDocument(); 21757 serializer.flush(); 21758 } catch (IllegalArgumentException e) { 21759 pw.println("Failed writing: " + e); 21760 } catch (IllegalStateException e) { 21761 pw.println("Failed writing: " + e); 21762 } catch (IOException e) { 21763 pw.println("Failed writing: " + e); 21764 } 21765 } 21766 21767 if (!checkin 21768 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 21769 && packageName == null) { 21770 pw.println(); 21771 int count = mSettings.mPackages.size(); 21772 if (count == 0) { 21773 pw.println("No applications!"); 21774 pw.println(); 21775 } else { 21776 final String prefix = " "; 21777 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 21778 if (allPackageSettings.size() == 0) { 21779 pw.println("No domain preferred apps!"); 21780 pw.println(); 21781 } else { 21782 pw.println("App verification status:"); 21783 pw.println(); 21784 count = 0; 21785 for (PackageSetting ps : allPackageSettings) { 21786 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 21787 if (ivi == null || ivi.getPackageName() == null) continue; 21788 pw.println(prefix + "Package: " + ivi.getPackageName()); 21789 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 21790 pw.println(prefix + "Status: " + ivi.getStatusString()); 21791 pw.println(); 21792 count++; 21793 } 21794 if (count == 0) { 21795 pw.println(prefix + "No app verification established."); 21796 pw.println(); 21797 } 21798 for (int userId : sUserManager.getUserIds()) { 21799 pw.println("App linkages for user " + userId + ":"); 21800 pw.println(); 21801 count = 0; 21802 for (PackageSetting ps : allPackageSettings) { 21803 final long status = ps.getDomainVerificationStatusForUser(userId); 21804 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 21805 && !DEBUG_DOMAIN_VERIFICATION) { 21806 continue; 21807 } 21808 pw.println(prefix + "Package: " + ps.name); 21809 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 21810 String statusStr = IntentFilterVerificationInfo. 21811 getStatusStringFromValue(status); 21812 pw.println(prefix + "Status: " + statusStr); 21813 pw.println(); 21814 count++; 21815 } 21816 if (count == 0) { 21817 pw.println(prefix + "No configured app linkages."); 21818 pw.println(); 21819 } 21820 } 21821 } 21822 } 21823 } 21824 21825 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 21826 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 21827 if (packageName == null && permissionNames == null) { 21828 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 21829 if (iperm == 0) { 21830 if (dumpState.onTitlePrinted()) 21831 pw.println(); 21832 pw.println("AppOp Permissions:"); 21833 } 21834 pw.print(" AppOp Permission "); 21835 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 21836 pw.println(":"); 21837 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 21838 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 21839 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 21840 } 21841 } 21842 } 21843 } 21844 21845 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 21846 boolean printedSomething = false; 21847 for (PackageParser.Provider p : mProviders.mProviders.values()) { 21848 if (packageName != null && !packageName.equals(p.info.packageName)) { 21849 continue; 21850 } 21851 if (!printedSomething) { 21852 if (dumpState.onTitlePrinted()) 21853 pw.println(); 21854 pw.println("Registered ContentProviders:"); 21855 printedSomething = true; 21856 } 21857 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 21858 pw.print(" "); pw.println(p.toString()); 21859 } 21860 printedSomething = false; 21861 for (Map.Entry<String, PackageParser.Provider> entry : 21862 mProvidersByAuthority.entrySet()) { 21863 PackageParser.Provider p = entry.getValue(); 21864 if (packageName != null && !packageName.equals(p.info.packageName)) { 21865 continue; 21866 } 21867 if (!printedSomething) { 21868 if (dumpState.onTitlePrinted()) 21869 pw.println(); 21870 pw.println("ContentProvider Authorities:"); 21871 printedSomething = true; 21872 } 21873 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 21874 pw.print(" "); pw.println(p.toString()); 21875 if (p.info != null && p.info.applicationInfo != null) { 21876 final String appInfo = p.info.applicationInfo.toString(); 21877 pw.print(" applicationInfo="); pw.println(appInfo); 21878 } 21879 } 21880 } 21881 21882 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 21883 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 21884 } 21885 21886 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 21887 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 21888 } 21889 21890 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 21891 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 21892 } 21893 21894 if (dumpState.isDumping(DumpState.DUMP_CHANGES)) { 21895 if (dumpState.onTitlePrinted()) pw.println(); 21896 pw.println("Package Changes:"); 21897 pw.print(" Sequence number="); pw.println(mChangedPackagesSequenceNumber); 21898 final int K = mChangedPackages.size(); 21899 for (int i = 0; i < K; i++) { 21900 final SparseArray<String> changes = mChangedPackages.valueAt(i); 21901 pw.print(" User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":"); 21902 final int N = changes.size(); 21903 if (N == 0) { 21904 pw.print(" "); pw.println("No packages changed"); 21905 } else { 21906 for (int j = 0; j < N; j++) { 21907 final String pkgName = changes.valueAt(j); 21908 final int sequenceNumber = changes.keyAt(j); 21909 pw.print(" "); 21910 pw.print("seq="); 21911 pw.print(sequenceNumber); 21912 pw.print(", package="); 21913 pw.println(pkgName); 21914 } 21915 } 21916 } 21917 } 21918 21919 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 21920 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 21921 } 21922 21923 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 21924 // XXX should handle packageName != null by dumping only install data that 21925 // the given package is involved with. 21926 if (dumpState.onTitlePrinted()) pw.println(); 21927 21928 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 21929 ipw.println(); 21930 ipw.println("Frozen packages:"); 21931 ipw.increaseIndent(); 21932 if (mFrozenPackages.size() == 0) { 21933 ipw.println("(none)"); 21934 } else { 21935 for (int i = 0; i < mFrozenPackages.size(); i++) { 21936 ipw.println(mFrozenPackages.valueAt(i)); 21937 } 21938 } 21939 ipw.decreaseIndent(); 21940 } 21941 21942 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 21943 if (dumpState.onTitlePrinted()) pw.println(); 21944 dumpDexoptStateLPr(pw, packageName); 21945 } 21946 21947 if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) { 21948 if (dumpState.onTitlePrinted()) pw.println(); 21949 dumpCompilerStatsLPr(pw, packageName); 21950 } 21951 21952 if (!checkin && dumpState.isDumping(DumpState.DUMP_ENABLED_OVERLAYS)) { 21953 if (dumpState.onTitlePrinted()) pw.println(); 21954 dumpEnabledOverlaysLPr(pw); 21955 } 21956 21957 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 21958 if (dumpState.onTitlePrinted()) pw.println(); 21959 mSettings.dumpReadMessagesLPr(pw, dumpState); 21960 21961 pw.println(); 21962 pw.println("Package warning messages:"); 21963 BufferedReader in = null; 21964 String line = null; 21965 try { 21966 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 21967 while ((line = in.readLine()) != null) { 21968 if (line.contains("ignored: updated version")) continue; 21969 pw.println(line); 21970 } 21971 } catch (IOException ignored) { 21972 } finally { 21973 IoUtils.closeQuietly(in); 21974 } 21975 } 21976 21977 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 21978 BufferedReader in = null; 21979 String line = null; 21980 try { 21981 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 21982 while ((line = in.readLine()) != null) { 21983 if (line.contains("ignored: updated version")) continue; 21984 pw.print("msg,"); 21985 pw.println(line); 21986 } 21987 } catch (IOException ignored) { 21988 } finally { 21989 IoUtils.closeQuietly(in); 21990 } 21991 } 21992 } 21993 21994 // PackageInstaller should be called outside of mPackages lock 21995 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 21996 // XXX should handle packageName != null by dumping only install data that 21997 // the given package is involved with. 21998 if (dumpState.onTitlePrinted()) pw.println(); 21999 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 22000 } 22001 } 22002 22003 private void dumpProto(FileDescriptor fd) { 22004 final ProtoOutputStream proto = new ProtoOutputStream(fd); 22005 22006 synchronized (mPackages) { 22007 final long requiredVerifierPackageToken = 22008 proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE); 22009 proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage); 22010 proto.write( 22011 PackageServiceDumpProto.PackageShortProto.UID, 22012 getPackageUid( 22013 mRequiredVerifierPackage, 22014 MATCH_DEBUG_TRIAGED_MISSING, 22015 UserHandle.USER_SYSTEM)); 22016 proto.end(requiredVerifierPackageToken); 22017 22018 if (mIntentFilterVerifierComponent != null) { 22019 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 22020 final long verifierPackageToken = 22021 proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE); 22022 proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName); 22023 proto.write( 22024 PackageServiceDumpProto.PackageShortProto.UID, 22025 getPackageUid( 22026 verifierPackageName, 22027 MATCH_DEBUG_TRIAGED_MISSING, 22028 UserHandle.USER_SYSTEM)); 22029 proto.end(verifierPackageToken); 22030 } 22031 22032 dumpSharedLibrariesProto(proto); 22033 dumpFeaturesProto(proto); 22034 mSettings.dumpPackagesProto(proto); 22035 mSettings.dumpSharedUsersProto(proto); 22036 dumpMessagesProto(proto); 22037 } 22038 proto.flush(); 22039 } 22040 22041 private void dumpMessagesProto(ProtoOutputStream proto) { 22042 BufferedReader in = null; 22043 String line = null; 22044 try { 22045 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 22046 while ((line = in.readLine()) != null) { 22047 if (line.contains("ignored: updated version")) continue; 22048 proto.write(PackageServiceDumpProto.MESSAGES, line); 22049 } 22050 } catch (IOException ignored) { 22051 } finally { 22052 IoUtils.closeQuietly(in); 22053 } 22054 } 22055 22056 private void dumpFeaturesProto(ProtoOutputStream proto) { 22057 synchronized (mAvailableFeatures) { 22058 final int count = mAvailableFeatures.size(); 22059 for (int i = 0; i < count; i++) { 22060 final FeatureInfo feat = mAvailableFeatures.valueAt(i); 22061 final long featureToken = proto.start(PackageServiceDumpProto.FEATURES); 22062 proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name); 22063 proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version); 22064 proto.end(featureToken); 22065 } 22066 } 22067 } 22068 22069 private void dumpSharedLibrariesProto(ProtoOutputStream proto) { 22070 final int count = mSharedLibraries.size(); 22071 for (int i = 0; i < count; i++) { 22072 final String libName = mSharedLibraries.keyAt(i); 22073 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName); 22074 if (versionedLib == null) { 22075 continue; 22076 } 22077 final int versionCount = versionedLib.size(); 22078 for (int j = 0; j < versionCount; j++) { 22079 final SharedLibraryEntry libEntry = versionedLib.valueAt(j); 22080 final long sharedLibraryToken = 22081 proto.start(PackageServiceDumpProto.SHARED_LIBRARIES); 22082 proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName()); 22083 final boolean isJar = (libEntry.path != null); 22084 proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar); 22085 if (isJar) { 22086 proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path); 22087 } else { 22088 proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk); 22089 } 22090 proto.end(sharedLibraryToken); 22091 } 22092 } 22093 } 22094 22095 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 22096 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 22097 ipw.println(); 22098 ipw.println("Dexopt state:"); 22099 ipw.increaseIndent(); 22100 Collection<PackageParser.Package> packages = null; 22101 if (packageName != null) { 22102 PackageParser.Package targetPackage = mPackages.get(packageName); 22103 if (targetPackage != null) { 22104 packages = Collections.singletonList(targetPackage); 22105 } else { 22106 ipw.println("Unable to find package: " + packageName); 22107 return; 22108 } 22109 } else { 22110 packages = mPackages.values(); 22111 } 22112 22113 for (PackageParser.Package pkg : packages) { 22114 ipw.println("[" + pkg.packageName + "]"); 22115 ipw.increaseIndent(); 22116 mPackageDexOptimizer.dumpDexoptState(ipw, pkg); 22117 ipw.decreaseIndent(); 22118 } 22119 } 22120 22121 private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) { 22122 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 22123 ipw.println(); 22124 ipw.println("Compiler stats:"); 22125 ipw.increaseIndent(); 22126 Collection<PackageParser.Package> packages = null; 22127 if (packageName != null) { 22128 PackageParser.Package targetPackage = mPackages.get(packageName); 22129 if (targetPackage != null) { 22130 packages = Collections.singletonList(targetPackage); 22131 } else { 22132 ipw.println("Unable to find package: " + packageName); 22133 return; 22134 } 22135 } else { 22136 packages = mPackages.values(); 22137 } 22138 22139 for (PackageParser.Package pkg : packages) { 22140 ipw.println("[" + pkg.packageName + "]"); 22141 ipw.increaseIndent(); 22142 22143 CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName); 22144 if (stats == null) { 22145 ipw.println("(No recorded stats)"); 22146 } else { 22147 stats.dump(ipw); 22148 } 22149 ipw.decreaseIndent(); 22150 } 22151 } 22152 22153 private void dumpEnabledOverlaysLPr(PrintWriter pw) { 22154 pw.println("Enabled overlay paths:"); 22155 final int N = mEnabledOverlayPaths.size(); 22156 for (int i = 0; i < N; i++) { 22157 final int userId = mEnabledOverlayPaths.keyAt(i); 22158 pw.println(String.format(" User %d:", userId)); 22159 final ArrayMap<String, ArrayList<String>> userSpecificOverlays = 22160 mEnabledOverlayPaths.valueAt(i); 22161 final int M = userSpecificOverlays.size(); 22162 for (int j = 0; j < M; j++) { 22163 final String targetPackageName = userSpecificOverlays.keyAt(j); 22164 final ArrayList<String> overlayPackagePaths = userSpecificOverlays.valueAt(j); 22165 pw.println(String.format(" %s: %s", targetPackageName, overlayPackagePaths)); 22166 } 22167 } 22168 } 22169 22170 private String dumpDomainString(String packageName) { 22171 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 22172 .getList(); 22173 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 22174 22175 ArraySet<String> result = new ArraySet<>(); 22176 if (iviList.size() > 0) { 22177 for (IntentFilterVerificationInfo ivi : iviList) { 22178 for (String host : ivi.getDomains()) { 22179 result.add(host); 22180 } 22181 } 22182 } 22183 if (filters != null && filters.size() > 0) { 22184 for (IntentFilter filter : filters) { 22185 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 22186 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 22187 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 22188 result.addAll(filter.getHostsList()); 22189 } 22190 } 22191 } 22192 22193 StringBuilder sb = new StringBuilder(result.size() * 16); 22194 for (String domain : result) { 22195 if (sb.length() > 0) sb.append(" "); 22196 sb.append(domain); 22197 } 22198 return sb.toString(); 22199 } 22200 22201 // ------- apps on sdcard specific code ------- 22202 static final boolean DEBUG_SD_INSTALL = false; 22203 22204 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 22205 22206 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 22207 22208 private boolean mMediaMounted = false; 22209 22210 static String getEncryptKey() { 22211 try { 22212 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 22213 SD_ENCRYPTION_KEYSTORE_NAME); 22214 if (sdEncKey == null) { 22215 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 22216 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 22217 if (sdEncKey == null) { 22218 Slog.e(TAG, "Failed to create encryption keys"); 22219 return null; 22220 } 22221 } 22222 return sdEncKey; 22223 } catch (NoSuchAlgorithmException nsae) { 22224 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 22225 return null; 22226 } catch (IOException ioe) { 22227 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 22228 return null; 22229 } 22230 } 22231 22232 /* 22233 * Update media status on PackageManager. 22234 */ 22235 @Override 22236 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 22237 enforceSystemOrRoot("Media status can only be updated by the system"); 22238 // reader; this apparently protects mMediaMounted, but should probably 22239 // be a different lock in that case. 22240 synchronized (mPackages) { 22241 Log.i(TAG, "Updating external media status from " 22242 + (mMediaMounted ? "mounted" : "unmounted") + " to " 22243 + (mediaStatus ? "mounted" : "unmounted")); 22244 if (DEBUG_SD_INSTALL) 22245 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 22246 + ", mMediaMounted=" + mMediaMounted); 22247 if (mediaStatus == mMediaMounted) { 22248 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 22249 : 0, -1); 22250 mHandler.sendMessage(msg); 22251 return; 22252 } 22253 mMediaMounted = mediaStatus; 22254 } 22255 // Queue up an async operation since the package installation may take a 22256 // little while. 22257 mHandler.post(new Runnable() { 22258 public void run() { 22259 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 22260 } 22261 }); 22262 } 22263 22264 /** 22265 * Called by StorageManagerService when the initial ASECs to scan are available. 22266 * Should block until all the ASEC containers are finished being scanned. 22267 */ 22268 public void scanAvailableAsecs() { 22269 updateExternalMediaStatusInner(true, false, false); 22270 } 22271 22272 /* 22273 * Collect information of applications on external media, map them against 22274 * existing containers and update information based on current mount status. 22275 * Please note that we always have to report status if reportStatus has been 22276 * set to true especially when unloading packages. 22277 */ 22278 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 22279 boolean externalStorage) { 22280 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 22281 int[] uidArr = EmptyArray.INT; 22282 22283 final String[] list = PackageHelper.getSecureContainerList(); 22284 if (ArrayUtils.isEmpty(list)) { 22285 Log.i(TAG, "No secure containers found"); 22286 } else { 22287 // Process list of secure containers and categorize them 22288 // as active or stale based on their package internal state. 22289 22290 // reader 22291 synchronized (mPackages) { 22292 for (String cid : list) { 22293 // Leave stages untouched for now; installer service owns them 22294 if (PackageInstallerService.isStageName(cid)) continue; 22295 22296 if (DEBUG_SD_INSTALL) 22297 Log.i(TAG, "Processing container " + cid); 22298 String pkgName = getAsecPackageName(cid); 22299 if (pkgName == null) { 22300 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 22301 continue; 22302 } 22303 if (DEBUG_SD_INSTALL) 22304 Log.i(TAG, "Looking for pkg : " + pkgName); 22305 22306 final PackageSetting ps = mSettings.mPackages.get(pkgName); 22307 if (ps == null) { 22308 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 22309 continue; 22310 } 22311 22312 /* 22313 * Skip packages that are not external if we're unmounting 22314 * external storage. 22315 */ 22316 if (externalStorage && !isMounted && !isExternal(ps)) { 22317 continue; 22318 } 22319 22320 final AsecInstallArgs args = new AsecInstallArgs(cid, 22321 getAppDexInstructionSets(ps), ps.isForwardLocked()); 22322 // The package status is changed only if the code path 22323 // matches between settings and the container id. 22324 if (ps.codePathString != null 22325 && ps.codePathString.startsWith(args.getCodePath())) { 22326 if (DEBUG_SD_INSTALL) { 22327 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 22328 + " at code path: " + ps.codePathString); 22329 } 22330 22331 // We do have a valid package installed on sdcard 22332 processCids.put(args, ps.codePathString); 22333 final int uid = ps.appId; 22334 if (uid != -1) { 22335 uidArr = ArrayUtils.appendInt(uidArr, uid); 22336 } 22337 } else { 22338 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 22339 + ps.codePathString); 22340 } 22341 } 22342 } 22343 22344 Arrays.sort(uidArr); 22345 } 22346 22347 // Process packages with valid entries. 22348 if (isMounted) { 22349 if (DEBUG_SD_INSTALL) 22350 Log.i(TAG, "Loading packages"); 22351 loadMediaPackages(processCids, uidArr, externalStorage); 22352 startCleaningPackages(); 22353 mInstallerService.onSecureContainersAvailable(); 22354 } else { 22355 if (DEBUG_SD_INSTALL) 22356 Log.i(TAG, "Unloading packages"); 22357 unloadMediaPackages(processCids, uidArr, reportStatus); 22358 } 22359 } 22360 22361 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 22362 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 22363 final int size = infos.size(); 22364 final String[] packageNames = new String[size]; 22365 final int[] packageUids = new int[size]; 22366 for (int i = 0; i < size; i++) { 22367 final ApplicationInfo info = infos.get(i); 22368 packageNames[i] = info.packageName; 22369 packageUids[i] = info.uid; 22370 } 22371 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 22372 finishedReceiver); 22373 } 22374 22375 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 22376 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 22377 sendResourcesChangedBroadcast(mediaStatus, replacing, 22378 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 22379 } 22380 22381 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 22382 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 22383 int size = pkgList.length; 22384 if (size > 0) { 22385 // Send broadcasts here 22386 Bundle extras = new Bundle(); 22387 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 22388 if (uidArr != null) { 22389 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 22390 } 22391 if (replacing) { 22392 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 22393 } 22394 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 22395 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 22396 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 22397 } 22398 } 22399 22400 /* 22401 * Look at potentially valid container ids from processCids If package 22402 * information doesn't match the one on record or package scanning fails, 22403 * the cid is added to list of removeCids. We currently don't delete stale 22404 * containers. 22405 */ 22406 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 22407 boolean externalStorage) { 22408 ArrayList<String> pkgList = new ArrayList<String>(); 22409 Set<AsecInstallArgs> keys = processCids.keySet(); 22410 22411 for (AsecInstallArgs args : keys) { 22412 String codePath = processCids.get(args); 22413 if (DEBUG_SD_INSTALL) 22414 Log.i(TAG, "Loading container : " + args.cid); 22415 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 22416 try { 22417 // Make sure there are no container errors first. 22418 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 22419 Slog.e(TAG, "Failed to mount cid : " + args.cid 22420 + " when installing from sdcard"); 22421 continue; 22422 } 22423 // Check code path here. 22424 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 22425 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 22426 + " does not match one in settings " + codePath); 22427 continue; 22428 } 22429 // Parse package 22430 int parseFlags = mDefParseFlags; 22431 if (args.isExternalAsec()) { 22432 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 22433 } 22434 if (args.isFwdLocked()) { 22435 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 22436 } 22437 22438 synchronized (mInstallLock) { 22439 PackageParser.Package pkg = null; 22440 try { 22441 // Sadly we don't know the package name yet to freeze it 22442 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 22443 SCAN_IGNORE_FROZEN, 0, null); 22444 } catch (PackageManagerException e) { 22445 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 22446 } 22447 // Scan the package 22448 if (pkg != null) { 22449 /* 22450 * TODO why is the lock being held? doPostInstall is 22451 * called in other places without the lock. This needs 22452 * to be straightened out. 22453 */ 22454 // writer 22455 synchronized (mPackages) { 22456 retCode = PackageManager.INSTALL_SUCCEEDED; 22457 pkgList.add(pkg.packageName); 22458 // Post process args 22459 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 22460 pkg.applicationInfo.uid); 22461 } 22462 } else { 22463 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 22464 } 22465 } 22466 22467 } finally { 22468 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 22469 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 22470 } 22471 } 22472 } 22473 // writer 22474 synchronized (mPackages) { 22475 // If the platform SDK has changed since the last time we booted, 22476 // we need to re-grant app permission to catch any new ones that 22477 // appear. This is really a hack, and means that apps can in some 22478 // cases get permissions that the user didn't initially explicitly 22479 // allow... it would be nice to have some better way to handle 22480 // this situation. 22481 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 22482 : mSettings.getInternalVersion(); 22483 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 22484 : StorageManager.UUID_PRIVATE_INTERNAL; 22485 22486 int updateFlags = UPDATE_PERMISSIONS_ALL; 22487 if (ver.sdkVersion != mSdkVersion) { 22488 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 22489 + mSdkVersion + "; regranting permissions for external"); 22490 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 22491 } 22492 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 22493 22494 // Yay, everything is now upgraded 22495 ver.forceCurrent(); 22496 22497 // can downgrade to reader 22498 // Persist settings 22499 mSettings.writeLPr(); 22500 } 22501 // Send a broadcast to let everyone know we are done processing 22502 if (pkgList.size() > 0) { 22503 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 22504 } 22505 } 22506 22507 /* 22508 * Utility method to unload a list of specified containers 22509 */ 22510 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 22511 // Just unmount all valid containers. 22512 for (AsecInstallArgs arg : cidArgs) { 22513 synchronized (mInstallLock) { 22514 arg.doPostDeleteLI(false); 22515 } 22516 } 22517 } 22518 22519 /* 22520 * Unload packages mounted on external media. This involves deleting package 22521 * data from internal structures, sending broadcasts about disabled packages, 22522 * gc'ing to free up references, unmounting all secure containers 22523 * corresponding to packages on external media, and posting a 22524 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 22525 * that we always have to post this message if status has been requested no 22526 * matter what. 22527 */ 22528 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 22529 final boolean reportStatus) { 22530 if (DEBUG_SD_INSTALL) 22531 Log.i(TAG, "unloading media packages"); 22532 ArrayList<String> pkgList = new ArrayList<String>(); 22533 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 22534 final Set<AsecInstallArgs> keys = processCids.keySet(); 22535 for (AsecInstallArgs args : keys) { 22536 String pkgName = args.getPackageName(); 22537 if (DEBUG_SD_INSTALL) 22538 Log.i(TAG, "Trying to unload pkg : " + pkgName); 22539 // Delete package internally 22540 PackageRemovedInfo outInfo = new PackageRemovedInfo(this); 22541 synchronized (mInstallLock) { 22542 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 22543 final boolean res; 22544 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 22545 "unloadMediaPackages")) { 22546 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 22547 null); 22548 } 22549 if (res) { 22550 pkgList.add(pkgName); 22551 } else { 22552 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 22553 failedList.add(args); 22554 } 22555 } 22556 } 22557 22558 // reader 22559 synchronized (mPackages) { 22560 // We didn't update the settings after removing each package; 22561 // write them now for all packages. 22562 mSettings.writeLPr(); 22563 } 22564 22565 // We have to absolutely send UPDATED_MEDIA_STATUS only 22566 // after confirming that all the receivers processed the ordered 22567 // broadcast when packages get disabled, force a gc to clean things up. 22568 // and unload all the containers. 22569 if (pkgList.size() > 0) { 22570 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 22571 new IIntentReceiver.Stub() { 22572 public void performReceive(Intent intent, int resultCode, String data, 22573 Bundle extras, boolean ordered, boolean sticky, 22574 int sendingUser) throws RemoteException { 22575 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 22576 reportStatus ? 1 : 0, 1, keys); 22577 mHandler.sendMessage(msg); 22578 } 22579 }); 22580 } else { 22581 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 22582 keys); 22583 mHandler.sendMessage(msg); 22584 } 22585 } 22586 22587 private void loadPrivatePackages(final VolumeInfo vol) { 22588 mHandler.post(new Runnable() { 22589 @Override 22590 public void run() { 22591 loadPrivatePackagesInner(vol); 22592 } 22593 }); 22594 } 22595 22596 private void loadPrivatePackagesInner(VolumeInfo vol) { 22597 final String volumeUuid = vol.fsUuid; 22598 if (TextUtils.isEmpty(volumeUuid)) { 22599 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 22600 return; 22601 } 22602 22603 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 22604 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 22605 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 22606 22607 final VersionInfo ver; 22608 final List<PackageSetting> packages; 22609 synchronized (mPackages) { 22610 ver = mSettings.findOrCreateVersion(volumeUuid); 22611 packages = mSettings.getVolumePackagesLPr(volumeUuid); 22612 } 22613 22614 for (PackageSetting ps : packages) { 22615 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 22616 synchronized (mInstallLock) { 22617 final PackageParser.Package pkg; 22618 try { 22619 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 22620 loaded.add(pkg.applicationInfo); 22621 22622 } catch (PackageManagerException e) { 22623 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 22624 } 22625 22626 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 22627 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 22628 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 22629 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 22630 } 22631 } 22632 } 22633 22634 // Reconcile app data for all started/unlocked users 22635 final StorageManager sm = mContext.getSystemService(StorageManager.class); 22636 final UserManager um = mContext.getSystemService(UserManager.class); 22637 UserManagerInternal umInternal = getUserManagerInternal(); 22638 for (UserInfo user : um.getUsers()) { 22639 final int flags; 22640 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 22641 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 22642 } else if (umInternal.isUserRunning(user.id)) { 22643 flags = StorageManager.FLAG_STORAGE_DE; 22644 } else { 22645 continue; 22646 } 22647 22648 try { 22649 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 22650 synchronized (mInstallLock) { 22651 reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */); 22652 } 22653 } catch (IllegalStateException e) { 22654 // Device was probably ejected, and we'll process that event momentarily 22655 Slog.w(TAG, "Failed to prepare storage: " + e); 22656 } 22657 } 22658 22659 synchronized (mPackages) { 22660 int updateFlags = UPDATE_PERMISSIONS_ALL; 22661 if (ver.sdkVersion != mSdkVersion) { 22662 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 22663 + mSdkVersion + "; regranting permissions for " + volumeUuid); 22664 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 22665 } 22666 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 22667 22668 // Yay, everything is now upgraded 22669 ver.forceCurrent(); 22670 22671 mSettings.writeLPr(); 22672 } 22673 22674 for (PackageFreezer freezer : freezers) { 22675 freezer.close(); 22676 } 22677 22678 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 22679 sendResourcesChangedBroadcast(true, false, loaded, null); 22680 } 22681 22682 private void unloadPrivatePackages(final VolumeInfo vol) { 22683 mHandler.post(new Runnable() { 22684 @Override 22685 public void run() { 22686 unloadPrivatePackagesInner(vol); 22687 } 22688 }); 22689 } 22690 22691 private void unloadPrivatePackagesInner(VolumeInfo vol) { 22692 final String volumeUuid = vol.fsUuid; 22693 if (TextUtils.isEmpty(volumeUuid)) { 22694 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 22695 return; 22696 } 22697 22698 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 22699 synchronized (mInstallLock) { 22700 synchronized (mPackages) { 22701 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 22702 for (PackageSetting ps : packages) { 22703 if (ps.pkg == null) continue; 22704 22705 final ApplicationInfo info = ps.pkg.applicationInfo; 22706 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 22707 final PackageRemovedInfo outInfo = new PackageRemovedInfo(this); 22708 22709 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 22710 "unloadPrivatePackagesInner")) { 22711 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 22712 false, null)) { 22713 unloaded.add(info); 22714 } else { 22715 Slog.w(TAG, "Failed to unload " + ps.codePath); 22716 } 22717 } 22718 22719 // Try very hard to release any references to this package 22720 // so we don't risk the system server being killed due to 22721 // open FDs 22722 AttributeCache.instance().removePackage(ps.name); 22723 } 22724 22725 mSettings.writeLPr(); 22726 } 22727 } 22728 22729 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 22730 sendResourcesChangedBroadcast(false, false, unloaded, null); 22731 22732 // Try very hard to release any references to this path so we don't risk 22733 // the system server being killed due to open FDs 22734 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 22735 22736 for (int i = 0; i < 3; i++) { 22737 System.gc(); 22738 System.runFinalization(); 22739 } 22740 } 22741 22742 private void assertPackageKnown(String volumeUuid, String packageName) 22743 throws PackageManagerException { 22744 synchronized (mPackages) { 22745 // Normalize package name to handle renamed packages 22746 packageName = normalizePackageNameLPr(packageName); 22747 22748 final PackageSetting ps = mSettings.mPackages.get(packageName); 22749 if (ps == null) { 22750 throw new PackageManagerException("Package " + packageName + " is unknown"); 22751 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 22752 throw new PackageManagerException( 22753 "Package " + packageName + " found on unknown volume " + volumeUuid 22754 + "; expected volume " + ps.volumeUuid); 22755 } 22756 } 22757 } 22758 22759 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 22760 throws PackageManagerException { 22761 synchronized (mPackages) { 22762 // Normalize package name to handle renamed packages 22763 packageName = normalizePackageNameLPr(packageName); 22764 22765 final PackageSetting ps = mSettings.mPackages.get(packageName); 22766 if (ps == null) { 22767 throw new PackageManagerException("Package " + packageName + " is unknown"); 22768 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 22769 throw new PackageManagerException( 22770 "Package " + packageName + " found on unknown volume " + volumeUuid 22771 + "; expected volume " + ps.volumeUuid); 22772 } else if (!ps.getInstalled(userId)) { 22773 throw new PackageManagerException( 22774 "Package " + packageName + " not installed for user " + userId); 22775 } 22776 } 22777 } 22778 22779 private List<String> collectAbsoluteCodePaths() { 22780 synchronized (mPackages) { 22781 List<String> codePaths = new ArrayList<>(); 22782 final int packageCount = mSettings.mPackages.size(); 22783 for (int i = 0; i < packageCount; i++) { 22784 final PackageSetting ps = mSettings.mPackages.valueAt(i); 22785 codePaths.add(ps.codePath.getAbsolutePath()); 22786 } 22787 return codePaths; 22788 } 22789 } 22790 22791 /** 22792 * Examine all apps present on given mounted volume, and destroy apps that 22793 * aren't expected, either due to uninstallation or reinstallation on 22794 * another volume. 22795 */ 22796 private void reconcileApps(String volumeUuid) { 22797 List<String> absoluteCodePaths = collectAbsoluteCodePaths(); 22798 List<File> filesToDelete = null; 22799 22800 final File[] files = FileUtils.listFilesOrEmpty( 22801 Environment.getDataAppDirectory(volumeUuid)); 22802 for (File file : files) { 22803 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 22804 && !PackageInstallerService.isStageName(file.getName()); 22805 if (!isPackage) { 22806 // Ignore entries which are not packages 22807 continue; 22808 } 22809 22810 String absolutePath = file.getAbsolutePath(); 22811 22812 boolean pathValid = false; 22813 final int absoluteCodePathCount = absoluteCodePaths.size(); 22814 for (int i = 0; i < absoluteCodePathCount; i++) { 22815 String absoluteCodePath = absoluteCodePaths.get(i); 22816 if (absolutePath.startsWith(absoluteCodePath)) { 22817 pathValid = true; 22818 break; 22819 } 22820 } 22821 22822 if (!pathValid) { 22823 if (filesToDelete == null) { 22824 filesToDelete = new ArrayList<>(); 22825 } 22826 filesToDelete.add(file); 22827 } 22828 } 22829 22830 if (filesToDelete != null) { 22831 final int fileToDeleteCount = filesToDelete.size(); 22832 for (int i = 0; i < fileToDeleteCount; i++) { 22833 File fileToDelete = filesToDelete.get(i); 22834 logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete); 22835 synchronized (mInstallLock) { 22836 removeCodePathLI(fileToDelete); 22837 } 22838 } 22839 } 22840 } 22841 22842 /** 22843 * Reconcile all app data for the given user. 22844 * <p> 22845 * Verifies that directories exist and that ownership and labeling is 22846 * correct for all installed apps on all mounted volumes. 22847 */ 22848 void reconcileAppsData(int userId, int flags, boolean migrateAppsData) { 22849 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22850 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 22851 final String volumeUuid = vol.getFsUuid(); 22852 synchronized (mInstallLock) { 22853 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData); 22854 } 22855 } 22856 } 22857 22858 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags, 22859 boolean migrateAppData) { 22860 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */); 22861 } 22862 22863 /** 22864 * Reconcile all app data on given mounted volume. 22865 * <p> 22866 * Destroys app data that isn't expected, either due to uninstallation or 22867 * reinstallation on another volume. 22868 * <p> 22869 * Verifies that directories exist and that ownership and labeling is 22870 * correct for all installed apps. 22871 * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true) 22872 */ 22873 private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags, 22874 boolean migrateAppData, boolean onlyCoreApps) { 22875 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 22876 + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData); 22877 List<String> result = onlyCoreApps ? new ArrayList<>() : null; 22878 22879 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 22880 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 22881 22882 // First look for stale data that doesn't belong, and check if things 22883 // have changed since we did our last restorecon 22884 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 22885 if (StorageManager.isFileEncryptedNativeOrEmulated() 22886 && !StorageManager.isUserKeyUnlocked(userId)) { 22887 throw new RuntimeException( 22888 "Yikes, someone asked us to reconcile CE storage while " + userId 22889 + " was still locked; this would have caused massive data loss!"); 22890 } 22891 22892 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 22893 for (File file : files) { 22894 final String packageName = file.getName(); 22895 try { 22896 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 22897 } catch (PackageManagerException e) { 22898 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 22899 try { 22900 mInstaller.destroyAppData(volumeUuid, packageName, userId, 22901 StorageManager.FLAG_STORAGE_CE, 0); 22902 } catch (InstallerException e2) { 22903 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 22904 } 22905 } 22906 } 22907 } 22908 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 22909 final File[] files = FileUtils.listFilesOrEmpty(deDir); 22910 for (File file : files) { 22911 final String packageName = file.getName(); 22912 try { 22913 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 22914 } catch (PackageManagerException e) { 22915 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 22916 try { 22917 mInstaller.destroyAppData(volumeUuid, packageName, userId, 22918 StorageManager.FLAG_STORAGE_DE, 0); 22919 } catch (InstallerException e2) { 22920 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 22921 } 22922 } 22923 } 22924 } 22925 22926 // Ensure that data directories are ready to roll for all packages 22927 // installed for this volume and user 22928 final List<PackageSetting> packages; 22929 synchronized (mPackages) { 22930 packages = mSettings.getVolumePackagesLPr(volumeUuid); 22931 } 22932 int preparedCount = 0; 22933 for (PackageSetting ps : packages) { 22934 final String packageName = ps.name; 22935 if (ps.pkg == null) { 22936 Slog.w(TAG, "Odd, missing scanned package " + packageName); 22937 // TODO: might be due to legacy ASEC apps; we should circle back 22938 // and reconcile again once they're scanned 22939 continue; 22940 } 22941 // Skip non-core apps if requested 22942 if (onlyCoreApps && !ps.pkg.coreApp) { 22943 result.add(packageName); 22944 continue; 22945 } 22946 22947 if (ps.getInstalled(userId)) { 22948 prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData); 22949 preparedCount++; 22950 } 22951 } 22952 22953 Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages"); 22954 return result; 22955 } 22956 22957 /** 22958 * Prepare app data for the given app just after it was installed or 22959 * upgraded. This method carefully only touches users that it's installed 22960 * for, and it forces a restorecon to handle any seinfo changes. 22961 * <p> 22962 * Verifies that directories exist and that ownership and labeling is 22963 * correct for all installed apps. If there is an ownership mismatch, it 22964 * will try recovering system apps by wiping data; third-party app data is 22965 * left intact. 22966 * <p> 22967 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 22968 */ 22969 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 22970 final PackageSetting ps; 22971 synchronized (mPackages) { 22972 ps = mSettings.mPackages.get(pkg.packageName); 22973 mSettings.writeKernelMappingLPr(ps); 22974 } 22975 22976 final UserManager um = mContext.getSystemService(UserManager.class); 22977 UserManagerInternal umInternal = getUserManagerInternal(); 22978 for (UserInfo user : um.getUsers()) { 22979 final int flags; 22980 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 22981 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 22982 } else if (umInternal.isUserRunning(user.id)) { 22983 flags = StorageManager.FLAG_STORAGE_DE; 22984 } else { 22985 continue; 22986 } 22987 22988 if (ps.getInstalled(user.id)) { 22989 // TODO: when user data is locked, mark that we're still dirty 22990 prepareAppDataLIF(pkg, user.id, flags); 22991 } 22992 } 22993 } 22994 22995 /** 22996 * Prepare app data for the given app. 22997 * <p> 22998 * Verifies that directories exist and that ownership and labeling is 22999 * correct for all installed apps. If there is an ownership mismatch, this 23000 * will try recovering system apps by wiping data; third-party app data is 23001 * left intact. 23002 */ 23003 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 23004 if (pkg == null) { 23005 Slog.wtf(TAG, "Package was null!", new Throwable()); 23006 return; 23007 } 23008 prepareAppDataLeafLIF(pkg, userId, flags); 23009 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 23010 for (int i = 0; i < childCount; i++) { 23011 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 23012 } 23013 } 23014 23015 private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags, 23016 boolean maybeMigrateAppData) { 23017 prepareAppDataLIF(pkg, userId, flags); 23018 23019 if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) { 23020 // We may have just shuffled around app data directories, so 23021 // prepare them one more time 23022 prepareAppDataLIF(pkg, userId, flags); 23023 } 23024 } 23025 23026 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 23027 if (DEBUG_APP_DATA) { 23028 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 23029 + Integer.toHexString(flags)); 23030 } 23031 23032 final String volumeUuid = pkg.volumeUuid; 23033 final String packageName = pkg.packageName; 23034 final ApplicationInfo app = pkg.applicationInfo; 23035 final int appId = UserHandle.getAppId(app.uid); 23036 23037 Preconditions.checkNotNull(app.seInfo); 23038 23039 long ceDataInode = -1; 23040 try { 23041 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 23042 appId, app.seInfo, app.targetSdkVersion); 23043 } catch (InstallerException e) { 23044 if (app.isSystemApp()) { 23045 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 23046 + ", but trying to recover: " + e); 23047 destroyAppDataLeafLIF(pkg, userId, flags); 23048 try { 23049 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 23050 appId, app.seInfo, app.targetSdkVersion); 23051 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 23052 } catch (InstallerException e2) { 23053 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 23054 } 23055 } else { 23056 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 23057 } 23058 } 23059 23060 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) { 23061 // TODO: mark this structure as dirty so we persist it! 23062 synchronized (mPackages) { 23063 final PackageSetting ps = mSettings.mPackages.get(packageName); 23064 if (ps != null) { 23065 ps.setCeDataInode(ceDataInode, userId); 23066 } 23067 } 23068 } 23069 23070 prepareAppDataContentsLeafLIF(pkg, userId, flags); 23071 } 23072 23073 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 23074 if (pkg == null) { 23075 Slog.wtf(TAG, "Package was null!", new Throwable()); 23076 return; 23077 } 23078 prepareAppDataContentsLeafLIF(pkg, userId, flags); 23079 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 23080 for (int i = 0; i < childCount; i++) { 23081 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 23082 } 23083 } 23084 23085 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 23086 final String volumeUuid = pkg.volumeUuid; 23087 final String packageName = pkg.packageName; 23088 final ApplicationInfo app = pkg.applicationInfo; 23089 23090 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 23091 // Create a native library symlink only if we have native libraries 23092 // and if the native libraries are 32 bit libraries. We do not provide 23093 // this symlink for 64 bit libraries. 23094 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 23095 final String nativeLibPath = app.nativeLibraryDir; 23096 try { 23097 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 23098 nativeLibPath, userId); 23099 } catch (InstallerException e) { 23100 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 23101 } 23102 } 23103 } 23104 } 23105 23106 /** 23107 * For system apps on non-FBE devices, this method migrates any existing 23108 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 23109 * requested by the app. 23110 */ 23111 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 23112 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 23113 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 23114 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 23115 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 23116 try { 23117 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 23118 storageTarget); 23119 } catch (InstallerException e) { 23120 logCriticalInfo(Log.WARN, 23121 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 23122 } 23123 return true; 23124 } else { 23125 return false; 23126 } 23127 } 23128 23129 public PackageFreezer freezePackage(String packageName, String killReason) { 23130 return freezePackage(packageName, UserHandle.USER_ALL, killReason); 23131 } 23132 23133 public PackageFreezer freezePackage(String packageName, int userId, String killReason) { 23134 return new PackageFreezer(packageName, userId, killReason); 23135 } 23136 23137 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 23138 String killReason) { 23139 return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason); 23140 } 23141 23142 public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags, 23143 String killReason) { 23144 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 23145 return new PackageFreezer(); 23146 } else { 23147 return freezePackage(packageName, userId, killReason); 23148 } 23149 } 23150 23151 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 23152 String killReason) { 23153 return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason); 23154 } 23155 23156 public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags, 23157 String killReason) { 23158 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 23159 return new PackageFreezer(); 23160 } else { 23161 return freezePackage(packageName, userId, killReason); 23162 } 23163 } 23164 23165 /** 23166 * Class that freezes and kills the given package upon creation, and 23167 * unfreezes it upon closing. This is typically used when doing surgery on 23168 * app code/data to prevent the app from running while you're working. 23169 */ 23170 private class PackageFreezer implements AutoCloseable { 23171 private final String mPackageName; 23172 private final PackageFreezer[] mChildren; 23173 23174 private final boolean mWeFroze; 23175 23176 private final AtomicBoolean mClosed = new AtomicBoolean(); 23177 private final CloseGuard mCloseGuard = CloseGuard.get(); 23178 23179 /** 23180 * Create and return a stub freezer that doesn't actually do anything, 23181 * typically used when someone requested 23182 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 23183 * {@link PackageManager#DELETE_DONT_KILL_APP}. 23184 */ 23185 public PackageFreezer() { 23186 mPackageName = null; 23187 mChildren = null; 23188 mWeFroze = false; 23189 mCloseGuard.open("close"); 23190 } 23191 23192 public PackageFreezer(String packageName, int userId, String killReason) { 23193 synchronized (mPackages) { 23194 mPackageName = packageName; 23195 mWeFroze = mFrozenPackages.add(mPackageName); 23196 23197 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 23198 if (ps != null) { 23199 killApplication(ps.name, ps.appId, userId, killReason); 23200 } 23201 23202 final PackageParser.Package p = mPackages.get(packageName); 23203 if (p != null && p.childPackages != null) { 23204 final int N = p.childPackages.size(); 23205 mChildren = new PackageFreezer[N]; 23206 for (int i = 0; i < N; i++) { 23207 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 23208 userId, killReason); 23209 } 23210 } else { 23211 mChildren = null; 23212 } 23213 } 23214 mCloseGuard.open("close"); 23215 } 23216 23217 @Override 23218 protected void finalize() throws Throwable { 23219 try { 23220 mCloseGuard.warnIfOpen(); 23221 close(); 23222 } finally { 23223 super.finalize(); 23224 } 23225 } 23226 23227 @Override 23228 public void close() { 23229 mCloseGuard.close(); 23230 if (mClosed.compareAndSet(false, true)) { 23231 synchronized (mPackages) { 23232 if (mWeFroze) { 23233 mFrozenPackages.remove(mPackageName); 23234 } 23235 23236 if (mChildren != null) { 23237 for (PackageFreezer freezer : mChildren) { 23238 freezer.close(); 23239 } 23240 } 23241 } 23242 } 23243 } 23244 } 23245 23246 /** 23247 * Verify that given package is currently frozen. 23248 */ 23249 private void checkPackageFrozen(String packageName) { 23250 synchronized (mPackages) { 23251 if (!mFrozenPackages.contains(packageName)) { 23252 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 23253 } 23254 } 23255 } 23256 23257 @Override 23258 public int movePackage(final String packageName, final String volumeUuid) { 23259 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 23260 23261 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 23262 final int moveId = mNextMoveId.getAndIncrement(); 23263 mHandler.post(new Runnable() { 23264 @Override 23265 public void run() { 23266 try { 23267 movePackageInternal(packageName, volumeUuid, moveId, user); 23268 } catch (PackageManagerException e) { 23269 Slog.w(TAG, "Failed to move " + packageName, e); 23270 mMoveCallbacks.notifyStatusChanged(moveId, 23271 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 23272 } 23273 } 23274 }); 23275 return moveId; 23276 } 23277 23278 private void movePackageInternal(final String packageName, final String volumeUuid, 23279 final int moveId, UserHandle user) throws PackageManagerException { 23280 final StorageManager storage = mContext.getSystemService(StorageManager.class); 23281 final PackageManager pm = mContext.getPackageManager(); 23282 23283 final boolean currentAsec; 23284 final String currentVolumeUuid; 23285 final File codeFile; 23286 final String installerPackageName; 23287 final String packageAbiOverride; 23288 final int appId; 23289 final String seinfo; 23290 final String label; 23291 final int targetSdkVersion; 23292 final PackageFreezer freezer; 23293 final int[] installedUserIds; 23294 23295 // reader 23296 synchronized (mPackages) { 23297 final PackageParser.Package pkg = mPackages.get(packageName); 23298 final PackageSetting ps = mSettings.mPackages.get(packageName); 23299 if (pkg == null || ps == null) { 23300 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 23301 } 23302 23303 if (pkg.applicationInfo.isSystemApp()) { 23304 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 23305 "Cannot move system application"); 23306 } 23307 23308 final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid); 23309 final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean( 23310 com.android.internal.R.bool.config_allow3rdPartyAppOnInternal); 23311 if (isInternalStorage && !allow3rdPartyOnInternal) { 23312 throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL, 23313 "3rd party apps are not allowed on internal storage"); 23314 } 23315 23316 if (pkg.applicationInfo.isExternalAsec()) { 23317 currentAsec = true; 23318 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 23319 } else if (pkg.applicationInfo.isForwardLocked()) { 23320 currentAsec = true; 23321 currentVolumeUuid = "forward_locked"; 23322 } else { 23323 currentAsec = false; 23324 currentVolumeUuid = ps.volumeUuid; 23325 23326 final File probe = new File(pkg.codePath); 23327 final File probeOat = new File(probe, "oat"); 23328 if (!probe.isDirectory() || !probeOat.isDirectory()) { 23329 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 23330 "Move only supported for modern cluster style installs"); 23331 } 23332 } 23333 23334 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 23335 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 23336 "Package already moved to " + volumeUuid); 23337 } 23338 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 23339 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 23340 "Device admin cannot be moved"); 23341 } 23342 23343 if (mFrozenPackages.contains(packageName)) { 23344 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 23345 "Failed to move already frozen package"); 23346 } 23347 23348 codeFile = new File(pkg.codePath); 23349 installerPackageName = ps.installerPackageName; 23350 packageAbiOverride = ps.cpuAbiOverrideString; 23351 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 23352 seinfo = pkg.applicationInfo.seInfo; 23353 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 23354 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 23355 freezer = freezePackage(packageName, "movePackageInternal"); 23356 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 23357 } 23358 23359 final Bundle extras = new Bundle(); 23360 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 23361 extras.putString(Intent.EXTRA_TITLE, label); 23362 mMoveCallbacks.notifyCreated(moveId, extras); 23363 23364 int installFlags; 23365 final boolean moveCompleteApp; 23366 final File measurePath; 23367 23368 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 23369 installFlags = INSTALL_INTERNAL; 23370 moveCompleteApp = !currentAsec; 23371 measurePath = Environment.getDataAppDirectory(volumeUuid); 23372 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 23373 installFlags = INSTALL_EXTERNAL; 23374 moveCompleteApp = false; 23375 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 23376 } else { 23377 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 23378 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 23379 || !volume.isMountedWritable()) { 23380 freezer.close(); 23381 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 23382 "Move location not mounted private volume"); 23383 } 23384 23385 Preconditions.checkState(!currentAsec); 23386 23387 installFlags = INSTALL_INTERNAL; 23388 moveCompleteApp = true; 23389 measurePath = Environment.getDataAppDirectory(volumeUuid); 23390 } 23391 23392 final PackageStats stats = new PackageStats(null, -1); 23393 synchronized (mInstaller) { 23394 for (int userId : installedUserIds) { 23395 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 23396 freezer.close(); 23397 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 23398 "Failed to measure package size"); 23399 } 23400 } 23401 } 23402 23403 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 23404 + stats.dataSize); 23405 23406 final long startFreeBytes = measurePath.getUsableSpace(); 23407 final long sizeBytes; 23408 if (moveCompleteApp) { 23409 sizeBytes = stats.codeSize + stats.dataSize; 23410 } else { 23411 sizeBytes = stats.codeSize; 23412 } 23413 23414 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 23415 freezer.close(); 23416 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 23417 "Not enough free space to move"); 23418 } 23419 23420 mMoveCallbacks.notifyStatusChanged(moveId, 10); 23421 23422 final CountDownLatch installedLatch = new CountDownLatch(1); 23423 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 23424 @Override 23425 public void onUserActionRequired(Intent intent) throws RemoteException { 23426 throw new IllegalStateException(); 23427 } 23428 23429 @Override 23430 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 23431 Bundle extras) throws RemoteException { 23432 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 23433 + PackageManager.installStatusToString(returnCode, msg)); 23434 23435 installedLatch.countDown(); 23436 freezer.close(); 23437 23438 final int status = PackageManager.installStatusToPublicStatus(returnCode); 23439 switch (status) { 23440 case PackageInstaller.STATUS_SUCCESS: 23441 mMoveCallbacks.notifyStatusChanged(moveId, 23442 PackageManager.MOVE_SUCCEEDED); 23443 break; 23444 case PackageInstaller.STATUS_FAILURE_STORAGE: 23445 mMoveCallbacks.notifyStatusChanged(moveId, 23446 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 23447 break; 23448 default: 23449 mMoveCallbacks.notifyStatusChanged(moveId, 23450 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 23451 break; 23452 } 23453 } 23454 }; 23455 23456 final MoveInfo move; 23457 if (moveCompleteApp) { 23458 // Kick off a thread to report progress estimates 23459 new Thread() { 23460 @Override 23461 public void run() { 23462 while (true) { 23463 try { 23464 if (installedLatch.await(1, TimeUnit.SECONDS)) { 23465 break; 23466 } 23467 } catch (InterruptedException ignored) { 23468 } 23469 23470 final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace(); 23471 final int progress = 10 + (int) MathUtils.constrain( 23472 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 23473 mMoveCallbacks.notifyStatusChanged(moveId, progress); 23474 } 23475 } 23476 }.start(); 23477 23478 final String dataAppName = codeFile.getName(); 23479 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 23480 dataAppName, appId, seinfo, targetSdkVersion); 23481 } else { 23482 move = null; 23483 } 23484 23485 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 23486 23487 final Message msg = mHandler.obtainMessage(INIT_COPY); 23488 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 23489 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 23490 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 23491 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/, 23492 PackageManager.INSTALL_REASON_UNKNOWN); 23493 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 23494 msg.obj = params; 23495 23496 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 23497 System.identityHashCode(msg.obj)); 23498 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 23499 System.identityHashCode(msg.obj)); 23500 23501 mHandler.sendMessage(msg); 23502 } 23503 23504 @Override 23505 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 23506 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 23507 23508 final int realMoveId = mNextMoveId.getAndIncrement(); 23509 final Bundle extras = new Bundle(); 23510 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 23511 mMoveCallbacks.notifyCreated(realMoveId, extras); 23512 23513 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 23514 @Override 23515 public void onCreated(int moveId, Bundle extras) { 23516 // Ignored 23517 } 23518 23519 @Override 23520 public void onStatusChanged(int moveId, int status, long estMillis) { 23521 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 23522 } 23523 }; 23524 23525 final StorageManager storage = mContext.getSystemService(StorageManager.class); 23526 storage.setPrimaryStorageUuid(volumeUuid, callback); 23527 return realMoveId; 23528 } 23529 23530 @Override 23531 public int getMoveStatus(int moveId) { 23532 mContext.enforceCallingOrSelfPermission( 23533 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 23534 return mMoveCallbacks.mLastStatus.get(moveId); 23535 } 23536 23537 @Override 23538 public void registerMoveCallback(IPackageMoveObserver callback) { 23539 mContext.enforceCallingOrSelfPermission( 23540 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 23541 mMoveCallbacks.register(callback); 23542 } 23543 23544 @Override 23545 public void unregisterMoveCallback(IPackageMoveObserver callback) { 23546 mContext.enforceCallingOrSelfPermission( 23547 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 23548 mMoveCallbacks.unregister(callback); 23549 } 23550 23551 @Override 23552 public boolean setInstallLocation(int loc) { 23553 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 23554 null); 23555 if (getInstallLocation() == loc) { 23556 return true; 23557 } 23558 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 23559 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 23560 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 23561 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 23562 return true; 23563 } 23564 return false; 23565 } 23566 23567 @Override 23568 public int getInstallLocation() { 23569 // allow instant app access 23570 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 23571 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 23572 PackageHelper.APP_INSTALL_AUTO); 23573 } 23574 23575 /** Called by UserManagerService */ 23576 void cleanUpUser(UserManagerService userManager, int userHandle) { 23577 synchronized (mPackages) { 23578 mDirtyUsers.remove(userHandle); 23579 mUserNeedsBadging.delete(userHandle); 23580 mSettings.removeUserLPw(userHandle); 23581 mPendingBroadcasts.remove(userHandle); 23582 mInstantAppRegistry.onUserRemovedLPw(userHandle); 23583 removeUnusedPackagesLPw(userManager, userHandle); 23584 } 23585 } 23586 23587 /** 23588 * We're removing userHandle and would like to remove any downloaded packages 23589 * that are no longer in use by any other user. 23590 * @param userHandle the user being removed 23591 */ 23592 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 23593 final boolean DEBUG_CLEAN_APKS = false; 23594 int [] users = userManager.getUserIds(); 23595 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 23596 while (psit.hasNext()) { 23597 PackageSetting ps = psit.next(); 23598 if (ps.pkg == null) { 23599 continue; 23600 } 23601 final String packageName = ps.pkg.packageName; 23602 // Skip over if system app 23603 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 23604 continue; 23605 } 23606 if (DEBUG_CLEAN_APKS) { 23607 Slog.i(TAG, "Checking package " + packageName); 23608 } 23609 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 23610 if (keep) { 23611 if (DEBUG_CLEAN_APKS) { 23612 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 23613 } 23614 } else { 23615 for (int i = 0; i < users.length; i++) { 23616 if (users[i] != userHandle && ps.getInstalled(users[i])) { 23617 keep = true; 23618 if (DEBUG_CLEAN_APKS) { 23619 Slog.i(TAG, " Keeping package " + packageName + " for user " 23620 + users[i]); 23621 } 23622 break; 23623 } 23624 } 23625 } 23626 if (!keep) { 23627 if (DEBUG_CLEAN_APKS) { 23628 Slog.i(TAG, " Removing package " + packageName); 23629 } 23630 mHandler.post(new Runnable() { 23631 public void run() { 23632 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 23633 userHandle, 0); 23634 } //end run 23635 }); 23636 } 23637 } 23638 } 23639 23640 /** Called by UserManagerService */ 23641 void createNewUser(int userId, String[] disallowedPackages) { 23642 synchronized (mInstallLock) { 23643 mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages); 23644 } 23645 synchronized (mPackages) { 23646 scheduleWritePackageRestrictionsLocked(userId); 23647 scheduleWritePackageListLocked(userId); 23648 applyFactoryDefaultBrowserLPw(userId); 23649 primeDomainVerificationsLPw(userId); 23650 } 23651 } 23652 23653 void onNewUserCreated(final int userId) { 23654 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 23655 // If permission review for legacy apps is required, we represent 23656 // dagerous permissions for such apps as always granted runtime 23657 // permissions to keep per user flag state whether review is needed. 23658 // Hence, if a new user is added we have to propagate dangerous 23659 // permission grants for these legacy apps. 23660 if (mPermissionReviewRequired) { 23661 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 23662 | UPDATE_PERMISSIONS_REPLACE_ALL); 23663 } 23664 } 23665 23666 @Override 23667 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 23668 mContext.enforceCallingOrSelfPermission( 23669 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 23670 "Only package verification agents can read the verifier device identity"); 23671 23672 synchronized (mPackages) { 23673 return mSettings.getVerifierDeviceIdentityLPw(); 23674 } 23675 } 23676 23677 @Override 23678 public void setPermissionEnforced(String permission, boolean enforced) { 23679 // TODO: Now that we no longer change GID for storage, this should to away. 23680 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 23681 "setPermissionEnforced"); 23682 if (READ_EXTERNAL_STORAGE.equals(permission)) { 23683 synchronized (mPackages) { 23684 if (mSettings.mReadExternalStorageEnforced == null 23685 || mSettings.mReadExternalStorageEnforced != enforced) { 23686 mSettings.mReadExternalStorageEnforced = enforced; 23687 mSettings.writeLPr(); 23688 } 23689 } 23690 // kill any non-foreground processes so we restart them and 23691 // grant/revoke the GID. 23692 final IActivityManager am = ActivityManager.getService(); 23693 if (am != null) { 23694 final long token = Binder.clearCallingIdentity(); 23695 try { 23696 am.killProcessesBelowForeground("setPermissionEnforcement"); 23697 } catch (RemoteException e) { 23698 } finally { 23699 Binder.restoreCallingIdentity(token); 23700 } 23701 } 23702 } else { 23703 throw new IllegalArgumentException("No selective enforcement for " + permission); 23704 } 23705 } 23706 23707 @Override 23708 @Deprecated 23709 public boolean isPermissionEnforced(String permission) { 23710 // allow instant applications 23711 return true; 23712 } 23713 23714 @Override 23715 public boolean isStorageLow() { 23716 // allow instant applications 23717 final long token = Binder.clearCallingIdentity(); 23718 try { 23719 final DeviceStorageMonitorInternal 23720 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 23721 if (dsm != null) { 23722 return dsm.isMemoryLow(); 23723 } else { 23724 return false; 23725 } 23726 } finally { 23727 Binder.restoreCallingIdentity(token); 23728 } 23729 } 23730 23731 @Override 23732 public IPackageInstaller getPackageInstaller() { 23733 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 23734 return null; 23735 } 23736 return mInstallerService; 23737 } 23738 23739 private boolean userNeedsBadging(int userId) { 23740 int index = mUserNeedsBadging.indexOfKey(userId); 23741 if (index < 0) { 23742 final UserInfo userInfo; 23743 final long token = Binder.clearCallingIdentity(); 23744 try { 23745 userInfo = sUserManager.getUserInfo(userId); 23746 } finally { 23747 Binder.restoreCallingIdentity(token); 23748 } 23749 final boolean b; 23750 if (userInfo != null && userInfo.isManagedProfile()) { 23751 b = true; 23752 } else { 23753 b = false; 23754 } 23755 mUserNeedsBadging.put(userId, b); 23756 return b; 23757 } 23758 return mUserNeedsBadging.valueAt(index); 23759 } 23760 23761 @Override 23762 public KeySet getKeySetByAlias(String packageName, String alias) { 23763 if (packageName == null || alias == null) { 23764 return null; 23765 } 23766 synchronized(mPackages) { 23767 final PackageParser.Package pkg = mPackages.get(packageName); 23768 if (pkg == null) { 23769 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 23770 throw new IllegalArgumentException("Unknown package: " + packageName); 23771 } 23772 KeySetManagerService ksms = mSettings.mKeySetManagerService; 23773 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 23774 } 23775 } 23776 23777 @Override 23778 public KeySet getSigningKeySet(String packageName) { 23779 if (packageName == null) { 23780 return null; 23781 } 23782 synchronized(mPackages) { 23783 final int callingUid = Binder.getCallingUid(); 23784 final int callingUserId = UserHandle.getUserId(callingUid); 23785 final PackageParser.Package pkg = mPackages.get(packageName); 23786 if (pkg == null) { 23787 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 23788 throw new IllegalArgumentException("Unknown package: " + packageName); 23789 } 23790 final PackageSetting ps = (PackageSetting) pkg.mExtras; 23791 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 23792 // filter and pretend the package doesn't exist 23793 Slog.w(TAG, "KeySet requested for filtered package: " + packageName 23794 + ", uid:" + callingUid); 23795 throw new IllegalArgumentException("Unknown package: " + packageName); 23796 } 23797 if (pkg.applicationInfo.uid != callingUid 23798 && Process.SYSTEM_UID != callingUid) { 23799 throw new SecurityException("May not access signing KeySet of other apps."); 23800 } 23801 KeySetManagerService ksms = mSettings.mKeySetManagerService; 23802 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 23803 } 23804 } 23805 23806 @Override 23807 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 23808 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 23809 return false; 23810 } 23811 if (packageName == null || ks == null) { 23812 return false; 23813 } 23814 synchronized(mPackages) { 23815 final PackageParser.Package pkg = mPackages.get(packageName); 23816 if (pkg == null) { 23817 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 23818 throw new IllegalArgumentException("Unknown package: " + packageName); 23819 } 23820 IBinder ksh = ks.getToken(); 23821 if (ksh instanceof KeySetHandle) { 23822 KeySetManagerService ksms = mSettings.mKeySetManagerService; 23823 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 23824 } 23825 return false; 23826 } 23827 } 23828 23829 @Override 23830 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 23831 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 23832 return false; 23833 } 23834 if (packageName == null || ks == null) { 23835 return false; 23836 } 23837 synchronized(mPackages) { 23838 final PackageParser.Package pkg = mPackages.get(packageName); 23839 if (pkg == null) { 23840 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 23841 throw new IllegalArgumentException("Unknown package: " + packageName); 23842 } 23843 IBinder ksh = ks.getToken(); 23844 if (ksh instanceof KeySetHandle) { 23845 KeySetManagerService ksms = mSettings.mKeySetManagerService; 23846 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 23847 } 23848 return false; 23849 } 23850 } 23851 23852 private void deletePackageIfUnusedLPr(final String packageName) { 23853 PackageSetting ps = mSettings.mPackages.get(packageName); 23854 if (ps == null) { 23855 return; 23856 } 23857 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 23858 // TODO Implement atomic delete if package is unused 23859 // It is currently possible that the package will be deleted even if it is installed 23860 // after this method returns. 23861 mHandler.post(new Runnable() { 23862 public void run() { 23863 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 23864 0, PackageManager.DELETE_ALL_USERS); 23865 } 23866 }); 23867 } 23868 } 23869 23870 /** 23871 * Check and throw if the given before/after packages would be considered a 23872 * downgrade. 23873 */ 23874 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 23875 throws PackageManagerException { 23876 if (after.versionCode < before.mVersionCode) { 23877 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 23878 "Update version code " + after.versionCode + " is older than current " 23879 + before.mVersionCode); 23880 } else if (after.versionCode == before.mVersionCode) { 23881 if (after.baseRevisionCode < before.baseRevisionCode) { 23882 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 23883 "Update base revision code " + after.baseRevisionCode 23884 + " is older than current " + before.baseRevisionCode); 23885 } 23886 23887 if (!ArrayUtils.isEmpty(after.splitNames)) { 23888 for (int i = 0; i < after.splitNames.length; i++) { 23889 final String splitName = after.splitNames[i]; 23890 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 23891 if (j != -1) { 23892 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 23893 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 23894 "Update split " + splitName + " revision code " 23895 + after.splitRevisionCodes[i] + " is older than current " 23896 + before.splitRevisionCodes[j]); 23897 } 23898 } 23899 } 23900 } 23901 } 23902 } 23903 23904 private static class MoveCallbacks extends Handler { 23905 private static final int MSG_CREATED = 1; 23906 private static final int MSG_STATUS_CHANGED = 2; 23907 23908 private final RemoteCallbackList<IPackageMoveObserver> 23909 mCallbacks = new RemoteCallbackList<>(); 23910 23911 private final SparseIntArray mLastStatus = new SparseIntArray(); 23912 23913 public MoveCallbacks(Looper looper) { 23914 super(looper); 23915 } 23916 23917 public void register(IPackageMoveObserver callback) { 23918 mCallbacks.register(callback); 23919 } 23920 23921 public void unregister(IPackageMoveObserver callback) { 23922 mCallbacks.unregister(callback); 23923 } 23924 23925 @Override 23926 public void handleMessage(Message msg) { 23927 final SomeArgs args = (SomeArgs) msg.obj; 23928 final int n = mCallbacks.beginBroadcast(); 23929 for (int i = 0; i < n; i++) { 23930 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 23931 try { 23932 invokeCallback(callback, msg.what, args); 23933 } catch (RemoteException ignored) { 23934 } 23935 } 23936 mCallbacks.finishBroadcast(); 23937 args.recycle(); 23938 } 23939 23940 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 23941 throws RemoteException { 23942 switch (what) { 23943 case MSG_CREATED: { 23944 callback.onCreated(args.argi1, (Bundle) args.arg2); 23945 break; 23946 } 23947 case MSG_STATUS_CHANGED: { 23948 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 23949 break; 23950 } 23951 } 23952 } 23953 23954 private void notifyCreated(int moveId, Bundle extras) { 23955 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 23956 23957 final SomeArgs args = SomeArgs.obtain(); 23958 args.argi1 = moveId; 23959 args.arg2 = extras; 23960 obtainMessage(MSG_CREATED, args).sendToTarget(); 23961 } 23962 23963 private void notifyStatusChanged(int moveId, int status) { 23964 notifyStatusChanged(moveId, status, -1); 23965 } 23966 23967 private void notifyStatusChanged(int moveId, int status, long estMillis) { 23968 Slog.v(TAG, "Move " + moveId + " status " + status); 23969 23970 final SomeArgs args = SomeArgs.obtain(); 23971 args.argi1 = moveId; 23972 args.argi2 = status; 23973 args.arg3 = estMillis; 23974 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 23975 23976 synchronized (mLastStatus) { 23977 mLastStatus.put(moveId, status); 23978 } 23979 } 23980 } 23981 23982 private final static class OnPermissionChangeListeners extends Handler { 23983 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 23984 23985 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 23986 new RemoteCallbackList<>(); 23987 23988 public OnPermissionChangeListeners(Looper looper) { 23989 super(looper); 23990 } 23991 23992 @Override 23993 public void handleMessage(Message msg) { 23994 switch (msg.what) { 23995 case MSG_ON_PERMISSIONS_CHANGED: { 23996 final int uid = msg.arg1; 23997 handleOnPermissionsChanged(uid); 23998 } break; 23999 } 24000 } 24001 24002 public void addListenerLocked(IOnPermissionsChangeListener listener) { 24003 mPermissionListeners.register(listener); 24004 24005 } 24006 24007 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 24008 mPermissionListeners.unregister(listener); 24009 } 24010 24011 public void onPermissionsChanged(int uid) { 24012 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 24013 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 24014 } 24015 } 24016 24017 private void handleOnPermissionsChanged(int uid) { 24018 final int count = mPermissionListeners.beginBroadcast(); 24019 try { 24020 for (int i = 0; i < count; i++) { 24021 IOnPermissionsChangeListener callback = mPermissionListeners 24022 .getBroadcastItem(i); 24023 try { 24024 callback.onPermissionsChanged(uid); 24025 } catch (RemoteException e) { 24026 Log.e(TAG, "Permission listener is dead", e); 24027 } 24028 } 24029 } finally { 24030 mPermissionListeners.finishBroadcast(); 24031 } 24032 } 24033 } 24034 24035 private class PackageManagerInternalImpl extends PackageManagerInternal { 24036 @Override 24037 public void setLocationPackagesProvider(PackagesProvider provider) { 24038 synchronized (mPackages) { 24039 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 24040 } 24041 } 24042 24043 @Override 24044 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 24045 synchronized (mPackages) { 24046 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 24047 } 24048 } 24049 24050 @Override 24051 public void setSmsAppPackagesProvider(PackagesProvider provider) { 24052 synchronized (mPackages) { 24053 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 24054 } 24055 } 24056 24057 @Override 24058 public void setDialerAppPackagesProvider(PackagesProvider provider) { 24059 synchronized (mPackages) { 24060 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 24061 } 24062 } 24063 24064 @Override 24065 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 24066 synchronized (mPackages) { 24067 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 24068 } 24069 } 24070 24071 @Override 24072 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 24073 synchronized (mPackages) { 24074 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 24075 } 24076 } 24077 24078 @Override 24079 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 24080 synchronized (mPackages) { 24081 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 24082 packageName, userId); 24083 } 24084 } 24085 24086 @Override 24087 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 24088 synchronized (mPackages) { 24089 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 24090 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 24091 packageName, userId); 24092 } 24093 } 24094 24095 @Override 24096 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 24097 synchronized (mPackages) { 24098 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 24099 packageName, userId); 24100 } 24101 } 24102 24103 @Override 24104 public void setKeepUninstalledPackages(final List<String> packageList) { 24105 Preconditions.checkNotNull(packageList); 24106 List<String> removedFromList = null; 24107 synchronized (mPackages) { 24108 if (mKeepUninstalledPackages != null) { 24109 final int packagesCount = mKeepUninstalledPackages.size(); 24110 for (int i = 0; i < packagesCount; i++) { 24111 String oldPackage = mKeepUninstalledPackages.get(i); 24112 if (packageList != null && packageList.contains(oldPackage)) { 24113 continue; 24114 } 24115 if (removedFromList == null) { 24116 removedFromList = new ArrayList<>(); 24117 } 24118 removedFromList.add(oldPackage); 24119 } 24120 } 24121 mKeepUninstalledPackages = new ArrayList<>(packageList); 24122 if (removedFromList != null) { 24123 final int removedCount = removedFromList.size(); 24124 for (int i = 0; i < removedCount; i++) { 24125 deletePackageIfUnusedLPr(removedFromList.get(i)); 24126 } 24127 } 24128 } 24129 } 24130 24131 @Override 24132 public boolean isPermissionsReviewRequired(String packageName, int userId) { 24133 synchronized (mPackages) { 24134 // If we do not support permission review, done. 24135 if (!mPermissionReviewRequired) { 24136 return false; 24137 } 24138 24139 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 24140 if (packageSetting == null) { 24141 return false; 24142 } 24143 24144 // Permission review applies only to apps not supporting the new permission model. 24145 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 24146 return false; 24147 } 24148 24149 // Legacy apps have the permission and get user consent on launch. 24150 PermissionsState permissionsState = packageSetting.getPermissionsState(); 24151 return permissionsState.isPermissionReviewRequired(userId); 24152 } 24153 } 24154 24155 @Override 24156 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 24157 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 24158 } 24159 24160 @Override 24161 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 24162 int userId) { 24163 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 24164 } 24165 24166 @Override 24167 public void setDeviceAndProfileOwnerPackages( 24168 int deviceOwnerUserId, String deviceOwnerPackage, 24169 SparseArray<String> profileOwnerPackages) { 24170 mProtectedPackages.setDeviceAndProfileOwnerPackages( 24171 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages); 24172 } 24173 24174 @Override 24175 public boolean isPackageDataProtected(int userId, String packageName) { 24176 return mProtectedPackages.isPackageDataProtected(userId, packageName); 24177 } 24178 24179 @Override 24180 public boolean isPackageEphemeral(int userId, String packageName) { 24181 synchronized (mPackages) { 24182 final PackageSetting ps = mSettings.mPackages.get(packageName); 24183 return ps != null ? ps.getInstantApp(userId) : false; 24184 } 24185 } 24186 24187 @Override 24188 public boolean wasPackageEverLaunched(String packageName, int userId) { 24189 synchronized (mPackages) { 24190 return mSettings.wasPackageEverLaunchedLPr(packageName, userId); 24191 } 24192 } 24193 24194 @Override 24195 public void grantRuntimePermission(String packageName, String name, int userId, 24196 boolean overridePolicy) { 24197 PackageManagerService.this.grantRuntimePermission(packageName, name, userId, 24198 overridePolicy); 24199 } 24200 24201 @Override 24202 public void revokeRuntimePermission(String packageName, String name, int userId, 24203 boolean overridePolicy) { 24204 PackageManagerService.this.revokeRuntimePermission(packageName, name, userId, 24205 overridePolicy); 24206 } 24207 24208 @Override 24209 public String getNameForUid(int uid) { 24210 return PackageManagerService.this.getNameForUid(uid); 24211 } 24212 24213 @Override 24214 public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj, 24215 Intent origIntent, String resolvedType, String callingPackage, 24216 Bundle verificationBundle, int userId) { 24217 PackageManagerService.this.requestInstantAppResolutionPhaseTwo( 24218 responseObj, origIntent, resolvedType, callingPackage, verificationBundle, 24219 userId); 24220 } 24221 24222 @Override 24223 public void grantEphemeralAccess(int userId, Intent intent, 24224 int targetAppId, int ephemeralAppId) { 24225 synchronized (mPackages) { 24226 mInstantAppRegistry.grantInstantAccessLPw(userId, intent, 24227 targetAppId, ephemeralAppId); 24228 } 24229 } 24230 24231 @Override 24232 public boolean isInstantAppInstallerComponent(ComponentName component) { 24233 synchronized (mPackages) { 24234 return mInstantAppInstallerActivity != null 24235 && mInstantAppInstallerActivity.getComponentName().equals(component); 24236 } 24237 } 24238 24239 @Override 24240 public void pruneInstantApps() { 24241 synchronized (mPackages) { 24242 mInstantAppRegistry.pruneInstantAppsLPw(); 24243 } 24244 } 24245 24246 @Override 24247 public String getSetupWizardPackageName() { 24248 return mSetupWizardPackage; 24249 } 24250 24251 public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) { 24252 if (policy != null) { 24253 mExternalSourcesPolicy = policy; 24254 } 24255 } 24256 24257 @Override 24258 public boolean isPackagePersistent(String packageName) { 24259 synchronized (mPackages) { 24260 PackageParser.Package pkg = mPackages.get(packageName); 24261 return pkg != null 24262 ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM 24263 | ApplicationInfo.FLAG_PERSISTENT)) == 24264 (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT)) 24265 : false; 24266 } 24267 } 24268 24269 @Override 24270 public List<PackageInfo> getOverlayPackages(int userId) { 24271 final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>(); 24272 synchronized (mPackages) { 24273 for (PackageParser.Package p : mPackages.values()) { 24274 if (p.mOverlayTarget != null) { 24275 PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId); 24276 if (pkg != null) { 24277 overlayPackages.add(pkg); 24278 } 24279 } 24280 } 24281 } 24282 return overlayPackages; 24283 } 24284 24285 @Override 24286 public List<String> getTargetPackageNames(int userId) { 24287 List<String> targetPackages = new ArrayList<>(); 24288 synchronized (mPackages) { 24289 for (PackageParser.Package p : mPackages.values()) { 24290 if (p.mOverlayTarget == null) { 24291 targetPackages.add(p.packageName); 24292 } 24293 } 24294 } 24295 return targetPackages; 24296 } 24297 24298 @Override 24299 public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName, 24300 @Nullable List<String> overlayPackageNames) { 24301 synchronized (mPackages) { 24302 if (targetPackageName == null || mPackages.get(targetPackageName) == null) { 24303 Slog.e(TAG, "failed to find package " + targetPackageName); 24304 return false; 24305 } 24306 24307 ArrayList<String> paths = null; 24308 if (overlayPackageNames != null) { 24309 final int N = overlayPackageNames.size(); 24310 paths = new ArrayList<>(N); 24311 for (int i = 0; i < N; i++) { 24312 final String packageName = overlayPackageNames.get(i); 24313 final PackageParser.Package pkg = mPackages.get(packageName); 24314 if (pkg == null) { 24315 Slog.e(TAG, "failed to find package " + packageName); 24316 return false; 24317 } 24318 paths.add(pkg.baseCodePath); 24319 } 24320 } 24321 24322 ArrayMap<String, ArrayList<String>> userSpecificOverlays = 24323 mEnabledOverlayPaths.get(userId); 24324 if (userSpecificOverlays == null) { 24325 userSpecificOverlays = new ArrayMap<>(); 24326 mEnabledOverlayPaths.put(userId, userSpecificOverlays); 24327 } 24328 24329 if (paths != null && paths.size() > 0) { 24330 userSpecificOverlays.put(targetPackageName, paths); 24331 } else { 24332 userSpecificOverlays.remove(targetPackageName); 24333 } 24334 return true; 24335 } 24336 } 24337 24338 @Override 24339 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 24340 int flags, int userId) { 24341 return resolveIntentInternal( 24342 intent, resolvedType, flags, userId, true /*resolveForStart*/); 24343 } 24344 24345 @Override 24346 public ResolveInfo resolveService(Intent intent, String resolvedType, 24347 int flags, int userId, int callingUid) { 24348 return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid); 24349 } 24350 24351 @Override 24352 public void addIsolatedUid(int isolatedUid, int ownerUid) { 24353 synchronized (mPackages) { 24354 mIsolatedOwners.put(isolatedUid, ownerUid); 24355 } 24356 } 24357 24358 @Override 24359 public void removeIsolatedUid(int isolatedUid) { 24360 synchronized (mPackages) { 24361 mIsolatedOwners.delete(isolatedUid); 24362 } 24363 } 24364 24365 @Override 24366 public int getUidTargetSdkVersion(int uid) { 24367 synchronized (mPackages) { 24368 return getUidTargetSdkVersionLockedLPr(uid); 24369 } 24370 } 24371 24372 @Override 24373 public boolean canAccessInstantApps(int callingUid) { 24374 return PackageManagerService.this.canAccessInstantApps(callingUid); 24375 } 24376 } 24377 24378 @Override 24379 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 24380 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 24381 synchronized (mPackages) { 24382 final long identity = Binder.clearCallingIdentity(); 24383 try { 24384 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 24385 packageNames, userId); 24386 } finally { 24387 Binder.restoreCallingIdentity(identity); 24388 } 24389 } 24390 } 24391 24392 @Override 24393 public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) { 24394 enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices"); 24395 synchronized (mPackages) { 24396 final long identity = Binder.clearCallingIdentity(); 24397 try { 24398 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr( 24399 packageNames, userId); 24400 } finally { 24401 Binder.restoreCallingIdentity(identity); 24402 } 24403 } 24404 } 24405 24406 private static void enforceSystemOrPhoneCaller(String tag) { 24407 int callingUid = Binder.getCallingUid(); 24408 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 24409 throw new SecurityException( 24410 "Cannot call " + tag + " from UID " + callingUid); 24411 } 24412 } 24413 24414 boolean isHistoricalPackageUsageAvailable() { 24415 return mPackageUsage.isHistoricalPackageUsageAvailable(); 24416 } 24417 24418 /** 24419 * Return a <b>copy</b> of the collection of packages known to the package manager. 24420 * @return A copy of the values of mPackages. 24421 */ 24422 Collection<PackageParser.Package> getPackages() { 24423 synchronized (mPackages) { 24424 return new ArrayList<>(mPackages.values()); 24425 } 24426 } 24427 24428 /** 24429 * Logs process start information (including base APK hash) to the security log. 24430 * @hide 24431 */ 24432 @Override 24433 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 24434 String apkFile, int pid) { 24435 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 24436 return; 24437 } 24438 if (!SecurityLog.isLoggingEnabled()) { 24439 return; 24440 } 24441 Bundle data = new Bundle(); 24442 data.putLong("startTimestamp", System.currentTimeMillis()); 24443 data.putString("processName", processName); 24444 data.putInt("uid", uid); 24445 data.putString("seinfo", seinfo); 24446 data.putString("apkFile", apkFile); 24447 data.putInt("pid", pid); 24448 Message msg = mProcessLoggingHandler.obtainMessage( 24449 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 24450 msg.setData(data); 24451 mProcessLoggingHandler.sendMessage(msg); 24452 } 24453 24454 public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) { 24455 return mCompilerStats.getPackageStats(pkgName); 24456 } 24457 24458 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) { 24459 return getOrCreateCompilerPackageStats(pkg.packageName); 24460 } 24461 24462 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) { 24463 return mCompilerStats.getOrCreatePackageStats(pkgName); 24464 } 24465 24466 public void deleteCompilerPackageStats(String pkgName) { 24467 mCompilerStats.deletePackageStats(pkgName); 24468 } 24469 24470 @Override 24471 public int getInstallReason(String packageName, int userId) { 24472 final int callingUid = Binder.getCallingUid(); 24473 enforceCrossUserPermission(callingUid, userId, 24474 true /* requireFullPermission */, false /* checkShell */, 24475 "get install reason"); 24476 synchronized (mPackages) { 24477 final PackageSetting ps = mSettings.mPackages.get(packageName); 24478 if (filterAppAccessLPr(ps, callingUid, userId)) { 24479 return PackageManager.INSTALL_REASON_UNKNOWN; 24480 } 24481 if (ps != null) { 24482 return ps.getInstallReason(userId); 24483 } 24484 } 24485 return PackageManager.INSTALL_REASON_UNKNOWN; 24486 } 24487 24488 @Override 24489 public boolean canRequestPackageInstalls(String packageName, int userId) { 24490 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 24491 return false; 24492 } 24493 return canRequestPackageInstallsInternal(packageName, 0, userId, 24494 true /* throwIfPermNotDeclared*/); 24495 } 24496 24497 private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId, 24498 boolean throwIfPermNotDeclared) { 24499 int callingUid = Binder.getCallingUid(); 24500 int uid = getPackageUid(packageName, 0, userId); 24501 if (callingUid != uid && callingUid != Process.ROOT_UID 24502 && callingUid != Process.SYSTEM_UID) { 24503 throw new SecurityException( 24504 "Caller uid " + callingUid + " does not own package " + packageName); 24505 } 24506 ApplicationInfo info = getApplicationInfo(packageName, flags, userId); 24507 if (info == null) { 24508 return false; 24509 } 24510 if (info.targetSdkVersion < Build.VERSION_CODES.O) { 24511 return false; 24512 } 24513 String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES; 24514 String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission); 24515 if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) { 24516 if (throwIfPermNotDeclared) { 24517 throw new SecurityException("Need to declare " + appOpPermission 24518 + " to call this api"); 24519 } else { 24520 Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api"); 24521 return false; 24522 } 24523 } 24524 if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) { 24525 return false; 24526 } 24527 if (mExternalSourcesPolicy != null) { 24528 int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid); 24529 if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) { 24530 return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED; 24531 } 24532 } 24533 return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED; 24534 } 24535 24536 @Override 24537 public ComponentName getInstantAppResolverSettingsComponent() { 24538 return mInstantAppResolverSettingsComponent; 24539 } 24540 24541 @Override 24542 public ComponentName getInstantAppInstallerComponent() { 24543 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 24544 return null; 24545 } 24546 return mInstantAppInstallerActivity == null 24547 ? null : mInstantAppInstallerActivity.getComponentName(); 24548 } 24549 24550 @Override 24551 public String getInstantAppAndroidId(String packageName, int userId) { 24552 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS, 24553 "getInstantAppAndroidId"); 24554 enforceCrossUserPermission(Binder.getCallingUid(), userId, 24555 true /* requireFullPermission */, false /* checkShell */, 24556 "getInstantAppAndroidId"); 24557 // Make sure the target is an Instant App. 24558 if (!isInstantApp(packageName, userId)) { 24559 return null; 24560 } 24561 synchronized (mPackages) { 24562 return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId); 24563 } 24564 } 24565} 24566 24567interface PackageSender { 24568 void sendPackageBroadcast(final String action, final String pkg, 24569 final Bundle extras, final int flags, final String targetPkg, 24570 final IIntentReceiver finishedReceiver, final int[] userIds); 24571 void sendPackageAddedForNewUsers(String packageName, boolean isSystem, 24572 int appId, int... userIds); 24573} 24574