PackageManagerService.java revision adb8c522a84b5c7531b009b7a8d4c854ca7dee08
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_SANDBOX_VERSION_DOWNGRADE; 52import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 53import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 54import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 55import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 56import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 57import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 58import static android.content.pm.PackageManager.INSTALL_INTERNAL; 59import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 60import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED; 61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK; 63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 65import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 66import static android.content.pm.PackageManager.MATCH_ALL; 67import static android.content.pm.PackageManager.MATCH_ANY_USER; 68import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 69import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE; 70import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE; 71import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS; 72import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY; 73import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES; 74import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY; 75import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES; 76import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL; 77import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN; 78import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 79import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 80import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 81import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 82import static android.content.pm.PackageManager.PERMISSION_DENIED; 83import static android.content.pm.PackageManager.PERMISSION_GRANTED; 84import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED; 85import static android.content.pm.PackageParser.isApkFile; 86import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 87import static android.system.OsConstants.O_CREAT; 88import static android.system.OsConstants.O_RDWR; 89import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 90import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 91import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 92import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 93import static com.android.internal.util.ArrayUtils.appendInt; 94import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 95import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 96import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 97import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 98import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 99import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason; 100import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter; 101import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 102import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 103import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 104import static dalvik.system.DexFile.getNonProfileGuidedCompilerFilter; 105 106import android.Manifest; 107import android.annotation.IntDef; 108import android.annotation.NonNull; 109import android.annotation.Nullable; 110import android.app.ActivityManager; 111import android.app.AppOpsManager; 112import android.app.IActivityManager; 113import android.app.ResourcesManager; 114import android.app.admin.IDevicePolicyManager; 115import android.app.admin.SecurityLog; 116import android.app.backup.IBackupManager; 117import android.content.BroadcastReceiver; 118import android.content.ComponentName; 119import android.content.ContentResolver; 120import android.content.Context; 121import android.content.IIntentReceiver; 122import android.content.Intent; 123import android.content.IntentFilter; 124import android.content.IntentSender; 125import android.content.IntentSender.SendIntentException; 126import android.content.ServiceConnection; 127import android.content.pm.ActivityInfo; 128import android.content.pm.ApplicationInfo; 129import android.content.pm.AppsQueryHelper; 130import android.content.pm.AuxiliaryResolveInfo; 131import android.content.pm.ChangedPackages; 132import android.content.pm.FallbackCategoryProvider; 133import android.content.pm.FeatureInfo; 134import android.content.pm.IOnPermissionsChangeListener; 135import android.content.pm.IPackageDataObserver; 136import android.content.pm.IPackageDeleteObserver; 137import android.content.pm.IPackageDeleteObserver2; 138import android.content.pm.IPackageInstallObserver2; 139import android.content.pm.IPackageInstaller; 140import android.content.pm.IPackageManager; 141import android.content.pm.IPackageMoveObserver; 142import android.content.pm.IPackageStatsObserver; 143import android.content.pm.InstantAppInfo; 144import android.content.pm.InstantAppRequest; 145import android.content.pm.InstantAppResolveInfo; 146import android.content.pm.InstrumentationInfo; 147import android.content.pm.IntentFilterVerificationInfo; 148import android.content.pm.KeySet; 149import android.content.pm.PackageCleanItem; 150import android.content.pm.PackageInfo; 151import android.content.pm.PackageInfoLite; 152import android.content.pm.PackageInstaller; 153import android.content.pm.PackageManager; 154import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 155import android.content.pm.PackageManagerInternal; 156import android.content.pm.PackageParser; 157import android.content.pm.PackageParser.ActivityIntentInfo; 158import android.content.pm.PackageParser.PackageLite; 159import android.content.pm.PackageParser.PackageParserException; 160import android.content.pm.PackageStats; 161import android.content.pm.PackageUserState; 162import android.content.pm.ParceledListSlice; 163import android.content.pm.PermissionGroupInfo; 164import android.content.pm.PermissionInfo; 165import android.content.pm.ProviderInfo; 166import android.content.pm.ResolveInfo; 167import android.content.pm.ServiceInfo; 168import android.content.pm.SharedLibraryInfo; 169import android.content.pm.Signature; 170import android.content.pm.UserInfo; 171import android.content.pm.VerifierDeviceIdentity; 172import android.content.pm.VerifierInfo; 173import android.content.pm.VersionedPackage; 174import android.content.res.Resources; 175import android.database.ContentObserver; 176import android.graphics.Bitmap; 177import android.hardware.display.DisplayManager; 178import android.net.Uri; 179import android.os.Binder; 180import android.os.Build; 181import android.os.Bundle; 182import android.os.Debug; 183import android.os.Environment; 184import android.os.Environment.UserEnvironment; 185import android.os.FileUtils; 186import android.os.Handler; 187import android.os.IBinder; 188import android.os.Looper; 189import android.os.Message; 190import android.os.Parcel; 191import android.os.ParcelFileDescriptor; 192import android.os.PatternMatcher; 193import android.os.Process; 194import android.os.RemoteCallbackList; 195import android.os.RemoteException; 196import android.os.ResultReceiver; 197import android.os.SELinux; 198import android.os.ServiceManager; 199import android.os.ShellCallback; 200import android.os.SystemClock; 201import android.os.SystemProperties; 202import android.os.Trace; 203import android.os.UserHandle; 204import android.os.UserManager; 205import android.os.UserManagerInternal; 206import android.os.storage.IStorageManager; 207import android.os.storage.StorageEventListener; 208import android.os.storage.StorageManager; 209import android.os.storage.StorageManagerInternal; 210import android.os.storage.VolumeInfo; 211import android.os.storage.VolumeRecord; 212import android.provider.Settings.Global; 213import android.provider.Settings.Secure; 214import android.security.KeyStore; 215import android.security.SystemKeyStore; 216import android.service.pm.PackageServiceDumpProto; 217import android.system.ErrnoException; 218import android.system.Os; 219import android.text.TextUtils; 220import android.text.format.DateUtils; 221import android.util.ArrayMap; 222import android.util.ArraySet; 223import android.util.Base64; 224import android.util.BootTimingsTraceLog; 225import android.util.DisplayMetrics; 226import android.util.EventLog; 227import android.util.ExceptionUtils; 228import android.util.Log; 229import android.util.LogPrinter; 230import android.util.MathUtils; 231import android.util.PackageUtils; 232import android.util.Pair; 233import android.util.PrintStreamPrinter; 234import android.util.Slog; 235import android.util.SparseArray; 236import android.util.SparseBooleanArray; 237import android.util.SparseIntArray; 238import android.util.Xml; 239import android.util.jar.StrictJarFile; 240import android.util.proto.ProtoOutputStream; 241import android.view.Display; 242 243import com.android.internal.R; 244import com.android.internal.annotations.GuardedBy; 245import com.android.internal.app.IMediaContainerService; 246import com.android.internal.app.ResolverActivity; 247import com.android.internal.content.NativeLibraryHelper; 248import com.android.internal.content.PackageHelper; 249import com.android.internal.logging.MetricsLogger; 250import com.android.internal.logging.nano.MetricsProto.MetricsEvent; 251import com.android.internal.os.IParcelFileDescriptorFactory; 252import com.android.internal.os.RoSystemProperties; 253import com.android.internal.os.SomeArgs; 254import com.android.internal.os.Zygote; 255import com.android.internal.telephony.CarrierAppUtils; 256import com.android.internal.util.ArrayUtils; 257import com.android.internal.util.ConcurrentUtils; 258import com.android.internal.util.DumpUtils; 259import com.android.internal.util.FastPrintWriter; 260import com.android.internal.util.FastXmlSerializer; 261import com.android.internal.util.IndentingPrintWriter; 262import com.android.internal.util.Preconditions; 263import com.android.internal.util.XmlUtils; 264import com.android.server.AttributeCache; 265import com.android.server.DeviceIdleController; 266import com.android.server.EventLogTags; 267import com.android.server.FgThread; 268import com.android.server.IntentResolver; 269import com.android.server.LocalServices; 270import com.android.server.LockGuard; 271import com.android.server.ServiceThread; 272import com.android.server.SystemConfig; 273import com.android.server.SystemServerInitThreadPool; 274import com.android.server.Watchdog; 275import com.android.server.net.NetworkPolicyManagerInternal; 276import com.android.server.pm.Installer.InstallerException; 277import com.android.server.pm.PermissionsState.PermissionState; 278import com.android.server.pm.Settings.DatabaseVersion; 279import com.android.server.pm.Settings.VersionInfo; 280import com.android.server.pm.dex.DexManager; 281import com.android.server.storage.DeviceStorageMonitorInternal; 282 283import dalvik.system.CloseGuard; 284import dalvik.system.DexFile; 285import dalvik.system.VMRuntime; 286 287import libcore.io.IoUtils; 288import libcore.util.EmptyArray; 289 290import org.xmlpull.v1.XmlPullParser; 291import org.xmlpull.v1.XmlPullParserException; 292import org.xmlpull.v1.XmlSerializer; 293 294import java.io.BufferedOutputStream; 295import java.io.BufferedReader; 296import java.io.ByteArrayInputStream; 297import java.io.ByteArrayOutputStream; 298import java.io.File; 299import java.io.FileDescriptor; 300import java.io.FileInputStream; 301import java.io.FileOutputStream; 302import java.io.FileReader; 303import java.io.FilenameFilter; 304import java.io.IOException; 305import java.io.PrintWriter; 306import java.lang.annotation.Retention; 307import java.lang.annotation.RetentionPolicy; 308import java.nio.charset.StandardCharsets; 309import java.security.DigestInputStream; 310import java.security.MessageDigest; 311import java.security.NoSuchAlgorithmException; 312import java.security.PublicKey; 313import java.security.SecureRandom; 314import java.security.cert.Certificate; 315import java.security.cert.CertificateEncodingException; 316import java.security.cert.CertificateException; 317import java.text.SimpleDateFormat; 318import java.util.ArrayList; 319import java.util.Arrays; 320import java.util.Collection; 321import java.util.Collections; 322import java.util.Comparator; 323import java.util.Date; 324import java.util.HashMap; 325import java.util.HashSet; 326import java.util.Iterator; 327import java.util.List; 328import java.util.Map; 329import java.util.Objects; 330import java.util.Set; 331import java.util.concurrent.CountDownLatch; 332import java.util.concurrent.Future; 333import java.util.concurrent.TimeUnit; 334import java.util.concurrent.atomic.AtomicBoolean; 335import java.util.concurrent.atomic.AtomicInteger; 336 337/** 338 * Keep track of all those APKs everywhere. 339 * <p> 340 * Internally there are two important locks: 341 * <ul> 342 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 343 * and other related state. It is a fine-grained lock that should only be held 344 * momentarily, as it's one of the most contended locks in the system. 345 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 346 * operations typically involve heavy lifting of application data on disk. Since 347 * {@code installd} is single-threaded, and it's operations can often be slow, 348 * this lock should never be acquired while already holding {@link #mPackages}. 349 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 350 * holding {@link #mInstallLock}. 351 * </ul> 352 * Many internal methods rely on the caller to hold the appropriate locks, and 353 * this contract is expressed through method name suffixes: 354 * <ul> 355 * <li>fooLI(): the caller must hold {@link #mInstallLock} 356 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 357 * being modified must be frozen 358 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 359 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 360 * </ul> 361 * <p> 362 * Because this class is very central to the platform's security; please run all 363 * CTS and unit tests whenever making modifications: 364 * 365 * <pre> 366 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 367 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases 368 * </pre> 369 */ 370public class PackageManagerService extends IPackageManager.Stub 371 implements PackageSender { 372 static final String TAG = "PackageManager"; 373 static final boolean DEBUG_SETTINGS = false; 374 static final boolean DEBUG_PREFERRED = false; 375 static final boolean DEBUG_UPGRADE = false; 376 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 377 private static final boolean DEBUG_BACKUP = false; 378 private static final boolean DEBUG_INSTALL = false; 379 private static final boolean DEBUG_REMOVE = false; 380 private static final boolean DEBUG_BROADCASTS = false; 381 private static final boolean DEBUG_SHOW_INFO = false; 382 private static final boolean DEBUG_PACKAGE_INFO = false; 383 private static final boolean DEBUG_INTENT_MATCHING = false; 384 private static final boolean DEBUG_PACKAGE_SCANNING = false; 385 private static final boolean DEBUG_VERIFY = false; 386 private static final boolean DEBUG_FILTERS = false; 387 private static final boolean DEBUG_PERMISSIONS = false; 388 private static final boolean DEBUG_SHARED_LIBRARIES = false; 389 390 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 391 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 392 // user, but by default initialize to this. 393 public static final boolean DEBUG_DEXOPT = false; 394 395 private static final boolean DEBUG_ABI_SELECTION = false; 396 private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE; 397 private static final boolean DEBUG_TRIAGED_MISSING = false; 398 private static final boolean DEBUG_APP_DATA = false; 399 400 /** REMOVE. According to Svet, this was only used to reset permissions during development. */ 401 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 402 403 private static final boolean HIDE_EPHEMERAL_APIS = false; 404 405 private static final boolean ENABLE_FREE_CACHE_V2 = 406 SystemProperties.getBoolean("fw.free_cache_v2", true); 407 408 private static final int RADIO_UID = Process.PHONE_UID; 409 private static final int LOG_UID = Process.LOG_UID; 410 private static final int NFC_UID = Process.NFC_UID; 411 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 412 private static final int SHELL_UID = Process.SHELL_UID; 413 414 // Cap the size of permission trees that 3rd party apps can define 415 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 416 417 // Suffix used during package installation when copying/moving 418 // package apks to install directory. 419 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 420 421 static final int SCAN_NO_DEX = 1<<1; 422 static final int SCAN_FORCE_DEX = 1<<2; 423 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 424 static final int SCAN_NEW_INSTALL = 1<<4; 425 static final int SCAN_UPDATE_TIME = 1<<5; 426 static final int SCAN_BOOTING = 1<<6; 427 static final int SCAN_TRUSTED_OVERLAY = 1<<7; 428 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8; 429 static final int SCAN_REPLACING = 1<<9; 430 static final int SCAN_REQUIRE_KNOWN = 1<<10; 431 static final int SCAN_MOVE = 1<<11; 432 static final int SCAN_INITIAL = 1<<12; 433 static final int SCAN_CHECK_ONLY = 1<<13; 434 static final int SCAN_DONT_KILL_APP = 1<<14; 435 static final int SCAN_IGNORE_FROZEN = 1<<15; 436 static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16; 437 static final int SCAN_AS_INSTANT_APP = 1<<17; 438 static final int SCAN_AS_FULL_APP = 1<<18; 439 /** Should not be with the scan flags */ 440 static final int FLAGS_REMOVE_CHATTY = 1<<31; 441 442 private static final String STATIC_SHARED_LIB_DELIMITER = "_"; 443 444 private static final int[] EMPTY_INT_ARRAY = new int[0]; 445 446 private static final int TYPE_UNKNOWN = 0; 447 private static final int TYPE_ACTIVITY = 1; 448 private static final int TYPE_RECEIVER = 2; 449 private static final int TYPE_SERVICE = 3; 450 private static final int TYPE_PROVIDER = 4; 451 @IntDef(prefix = { "TYPE_" }, value = { 452 TYPE_UNKNOWN, 453 TYPE_ACTIVITY, 454 TYPE_RECEIVER, 455 TYPE_SERVICE, 456 TYPE_PROVIDER, 457 }) 458 @Retention(RetentionPolicy.SOURCE) 459 public @interface ComponentType {} 460 461 /** 462 * Timeout (in milliseconds) after which the watchdog should declare that 463 * our handler thread is wedged. The usual default for such things is one 464 * minute but we sometimes do very lengthy I/O operations on this thread, 465 * such as installing multi-gigabyte applications, so ours needs to be longer. 466 */ 467 static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 468 469 /** 470 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 471 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 472 * settings entry if available, otherwise we use the hardcoded default. If it's been 473 * more than this long since the last fstrim, we force one during the boot sequence. 474 * 475 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 476 * one gets run at the next available charging+idle time. This final mandatory 477 * no-fstrim check kicks in only of the other scheduling criteria is never met. 478 */ 479 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 480 481 /** 482 * Whether verification is enabled by default. 483 */ 484 private static final boolean DEFAULT_VERIFY_ENABLE = true; 485 486 /** 487 * The default maximum time to wait for the verification agent to return in 488 * milliseconds. 489 */ 490 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 491 492 /** 493 * The default response for package verification timeout. 494 * 495 * This can be either PackageManager.VERIFICATION_ALLOW or 496 * PackageManager.VERIFICATION_REJECT. 497 */ 498 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 499 500 static final String PLATFORM_PACKAGE_NAME = "android"; 501 502 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 503 504 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 505 DEFAULT_CONTAINER_PACKAGE, 506 "com.android.defcontainer.DefaultContainerService"); 507 508 private static final String KILL_APP_REASON_GIDS_CHANGED = 509 "permission grant or revoke changed gids"; 510 511 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 512 "permissions revoked"; 513 514 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 515 516 private static final String PACKAGE_SCHEME = "package"; 517 518 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 519 520 /** Permission grant: not grant the permission. */ 521 private static final int GRANT_DENIED = 1; 522 523 /** Permission grant: grant the permission as an install permission. */ 524 private static final int GRANT_INSTALL = 2; 525 526 /** Permission grant: grant the permission as a runtime one. */ 527 private static final int GRANT_RUNTIME = 3; 528 529 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 530 private static final int GRANT_UPGRADE = 4; 531 532 /** Canonical intent used to identify what counts as a "web browser" app */ 533 private static final Intent sBrowserIntent; 534 static { 535 sBrowserIntent = new Intent(); 536 sBrowserIntent.setAction(Intent.ACTION_VIEW); 537 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 538 sBrowserIntent.setData(Uri.parse("http:")); 539 } 540 541 /** 542 * The set of all protected actions [i.e. those actions for which a high priority 543 * intent filter is disallowed]. 544 */ 545 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 546 static { 547 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 548 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 549 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 550 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 551 } 552 553 // Compilation reasons. 554 public static final int REASON_FIRST_BOOT = 0; 555 public static final int REASON_BOOT = 1; 556 public static final int REASON_INSTALL = 2; 557 public static final int REASON_BACKGROUND_DEXOPT = 3; 558 public static final int REASON_AB_OTA = 4; 559 560 public static final int REASON_LAST = REASON_AB_OTA; 561 562 /** All dangerous permission names in the same order as the events in MetricsEvent */ 563 private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList( 564 Manifest.permission.READ_CALENDAR, 565 Manifest.permission.WRITE_CALENDAR, 566 Manifest.permission.CAMERA, 567 Manifest.permission.READ_CONTACTS, 568 Manifest.permission.WRITE_CONTACTS, 569 Manifest.permission.GET_ACCOUNTS, 570 Manifest.permission.ACCESS_FINE_LOCATION, 571 Manifest.permission.ACCESS_COARSE_LOCATION, 572 Manifest.permission.RECORD_AUDIO, 573 Manifest.permission.READ_PHONE_STATE, 574 Manifest.permission.CALL_PHONE, 575 Manifest.permission.READ_CALL_LOG, 576 Manifest.permission.WRITE_CALL_LOG, 577 Manifest.permission.ADD_VOICEMAIL, 578 Manifest.permission.USE_SIP, 579 Manifest.permission.PROCESS_OUTGOING_CALLS, 580 Manifest.permission.READ_CELL_BROADCASTS, 581 Manifest.permission.BODY_SENSORS, 582 Manifest.permission.SEND_SMS, 583 Manifest.permission.RECEIVE_SMS, 584 Manifest.permission.READ_SMS, 585 Manifest.permission.RECEIVE_WAP_PUSH, 586 Manifest.permission.RECEIVE_MMS, 587 Manifest.permission.READ_EXTERNAL_STORAGE, 588 Manifest.permission.WRITE_EXTERNAL_STORAGE, 589 Manifest.permission.READ_PHONE_NUMBERS, 590 Manifest.permission.ANSWER_PHONE_CALLS); 591 592 593 /** 594 * Version number for the package parser cache. Increment this whenever the format or 595 * extent of cached data changes. See {@code PackageParser#setCacheDir}. 596 */ 597 private static final String PACKAGE_PARSER_CACHE_VERSION = "1"; 598 599 /** 600 * Whether the package parser cache is enabled. 601 */ 602 private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true; 603 604 final ServiceThread mHandlerThread; 605 606 final PackageHandler mHandler; 607 608 private final ProcessLoggingHandler mProcessLoggingHandler; 609 610 /** 611 * Messages for {@link #mHandler} that need to wait for system ready before 612 * being dispatched. 613 */ 614 private ArrayList<Message> mPostSystemReadyMessages; 615 616 final int mSdkVersion = Build.VERSION.SDK_INT; 617 618 final Context mContext; 619 final boolean mFactoryTest; 620 final boolean mOnlyCore; 621 final DisplayMetrics mMetrics; 622 final int mDefParseFlags; 623 final String[] mSeparateProcesses; 624 final boolean mIsUpgrade; 625 final boolean mIsPreNUpgrade; 626 final boolean mIsPreNMR1Upgrade; 627 628 // Have we told the Activity Manager to whitelist the default container service by uid yet? 629 @GuardedBy("mPackages") 630 boolean mDefaultContainerWhitelisted = false; 631 632 @GuardedBy("mPackages") 633 private boolean mDexOptDialogShown; 634 635 /** The location for ASEC container files on internal storage. */ 636 final String mAsecInternalPath; 637 638 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 639 // LOCK HELD. Can be called with mInstallLock held. 640 @GuardedBy("mInstallLock") 641 final Installer mInstaller; 642 643 /** Directory where installed third-party apps stored */ 644 final File mAppInstallDir; 645 646 /** 647 * Directory to which applications installed internally have their 648 * 32 bit native libraries copied. 649 */ 650 private File mAppLib32InstallDir; 651 652 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 653 // apps. 654 final File mDrmAppPrivateInstallDir; 655 656 // ---------------------------------------------------------------- 657 658 // Lock for state used when installing and doing other long running 659 // operations. Methods that must be called with this lock held have 660 // the suffix "LI". 661 final Object mInstallLock = new Object(); 662 663 // ---------------------------------------------------------------- 664 665 // Keys are String (package name), values are Package. This also serves 666 // as the lock for the global state. Methods that must be called with 667 // this lock held have the prefix "LP". 668 @GuardedBy("mPackages") 669 final ArrayMap<String, PackageParser.Package> mPackages = 670 new ArrayMap<String, PackageParser.Package>(); 671 672 final ArrayMap<String, Set<String>> mKnownCodebase = 673 new ArrayMap<String, Set<String>>(); 674 675 // Keys are isolated uids and values are the uid of the application 676 // that created the isolated proccess. 677 @GuardedBy("mPackages") 678 final SparseIntArray mIsolatedOwners = new SparseIntArray(); 679 680 /** 681 * Tracks new system packages [received in an OTA] that we expect to 682 * find updated user-installed versions. Keys are package name, values 683 * are package location. 684 */ 685 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 686 /** 687 * Tracks high priority intent filters for protected actions. During boot, certain 688 * filter actions are protected and should never be allowed to have a high priority 689 * intent filter for them. However, there is one, and only one exception -- the 690 * setup wizard. It must be able to define a high priority intent filter for these 691 * actions to ensure there are no escapes from the wizard. We need to delay processing 692 * of these during boot as we need to look at all of the system packages in order 693 * to know which component is the setup wizard. 694 */ 695 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 696 /** 697 * Whether or not processing protected filters should be deferred. 698 */ 699 private boolean mDeferProtectedFilters = true; 700 701 /** 702 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 703 */ 704 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 705 /** 706 * Whether or not system app permissions should be promoted from install to runtime. 707 */ 708 boolean mPromoteSystemApps; 709 710 @GuardedBy("mPackages") 711 final Settings mSettings; 712 713 /** 714 * Set of package names that are currently "frozen", which means active 715 * surgery is being done on the code/data for that package. The platform 716 * will refuse to launch frozen packages to avoid race conditions. 717 * 718 * @see PackageFreezer 719 */ 720 @GuardedBy("mPackages") 721 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 722 723 final ProtectedPackages mProtectedPackages; 724 725 boolean mFirstBoot; 726 727 PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy; 728 729 // System configuration read by SystemConfig. 730 final int[] mGlobalGids; 731 final SparseArray<ArraySet<String>> mSystemPermissions; 732 @GuardedBy("mAvailableFeatures") 733 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 734 735 // If mac_permissions.xml was found for seinfo labeling. 736 boolean mFoundPolicyFile; 737 738 private final InstantAppRegistry mInstantAppRegistry; 739 740 @GuardedBy("mPackages") 741 int mChangedPackagesSequenceNumber; 742 /** 743 * List of changed [installed, removed or updated] packages. 744 * mapping from user id -> sequence number -> package name 745 */ 746 @GuardedBy("mPackages") 747 final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>(); 748 /** 749 * The sequence number of the last change to a package. 750 * mapping from user id -> package name -> sequence number 751 */ 752 @GuardedBy("mPackages") 753 final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>(); 754 755 class PackageParserCallback implements PackageParser.Callback { 756 @Override public final boolean hasFeature(String feature) { 757 return PackageManagerService.this.hasSystemFeature(feature, 0); 758 } 759 760 final List<PackageParser.Package> getStaticOverlayPackagesLocked( 761 Collection<PackageParser.Package> allPackages, String targetPackageName) { 762 List<PackageParser.Package> overlayPackages = null; 763 for (PackageParser.Package p : allPackages) { 764 if (targetPackageName.equals(p.mOverlayTarget) && p.mIsStaticOverlay) { 765 if (overlayPackages == null) { 766 overlayPackages = new ArrayList<PackageParser.Package>(); 767 } 768 overlayPackages.add(p); 769 } 770 } 771 if (overlayPackages != null) { 772 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 773 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 774 return p1.mOverlayPriority - p2.mOverlayPriority; 775 } 776 }; 777 Collections.sort(overlayPackages, cmp); 778 } 779 return overlayPackages; 780 } 781 782 final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages, 783 String targetPackageName, String targetPath) { 784 if ("android".equals(targetPackageName)) { 785 // Static RROs targeting to "android", ie framework-res.apk, are already applied by 786 // native AssetManager. 787 return null; 788 } 789 List<PackageParser.Package> overlayPackages = 790 getStaticOverlayPackagesLocked(allPackages, targetPackageName); 791 if (overlayPackages == null || overlayPackages.isEmpty()) { 792 return null; 793 } 794 List<String> overlayPathList = null; 795 for (PackageParser.Package overlayPackage : overlayPackages) { 796 if (targetPath == null) { 797 if (overlayPathList == null) { 798 overlayPathList = new ArrayList<String>(); 799 } 800 overlayPathList.add(overlayPackage.baseCodePath); 801 continue; 802 } 803 804 try { 805 // Creates idmaps for system to parse correctly the Android manifest of the 806 // target package. 807 // 808 // OverlayManagerService will update each of them with a correct gid from its 809 // target package app id. 810 mInstaller.idmap(targetPath, overlayPackage.baseCodePath, 811 UserHandle.getSharedAppGid( 812 UserHandle.getUserGid(UserHandle.USER_SYSTEM))); 813 if (overlayPathList == null) { 814 overlayPathList = new ArrayList<String>(); 815 } 816 overlayPathList.add(overlayPackage.baseCodePath); 817 } catch (InstallerException e) { 818 Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " + 819 overlayPackage.baseCodePath); 820 } 821 } 822 return overlayPathList == null ? null : overlayPathList.toArray(new String[0]); 823 } 824 825 String[] getStaticOverlayPaths(String targetPackageName, String targetPath) { 826 synchronized (mPackages) { 827 return getStaticOverlayPathsLocked( 828 mPackages.values(), targetPackageName, targetPath); 829 } 830 } 831 832 @Override public final String[] getOverlayApks(String targetPackageName) { 833 return getStaticOverlayPaths(targetPackageName, null); 834 } 835 836 @Override public final String[] getOverlayPaths(String targetPackageName, 837 String targetPath) { 838 return getStaticOverlayPaths(targetPackageName, targetPath); 839 } 840 }; 841 842 class ParallelPackageParserCallback extends PackageParserCallback { 843 List<PackageParser.Package> mOverlayPackages = null; 844 845 void findStaticOverlayPackages() { 846 synchronized (mPackages) { 847 for (PackageParser.Package p : mPackages.values()) { 848 if (p.mIsStaticOverlay) { 849 if (mOverlayPackages == null) { 850 mOverlayPackages = new ArrayList<PackageParser.Package>(); 851 } 852 mOverlayPackages.add(p); 853 } 854 } 855 } 856 } 857 858 @Override 859 synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) { 860 // We can trust mOverlayPackages without holding mPackages because package uninstall 861 // can't happen while running parallel parsing. 862 // Moreover holding mPackages on each parsing thread causes dead-lock. 863 return mOverlayPackages == null ? null : 864 getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath); 865 } 866 } 867 868 final PackageParser.Callback mPackageParserCallback = new PackageParserCallback(); 869 final ParallelPackageParserCallback mParallelPackageParserCallback = 870 new ParallelPackageParserCallback(); 871 872 public static final class SharedLibraryEntry { 873 public final @Nullable String path; 874 public final @Nullable String apk; 875 public final @NonNull SharedLibraryInfo info; 876 877 SharedLibraryEntry(String _path, String _apk, String name, int version, int type, 878 String declaringPackageName, int declaringPackageVersionCode) { 879 path = _path; 880 apk = _apk; 881 info = new SharedLibraryInfo(name, version, type, new VersionedPackage( 882 declaringPackageName, declaringPackageVersionCode), null); 883 } 884 } 885 886 // Currently known shared libraries. 887 final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>(); 888 final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage = 889 new ArrayMap<>(); 890 891 // All available activities, for your resolving pleasure. 892 final ActivityIntentResolver mActivities = 893 new ActivityIntentResolver(); 894 895 // All available receivers, for your resolving pleasure. 896 final ActivityIntentResolver mReceivers = 897 new ActivityIntentResolver(); 898 899 // All available services, for your resolving pleasure. 900 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 901 902 // All available providers, for your resolving pleasure. 903 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 904 905 // Mapping from provider base names (first directory in content URI codePath) 906 // to the provider information. 907 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 908 new ArrayMap<String, PackageParser.Provider>(); 909 910 // Mapping from instrumentation class names to info about them. 911 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 912 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 913 914 // Mapping from permission names to info about them. 915 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 916 new ArrayMap<String, PackageParser.PermissionGroup>(); 917 918 // Packages whose data we have transfered into another package, thus 919 // should no longer exist. 920 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 921 922 // Broadcast actions that are only available to the system. 923 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 924 925 /** List of packages waiting for verification. */ 926 final SparseArray<PackageVerificationState> mPendingVerification 927 = new SparseArray<PackageVerificationState>(); 928 929 /** Set of packages associated with each app op permission. */ 930 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 931 932 final PackageInstallerService mInstallerService; 933 934 private final PackageDexOptimizer mPackageDexOptimizer; 935 // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package 936 // is used by other apps). 937 private final DexManager mDexManager; 938 939 private AtomicInteger mNextMoveId = new AtomicInteger(); 940 private final MoveCallbacks mMoveCallbacks; 941 942 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 943 944 // Cache of users who need badging. 945 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 946 947 /** Token for keys in mPendingVerification. */ 948 private int mPendingVerificationToken = 0; 949 950 volatile boolean mSystemReady; 951 volatile boolean mSafeMode; 952 volatile boolean mHasSystemUidErrors; 953 private volatile boolean mEphemeralAppsDisabled; 954 955 ApplicationInfo mAndroidApplication; 956 final ActivityInfo mResolveActivity = new ActivityInfo(); 957 final ResolveInfo mResolveInfo = new ResolveInfo(); 958 ComponentName mResolveComponentName; 959 PackageParser.Package mPlatformPackage; 960 ComponentName mCustomResolverComponentName; 961 962 boolean mResolverReplaced = false; 963 964 private final @Nullable ComponentName mIntentFilterVerifierComponent; 965 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 966 967 private int mIntentFilterVerificationToken = 0; 968 969 /** The service connection to the ephemeral resolver */ 970 final EphemeralResolverConnection mInstantAppResolverConnection; 971 /** Component used to show resolver settings for Instant Apps */ 972 final ComponentName mInstantAppResolverSettingsComponent; 973 974 /** Activity used to install instant applications */ 975 ActivityInfo mInstantAppInstallerActivity; 976 final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo(); 977 978 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 979 = new SparseArray<IntentFilterVerificationState>(); 980 981 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy; 982 983 // List of packages names to keep cached, even if they are uninstalled for all users 984 private List<String> mKeepUninstalledPackages; 985 986 private UserManagerInternal mUserManagerInternal; 987 988 private DeviceIdleController.LocalService mDeviceIdleController; 989 990 private File mCacheDir; 991 992 private ArraySet<String> mPrivappPermissionsViolations; 993 994 private Future<?> mPrepareAppDataFuture; 995 996 private static class IFVerificationParams { 997 PackageParser.Package pkg; 998 boolean replacing; 999 int userId; 1000 int verifierUid; 1001 1002 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 1003 int _userId, int _verifierUid) { 1004 pkg = _pkg; 1005 replacing = _replacing; 1006 userId = _userId; 1007 replacing = _replacing; 1008 verifierUid = _verifierUid; 1009 } 1010 } 1011 1012 private interface IntentFilterVerifier<T extends IntentFilter> { 1013 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 1014 T filter, String packageName); 1015 void startVerifications(int userId); 1016 void receiveVerificationResponse(int verificationId); 1017 } 1018 1019 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 1020 private Context mContext; 1021 private ComponentName mIntentFilterVerifierComponent; 1022 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 1023 1024 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 1025 mContext = context; 1026 mIntentFilterVerifierComponent = verifierComponent; 1027 } 1028 1029 private String getDefaultScheme() { 1030 return IntentFilter.SCHEME_HTTPS; 1031 } 1032 1033 @Override 1034 public void startVerifications(int userId) { 1035 // Launch verifications requests 1036 int count = mCurrentIntentFilterVerifications.size(); 1037 for (int n=0; n<count; n++) { 1038 int verificationId = mCurrentIntentFilterVerifications.get(n); 1039 final IntentFilterVerificationState ivs = 1040 mIntentFilterVerificationStates.get(verificationId); 1041 1042 String packageName = ivs.getPackageName(); 1043 1044 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 1045 final int filterCount = filters.size(); 1046 ArraySet<String> domainsSet = new ArraySet<>(); 1047 for (int m=0; m<filterCount; m++) { 1048 PackageParser.ActivityIntentInfo filter = filters.get(m); 1049 domainsSet.addAll(filter.getHostsList()); 1050 } 1051 synchronized (mPackages) { 1052 if (mSettings.createIntentFilterVerificationIfNeededLPw( 1053 packageName, domainsSet) != null) { 1054 scheduleWriteSettingsLocked(); 1055 } 1056 } 1057 sendVerificationRequest(userId, verificationId, ivs); 1058 } 1059 mCurrentIntentFilterVerifications.clear(); 1060 } 1061 1062 private void sendVerificationRequest(int userId, int verificationId, 1063 IntentFilterVerificationState ivs) { 1064 1065 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 1066 verificationIntent.putExtra( 1067 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 1068 verificationId); 1069 verificationIntent.putExtra( 1070 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 1071 getDefaultScheme()); 1072 verificationIntent.putExtra( 1073 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 1074 ivs.getHostsString()); 1075 verificationIntent.putExtra( 1076 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 1077 ivs.getPackageName()); 1078 verificationIntent.setComponent(mIntentFilterVerifierComponent); 1079 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 1080 1081 DeviceIdleController.LocalService idleController = getDeviceIdleController(); 1082 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 1083 mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(), 1084 userId, false, "intent filter verifier"); 1085 1086 UserHandle user = new UserHandle(userId); 1087 mContext.sendBroadcastAsUser(verificationIntent, user); 1088 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1089 "Sending IntentFilter verification broadcast"); 1090 } 1091 1092 public void receiveVerificationResponse(int verificationId) { 1093 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 1094 1095 final boolean verified = ivs.isVerified(); 1096 1097 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 1098 final int count = filters.size(); 1099 if (DEBUG_DOMAIN_VERIFICATION) { 1100 Slog.i(TAG, "Received verification response " + verificationId 1101 + " for " + count + " filters, verified=" + verified); 1102 } 1103 for (int n=0; n<count; n++) { 1104 PackageParser.ActivityIntentInfo filter = filters.get(n); 1105 filter.setVerified(verified); 1106 1107 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 1108 + " verified with result:" + verified + " and hosts:" 1109 + ivs.getHostsString()); 1110 } 1111 1112 mIntentFilterVerificationStates.remove(verificationId); 1113 1114 final String packageName = ivs.getPackageName(); 1115 IntentFilterVerificationInfo ivi = null; 1116 1117 synchronized (mPackages) { 1118 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 1119 } 1120 if (ivi == null) { 1121 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 1122 + verificationId + " packageName:" + packageName); 1123 return; 1124 } 1125 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1126 "Updating IntentFilterVerificationInfo for package " + packageName 1127 +" verificationId:" + verificationId); 1128 1129 synchronized (mPackages) { 1130 if (verified) { 1131 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 1132 } else { 1133 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 1134 } 1135 scheduleWriteSettingsLocked(); 1136 1137 final int userId = ivs.getUserId(); 1138 if (userId != UserHandle.USER_ALL) { 1139 final int userStatus = 1140 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 1141 1142 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 1143 boolean needUpdate = false; 1144 1145 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 1146 // already been set by the User thru the Disambiguation dialog 1147 switch (userStatus) { 1148 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 1149 if (verified) { 1150 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 1151 } else { 1152 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 1153 } 1154 needUpdate = true; 1155 break; 1156 1157 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 1158 if (verified) { 1159 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 1160 needUpdate = true; 1161 } 1162 break; 1163 1164 default: 1165 // Nothing to do 1166 } 1167 1168 if (needUpdate) { 1169 mSettings.updateIntentFilterVerificationStatusLPw( 1170 packageName, updatedStatus, userId); 1171 scheduleWritePackageRestrictionsLocked(userId); 1172 } 1173 } 1174 } 1175 } 1176 1177 @Override 1178 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 1179 ActivityIntentInfo filter, String packageName) { 1180 if (!hasValidDomains(filter)) { 1181 return false; 1182 } 1183 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 1184 if (ivs == null) { 1185 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 1186 packageName); 1187 } 1188 if (DEBUG_DOMAIN_VERIFICATION) { 1189 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 1190 } 1191 ivs.addFilter(filter); 1192 return true; 1193 } 1194 1195 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 1196 int userId, int verificationId, String packageName) { 1197 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 1198 verifierUid, userId, packageName); 1199 ivs.setPendingState(); 1200 synchronized (mPackages) { 1201 mIntentFilterVerificationStates.append(verificationId, ivs); 1202 mCurrentIntentFilterVerifications.add(verificationId); 1203 } 1204 return ivs; 1205 } 1206 } 1207 1208 private static boolean hasValidDomains(ActivityIntentInfo filter) { 1209 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 1210 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 1211 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 1212 } 1213 1214 // Set of pending broadcasts for aggregating enable/disable of components. 1215 static class PendingPackageBroadcasts { 1216 // for each user id, a map of <package name -> components within that package> 1217 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 1218 1219 public PendingPackageBroadcasts() { 1220 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 1221 } 1222 1223 public ArrayList<String> get(int userId, String packageName) { 1224 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1225 return packages.get(packageName); 1226 } 1227 1228 public void put(int userId, String packageName, ArrayList<String> components) { 1229 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1230 packages.put(packageName, components); 1231 } 1232 1233 public void remove(int userId, String packageName) { 1234 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 1235 if (packages != null) { 1236 packages.remove(packageName); 1237 } 1238 } 1239 1240 public void remove(int userId) { 1241 mUidMap.remove(userId); 1242 } 1243 1244 public int userIdCount() { 1245 return mUidMap.size(); 1246 } 1247 1248 public int userIdAt(int n) { 1249 return mUidMap.keyAt(n); 1250 } 1251 1252 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 1253 return mUidMap.get(userId); 1254 } 1255 1256 public int size() { 1257 // total number of pending broadcast entries across all userIds 1258 int num = 0; 1259 for (int i = 0; i< mUidMap.size(); i++) { 1260 num += mUidMap.valueAt(i).size(); 1261 } 1262 return num; 1263 } 1264 1265 public void clear() { 1266 mUidMap.clear(); 1267 } 1268 1269 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1270 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1271 if (map == null) { 1272 map = new ArrayMap<String, ArrayList<String>>(); 1273 mUidMap.put(userId, map); 1274 } 1275 return map; 1276 } 1277 } 1278 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1279 1280 // Service Connection to remote media container service to copy 1281 // package uri's from external media onto secure containers 1282 // or internal storage. 1283 private IMediaContainerService mContainerService = null; 1284 1285 static final int SEND_PENDING_BROADCAST = 1; 1286 static final int MCS_BOUND = 3; 1287 static final int END_COPY = 4; 1288 static final int INIT_COPY = 5; 1289 static final int MCS_UNBIND = 6; 1290 static final int START_CLEANING_PACKAGE = 7; 1291 static final int FIND_INSTALL_LOC = 8; 1292 static final int POST_INSTALL = 9; 1293 static final int MCS_RECONNECT = 10; 1294 static final int MCS_GIVE_UP = 11; 1295 static final int UPDATED_MEDIA_STATUS = 12; 1296 static final int WRITE_SETTINGS = 13; 1297 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1298 static final int PACKAGE_VERIFIED = 15; 1299 static final int CHECK_PENDING_VERIFICATION = 16; 1300 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1301 static final int INTENT_FILTER_VERIFIED = 18; 1302 static final int WRITE_PACKAGE_LIST = 19; 1303 static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20; 1304 1305 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1306 1307 // Delay time in millisecs 1308 static final int BROADCAST_DELAY = 10 * 1000; 1309 1310 private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD = 1311 2 * 60 * 60 * 1000L; /* two hours */ 1312 1313 static UserManagerService sUserManager; 1314 1315 // Stores a list of users whose package restrictions file needs to be updated 1316 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1317 1318 final private DefaultContainerConnection mDefContainerConn = 1319 new DefaultContainerConnection(); 1320 class DefaultContainerConnection implements ServiceConnection { 1321 public void onServiceConnected(ComponentName name, IBinder service) { 1322 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1323 final IMediaContainerService imcs = IMediaContainerService.Stub 1324 .asInterface(Binder.allowBlocking(service)); 1325 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1326 } 1327 1328 public void onServiceDisconnected(ComponentName name) { 1329 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1330 } 1331 } 1332 1333 // Recordkeeping of restore-after-install operations that are currently in flight 1334 // between the Package Manager and the Backup Manager 1335 static class PostInstallData { 1336 public InstallArgs args; 1337 public PackageInstalledInfo res; 1338 1339 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1340 args = _a; 1341 res = _r; 1342 } 1343 } 1344 1345 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1346 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1347 1348 // XML tags for backup/restore of various bits of state 1349 private static final String TAG_PREFERRED_BACKUP = "pa"; 1350 private static final String TAG_DEFAULT_APPS = "da"; 1351 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1352 1353 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1354 private static final String TAG_ALL_GRANTS = "rt-grants"; 1355 private static final String TAG_GRANT = "grant"; 1356 private static final String ATTR_PACKAGE_NAME = "pkg"; 1357 1358 private static final String TAG_PERMISSION = "perm"; 1359 private static final String ATTR_PERMISSION_NAME = "name"; 1360 private static final String ATTR_IS_GRANTED = "g"; 1361 private static final String ATTR_USER_SET = "set"; 1362 private static final String ATTR_USER_FIXED = "fixed"; 1363 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1364 1365 // System/policy permission grants are not backed up 1366 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1367 FLAG_PERMISSION_POLICY_FIXED 1368 | FLAG_PERMISSION_SYSTEM_FIXED 1369 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1370 1371 // And we back up these user-adjusted states 1372 private static final int USER_RUNTIME_GRANT_MASK = 1373 FLAG_PERMISSION_USER_SET 1374 | FLAG_PERMISSION_USER_FIXED 1375 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1376 1377 final @Nullable String mRequiredVerifierPackage; 1378 final @NonNull String mRequiredInstallerPackage; 1379 final @NonNull String mRequiredUninstallerPackage; 1380 final @Nullable String mSetupWizardPackage; 1381 final @Nullable String mStorageManagerPackage; 1382 final @NonNull String mServicesSystemSharedLibraryPackageName; 1383 final @NonNull String mSharedSystemSharedLibraryPackageName; 1384 1385 final boolean mPermissionReviewRequired; 1386 1387 private final PackageUsage mPackageUsage = new PackageUsage(); 1388 private final CompilerStats mCompilerStats = new CompilerStats(); 1389 1390 class PackageHandler extends Handler { 1391 private boolean mBound = false; 1392 final ArrayList<HandlerParams> mPendingInstalls = 1393 new ArrayList<HandlerParams>(); 1394 1395 private boolean connectToService() { 1396 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1397 " DefaultContainerService"); 1398 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1399 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1400 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1401 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1402 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1403 mBound = true; 1404 return true; 1405 } 1406 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1407 return false; 1408 } 1409 1410 private void disconnectService() { 1411 mContainerService = null; 1412 mBound = false; 1413 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1414 mContext.unbindService(mDefContainerConn); 1415 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1416 } 1417 1418 PackageHandler(Looper looper) { 1419 super(looper); 1420 } 1421 1422 public void handleMessage(Message msg) { 1423 try { 1424 doHandleMessage(msg); 1425 } finally { 1426 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1427 } 1428 } 1429 1430 void doHandleMessage(Message msg) { 1431 switch (msg.what) { 1432 case INIT_COPY: { 1433 HandlerParams params = (HandlerParams) msg.obj; 1434 int idx = mPendingInstalls.size(); 1435 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1436 // If a bind was already initiated we dont really 1437 // need to do anything. The pending install 1438 // will be processed later on. 1439 if (!mBound) { 1440 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1441 System.identityHashCode(mHandler)); 1442 // If this is the only one pending we might 1443 // have to bind to the service again. 1444 if (!connectToService()) { 1445 Slog.e(TAG, "Failed to bind to media container service"); 1446 params.serviceError(); 1447 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1448 System.identityHashCode(mHandler)); 1449 if (params.traceMethod != null) { 1450 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1451 params.traceCookie); 1452 } 1453 return; 1454 } else { 1455 // Once we bind to the service, the first 1456 // pending request will be processed. 1457 mPendingInstalls.add(idx, params); 1458 } 1459 } else { 1460 mPendingInstalls.add(idx, params); 1461 // Already bound to the service. Just make 1462 // sure we trigger off processing the first request. 1463 if (idx == 0) { 1464 mHandler.sendEmptyMessage(MCS_BOUND); 1465 } 1466 } 1467 break; 1468 } 1469 case MCS_BOUND: { 1470 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1471 if (msg.obj != null) { 1472 mContainerService = (IMediaContainerService) msg.obj; 1473 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1474 System.identityHashCode(mHandler)); 1475 } 1476 if (mContainerService == null) { 1477 if (!mBound) { 1478 // Something seriously wrong since we are not bound and we are not 1479 // waiting for connection. Bail out. 1480 Slog.e(TAG, "Cannot bind to media container service"); 1481 for (HandlerParams params : mPendingInstalls) { 1482 // Indicate service bind error 1483 params.serviceError(); 1484 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1485 System.identityHashCode(params)); 1486 if (params.traceMethod != null) { 1487 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1488 params.traceMethod, params.traceCookie); 1489 } 1490 return; 1491 } 1492 mPendingInstalls.clear(); 1493 } else { 1494 Slog.w(TAG, "Waiting to connect to media container service"); 1495 } 1496 } else if (mPendingInstalls.size() > 0) { 1497 HandlerParams params = mPendingInstalls.get(0); 1498 if (params != null) { 1499 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1500 System.identityHashCode(params)); 1501 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1502 if (params.startCopy()) { 1503 // We are done... look for more work or to 1504 // go idle. 1505 if (DEBUG_SD_INSTALL) Log.i(TAG, 1506 "Checking for more work or unbind..."); 1507 // Delete pending install 1508 if (mPendingInstalls.size() > 0) { 1509 mPendingInstalls.remove(0); 1510 } 1511 if (mPendingInstalls.size() == 0) { 1512 if (mBound) { 1513 if (DEBUG_SD_INSTALL) Log.i(TAG, 1514 "Posting delayed MCS_UNBIND"); 1515 removeMessages(MCS_UNBIND); 1516 Message ubmsg = obtainMessage(MCS_UNBIND); 1517 // Unbind after a little delay, to avoid 1518 // continual thrashing. 1519 sendMessageDelayed(ubmsg, 10000); 1520 } 1521 } else { 1522 // There are more pending requests in queue. 1523 // Just post MCS_BOUND message to trigger processing 1524 // of next pending install. 1525 if (DEBUG_SD_INSTALL) Log.i(TAG, 1526 "Posting MCS_BOUND for next work"); 1527 mHandler.sendEmptyMessage(MCS_BOUND); 1528 } 1529 } 1530 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1531 } 1532 } else { 1533 // Should never happen ideally. 1534 Slog.w(TAG, "Empty queue"); 1535 } 1536 break; 1537 } 1538 case MCS_RECONNECT: { 1539 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1540 if (mPendingInstalls.size() > 0) { 1541 if (mBound) { 1542 disconnectService(); 1543 } 1544 if (!connectToService()) { 1545 Slog.e(TAG, "Failed to bind to media container service"); 1546 for (HandlerParams params : mPendingInstalls) { 1547 // Indicate service bind error 1548 params.serviceError(); 1549 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1550 System.identityHashCode(params)); 1551 } 1552 mPendingInstalls.clear(); 1553 } 1554 } 1555 break; 1556 } 1557 case MCS_UNBIND: { 1558 // If there is no actual work left, then time to unbind. 1559 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1560 1561 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1562 if (mBound) { 1563 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1564 1565 disconnectService(); 1566 } 1567 } else if (mPendingInstalls.size() > 0) { 1568 // There are more pending requests in queue. 1569 // Just post MCS_BOUND message to trigger processing 1570 // of next pending install. 1571 mHandler.sendEmptyMessage(MCS_BOUND); 1572 } 1573 1574 break; 1575 } 1576 case MCS_GIVE_UP: { 1577 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1578 HandlerParams params = mPendingInstalls.remove(0); 1579 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1580 System.identityHashCode(params)); 1581 break; 1582 } 1583 case SEND_PENDING_BROADCAST: { 1584 String packages[]; 1585 ArrayList<String> components[]; 1586 int size = 0; 1587 int uids[]; 1588 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1589 synchronized (mPackages) { 1590 if (mPendingBroadcasts == null) { 1591 return; 1592 } 1593 size = mPendingBroadcasts.size(); 1594 if (size <= 0) { 1595 // Nothing to be done. Just return 1596 return; 1597 } 1598 packages = new String[size]; 1599 components = new ArrayList[size]; 1600 uids = new int[size]; 1601 int i = 0; // filling out the above arrays 1602 1603 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1604 int packageUserId = mPendingBroadcasts.userIdAt(n); 1605 Iterator<Map.Entry<String, ArrayList<String>>> it 1606 = mPendingBroadcasts.packagesForUserId(packageUserId) 1607 .entrySet().iterator(); 1608 while (it.hasNext() && i < size) { 1609 Map.Entry<String, ArrayList<String>> ent = it.next(); 1610 packages[i] = ent.getKey(); 1611 components[i] = ent.getValue(); 1612 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1613 uids[i] = (ps != null) 1614 ? UserHandle.getUid(packageUserId, ps.appId) 1615 : -1; 1616 i++; 1617 } 1618 } 1619 size = i; 1620 mPendingBroadcasts.clear(); 1621 } 1622 // Send broadcasts 1623 for (int i = 0; i < size; i++) { 1624 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1625 } 1626 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1627 break; 1628 } 1629 case START_CLEANING_PACKAGE: { 1630 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1631 final String packageName = (String)msg.obj; 1632 final int userId = msg.arg1; 1633 final boolean andCode = msg.arg2 != 0; 1634 synchronized (mPackages) { 1635 if (userId == UserHandle.USER_ALL) { 1636 int[] users = sUserManager.getUserIds(); 1637 for (int user : users) { 1638 mSettings.addPackageToCleanLPw( 1639 new PackageCleanItem(user, packageName, andCode)); 1640 } 1641 } else { 1642 mSettings.addPackageToCleanLPw( 1643 new PackageCleanItem(userId, packageName, andCode)); 1644 } 1645 } 1646 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1647 startCleaningPackages(); 1648 } break; 1649 case POST_INSTALL: { 1650 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1651 1652 PostInstallData data = mRunningInstalls.get(msg.arg1); 1653 final boolean didRestore = (msg.arg2 != 0); 1654 mRunningInstalls.delete(msg.arg1); 1655 1656 if (data != null) { 1657 InstallArgs args = data.args; 1658 PackageInstalledInfo parentRes = data.res; 1659 1660 final boolean grantPermissions = (args.installFlags 1661 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1662 final boolean killApp = (args.installFlags 1663 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1664 final String[] grantedPermissions = args.installGrantPermissions; 1665 1666 // Handle the parent package 1667 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1668 grantedPermissions, didRestore, args.installerPackageName, 1669 args.observer); 1670 1671 // Handle the child packages 1672 final int childCount = (parentRes.addedChildPackages != null) 1673 ? parentRes.addedChildPackages.size() : 0; 1674 for (int i = 0; i < childCount; i++) { 1675 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1676 handlePackagePostInstall(childRes, grantPermissions, killApp, 1677 grantedPermissions, false, args.installerPackageName, 1678 args.observer); 1679 } 1680 1681 // Log tracing if needed 1682 if (args.traceMethod != null) { 1683 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1684 args.traceCookie); 1685 } 1686 } else { 1687 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1688 } 1689 1690 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1691 } break; 1692 case UPDATED_MEDIA_STATUS: { 1693 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1694 boolean reportStatus = msg.arg1 == 1; 1695 boolean doGc = msg.arg2 == 1; 1696 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1697 if (doGc) { 1698 // Force a gc to clear up stale containers. 1699 Runtime.getRuntime().gc(); 1700 } 1701 if (msg.obj != null) { 1702 @SuppressWarnings("unchecked") 1703 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1704 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1705 // Unload containers 1706 unloadAllContainers(args); 1707 } 1708 if (reportStatus) { 1709 try { 1710 if (DEBUG_SD_INSTALL) Log.i(TAG, 1711 "Invoking StorageManagerService call back"); 1712 PackageHelper.getStorageManager().finishMediaUpdate(); 1713 } catch (RemoteException e) { 1714 Log.e(TAG, "StorageManagerService not running?"); 1715 } 1716 } 1717 } break; 1718 case WRITE_SETTINGS: { 1719 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1720 synchronized (mPackages) { 1721 removeMessages(WRITE_SETTINGS); 1722 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1723 mSettings.writeLPr(); 1724 mDirtyUsers.clear(); 1725 } 1726 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1727 } break; 1728 case WRITE_PACKAGE_RESTRICTIONS: { 1729 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1730 synchronized (mPackages) { 1731 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1732 for (int userId : mDirtyUsers) { 1733 mSettings.writePackageRestrictionsLPr(userId); 1734 } 1735 mDirtyUsers.clear(); 1736 } 1737 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1738 } break; 1739 case WRITE_PACKAGE_LIST: { 1740 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1741 synchronized (mPackages) { 1742 removeMessages(WRITE_PACKAGE_LIST); 1743 mSettings.writePackageListLPr(msg.arg1); 1744 } 1745 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1746 } break; 1747 case CHECK_PENDING_VERIFICATION: { 1748 final int verificationId = msg.arg1; 1749 final PackageVerificationState state = mPendingVerification.get(verificationId); 1750 1751 if ((state != null) && !state.timeoutExtended()) { 1752 final InstallArgs args = state.getInstallArgs(); 1753 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1754 1755 Slog.i(TAG, "Verification timed out for " + originUri); 1756 mPendingVerification.remove(verificationId); 1757 1758 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1759 1760 final UserHandle user = args.getUser(); 1761 if (getDefaultVerificationResponse(user) 1762 == PackageManager.VERIFICATION_ALLOW) { 1763 Slog.i(TAG, "Continuing with installation of " + originUri); 1764 state.setVerifierResponse(Binder.getCallingUid(), 1765 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1766 broadcastPackageVerified(verificationId, originUri, 1767 PackageManager.VERIFICATION_ALLOW, user); 1768 try { 1769 ret = args.copyApk(mContainerService, true); 1770 } catch (RemoteException e) { 1771 Slog.e(TAG, "Could not contact the ContainerService"); 1772 } 1773 } else { 1774 broadcastPackageVerified(verificationId, originUri, 1775 PackageManager.VERIFICATION_REJECT, user); 1776 } 1777 1778 Trace.asyncTraceEnd( 1779 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1780 1781 processPendingInstall(args, ret); 1782 mHandler.sendEmptyMessage(MCS_UNBIND); 1783 } 1784 break; 1785 } 1786 case PACKAGE_VERIFIED: { 1787 final int verificationId = msg.arg1; 1788 1789 final PackageVerificationState state = mPendingVerification.get(verificationId); 1790 if (state == null) { 1791 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1792 break; 1793 } 1794 1795 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1796 1797 state.setVerifierResponse(response.callerUid, response.code); 1798 1799 if (state.isVerificationComplete()) { 1800 mPendingVerification.remove(verificationId); 1801 1802 final InstallArgs args = state.getInstallArgs(); 1803 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1804 1805 int ret; 1806 if (state.isInstallAllowed()) { 1807 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1808 broadcastPackageVerified(verificationId, originUri, 1809 response.code, state.getInstallArgs().getUser()); 1810 try { 1811 ret = args.copyApk(mContainerService, true); 1812 } catch (RemoteException e) { 1813 Slog.e(TAG, "Could not contact the ContainerService"); 1814 } 1815 } else { 1816 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1817 } 1818 1819 Trace.asyncTraceEnd( 1820 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1821 1822 processPendingInstall(args, ret); 1823 mHandler.sendEmptyMessage(MCS_UNBIND); 1824 } 1825 1826 break; 1827 } 1828 case START_INTENT_FILTER_VERIFICATIONS: { 1829 IFVerificationParams params = (IFVerificationParams) msg.obj; 1830 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1831 params.replacing, params.pkg); 1832 break; 1833 } 1834 case INTENT_FILTER_VERIFIED: { 1835 final int verificationId = msg.arg1; 1836 1837 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1838 verificationId); 1839 if (state == null) { 1840 Slog.w(TAG, "Invalid IntentFilter verification token " 1841 + verificationId + " received"); 1842 break; 1843 } 1844 1845 final int userId = state.getUserId(); 1846 1847 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1848 "Processing IntentFilter verification with token:" 1849 + verificationId + " and userId:" + userId); 1850 1851 final IntentFilterVerificationResponse response = 1852 (IntentFilterVerificationResponse) msg.obj; 1853 1854 state.setVerifierResponse(response.callerUid, response.code); 1855 1856 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1857 "IntentFilter verification with token:" + verificationId 1858 + " and userId:" + userId 1859 + " is settings verifier response with response code:" 1860 + response.code); 1861 1862 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1863 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1864 + response.getFailedDomainsString()); 1865 } 1866 1867 if (state.isVerificationComplete()) { 1868 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1869 } else { 1870 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1871 "IntentFilter verification with token:" + verificationId 1872 + " was not said to be complete"); 1873 } 1874 1875 break; 1876 } 1877 case INSTANT_APP_RESOLUTION_PHASE_TWO: { 1878 InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext, 1879 mInstantAppResolverConnection, 1880 (InstantAppRequest) msg.obj, 1881 mInstantAppInstallerActivity, 1882 mHandler); 1883 } 1884 } 1885 } 1886 } 1887 1888 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1889 boolean killApp, String[] grantedPermissions, 1890 boolean launchedForRestore, String installerPackage, 1891 IPackageInstallObserver2 installObserver) { 1892 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1893 // Send the removed broadcasts 1894 if (res.removedInfo != null) { 1895 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1896 } 1897 1898 // Now that we successfully installed the package, grant runtime 1899 // permissions if requested before broadcasting the install. Also 1900 // for legacy apps in permission review mode we clear the permission 1901 // review flag which is used to emulate runtime permissions for 1902 // legacy apps. 1903 if (grantPermissions) { 1904 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1905 } 1906 1907 final boolean update = res.removedInfo != null 1908 && res.removedInfo.removedPackage != null; 1909 final String origInstallerPackageName = res.removedInfo != null 1910 ? res.removedInfo.installerPackageName : null; 1911 1912 // If this is the first time we have child packages for a disabled privileged 1913 // app that had no children, we grant requested runtime permissions to the new 1914 // children if the parent on the system image had them already granted. 1915 if (res.pkg.parentPackage != null) { 1916 synchronized (mPackages) { 1917 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1918 } 1919 } 1920 1921 synchronized (mPackages) { 1922 mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers); 1923 } 1924 1925 final String packageName = res.pkg.applicationInfo.packageName; 1926 1927 // Determine the set of users who are adding this package for 1928 // the first time vs. those who are seeing an update. 1929 int[] firstUsers = EMPTY_INT_ARRAY; 1930 int[] updateUsers = EMPTY_INT_ARRAY; 1931 final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0; 1932 final PackageSetting ps = (PackageSetting) res.pkg.mExtras; 1933 for (int newUser : res.newUsers) { 1934 if (ps.getInstantApp(newUser)) { 1935 continue; 1936 } 1937 if (allNewUsers) { 1938 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1939 continue; 1940 } 1941 boolean isNew = true; 1942 for (int origUser : res.origUsers) { 1943 if (origUser == newUser) { 1944 isNew = false; 1945 break; 1946 } 1947 } 1948 if (isNew) { 1949 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1950 } else { 1951 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1952 } 1953 } 1954 1955 // Send installed broadcasts if the package is not a static shared lib. 1956 if (res.pkg.staticSharedLibName == null) { 1957 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1958 1959 // Send added for users that see the package for the first time 1960 // sendPackageAddedForNewUsers also deals with system apps 1961 int appId = UserHandle.getAppId(res.uid); 1962 boolean isSystem = res.pkg.applicationInfo.isSystemApp(); 1963 sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers); 1964 1965 // Send added for users that don't see the package for the first time 1966 Bundle extras = new Bundle(1); 1967 extras.putInt(Intent.EXTRA_UID, res.uid); 1968 if (update) { 1969 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1970 } 1971 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1972 extras, 0 /*flags*/, 1973 null /*targetPackage*/, null /*finishedReceiver*/, updateUsers); 1974 if (origInstallerPackageName != null) { 1975 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1976 extras, 0 /*flags*/, 1977 origInstallerPackageName, null /*finishedReceiver*/, updateUsers); 1978 } 1979 1980 // Send replaced for users that don't see the package for the first time 1981 if (update) { 1982 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1983 packageName, extras, 0 /*flags*/, 1984 null /*targetPackage*/, null /*finishedReceiver*/, 1985 updateUsers); 1986 if (origInstallerPackageName != null) { 1987 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 1988 extras, 0 /*flags*/, 1989 origInstallerPackageName, null /*finishedReceiver*/, updateUsers); 1990 } 1991 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1992 null /*package*/, null /*extras*/, 0 /*flags*/, 1993 packageName /*targetPackage*/, 1994 null /*finishedReceiver*/, updateUsers); 1995 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 1996 // First-install and we did a restore, so we're responsible for the 1997 // first-launch broadcast. 1998 if (DEBUG_BACKUP) { 1999 Slog.i(TAG, "Post-restore of " + packageName 2000 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers)); 2001 } 2002 sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers); 2003 } 2004 2005 // Send broadcast package appeared if forward locked/external for all users 2006 // treat asec-hosted packages like removable media on upgrade 2007 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 2008 if (DEBUG_INSTALL) { 2009 Slog.i(TAG, "upgrading pkg " + res.pkg 2010 + " is ASEC-hosted -> AVAILABLE"); 2011 } 2012 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 2013 ArrayList<String> pkgList = new ArrayList<>(1); 2014 pkgList.add(packageName); 2015 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 2016 } 2017 } 2018 2019 // Work that needs to happen on first install within each user 2020 if (firstUsers != null && firstUsers.length > 0) { 2021 synchronized (mPackages) { 2022 for (int userId : firstUsers) { 2023 // If this app is a browser and it's newly-installed for some 2024 // users, clear any default-browser state in those users. The 2025 // app's nature doesn't depend on the user, so we can just check 2026 // its browser nature in any user and generalize. 2027 if (packageIsBrowser(packageName, userId)) { 2028 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 2029 } 2030 2031 // We may also need to apply pending (restored) runtime 2032 // permission grants within these users. 2033 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 2034 } 2035 } 2036 } 2037 2038 // Log current value of "unknown sources" setting 2039 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 2040 getUnknownSourcesSettings()); 2041 2042 // Remove the replaced package's older resources safely now 2043 // We delete after a gc for applications on sdcard. 2044 if (res.removedInfo != null && res.removedInfo.args != null) { 2045 Runtime.getRuntime().gc(); 2046 synchronized (mInstallLock) { 2047 res.removedInfo.args.doPostDeleteLI(true); 2048 } 2049 } else { 2050 // Force a gc to clear up things. Ask for a background one, it's fine to go on 2051 // and not block here. 2052 VMRuntime.getRuntime().requestConcurrentGC(); 2053 } 2054 2055 // Notify DexManager that the package was installed for new users. 2056 // The updated users should already be indexed and the package code paths 2057 // should not change. 2058 // Don't notify the manager for ephemeral apps as they are not expected to 2059 // survive long enough to benefit of background optimizations. 2060 for (int userId : firstUsers) { 2061 PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId); 2062 // There's a race currently where some install events may interleave with an uninstall. 2063 // This can lead to package info being null (b/36642664). 2064 if (info != null) { 2065 mDexManager.notifyPackageInstalled(info, userId); 2066 } 2067 } 2068 } 2069 2070 // If someone is watching installs - notify them 2071 if (installObserver != null) { 2072 try { 2073 Bundle extras = extrasForInstallResult(res); 2074 installObserver.onPackageInstalled(res.name, res.returnCode, 2075 res.returnMsg, extras); 2076 } catch (RemoteException e) { 2077 Slog.i(TAG, "Observer no longer exists."); 2078 } 2079 } 2080 } 2081 2082 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 2083 PackageParser.Package pkg) { 2084 if (pkg.parentPackage == null) { 2085 return; 2086 } 2087 if (pkg.requestedPermissions == null) { 2088 return; 2089 } 2090 final PackageSetting disabledSysParentPs = mSettings 2091 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 2092 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 2093 || !disabledSysParentPs.isPrivileged() 2094 || (disabledSysParentPs.childPackageNames != null 2095 && !disabledSysParentPs.childPackageNames.isEmpty())) { 2096 return; 2097 } 2098 final int[] allUserIds = sUserManager.getUserIds(); 2099 final int permCount = pkg.requestedPermissions.size(); 2100 for (int i = 0; i < permCount; i++) { 2101 String permission = pkg.requestedPermissions.get(i); 2102 BasePermission bp = mSettings.mPermissions.get(permission); 2103 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 2104 continue; 2105 } 2106 for (int userId : allUserIds) { 2107 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 2108 permission, userId)) { 2109 grantRuntimePermission(pkg.packageName, permission, userId); 2110 } 2111 } 2112 } 2113 } 2114 2115 private StorageEventListener mStorageListener = new StorageEventListener() { 2116 @Override 2117 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 2118 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 2119 if (vol.state == VolumeInfo.STATE_MOUNTED) { 2120 final String volumeUuid = vol.getFsUuid(); 2121 2122 // Clean up any users or apps that were removed or recreated 2123 // while this volume was missing 2124 sUserManager.reconcileUsers(volumeUuid); 2125 reconcileApps(volumeUuid); 2126 2127 // Clean up any install sessions that expired or were 2128 // cancelled while this volume was missing 2129 mInstallerService.onPrivateVolumeMounted(volumeUuid); 2130 2131 loadPrivatePackages(vol); 2132 2133 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2134 unloadPrivatePackages(vol); 2135 } 2136 } 2137 2138 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 2139 if (vol.state == VolumeInfo.STATE_MOUNTED) { 2140 updateExternalMediaStatus(true, false); 2141 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2142 updateExternalMediaStatus(false, false); 2143 } 2144 } 2145 } 2146 2147 @Override 2148 public void onVolumeForgotten(String fsUuid) { 2149 if (TextUtils.isEmpty(fsUuid)) { 2150 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 2151 return; 2152 } 2153 2154 // Remove any apps installed on the forgotten volume 2155 synchronized (mPackages) { 2156 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 2157 for (PackageSetting ps : packages) { 2158 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 2159 deletePackageVersioned(new VersionedPackage(ps.name, 2160 PackageManager.VERSION_CODE_HIGHEST), 2161 new LegacyPackageDeleteObserver(null).getBinder(), 2162 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 2163 // Try very hard to release any references to this package 2164 // so we don't risk the system server being killed due to 2165 // open FDs 2166 AttributeCache.instance().removePackage(ps.name); 2167 } 2168 2169 mSettings.onVolumeForgotten(fsUuid); 2170 mSettings.writeLPr(); 2171 } 2172 } 2173 }; 2174 2175 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 2176 String[] grantedPermissions) { 2177 for (int userId : userIds) { 2178 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 2179 } 2180 } 2181 2182 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 2183 String[] grantedPermissions) { 2184 PackageSetting ps = (PackageSetting) pkg.mExtras; 2185 if (ps == null) { 2186 return; 2187 } 2188 2189 PermissionsState permissionsState = ps.getPermissionsState(); 2190 2191 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 2192 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 2193 2194 final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 2195 >= Build.VERSION_CODES.M; 2196 2197 final boolean instantApp = isInstantApp(pkg.packageName, userId); 2198 2199 for (String permission : pkg.requestedPermissions) { 2200 final BasePermission bp; 2201 synchronized (mPackages) { 2202 bp = mSettings.mPermissions.get(permission); 2203 } 2204 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 2205 && (!instantApp || bp.isInstant()) 2206 && (supportsRuntimePermissions || !bp.isRuntimeOnly()) 2207 && (grantedPermissions == null 2208 || ArrayUtils.contains(grantedPermissions, permission))) { 2209 final int flags = permissionsState.getPermissionFlags(permission, userId); 2210 if (supportsRuntimePermissions) { 2211 // Installer cannot change immutable permissions. 2212 if ((flags & immutableFlags) == 0) { 2213 grantRuntimePermission(pkg.packageName, permission, userId); 2214 } 2215 } else if (mPermissionReviewRequired) { 2216 // In permission review mode we clear the review flag when we 2217 // are asked to install the app with all permissions granted. 2218 if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 2219 updatePermissionFlags(permission, pkg.packageName, 2220 PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId); 2221 } 2222 } 2223 } 2224 } 2225 } 2226 2227 Bundle extrasForInstallResult(PackageInstalledInfo res) { 2228 Bundle extras = null; 2229 switch (res.returnCode) { 2230 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 2231 extras = new Bundle(); 2232 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 2233 res.origPermission); 2234 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 2235 res.origPackage); 2236 break; 2237 } 2238 case PackageManager.INSTALL_SUCCEEDED: { 2239 extras = new Bundle(); 2240 extras.putBoolean(Intent.EXTRA_REPLACING, 2241 res.removedInfo != null && res.removedInfo.removedPackage != null); 2242 break; 2243 } 2244 } 2245 return extras; 2246 } 2247 2248 void scheduleWriteSettingsLocked() { 2249 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2250 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2251 } 2252 } 2253 2254 void scheduleWritePackageListLocked(int userId) { 2255 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) { 2256 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST); 2257 msg.arg1 = userId; 2258 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY); 2259 } 2260 } 2261 2262 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2263 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2264 scheduleWritePackageRestrictionsLocked(userId); 2265 } 2266 2267 void scheduleWritePackageRestrictionsLocked(int userId) { 2268 final int[] userIds = (userId == UserHandle.USER_ALL) 2269 ? sUserManager.getUserIds() : new int[]{userId}; 2270 for (int nextUserId : userIds) { 2271 if (!sUserManager.exists(nextUserId)) return; 2272 mDirtyUsers.add(nextUserId); 2273 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2274 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2275 } 2276 } 2277 } 2278 2279 public static PackageManagerService main(Context context, Installer installer, 2280 boolean factoryTest, boolean onlyCore) { 2281 // Self-check for initial settings. 2282 PackageManagerServiceCompilerMapping.checkProperties(); 2283 2284 PackageManagerService m = new PackageManagerService(context, installer, 2285 factoryTest, onlyCore); 2286 m.enableSystemUserPackages(); 2287 ServiceManager.addService("package", m); 2288 return m; 2289 } 2290 2291 private void enableSystemUserPackages() { 2292 if (!UserManager.isSplitSystemUser()) { 2293 return; 2294 } 2295 // For system user, enable apps based on the following conditions: 2296 // - app is whitelisted or belong to one of these groups: 2297 // -- system app which has no launcher icons 2298 // -- system app which has INTERACT_ACROSS_USERS permission 2299 // -- system IME app 2300 // - app is not in the blacklist 2301 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2302 Set<String> enableApps = new ArraySet<>(); 2303 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2304 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2305 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2306 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2307 enableApps.addAll(wlApps); 2308 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2309 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2310 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2311 enableApps.removeAll(blApps); 2312 Log.i(TAG, "Applications installed for system user: " + enableApps); 2313 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2314 UserHandle.SYSTEM); 2315 final int allAppsSize = allAps.size(); 2316 synchronized (mPackages) { 2317 for (int i = 0; i < allAppsSize; i++) { 2318 String pName = allAps.get(i); 2319 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2320 // Should not happen, but we shouldn't be failing if it does 2321 if (pkgSetting == null) { 2322 continue; 2323 } 2324 boolean install = enableApps.contains(pName); 2325 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2326 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2327 + " for system user"); 2328 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2329 } 2330 } 2331 scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM); 2332 } 2333 } 2334 2335 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2336 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2337 Context.DISPLAY_SERVICE); 2338 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2339 } 2340 2341 /** 2342 * Requests that files preopted on a secondary system partition be copied to the data partition 2343 * if possible. Note that the actual copying of the files is accomplished by init for security 2344 * reasons. This simply requests that the copy takes place and awaits confirmation of its 2345 * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy. 2346 */ 2347 private static void requestCopyPreoptedFiles() { 2348 final int WAIT_TIME_MS = 100; 2349 final String CP_PREOPT_PROPERTY = "sys.cppreopt"; 2350 if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) { 2351 SystemProperties.set(CP_PREOPT_PROPERTY, "requested"); 2352 // We will wait for up to 100 seconds. 2353 final long timeStart = SystemClock.uptimeMillis(); 2354 final long timeEnd = timeStart + 100 * 1000; 2355 long timeNow = timeStart; 2356 while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) { 2357 try { 2358 Thread.sleep(WAIT_TIME_MS); 2359 } catch (InterruptedException e) { 2360 // Do nothing 2361 } 2362 timeNow = SystemClock.uptimeMillis(); 2363 if (timeNow > timeEnd) { 2364 SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out"); 2365 Slog.wtf(TAG, "cppreopt did not finish!"); 2366 break; 2367 } 2368 } 2369 2370 Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms"); 2371 } 2372 } 2373 2374 public PackageManagerService(Context context, Installer installer, 2375 boolean factoryTest, boolean onlyCore) { 2376 LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES); 2377 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager"); 2378 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2379 SystemClock.uptimeMillis()); 2380 2381 if (mSdkVersion <= 0) { 2382 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2383 } 2384 2385 mContext = context; 2386 2387 mPermissionReviewRequired = context.getResources().getBoolean( 2388 R.bool.config_permissionReviewRequired); 2389 2390 mFactoryTest = factoryTest; 2391 mOnlyCore = onlyCore; 2392 mMetrics = new DisplayMetrics(); 2393 mSettings = new Settings(mPackages); 2394 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2395 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2396 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2397 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2398 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2399 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2400 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2401 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2402 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2403 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2404 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2405 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2406 2407 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2408 if (separateProcesses != null && separateProcesses.length() > 0) { 2409 if ("*".equals(separateProcesses)) { 2410 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2411 mSeparateProcesses = null; 2412 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2413 } else { 2414 mDefParseFlags = 0; 2415 mSeparateProcesses = separateProcesses.split(","); 2416 Slog.w(TAG, "Running with debug.separate_processes: " 2417 + separateProcesses); 2418 } 2419 } else { 2420 mDefParseFlags = 0; 2421 mSeparateProcesses = null; 2422 } 2423 2424 mInstaller = installer; 2425 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2426 "*dexopt*"); 2427 mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock); 2428 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2429 2430 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2431 FgThread.get().getLooper()); 2432 2433 getDefaultDisplayMetrics(context, mMetrics); 2434 2435 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config"); 2436 SystemConfig systemConfig = SystemConfig.getInstance(); 2437 mGlobalGids = systemConfig.getGlobalGids(); 2438 mSystemPermissions = systemConfig.getSystemPermissions(); 2439 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2440 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2441 2442 mProtectedPackages = new ProtectedPackages(mContext); 2443 2444 synchronized (mInstallLock) { 2445 // writer 2446 synchronized (mPackages) { 2447 mHandlerThread = new ServiceThread(TAG, 2448 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2449 mHandlerThread.start(); 2450 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2451 mProcessLoggingHandler = new ProcessLoggingHandler(); 2452 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2453 2454 mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this); 2455 mInstantAppRegistry = new InstantAppRegistry(this); 2456 2457 File dataDir = Environment.getDataDirectory(); 2458 mAppInstallDir = new File(dataDir, "app"); 2459 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2460 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2461 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2462 sUserManager = new UserManagerService(context, this, 2463 new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages); 2464 2465 // Propagate permission configuration in to package manager. 2466 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2467 = systemConfig.getPermissions(); 2468 for (int i=0; i<permConfig.size(); i++) { 2469 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2470 BasePermission bp = mSettings.mPermissions.get(perm.name); 2471 if (bp == null) { 2472 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2473 mSettings.mPermissions.put(perm.name, bp); 2474 } 2475 if (perm.gids != null) { 2476 bp.setGids(perm.gids, perm.perUser); 2477 } 2478 } 2479 2480 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2481 final int builtInLibCount = libConfig.size(); 2482 for (int i = 0; i < builtInLibCount; i++) { 2483 String name = libConfig.keyAt(i); 2484 String path = libConfig.valueAt(i); 2485 addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED, 2486 SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0); 2487 } 2488 2489 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2490 2491 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings"); 2492 mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false)); 2493 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2494 2495 // Clean up orphaned packages for which the code path doesn't exist 2496 // and they are an update to a system app - caused by bug/32321269 2497 final int packageSettingCount = mSettings.mPackages.size(); 2498 for (int i = packageSettingCount - 1; i >= 0; i--) { 2499 PackageSetting ps = mSettings.mPackages.valueAt(i); 2500 if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists()) 2501 && mSettings.getDisabledSystemPkgLPr(ps.name) != null) { 2502 mSettings.mPackages.removeAt(i); 2503 mSettings.enableSystemPackageLPw(ps.name); 2504 } 2505 } 2506 2507 if (mFirstBoot) { 2508 requestCopyPreoptedFiles(); 2509 } 2510 2511 String customResolverActivity = Resources.getSystem().getString( 2512 R.string.config_customResolverActivity); 2513 if (TextUtils.isEmpty(customResolverActivity)) { 2514 customResolverActivity = null; 2515 } else { 2516 mCustomResolverComponentName = ComponentName.unflattenFromString( 2517 customResolverActivity); 2518 } 2519 2520 long startTime = SystemClock.uptimeMillis(); 2521 2522 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2523 startTime); 2524 2525 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2526 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2527 2528 if (bootClassPath == null) { 2529 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2530 } 2531 2532 if (systemServerClassPath == null) { 2533 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2534 } 2535 2536 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2537 2538 final VersionInfo ver = mSettings.getInternalVersion(); 2539 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2540 if (mIsUpgrade) { 2541 logCriticalInfo(Log.INFO, 2542 "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT); 2543 } 2544 2545 // when upgrading from pre-M, promote system app permissions from install to runtime 2546 mPromoteSystemApps = 2547 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2548 2549 // When upgrading from pre-N, we need to handle package extraction like first boot, 2550 // as there is no profiling data available. 2551 mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N; 2552 2553 mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1; 2554 2555 // save off the names of pre-existing system packages prior to scanning; we don't 2556 // want to automatically grant runtime permissions for new system apps 2557 if (mPromoteSystemApps) { 2558 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2559 while (pkgSettingIter.hasNext()) { 2560 PackageSetting ps = pkgSettingIter.next(); 2561 if (isSystemApp(ps)) { 2562 mExistingSystemPackages.add(ps.name); 2563 } 2564 } 2565 } 2566 2567 mCacheDir = preparePackageParserCache(mIsUpgrade); 2568 2569 // Set flag to monitor and not change apk file paths when 2570 // scanning install directories. 2571 int scanFlags = SCAN_BOOTING | SCAN_INITIAL; 2572 2573 if (mIsUpgrade || mFirstBoot) { 2574 scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE; 2575 } 2576 2577 // Collect vendor overlay packages. (Do this before scanning any apps.) 2578 // For security and version matching reason, only consider 2579 // overlay packages if they reside in the right directory. 2580 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags 2581 | PackageParser.PARSE_IS_SYSTEM 2582 | PackageParser.PARSE_IS_SYSTEM_DIR 2583 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2584 2585 mParallelPackageParserCallback.findStaticOverlayPackages(); 2586 2587 // Find base frameworks (resource packages without code). 2588 scanDirTracedLI(frameworkDir, mDefParseFlags 2589 | PackageParser.PARSE_IS_SYSTEM 2590 | PackageParser.PARSE_IS_SYSTEM_DIR 2591 | PackageParser.PARSE_IS_PRIVILEGED, 2592 scanFlags | SCAN_NO_DEX, 0); 2593 2594 // Collected privileged system packages. 2595 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2596 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2597 | PackageParser.PARSE_IS_SYSTEM 2598 | PackageParser.PARSE_IS_SYSTEM_DIR 2599 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2600 2601 // Collect ordinary system packages. 2602 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2603 scanDirTracedLI(systemAppDir, mDefParseFlags 2604 | PackageParser.PARSE_IS_SYSTEM 2605 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2606 2607 // Collect all vendor packages. 2608 File vendorAppDir = new File("/vendor/app"); 2609 try { 2610 vendorAppDir = vendorAppDir.getCanonicalFile(); 2611 } catch (IOException e) { 2612 // failed to look up canonical path, continue with original one 2613 } 2614 scanDirTracedLI(vendorAppDir, mDefParseFlags 2615 | PackageParser.PARSE_IS_SYSTEM 2616 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2617 2618 // Collect all OEM packages. 2619 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2620 scanDirTracedLI(oemAppDir, mDefParseFlags 2621 | PackageParser.PARSE_IS_SYSTEM 2622 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2623 2624 // Prune any system packages that no longer exist. 2625 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2626 if (!mOnlyCore) { 2627 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2628 while (psit.hasNext()) { 2629 PackageSetting ps = psit.next(); 2630 2631 /* 2632 * If this is not a system app, it can't be a 2633 * disable system app. 2634 */ 2635 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2636 continue; 2637 } 2638 2639 /* 2640 * If the package is scanned, it's not erased. 2641 */ 2642 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2643 if (scannedPkg != null) { 2644 /* 2645 * If the system app is both scanned and in the 2646 * disabled packages list, then it must have been 2647 * added via OTA. Remove it from the currently 2648 * scanned package so the previously user-installed 2649 * application can be scanned. 2650 */ 2651 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2652 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2653 + ps.name + "; removing system app. Last known codePath=" 2654 + ps.codePathString + ", installStatus=" + ps.installStatus 2655 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2656 + scannedPkg.mVersionCode); 2657 removePackageLI(scannedPkg, true); 2658 mExpectingBetter.put(ps.name, ps.codePath); 2659 } 2660 2661 continue; 2662 } 2663 2664 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2665 psit.remove(); 2666 logCriticalInfo(Log.WARN, "System package " + ps.name 2667 + " no longer exists; it's data will be wiped"); 2668 // Actual deletion of code and data will be handled by later 2669 // reconciliation step 2670 } else { 2671 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2672 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2673 possiblyDeletedUpdatedSystemApps.add(ps.name); 2674 } 2675 } 2676 } 2677 } 2678 2679 //look for any incomplete package installations 2680 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2681 for (int i = 0; i < deletePkgsList.size(); i++) { 2682 // Actual deletion of code and data will be handled by later 2683 // reconciliation step 2684 final String packageName = deletePkgsList.get(i).name; 2685 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2686 synchronized (mPackages) { 2687 mSettings.removePackageLPw(packageName); 2688 } 2689 } 2690 2691 //delete tmp files 2692 deleteTempPackageFiles(); 2693 2694 // Remove any shared userIDs that have no associated packages 2695 mSettings.pruneSharedUsersLPw(); 2696 2697 if (!mOnlyCore) { 2698 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2699 SystemClock.uptimeMillis()); 2700 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2701 2702 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2703 | PackageParser.PARSE_FORWARD_LOCK, 2704 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2705 2706 /** 2707 * Remove disable package settings for any updated system 2708 * apps that were removed via an OTA. If they're not a 2709 * previously-updated app, remove them completely. 2710 * Otherwise, just revoke their system-level permissions. 2711 */ 2712 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2713 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2714 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2715 2716 String msg; 2717 if (deletedPkg == null) { 2718 msg = "Updated system package " + deletedAppName 2719 + " no longer exists; it's data will be wiped"; 2720 // Actual deletion of code and data will be handled by later 2721 // reconciliation step 2722 } else { 2723 msg = "Updated system app + " + deletedAppName 2724 + " no longer present; removing system privileges for " 2725 + deletedAppName; 2726 2727 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2728 2729 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2730 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2731 } 2732 logCriticalInfo(Log.WARN, msg); 2733 } 2734 2735 /** 2736 * Make sure all system apps that we expected to appear on 2737 * the userdata partition actually showed up. If they never 2738 * appeared, crawl back and revive the system version. 2739 */ 2740 for (int i = 0; i < mExpectingBetter.size(); i++) { 2741 final String packageName = mExpectingBetter.keyAt(i); 2742 if (!mPackages.containsKey(packageName)) { 2743 final File scanFile = mExpectingBetter.valueAt(i); 2744 2745 logCriticalInfo(Log.WARN, "Expected better " + packageName 2746 + " but never showed up; reverting to system"); 2747 2748 int reparseFlags = mDefParseFlags; 2749 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2750 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2751 | PackageParser.PARSE_IS_SYSTEM_DIR 2752 | PackageParser.PARSE_IS_PRIVILEGED; 2753 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2754 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2755 | PackageParser.PARSE_IS_SYSTEM_DIR; 2756 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2757 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2758 | PackageParser.PARSE_IS_SYSTEM_DIR; 2759 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2760 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2761 | PackageParser.PARSE_IS_SYSTEM_DIR; 2762 } else { 2763 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2764 continue; 2765 } 2766 2767 mSettings.enableSystemPackageLPw(packageName); 2768 2769 try { 2770 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2771 } catch (PackageManagerException e) { 2772 Slog.e(TAG, "Failed to parse original system package: " 2773 + e.getMessage()); 2774 } 2775 } 2776 } 2777 } 2778 mExpectingBetter.clear(); 2779 2780 // Resolve the storage manager. 2781 mStorageManagerPackage = getStorageManagerPackageName(); 2782 2783 // Resolve protected action filters. Only the setup wizard is allowed to 2784 // have a high priority filter for these actions. 2785 mSetupWizardPackage = getSetupWizardPackageName(); 2786 if (mProtectedFilters.size() > 0) { 2787 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2788 Slog.i(TAG, "No setup wizard;" 2789 + " All protected intents capped to priority 0"); 2790 } 2791 for (ActivityIntentInfo filter : mProtectedFilters) { 2792 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2793 if (DEBUG_FILTERS) { 2794 Slog.i(TAG, "Found setup wizard;" 2795 + " allow priority " + filter.getPriority() + ";" 2796 + " package: " + filter.activity.info.packageName 2797 + " activity: " + filter.activity.className 2798 + " priority: " + filter.getPriority()); 2799 } 2800 // skip setup wizard; allow it to keep the high priority filter 2801 continue; 2802 } 2803 if (DEBUG_FILTERS) { 2804 Slog.i(TAG, "Protected action; cap priority to 0;" 2805 + " package: " + filter.activity.info.packageName 2806 + " activity: " + filter.activity.className 2807 + " origPrio: " + filter.getPriority()); 2808 } 2809 filter.setPriority(0); 2810 } 2811 } 2812 mDeferProtectedFilters = false; 2813 mProtectedFilters.clear(); 2814 2815 // Now that we know all of the shared libraries, update all clients to have 2816 // the correct library paths. 2817 updateAllSharedLibrariesLPw(null); 2818 2819 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2820 // NOTE: We ignore potential failures here during a system scan (like 2821 // the rest of the commands above) because there's precious little we 2822 // can do about it. A settings error is reported, though. 2823 adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/); 2824 } 2825 2826 // Now that we know all the packages we are keeping, 2827 // read and update their last usage times. 2828 mPackageUsage.read(mPackages); 2829 mCompilerStats.read(); 2830 2831 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2832 SystemClock.uptimeMillis()); 2833 Slog.i(TAG, "Time to scan packages: " 2834 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2835 + " seconds"); 2836 2837 // If the platform SDK has changed since the last time we booted, 2838 // we need to re-grant app permission to catch any new ones that 2839 // appear. This is really a hack, and means that apps can in some 2840 // cases get permissions that the user didn't initially explicitly 2841 // allow... it would be nice to have some better way to handle 2842 // this situation. 2843 int updateFlags = UPDATE_PERMISSIONS_ALL; 2844 if (ver.sdkVersion != mSdkVersion) { 2845 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2846 + mSdkVersion + "; regranting permissions for internal storage"); 2847 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2848 } 2849 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2850 ver.sdkVersion = mSdkVersion; 2851 2852 // If this is the first boot or an update from pre-M, and it is a normal 2853 // boot, then we need to initialize the default preferred apps across 2854 // all defined users. 2855 if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) { 2856 for (UserInfo user : sUserManager.getUsers(true)) { 2857 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2858 applyFactoryDefaultBrowserLPw(user.id); 2859 primeDomainVerificationsLPw(user.id); 2860 } 2861 } 2862 2863 // Prepare storage for system user really early during boot, 2864 // since core system apps like SettingsProvider and SystemUI 2865 // can't wait for user to start 2866 final int storageFlags; 2867 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2868 storageFlags = StorageManager.FLAG_STORAGE_DE; 2869 } else { 2870 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2871 } 2872 List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, 2873 UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */, 2874 true /* onlyCoreApps */); 2875 mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> { 2876 BootTimingsTraceLog traceLog = new BootTimingsTraceLog("SystemServerTimingAsync", 2877 Trace.TRACE_TAG_PACKAGE_MANAGER); 2878 traceLog.traceBegin("AppDataFixup"); 2879 try { 2880 mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL, 2881 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 2882 } catch (InstallerException e) { 2883 Slog.w(TAG, "Trouble fixing GIDs", e); 2884 } 2885 traceLog.traceEnd(); 2886 2887 traceLog.traceBegin("AppDataPrepare"); 2888 if (deferPackages == null || deferPackages.isEmpty()) { 2889 return; 2890 } 2891 int count = 0; 2892 for (String pkgName : deferPackages) { 2893 PackageParser.Package pkg = null; 2894 synchronized (mPackages) { 2895 PackageSetting ps = mSettings.getPackageLPr(pkgName); 2896 if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) { 2897 pkg = ps.pkg; 2898 } 2899 } 2900 if (pkg != null) { 2901 synchronized (mInstallLock) { 2902 prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags, 2903 true /* maybeMigrateAppData */); 2904 } 2905 count++; 2906 } 2907 } 2908 traceLog.traceEnd(); 2909 Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages"); 2910 }, "prepareAppData"); 2911 2912 // If this is first boot after an OTA, and a normal boot, then 2913 // we need to clear code cache directories. 2914 // Note that we do *not* clear the application profiles. These remain valid 2915 // across OTAs and are used to drive profile verification (post OTA) and 2916 // profile compilation (without waiting to collect a fresh set of profiles). 2917 if (mIsUpgrade && !onlyCore) { 2918 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2919 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2920 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2921 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2922 // No apps are running this early, so no need to freeze 2923 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2924 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2925 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2926 } 2927 } 2928 ver.fingerprint = Build.FINGERPRINT; 2929 } 2930 2931 checkDefaultBrowser(); 2932 2933 // clear only after permissions and other defaults have been updated 2934 mExistingSystemPackages.clear(); 2935 mPromoteSystemApps = false; 2936 2937 // All the changes are done during package scanning. 2938 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2939 2940 // can downgrade to reader 2941 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings"); 2942 mSettings.writeLPr(); 2943 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2944 2945 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2946 SystemClock.uptimeMillis()); 2947 2948 if (!mOnlyCore) { 2949 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2950 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2951 mRequiredUninstallerPackage = getRequiredUninstallerLPr(); 2952 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2953 if (mIntentFilterVerifierComponent != null) { 2954 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2955 mIntentFilterVerifierComponent); 2956 } else { 2957 mIntentFilterVerifier = null; 2958 } 2959 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2960 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES, 2961 SharedLibraryInfo.VERSION_UNDEFINED); 2962 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2963 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED, 2964 SharedLibraryInfo.VERSION_UNDEFINED); 2965 } else { 2966 mRequiredVerifierPackage = null; 2967 mRequiredInstallerPackage = null; 2968 mRequiredUninstallerPackage = null; 2969 mIntentFilterVerifierComponent = null; 2970 mIntentFilterVerifier = null; 2971 mServicesSystemSharedLibraryPackageName = null; 2972 mSharedSystemSharedLibraryPackageName = null; 2973 } 2974 2975 mInstallerService = new PackageInstallerService(context, this); 2976 final Pair<ComponentName, String> instantAppResolverComponent = 2977 getInstantAppResolverLPr(); 2978 if (instantAppResolverComponent != null) { 2979 if (DEBUG_EPHEMERAL) { 2980 Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent); 2981 } 2982 mInstantAppResolverConnection = new EphemeralResolverConnection( 2983 mContext, instantAppResolverComponent.first, 2984 instantAppResolverComponent.second); 2985 mInstantAppResolverSettingsComponent = 2986 getInstantAppResolverSettingsLPr(instantAppResolverComponent.first); 2987 } else { 2988 mInstantAppResolverConnection = null; 2989 mInstantAppResolverSettingsComponent = null; 2990 } 2991 updateInstantAppInstallerLocked(null); 2992 2993 // Read and update the usage of dex files. 2994 // Do this at the end of PM init so that all the packages have their 2995 // data directory reconciled. 2996 // At this point we know the code paths of the packages, so we can validate 2997 // the disk file and build the internal cache. 2998 // The usage file is expected to be small so loading and verifying it 2999 // should take a fairly small time compare to the other activities (e.g. package 3000 // scanning). 3001 final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>(); 3002 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 3003 for (int userId : currentUserIds) { 3004 userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList()); 3005 } 3006 mDexManager.load(userPackages); 3007 } // synchronized (mPackages) 3008 } // synchronized (mInstallLock) 3009 3010 // Now after opening every single application zip, make sure they 3011 // are all flushed. Not really needed, but keeps things nice and 3012 // tidy. 3013 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC"); 3014 Runtime.getRuntime().gc(); 3015 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 3016 3017 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks"); 3018 FallbackCategoryProvider.loadFallbacks(); 3019 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 3020 3021 // The initial scanning above does many calls into installd while 3022 // holding the mPackages lock, but we're mostly interested in yelling 3023 // once we have a booted system. 3024 mInstaller.setWarnIfHeld(mPackages); 3025 3026 // Expose private service for system components to use. 3027 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 3028 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 3029 } 3030 3031 private void updateInstantAppInstallerLocked(String modifiedPackage) { 3032 // we're only interested in updating the installer appliction when 1) it's not 3033 // already set or 2) the modified package is the installer 3034 if (mInstantAppInstallerActivity != null 3035 && !mInstantAppInstallerActivity.getComponentName().getPackageName() 3036 .equals(modifiedPackage)) { 3037 return; 3038 } 3039 setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr()); 3040 } 3041 3042 private static File preparePackageParserCache(boolean isUpgrade) { 3043 if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) { 3044 return null; 3045 } 3046 3047 // Disable package parsing on eng builds to allow for faster incremental development. 3048 if ("eng".equals(Build.TYPE)) { 3049 return null; 3050 } 3051 3052 if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) { 3053 Slog.i(TAG, "Disabling package parser cache due to system property."); 3054 return null; 3055 } 3056 3057 // The base directory for the package parser cache lives under /data/system/. 3058 final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(), 3059 "package_cache"); 3060 if (cacheBaseDir == null) { 3061 return null; 3062 } 3063 3064 // If this is a system upgrade scenario, delete the contents of the package cache dir. 3065 // This also serves to "GC" unused entries when the package cache version changes (which 3066 // can only happen during upgrades). 3067 if (isUpgrade) { 3068 FileUtils.deleteContents(cacheBaseDir); 3069 } 3070 3071 3072 // Return the versioned package cache directory. This is something like 3073 // "/data/system/package_cache/1" 3074 File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION); 3075 3076 // The following is a workaround to aid development on non-numbered userdebug 3077 // builds or cases where "adb sync" is used on userdebug builds. If we detect that 3078 // the system partition is newer. 3079 // 3080 // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build 3081 // that starts with "eng." to signify that this is an engineering build and not 3082 // destined for release. 3083 if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) { 3084 Slog.w(TAG, "Wiping cache directory because the system partition changed."); 3085 3086 // Heuristic: If the /system directory has been modified recently due to an "adb sync" 3087 // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable 3088 // in general and should not be used for production changes. In this specific case, 3089 // we know that they will work. 3090 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 3091 if (cacheDir.lastModified() < frameworkDir.lastModified()) { 3092 FileUtils.deleteContents(cacheBaseDir); 3093 cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION); 3094 } 3095 } 3096 3097 return cacheDir; 3098 } 3099 3100 @Override 3101 public boolean isFirstBoot() { 3102 // allow instant applications 3103 return mFirstBoot; 3104 } 3105 3106 @Override 3107 public boolean isOnlyCoreApps() { 3108 // allow instant applications 3109 return mOnlyCore; 3110 } 3111 3112 @Override 3113 public boolean isUpgrade() { 3114 // allow instant applications 3115 return mIsUpgrade; 3116 } 3117 3118 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 3119 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 3120 3121 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 3122 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3123 UserHandle.USER_SYSTEM); 3124 if (matches.size() == 1) { 3125 return matches.get(0).getComponentInfo().packageName; 3126 } else if (matches.size() == 0) { 3127 Log.e(TAG, "There should probably be a verifier, but, none were found"); 3128 return null; 3129 } 3130 throw new RuntimeException("There must be exactly one verifier; found " + matches); 3131 } 3132 3133 private @NonNull String getRequiredSharedLibraryLPr(String name, int version) { 3134 synchronized (mPackages) { 3135 SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version); 3136 if (libraryEntry == null) { 3137 throw new IllegalStateException("Missing required shared library:" + name); 3138 } 3139 return libraryEntry.apk; 3140 } 3141 } 3142 3143 private @NonNull String getRequiredInstallerLPr() { 3144 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 3145 intent.addCategory(Intent.CATEGORY_DEFAULT); 3146 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 3147 3148 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3149 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3150 UserHandle.USER_SYSTEM); 3151 if (matches.size() == 1) { 3152 ResolveInfo resolveInfo = matches.get(0); 3153 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 3154 throw new RuntimeException("The installer must be a privileged app"); 3155 } 3156 return matches.get(0).getComponentInfo().packageName; 3157 } else { 3158 throw new RuntimeException("There must be exactly one installer; found " + matches); 3159 } 3160 } 3161 3162 private @NonNull String getRequiredUninstallerLPr() { 3163 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 3164 intent.addCategory(Intent.CATEGORY_DEFAULT); 3165 intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null)); 3166 3167 final ResolveInfo resolveInfo = resolveIntent(intent, null, 3168 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3169 UserHandle.USER_SYSTEM); 3170 if (resolveInfo == null || 3171 mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) { 3172 throw new RuntimeException("There must be exactly one uninstaller; found " 3173 + resolveInfo); 3174 } 3175 return resolveInfo.getComponentInfo().packageName; 3176 } 3177 3178 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 3179 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 3180 3181 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 3182 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3183 UserHandle.USER_SYSTEM); 3184 ResolveInfo best = null; 3185 final int N = matches.size(); 3186 for (int i = 0; i < N; i++) { 3187 final ResolveInfo cur = matches.get(i); 3188 final String packageName = cur.getComponentInfo().packageName; 3189 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 3190 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 3191 continue; 3192 } 3193 3194 if (best == null || cur.priority > best.priority) { 3195 best = cur; 3196 } 3197 } 3198 3199 if (best != null) { 3200 return best.getComponentInfo().getComponentName(); 3201 } 3202 Slog.w(TAG, "Intent filter verifier not found"); 3203 return null; 3204 } 3205 3206 @Override 3207 public @Nullable ComponentName getInstantAppResolverComponent() { 3208 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 3209 return null; 3210 } 3211 synchronized (mPackages) { 3212 final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr(); 3213 if (instantAppResolver == null) { 3214 return null; 3215 } 3216 return instantAppResolver.first; 3217 } 3218 } 3219 3220 private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() { 3221 final String[] packageArray = 3222 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 3223 if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) { 3224 if (DEBUG_EPHEMERAL) { 3225 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 3226 } 3227 return null; 3228 } 3229 3230 final int callingUid = Binder.getCallingUid(); 3231 final int resolveFlags = 3232 MATCH_DIRECT_BOOT_AWARE 3233 | MATCH_DIRECT_BOOT_UNAWARE 3234 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3235 String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE; 3236 final Intent resolverIntent = new Intent(actionName); 3237 List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 3238 resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/); 3239 // temporarily look for the old action 3240 if (resolvers.size() == 0) { 3241 if (DEBUG_EPHEMERAL) { 3242 Slog.d(TAG, "Ephemeral resolver not found with new action; try old one"); 3243 } 3244 actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE; 3245 resolverIntent.setAction(actionName); 3246 resolvers = queryIntentServicesInternal(resolverIntent, null, 3247 resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/); 3248 } 3249 final int N = resolvers.size(); 3250 if (N == 0) { 3251 if (DEBUG_EPHEMERAL) { 3252 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 3253 } 3254 return null; 3255 } 3256 3257 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 3258 for (int i = 0; i < N; i++) { 3259 final ResolveInfo info = resolvers.get(i); 3260 3261 if (info.serviceInfo == null) { 3262 continue; 3263 } 3264 3265 final String packageName = info.serviceInfo.packageName; 3266 if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) { 3267 if (DEBUG_EPHEMERAL) { 3268 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 3269 + " pkg: " + packageName + ", info:" + info); 3270 } 3271 continue; 3272 } 3273 3274 if (DEBUG_EPHEMERAL) { 3275 Slog.v(TAG, "Ephemeral resolver found;" 3276 + " pkg: " + packageName + ", info:" + info); 3277 } 3278 return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName); 3279 } 3280 if (DEBUG_EPHEMERAL) { 3281 Slog.v(TAG, "Ephemeral resolver NOT found"); 3282 } 3283 return null; 3284 } 3285 3286 private @Nullable ActivityInfo getInstantAppInstallerLPr() { 3287 final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE); 3288 intent.addCategory(Intent.CATEGORY_DEFAULT); 3289 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 3290 3291 final int resolveFlags = 3292 MATCH_DIRECT_BOOT_AWARE 3293 | MATCH_DIRECT_BOOT_UNAWARE 3294 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3295 List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3296 resolveFlags, UserHandle.USER_SYSTEM); 3297 // temporarily look for the old action 3298 if (matches.isEmpty()) { 3299 if (DEBUG_EPHEMERAL) { 3300 Slog.d(TAG, "Ephemeral installer not found with new action; try old one"); 3301 } 3302 intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 3303 matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3304 resolveFlags, UserHandle.USER_SYSTEM); 3305 } 3306 Iterator<ResolveInfo> iter = matches.iterator(); 3307 while (iter.hasNext()) { 3308 final ResolveInfo rInfo = iter.next(); 3309 final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName); 3310 if (ps != null) { 3311 final PermissionsState permissionsState = ps.getPermissionsState(); 3312 if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) { 3313 continue; 3314 } 3315 } 3316 iter.remove(); 3317 } 3318 if (matches.size() == 0) { 3319 return null; 3320 } else if (matches.size() == 1) { 3321 return (ActivityInfo) matches.get(0).getComponentInfo(); 3322 } else { 3323 throw new RuntimeException( 3324 "There must be at most one ephemeral installer; found " + matches); 3325 } 3326 } 3327 3328 private @Nullable ComponentName getInstantAppResolverSettingsLPr( 3329 @NonNull ComponentName resolver) { 3330 final Intent intent = new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS) 3331 .addCategory(Intent.CATEGORY_DEFAULT) 3332 .setPackage(resolver.getPackageName()); 3333 final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3334 List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags, 3335 UserHandle.USER_SYSTEM); 3336 // temporarily look for the old action 3337 if (matches.isEmpty()) { 3338 if (DEBUG_EPHEMERAL) { 3339 Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one"); 3340 } 3341 intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS); 3342 matches = queryIntentActivitiesInternal(intent, null, resolveFlags, 3343 UserHandle.USER_SYSTEM); 3344 } 3345 if (matches.isEmpty()) { 3346 return null; 3347 } 3348 return matches.get(0).getComponentInfo().getComponentName(); 3349 } 3350 3351 private void primeDomainVerificationsLPw(int userId) { 3352 if (DEBUG_DOMAIN_VERIFICATION) { 3353 Slog.d(TAG, "Priming domain verifications in user " + userId); 3354 } 3355 3356 SystemConfig systemConfig = SystemConfig.getInstance(); 3357 ArraySet<String> packages = systemConfig.getLinkedApps(); 3358 3359 for (String packageName : packages) { 3360 PackageParser.Package pkg = mPackages.get(packageName); 3361 if (pkg != null) { 3362 if (!pkg.isSystemApp()) { 3363 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 3364 continue; 3365 } 3366 3367 ArraySet<String> domains = null; 3368 for (PackageParser.Activity a : pkg.activities) { 3369 for (ActivityIntentInfo filter : a.intents) { 3370 if (hasValidDomains(filter)) { 3371 if (domains == null) { 3372 domains = new ArraySet<String>(); 3373 } 3374 domains.addAll(filter.getHostsList()); 3375 } 3376 } 3377 } 3378 3379 if (domains != null && domains.size() > 0) { 3380 if (DEBUG_DOMAIN_VERIFICATION) { 3381 Slog.v(TAG, " + " + packageName); 3382 } 3383 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 3384 // state w.r.t. the formal app-linkage "no verification attempted" state; 3385 // and then 'always' in the per-user state actually used for intent resolution. 3386 final IntentFilterVerificationInfo ivi; 3387 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains); 3388 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 3389 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 3390 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 3391 } else { 3392 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 3393 + "' does not handle web links"); 3394 } 3395 } else { 3396 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 3397 } 3398 } 3399 3400 scheduleWritePackageRestrictionsLocked(userId); 3401 scheduleWriteSettingsLocked(); 3402 } 3403 3404 private void applyFactoryDefaultBrowserLPw(int userId) { 3405 // The default browser app's package name is stored in a string resource, 3406 // with a product-specific overlay used for vendor customization. 3407 String browserPkg = mContext.getResources().getString( 3408 com.android.internal.R.string.default_browser); 3409 if (!TextUtils.isEmpty(browserPkg)) { 3410 // non-empty string => required to be a known package 3411 PackageSetting ps = mSettings.mPackages.get(browserPkg); 3412 if (ps == null) { 3413 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 3414 browserPkg = null; 3415 } else { 3416 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3417 } 3418 } 3419 3420 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3421 // default. If there's more than one, just leave everything alone. 3422 if (browserPkg == null) { 3423 calculateDefaultBrowserLPw(userId); 3424 } 3425 } 3426 3427 private void calculateDefaultBrowserLPw(int userId) { 3428 List<String> allBrowsers = resolveAllBrowserApps(userId); 3429 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3430 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3431 } 3432 3433 private List<String> resolveAllBrowserApps(int userId) { 3434 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3435 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3436 PackageManager.MATCH_ALL, userId); 3437 3438 final int count = list.size(); 3439 List<String> result = new ArrayList<String>(count); 3440 for (int i=0; i<count; i++) { 3441 ResolveInfo info = list.get(i); 3442 if (info.activityInfo == null 3443 || !info.handleAllWebDataURI 3444 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3445 || result.contains(info.activityInfo.packageName)) { 3446 continue; 3447 } 3448 result.add(info.activityInfo.packageName); 3449 } 3450 3451 return result; 3452 } 3453 3454 private boolean packageIsBrowser(String packageName, int userId) { 3455 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3456 PackageManager.MATCH_ALL, userId); 3457 final int N = list.size(); 3458 for (int i = 0; i < N; i++) { 3459 ResolveInfo info = list.get(i); 3460 if (packageName.equals(info.activityInfo.packageName)) { 3461 return true; 3462 } 3463 } 3464 return false; 3465 } 3466 3467 private void checkDefaultBrowser() { 3468 final int myUserId = UserHandle.myUserId(); 3469 final String packageName = getDefaultBrowserPackageName(myUserId); 3470 if (packageName != null) { 3471 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3472 if (info == null) { 3473 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3474 synchronized (mPackages) { 3475 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3476 } 3477 } 3478 } 3479 } 3480 3481 @Override 3482 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3483 throws RemoteException { 3484 try { 3485 return super.onTransact(code, data, reply, flags); 3486 } catch (RuntimeException e) { 3487 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3488 Slog.wtf(TAG, "Package Manager Crash", e); 3489 } 3490 throw e; 3491 } 3492 } 3493 3494 static int[] appendInts(int[] cur, int[] add) { 3495 if (add == null) return cur; 3496 if (cur == null) return add; 3497 final int N = add.length; 3498 for (int i=0; i<N; i++) { 3499 cur = appendInt(cur, add[i]); 3500 } 3501 return cur; 3502 } 3503 3504 /** 3505 * Returns whether or not a full application can see an instant application. 3506 * <p> 3507 * Currently, there are three cases in which this can occur: 3508 * <ol> 3509 * <li>The calling application is a "special" process. The special 3510 * processes are {@link Process#SYSTEM_UID}, {@link Process#SHELL_UID} 3511 * and {@code 0}</li> 3512 * <li>The calling application has the permission 3513 * {@link android.Manifest.permission#ACCESS_INSTANT_APPS}</li> 3514 * <li>The calling application is the default launcher on the 3515 * system partition.</li> 3516 * </ol> 3517 */ 3518 private boolean canViewInstantApps(int callingUid, int userId) { 3519 if (callingUid == Process.SYSTEM_UID 3520 || callingUid == Process.SHELL_UID 3521 || callingUid == Process.ROOT_UID) { 3522 return true; 3523 } 3524 if (mContext.checkCallingOrSelfPermission( 3525 android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) { 3526 return true; 3527 } 3528 if (mContext.checkCallingOrSelfPermission( 3529 android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) { 3530 final ComponentName homeComponent = getDefaultHomeActivity(userId); 3531 if (homeComponent != null 3532 && isCallerSameApp(homeComponent.getPackageName(), callingUid)) { 3533 return true; 3534 } 3535 } 3536 return false; 3537 } 3538 3539 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3540 if (!sUserManager.exists(userId)) return null; 3541 if (ps == null) { 3542 return null; 3543 } 3544 PackageParser.Package p = ps.pkg; 3545 if (p == null) { 3546 return null; 3547 } 3548 final int callingUid = Binder.getCallingUid(); 3549 // Filter out ephemeral app metadata: 3550 // * The system/shell/root can see metadata for any app 3551 // * An installed app can see metadata for 1) other installed apps 3552 // and 2) ephemeral apps that have explicitly interacted with it 3553 // * Ephemeral apps can only see their own data and exposed installed apps 3554 // * Holding a signature permission allows seeing instant apps 3555 if (filterAppAccessLPr(ps, callingUid, userId)) { 3556 return null; 3557 } 3558 3559 final PermissionsState permissionsState = ps.getPermissionsState(); 3560 3561 // Compute GIDs only if requested 3562 final int[] gids = (flags & PackageManager.GET_GIDS) == 0 3563 ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId); 3564 // Compute granted permissions only if package has requested permissions 3565 final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions) 3566 ? Collections.<String>emptySet() : permissionsState.getPermissions(userId); 3567 final PackageUserState state = ps.readUserState(userId); 3568 3569 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0 3570 && ps.isSystem()) { 3571 flags |= MATCH_ANY_USER; 3572 } 3573 3574 PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags, 3575 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3576 3577 if (packageInfo == null) { 3578 return null; 3579 } 3580 3581 packageInfo.packageName = packageInfo.applicationInfo.packageName = 3582 resolveExternalPackageNameLPr(p); 3583 3584 return packageInfo; 3585 } 3586 3587 @Override 3588 public void checkPackageStartable(String packageName, int userId) { 3589 final int callingUid = Binder.getCallingUid(); 3590 if (getInstantAppPackageName(callingUid) != null) { 3591 throw new SecurityException("Instant applications don't have access to this method"); 3592 } 3593 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3594 synchronized (mPackages) { 3595 final PackageSetting ps = mSettings.mPackages.get(packageName); 3596 if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) { 3597 throw new SecurityException("Package " + packageName + " was not found!"); 3598 } 3599 3600 if (!ps.getInstalled(userId)) { 3601 throw new SecurityException( 3602 "Package " + packageName + " was not installed for user " + userId + "!"); 3603 } 3604 3605 if (mSafeMode && !ps.isSystem()) { 3606 throw new SecurityException("Package " + packageName + " not a system app!"); 3607 } 3608 3609 if (mFrozenPackages.contains(packageName)) { 3610 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3611 } 3612 3613 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3614 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3615 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3616 } 3617 } 3618 } 3619 3620 @Override 3621 public boolean isPackageAvailable(String packageName, int userId) { 3622 if (!sUserManager.exists(userId)) return false; 3623 final int callingUid = Binder.getCallingUid(); 3624 enforceCrossUserPermission(callingUid, userId, 3625 false /*requireFullPermission*/, false /*checkShell*/, "is package available"); 3626 synchronized (mPackages) { 3627 PackageParser.Package p = mPackages.get(packageName); 3628 if (p != null) { 3629 final PackageSetting ps = (PackageSetting) p.mExtras; 3630 if (filterAppAccessLPr(ps, callingUid, userId)) { 3631 return false; 3632 } 3633 if (ps != null) { 3634 final PackageUserState state = ps.readUserState(userId); 3635 if (state != null) { 3636 return PackageParser.isAvailable(state); 3637 } 3638 } 3639 } 3640 } 3641 return false; 3642 } 3643 3644 @Override 3645 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3646 return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST, 3647 flags, Binder.getCallingUid(), userId); 3648 } 3649 3650 @Override 3651 public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage, 3652 int flags, int userId) { 3653 return getPackageInfoInternal(versionedPackage.getPackageName(), 3654 versionedPackage.getVersionCode(), flags, Binder.getCallingUid(), userId); 3655 } 3656 3657 /** 3658 * Important: The provided filterCallingUid is used exclusively to filter out packages 3659 * that can be seen based on user state. It's typically the original caller uid prior 3660 * to clearing. Because it can only be provided by trusted code, it's value can be 3661 * trusted and will be used as-is; unlike userId which will be validated by this method. 3662 */ 3663 private PackageInfo getPackageInfoInternal(String packageName, int versionCode, 3664 int flags, int filterCallingUid, int userId) { 3665 if (!sUserManager.exists(userId)) return null; 3666 flags = updateFlagsForPackage(flags, userId, packageName); 3667 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3668 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3669 3670 // reader 3671 synchronized (mPackages) { 3672 // Normalize package name to handle renamed packages and static libs 3673 packageName = resolveInternalPackageNameLPr(packageName, versionCode); 3674 3675 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3676 if (matchFactoryOnly) { 3677 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3678 if (ps != null) { 3679 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 3680 return null; 3681 } 3682 if (filterAppAccessLPr(ps, filterCallingUid, userId)) { 3683 return null; 3684 } 3685 return generatePackageInfo(ps, flags, userId); 3686 } 3687 } 3688 3689 PackageParser.Package p = mPackages.get(packageName); 3690 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3691 return null; 3692 } 3693 if (DEBUG_PACKAGE_INFO) 3694 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3695 if (p != null) { 3696 final PackageSetting ps = (PackageSetting) p.mExtras; 3697 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 3698 return null; 3699 } 3700 if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) { 3701 return null; 3702 } 3703 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3704 } 3705 if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) { 3706 final PackageSetting ps = mSettings.mPackages.get(packageName); 3707 if (ps == null) return null; 3708 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 3709 return null; 3710 } 3711 if (filterAppAccessLPr(ps, filterCallingUid, userId)) { 3712 return null; 3713 } 3714 return generatePackageInfo(ps, flags, userId); 3715 } 3716 } 3717 return null; 3718 } 3719 3720 private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) { 3721 if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) { 3722 return true; 3723 } 3724 if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) { 3725 return true; 3726 } 3727 if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) { 3728 return true; 3729 } 3730 return false; 3731 } 3732 3733 private boolean isComponentVisibleToInstantApp( 3734 @Nullable ComponentName component, @ComponentType int type) { 3735 if (type == TYPE_ACTIVITY) { 3736 final PackageParser.Activity activity = mActivities.mActivities.get(component); 3737 return activity != null 3738 ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0 3739 : false; 3740 } else if (type == TYPE_RECEIVER) { 3741 final PackageParser.Activity activity = mReceivers.mActivities.get(component); 3742 return activity != null 3743 ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0 3744 : false; 3745 } else if (type == TYPE_SERVICE) { 3746 final PackageParser.Service service = mServices.mServices.get(component); 3747 return service != null 3748 ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0 3749 : false; 3750 } else if (type == TYPE_PROVIDER) { 3751 final PackageParser.Provider provider = mProviders.mProviders.get(component); 3752 return provider != null 3753 ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0 3754 : false; 3755 } else if (type == TYPE_UNKNOWN) { 3756 return isComponentVisibleToInstantApp(component); 3757 } 3758 return false; 3759 } 3760 3761 /** 3762 * Returns whether or not access to the application should be filtered. 3763 * <p> 3764 * Access may be limited based upon whether the calling or target applications 3765 * are instant applications. 3766 * 3767 * @see #canAccessInstantApps(int) 3768 */ 3769 private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, 3770 @Nullable ComponentName component, @ComponentType int componentType, int userId) { 3771 // if we're in an isolated process, get the real calling UID 3772 if (Process.isIsolated(callingUid)) { 3773 callingUid = mIsolatedOwners.get(callingUid); 3774 } 3775 final String instantAppPkgName = getInstantAppPackageName(callingUid); 3776 final boolean callerIsInstantApp = instantAppPkgName != null; 3777 if (ps == null) { 3778 if (callerIsInstantApp) { 3779 // pretend the application exists, but, needs to be filtered 3780 return true; 3781 } 3782 return false; 3783 } 3784 // if the target and caller are the same application, don't filter 3785 if (isCallerSameApp(ps.name, callingUid)) { 3786 return false; 3787 } 3788 if (callerIsInstantApp) { 3789 // request for a specific component; if it hasn't been explicitly exposed, filter 3790 if (component != null) { 3791 return !isComponentVisibleToInstantApp(component, componentType); 3792 } 3793 // request for application; if no components have been explicitly exposed, filter 3794 return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps; 3795 } 3796 if (ps.getInstantApp(userId)) { 3797 // caller can see all components of all instant applications, don't filter 3798 if (canViewInstantApps(callingUid, userId)) { 3799 return false; 3800 } 3801 // request for a specific instant application component, filter 3802 if (component != null) { 3803 return true; 3804 } 3805 // request for an instant application; if the caller hasn't been granted access, filter 3806 return !mInstantAppRegistry.isInstantAccessGranted( 3807 userId, UserHandle.getAppId(callingUid), ps.appId); 3808 } 3809 return false; 3810 } 3811 3812 /** 3813 * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int) 3814 */ 3815 private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) { 3816 return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId); 3817 } 3818 3819 private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId, 3820 int flags) { 3821 // Callers can access only the libs they depend on, otherwise they need to explicitly 3822 // ask for the shared libraries given the caller is allowed to access all static libs. 3823 if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) { 3824 // System/shell/root get to see all static libs 3825 final int appId = UserHandle.getAppId(uid); 3826 if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID 3827 || appId == Process.ROOT_UID) { 3828 return false; 3829 } 3830 } 3831 3832 // No package means no static lib as it is always on internal storage 3833 if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) { 3834 return false; 3835 } 3836 3837 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName, 3838 ps.pkg.staticSharedLibVersion); 3839 if (libEntry == null) { 3840 return false; 3841 } 3842 3843 final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid)); 3844 final String[] uidPackageNames = getPackagesForUid(resolvedUid); 3845 if (uidPackageNames == null) { 3846 return true; 3847 } 3848 3849 for (String uidPackageName : uidPackageNames) { 3850 if (ps.name.equals(uidPackageName)) { 3851 return false; 3852 } 3853 PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName); 3854 if (uidPs != null) { 3855 final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries, 3856 libEntry.info.getName()); 3857 if (index < 0) { 3858 continue; 3859 } 3860 if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) { 3861 return false; 3862 } 3863 } 3864 } 3865 return true; 3866 } 3867 3868 @Override 3869 public String[] currentToCanonicalPackageNames(String[] names) { 3870 final int callingUid = Binder.getCallingUid(); 3871 if (getInstantAppPackageName(callingUid) != null) { 3872 return names; 3873 } 3874 final String[] out = new String[names.length]; 3875 // reader 3876 synchronized (mPackages) { 3877 final int callingUserId = UserHandle.getUserId(callingUid); 3878 final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId); 3879 for (int i=names.length-1; i>=0; i--) { 3880 final PackageSetting ps = mSettings.mPackages.get(names[i]); 3881 boolean translateName = false; 3882 if (ps != null && ps.realName != null) { 3883 final boolean targetIsInstantApp = ps.getInstantApp(callingUserId); 3884 translateName = !targetIsInstantApp 3885 || canViewInstantApps 3886 || mInstantAppRegistry.isInstantAccessGranted(callingUserId, 3887 UserHandle.getAppId(callingUid), ps.appId); 3888 } 3889 out[i] = translateName ? ps.realName : names[i]; 3890 } 3891 } 3892 return out; 3893 } 3894 3895 @Override 3896 public String[] canonicalToCurrentPackageNames(String[] names) { 3897 final int callingUid = Binder.getCallingUid(); 3898 if (getInstantAppPackageName(callingUid) != null) { 3899 return names; 3900 } 3901 final String[] out = new String[names.length]; 3902 // reader 3903 synchronized (mPackages) { 3904 final int callingUserId = UserHandle.getUserId(callingUid); 3905 final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId); 3906 for (int i=names.length-1; i>=0; i--) { 3907 final String cur = mSettings.getRenamedPackageLPr(names[i]); 3908 boolean translateName = false; 3909 if (cur != null) { 3910 final PackageSetting ps = mSettings.mPackages.get(names[i]); 3911 final boolean targetIsInstantApp = 3912 ps != null && ps.getInstantApp(callingUserId); 3913 translateName = !targetIsInstantApp 3914 || canViewInstantApps 3915 || mInstantAppRegistry.isInstantAccessGranted(callingUserId, 3916 UserHandle.getAppId(callingUid), ps.appId); 3917 } 3918 out[i] = translateName ? cur : names[i]; 3919 } 3920 } 3921 return out; 3922 } 3923 3924 @Override 3925 public int getPackageUid(String packageName, int flags, int userId) { 3926 if (!sUserManager.exists(userId)) return -1; 3927 final int callingUid = Binder.getCallingUid(); 3928 flags = updateFlagsForPackage(flags, userId, packageName); 3929 enforceCrossUserPermission(callingUid, userId, 3930 false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid"); 3931 3932 // reader 3933 synchronized (mPackages) { 3934 final PackageParser.Package p = mPackages.get(packageName); 3935 if (p != null && p.isMatch(flags)) { 3936 PackageSetting ps = (PackageSetting) p.mExtras; 3937 if (filterAppAccessLPr(ps, callingUid, userId)) { 3938 return -1; 3939 } 3940 return UserHandle.getUid(userId, p.applicationInfo.uid); 3941 } 3942 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3943 final PackageSetting ps = mSettings.mPackages.get(packageName); 3944 if (ps != null && ps.isMatch(flags) 3945 && !filterAppAccessLPr(ps, callingUid, userId)) { 3946 return UserHandle.getUid(userId, ps.appId); 3947 } 3948 } 3949 } 3950 3951 return -1; 3952 } 3953 3954 @Override 3955 public int[] getPackageGids(String packageName, int flags, int userId) { 3956 if (!sUserManager.exists(userId)) return null; 3957 final int callingUid = Binder.getCallingUid(); 3958 flags = updateFlagsForPackage(flags, userId, packageName); 3959 enforceCrossUserPermission(callingUid, userId, 3960 false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids"); 3961 3962 // reader 3963 synchronized (mPackages) { 3964 final PackageParser.Package p = mPackages.get(packageName); 3965 if (p != null && p.isMatch(flags)) { 3966 PackageSetting ps = (PackageSetting) p.mExtras; 3967 if (filterAppAccessLPr(ps, callingUid, userId)) { 3968 return null; 3969 } 3970 // TODO: Shouldn't this be checking for package installed state for userId and 3971 // return null? 3972 return ps.getPermissionsState().computeGids(userId); 3973 } 3974 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3975 final PackageSetting ps = mSettings.mPackages.get(packageName); 3976 if (ps != null && ps.isMatch(flags) 3977 && !filterAppAccessLPr(ps, callingUid, userId)) { 3978 return ps.getPermissionsState().computeGids(userId); 3979 } 3980 } 3981 } 3982 3983 return null; 3984 } 3985 3986 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3987 if (bp.perm != null) { 3988 return PackageParser.generatePermissionInfo(bp.perm, flags); 3989 } 3990 PermissionInfo pi = new PermissionInfo(); 3991 pi.name = bp.name; 3992 pi.packageName = bp.sourcePackage; 3993 pi.nonLocalizedLabel = bp.name; 3994 pi.protectionLevel = bp.protectionLevel; 3995 return pi; 3996 } 3997 3998 @Override 3999 public PermissionInfo getPermissionInfo(String name, String packageName, int flags) { 4000 final int callingUid = Binder.getCallingUid(); 4001 if (getInstantAppPackageName(callingUid) != null) { 4002 return null; 4003 } 4004 // reader 4005 synchronized (mPackages) { 4006 final BasePermission p = mSettings.mPermissions.get(name); 4007 // If the caller is an app that targets pre 26 SDK drop protection flags. 4008 final PermissionInfo permissionInfo = generatePermissionInfo(p, flags); 4009 permissionInfo.protectionLevel = adjustPermissionProtectionFlagsLPr( 4010 permissionInfo.protectionLevel, packageName, callingUid); 4011 return permissionInfo; 4012 } 4013 } 4014 4015 private int adjustPermissionProtectionFlagsLPr(int protectionLevel, 4016 String packageName, int uid) { 4017 // Signature permission flags area always reported 4018 final int protectionLevelMasked = protectionLevel 4019 & (PermissionInfo.PROTECTION_NORMAL 4020 | PermissionInfo.PROTECTION_DANGEROUS 4021 | PermissionInfo.PROTECTION_SIGNATURE); 4022 if (protectionLevelMasked == PermissionInfo.PROTECTION_SIGNATURE) { 4023 return protectionLevel; 4024 } 4025 4026 // System sees all flags. 4027 final int appId = UserHandle.getAppId(uid); 4028 if (appId == Process.SYSTEM_UID || appId == Process.ROOT_UID 4029 || appId == Process.SHELL_UID) { 4030 return protectionLevel; 4031 } 4032 4033 // Normalize package name to handle renamed packages and static libs 4034 packageName = resolveInternalPackageNameLPr(packageName, 4035 PackageManager.VERSION_CODE_HIGHEST); 4036 4037 // Apps that target O see flags for all protection levels. 4038 final PackageSetting ps = mSettings.mPackages.get(packageName); 4039 if (ps == null) { 4040 return protectionLevel; 4041 } 4042 if (ps.appId != appId) { 4043 return protectionLevel; 4044 } 4045 4046 final PackageParser.Package pkg = mPackages.get(packageName); 4047 if (pkg == null) { 4048 return protectionLevel; 4049 } 4050 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) { 4051 return protectionLevelMasked; 4052 } 4053 4054 return protectionLevel; 4055 } 4056 4057 @Override 4058 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 4059 int flags) { 4060 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 4061 return null; 4062 } 4063 // reader 4064 synchronized (mPackages) { 4065 if (group != null && !mPermissionGroups.containsKey(group)) { 4066 // This is thrown as NameNotFoundException 4067 return null; 4068 } 4069 4070 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 4071 for (BasePermission p : mSettings.mPermissions.values()) { 4072 if (group == null) { 4073 if (p.perm == null || p.perm.info.group == null) { 4074 out.add(generatePermissionInfo(p, flags)); 4075 } 4076 } else { 4077 if (p.perm != null && group.equals(p.perm.info.group)) { 4078 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 4079 } 4080 } 4081 } 4082 return new ParceledListSlice<>(out); 4083 } 4084 } 4085 4086 @Override 4087 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 4088 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 4089 return null; 4090 } 4091 // reader 4092 synchronized (mPackages) { 4093 return PackageParser.generatePermissionGroupInfo( 4094 mPermissionGroups.get(name), flags); 4095 } 4096 } 4097 4098 @Override 4099 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 4100 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 4101 return ParceledListSlice.emptyList(); 4102 } 4103 // reader 4104 synchronized (mPackages) { 4105 final int N = mPermissionGroups.size(); 4106 ArrayList<PermissionGroupInfo> out 4107 = new ArrayList<PermissionGroupInfo>(N); 4108 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 4109 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 4110 } 4111 return new ParceledListSlice<>(out); 4112 } 4113 } 4114 4115 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 4116 int filterCallingUid, int userId) { 4117 if (!sUserManager.exists(userId)) return null; 4118 PackageSetting ps = mSettings.mPackages.get(packageName); 4119 if (ps != null) { 4120 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 4121 return null; 4122 } 4123 if (filterAppAccessLPr(ps, filterCallingUid, userId)) { 4124 return null; 4125 } 4126 if (ps.pkg == null) { 4127 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 4128 if (pInfo != null) { 4129 return pInfo.applicationInfo; 4130 } 4131 return null; 4132 } 4133 ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 4134 ps.readUserState(userId), userId); 4135 if (ai != null) { 4136 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 4137 } 4138 return ai; 4139 } 4140 return null; 4141 } 4142 4143 @Override 4144 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 4145 return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId); 4146 } 4147 4148 /** 4149 * Important: The provided filterCallingUid is used exclusively to filter out applications 4150 * that can be seen based on user state. It's typically the original caller uid prior 4151 * to clearing. Because it can only be provided by trusted code, it's value can be 4152 * trusted and will be used as-is; unlike userId which will be validated by this method. 4153 */ 4154 private ApplicationInfo getApplicationInfoInternal(String packageName, int flags, 4155 int filterCallingUid, int userId) { 4156 if (!sUserManager.exists(userId)) return null; 4157 flags = updateFlagsForApplication(flags, userId, packageName); 4158 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4159 false /* requireFullPermission */, false /* checkShell */, "get application info"); 4160 4161 // writer 4162 synchronized (mPackages) { 4163 // Normalize package name to handle renamed packages and static libs 4164 packageName = resolveInternalPackageNameLPr(packageName, 4165 PackageManager.VERSION_CODE_HIGHEST); 4166 4167 PackageParser.Package p = mPackages.get(packageName); 4168 if (DEBUG_PACKAGE_INFO) Log.v( 4169 TAG, "getApplicationInfo " + packageName 4170 + ": " + p); 4171 if (p != null) { 4172 PackageSetting ps = mSettings.mPackages.get(packageName); 4173 if (ps == null) return null; 4174 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 4175 return null; 4176 } 4177 if (filterAppAccessLPr(ps, filterCallingUid, userId)) { 4178 return null; 4179 } 4180 // Note: isEnabledLP() does not apply here - always return info 4181 ApplicationInfo ai = PackageParser.generateApplicationInfo( 4182 p, flags, ps.readUserState(userId), userId); 4183 if (ai != null) { 4184 ai.packageName = resolveExternalPackageNameLPr(p); 4185 } 4186 return ai; 4187 } 4188 if ("android".equals(packageName)||"system".equals(packageName)) { 4189 return mAndroidApplication; 4190 } 4191 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 4192 // Already generates the external package name 4193 return generateApplicationInfoFromSettingsLPw(packageName, 4194 flags, filterCallingUid, userId); 4195 } 4196 } 4197 return null; 4198 } 4199 4200 private String normalizePackageNameLPr(String packageName) { 4201 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 4202 return normalizedPackageName != null ? normalizedPackageName : packageName; 4203 } 4204 4205 @Override 4206 public void deletePreloadsFileCache() { 4207 if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) { 4208 throw new SecurityException("Only system or settings may call deletePreloadsFileCache"); 4209 } 4210 File dir = Environment.getDataPreloadsFileCacheDirectory(); 4211 Slog.i(TAG, "Deleting preloaded file cache " + dir); 4212 FileUtils.deleteContents(dir); 4213 } 4214 4215 @Override 4216 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 4217 final int storageFlags, final IPackageDataObserver observer) { 4218 mContext.enforceCallingOrSelfPermission( 4219 android.Manifest.permission.CLEAR_APP_CACHE, null); 4220 mHandler.post(() -> { 4221 boolean success = false; 4222 try { 4223 freeStorage(volumeUuid, freeStorageSize, storageFlags); 4224 success = true; 4225 } catch (IOException e) { 4226 Slog.w(TAG, e); 4227 } 4228 if (observer != null) { 4229 try { 4230 observer.onRemoveCompleted(null, success); 4231 } catch (RemoteException e) { 4232 Slog.w(TAG, e); 4233 } 4234 } 4235 }); 4236 } 4237 4238 @Override 4239 public void freeStorage(final String volumeUuid, final long freeStorageSize, 4240 final int storageFlags, final IntentSender pi) { 4241 mContext.enforceCallingOrSelfPermission( 4242 android.Manifest.permission.CLEAR_APP_CACHE, TAG); 4243 mHandler.post(() -> { 4244 boolean success = false; 4245 try { 4246 freeStorage(volumeUuid, freeStorageSize, storageFlags); 4247 success = true; 4248 } catch (IOException e) { 4249 Slog.w(TAG, e); 4250 } 4251 if (pi != null) { 4252 try { 4253 pi.sendIntent(null, success ? 1 : 0, null, null, null); 4254 } catch (SendIntentException e) { 4255 Slog.w(TAG, e); 4256 } 4257 } 4258 }); 4259 } 4260 4261 /** 4262 * Blocking call to clear various types of cached data across the system 4263 * until the requested bytes are available. 4264 */ 4265 public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException { 4266 final StorageManager storage = mContext.getSystemService(StorageManager.class); 4267 final File file = storage.findPathForUuid(volumeUuid); 4268 if (file.getUsableSpace() >= bytes) return; 4269 4270 if (ENABLE_FREE_CACHE_V2) { 4271 final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, 4272 volumeUuid); 4273 final boolean aggressive = (storageFlags 4274 & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0; 4275 final boolean defyReserved = (storageFlags 4276 & StorageManager.FLAG_ALLOCATE_DEFY_RESERVED) != 0; 4277 final long reservedBytes = (aggressive || defyReserved) ? 0 4278 : storage.getStorageCacheBytes(file); 4279 4280 // 1. Pre-flight to determine if we have any chance to succeed 4281 // 2. Consider preloaded data (after 1w honeymoon, unless aggressive) 4282 if (internalVolume && (aggressive || SystemProperties 4283 .getBoolean("persist.sys.preloads.file_cache_expired", false))) { 4284 deletePreloadsFileCache(); 4285 if (file.getUsableSpace() >= bytes) return; 4286 } 4287 4288 // 3. Consider parsed APK data (aggressive only) 4289 if (internalVolume && aggressive) { 4290 FileUtils.deleteContents(mCacheDir); 4291 if (file.getUsableSpace() >= bytes) return; 4292 } 4293 4294 // 4. Consider cached app data (above quotas) 4295 try { 4296 mInstaller.freeCache(volumeUuid, bytes, reservedBytes, 4297 Installer.FLAG_FREE_CACHE_V2); 4298 } catch (InstallerException ignored) { 4299 } 4300 if (file.getUsableSpace() >= bytes) return; 4301 4302 // 5. Consider shared libraries with refcount=0 and age>min cache period 4303 if (internalVolume && pruneUnusedStaticSharedLibraries(bytes, 4304 android.provider.Settings.Global.getLong(mContext.getContentResolver(), 4305 Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD, 4306 DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) { 4307 return; 4308 } 4309 4310 // 6. Consider dexopt output (aggressive only) 4311 // TODO: Implement 4312 4313 // 7. Consider installed instant apps unused longer than min cache period 4314 if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes, 4315 android.provider.Settings.Global.getLong(mContext.getContentResolver(), 4316 Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD, 4317 InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) { 4318 return; 4319 } 4320 4321 // 8. Consider cached app data (below quotas) 4322 try { 4323 mInstaller.freeCache(volumeUuid, bytes, reservedBytes, 4324 Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA); 4325 } catch (InstallerException ignored) { 4326 } 4327 if (file.getUsableSpace() >= bytes) return; 4328 4329 // 9. Consider DropBox entries 4330 // TODO: Implement 4331 4332 // 10. Consider instant meta-data (uninstalled apps) older that min cache period 4333 if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes, 4334 android.provider.Settings.Global.getLong(mContext.getContentResolver(), 4335 Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD, 4336 InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) { 4337 return; 4338 } 4339 } else { 4340 try { 4341 mInstaller.freeCache(volumeUuid, bytes, 0, 0); 4342 } catch (InstallerException ignored) { 4343 } 4344 if (file.getUsableSpace() >= bytes) return; 4345 } 4346 4347 throw new IOException("Failed to free " + bytes + " on storage device at " + file); 4348 } 4349 4350 private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod) 4351 throws IOException { 4352 final StorageManager storage = mContext.getSystemService(StorageManager.class); 4353 final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL); 4354 4355 List<VersionedPackage> packagesToDelete = null; 4356 final long now = System.currentTimeMillis(); 4357 4358 synchronized (mPackages) { 4359 final int[] allUsers = sUserManager.getUserIds(); 4360 final int libCount = mSharedLibraries.size(); 4361 for (int i = 0; i < libCount; i++) { 4362 final SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 4363 if (versionedLib == null) { 4364 continue; 4365 } 4366 final int versionCount = versionedLib.size(); 4367 for (int j = 0; j < versionCount; j++) { 4368 SharedLibraryInfo libInfo = versionedLib.valueAt(j).info; 4369 // Skip packages that are not static shared libs. 4370 if (!libInfo.isStatic()) { 4371 break; 4372 } 4373 // Important: We skip static shared libs used for some user since 4374 // in such a case we need to keep the APK on the device. The check for 4375 // a lib being used for any user is performed by the uninstall call. 4376 final VersionedPackage declaringPackage = libInfo.getDeclaringPackage(); 4377 // Resolve the package name - we use synthetic package names internally 4378 final String internalPackageName = resolveInternalPackageNameLPr( 4379 declaringPackage.getPackageName(), declaringPackage.getVersionCode()); 4380 final PackageSetting ps = mSettings.getPackageLPr(internalPackageName); 4381 // Skip unused static shared libs cached less than the min period 4382 // to prevent pruning a lib needed by a subsequently installed package. 4383 if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) { 4384 continue; 4385 } 4386 if (packagesToDelete == null) { 4387 packagesToDelete = new ArrayList<>(); 4388 } 4389 packagesToDelete.add(new VersionedPackage(internalPackageName, 4390 declaringPackage.getVersionCode())); 4391 } 4392 } 4393 } 4394 4395 if (packagesToDelete != null) { 4396 final int packageCount = packagesToDelete.size(); 4397 for (int i = 0; i < packageCount; i++) { 4398 final VersionedPackage pkgToDelete = packagesToDelete.get(i); 4399 // Delete the package synchronously (will fail of the lib used for any user). 4400 if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getVersionCode(), 4401 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS) 4402 == PackageManager.DELETE_SUCCEEDED) { 4403 if (volume.getUsableSpace() >= neededSpace) { 4404 return true; 4405 } 4406 } 4407 } 4408 } 4409 4410 return false; 4411 } 4412 4413 /** 4414 * Update given flags based on encryption status of current user. 4415 */ 4416 private int updateFlags(int flags, int userId) { 4417 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 4418 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 4419 // Caller expressed an explicit opinion about what encryption 4420 // aware/unaware components they want to see, so fall through and 4421 // give them what they want 4422 } else { 4423 // Caller expressed no opinion, so match based on user state 4424 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 4425 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 4426 } else { 4427 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 4428 } 4429 } 4430 return flags; 4431 } 4432 4433 private UserManagerInternal getUserManagerInternal() { 4434 if (mUserManagerInternal == null) { 4435 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 4436 } 4437 return mUserManagerInternal; 4438 } 4439 4440 private DeviceIdleController.LocalService getDeviceIdleController() { 4441 if (mDeviceIdleController == null) { 4442 mDeviceIdleController = 4443 LocalServices.getService(DeviceIdleController.LocalService.class); 4444 } 4445 return mDeviceIdleController; 4446 } 4447 4448 /** 4449 * Update given flags when being used to request {@link PackageInfo}. 4450 */ 4451 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 4452 final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM; 4453 boolean triaged = true; 4454 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 4455 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 4456 // Caller is asking for component details, so they'd better be 4457 // asking for specific encryption matching behavior, or be triaged 4458 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 4459 | PackageManager.MATCH_DIRECT_BOOT_AWARE 4460 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 4461 triaged = false; 4462 } 4463 } 4464 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 4465 | PackageManager.MATCH_SYSTEM_ONLY 4466 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 4467 triaged = false; 4468 } 4469 if ((flags & PackageManager.MATCH_ANY_USER) != 0) { 4470 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 4471 "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at " 4472 + Debug.getCallers(5)); 4473 } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser 4474 && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) { 4475 // If the caller wants all packages and has a restricted profile associated with it, 4476 // then match all users. This is to make sure that launchers that need to access work 4477 // profile apps don't start breaking. TODO: Remove this hack when launchers stop using 4478 // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380 4479 flags |= PackageManager.MATCH_ANY_USER; 4480 } 4481 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 4482 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 4483 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 4484 } 4485 return updateFlags(flags, userId); 4486 } 4487 4488 /** 4489 * Update given flags when being used to request {@link ApplicationInfo}. 4490 */ 4491 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 4492 return updateFlagsForPackage(flags, userId, cookie); 4493 } 4494 4495 /** 4496 * Update given flags when being used to request {@link ComponentInfo}. 4497 */ 4498 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 4499 if (cookie instanceof Intent) { 4500 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 4501 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 4502 } 4503 } 4504 4505 boolean triaged = true; 4506 // Caller is asking for component details, so they'd better be 4507 // asking for specific encryption matching behavior, or be triaged 4508 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 4509 | PackageManager.MATCH_DIRECT_BOOT_AWARE 4510 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 4511 triaged = false; 4512 } 4513 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 4514 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 4515 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 4516 } 4517 4518 return updateFlags(flags, userId); 4519 } 4520 4521 /** 4522 * Update given intent when being used to request {@link ResolveInfo}. 4523 */ 4524 private Intent updateIntentForResolve(Intent intent) { 4525 if (intent.getSelector() != null) { 4526 intent = intent.getSelector(); 4527 } 4528 if (DEBUG_PREFERRED) { 4529 intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4530 } 4531 return intent; 4532 } 4533 4534 /** 4535 * Update given flags when being used to request {@link ResolveInfo}. 4536 * <p>Instant apps are resolved specially, depending upon context. Minimally, 4537 * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT} 4538 * flag set. However, this flag is only honoured in three circumstances: 4539 * <ul> 4540 * <li>when called from a system process</li> 4541 * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li> 4542 * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW} 4543 * action and a {@code android.intent.category.BROWSABLE} category</li> 4544 * </ul> 4545 */ 4546 int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) { 4547 return updateFlagsForResolve(flags, userId, intent, callingUid, 4548 false /*wantInstantApps*/, false /*onlyExposedExplicitly*/); 4549 } 4550 int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid, 4551 boolean wantInstantApps) { 4552 return updateFlagsForResolve(flags, userId, intent, callingUid, 4553 wantInstantApps, false /*onlyExposedExplicitly*/); 4554 } 4555 int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid, 4556 boolean wantInstantApps, boolean onlyExposedExplicitly) { 4557 // Safe mode means we shouldn't match any third-party components 4558 if (mSafeMode) { 4559 flags |= PackageManager.MATCH_SYSTEM_ONLY; 4560 } 4561 if (getInstantAppPackageName(callingUid) != null) { 4562 // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components 4563 if (onlyExposedExplicitly) { 4564 flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY; 4565 } 4566 flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY; 4567 flags |= PackageManager.MATCH_INSTANT; 4568 } else { 4569 final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0; 4570 final boolean allowMatchInstant = 4571 (wantInstantApps 4572 && Intent.ACTION_VIEW.equals(intent.getAction()) 4573 && hasWebURI(intent)) 4574 || (wantMatchInstant && canViewInstantApps(callingUid, userId)); 4575 flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY 4576 | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY); 4577 if (!allowMatchInstant) { 4578 flags &= ~PackageManager.MATCH_INSTANT; 4579 } 4580 } 4581 return updateFlagsForComponent(flags, userId, intent /*cookie*/); 4582 } 4583 4584 @Override 4585 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 4586 return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId); 4587 } 4588 4589 /** 4590 * Important: The provided filterCallingUid is used exclusively to filter out activities 4591 * that can be seen based on user state. It's typically the original caller uid prior 4592 * to clearing. Because it can only be provided by trusted code, it's value can be 4593 * trusted and will be used as-is; unlike userId which will be validated by this method. 4594 */ 4595 private ActivityInfo getActivityInfoInternal(ComponentName component, int flags, 4596 int filterCallingUid, int userId) { 4597 if (!sUserManager.exists(userId)) return null; 4598 flags = updateFlagsForComponent(flags, userId, component); 4599 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4600 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 4601 synchronized (mPackages) { 4602 PackageParser.Activity a = mActivities.mActivities.get(component); 4603 4604 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 4605 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 4606 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4607 if (ps == null) return null; 4608 if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) { 4609 return null; 4610 } 4611 return PackageParser.generateActivityInfo( 4612 a, flags, ps.readUserState(userId), userId); 4613 } 4614 if (mResolveComponentName.equals(component)) { 4615 return PackageParser.generateActivityInfo( 4616 mResolveActivity, flags, new PackageUserState(), userId); 4617 } 4618 } 4619 return null; 4620 } 4621 4622 @Override 4623 public boolean activitySupportsIntent(ComponentName component, Intent intent, 4624 String resolvedType) { 4625 synchronized (mPackages) { 4626 if (component.equals(mResolveComponentName)) { 4627 // The resolver supports EVERYTHING! 4628 return true; 4629 } 4630 final int callingUid = Binder.getCallingUid(); 4631 final int callingUserId = UserHandle.getUserId(callingUid); 4632 PackageParser.Activity a = mActivities.mActivities.get(component); 4633 if (a == null) { 4634 return false; 4635 } 4636 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4637 if (ps == null) { 4638 return false; 4639 } 4640 if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) { 4641 return false; 4642 } 4643 for (int i=0; i<a.intents.size(); i++) { 4644 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 4645 intent.getData(), intent.getCategories(), TAG) >= 0) { 4646 return true; 4647 } 4648 } 4649 return false; 4650 } 4651 } 4652 4653 @Override 4654 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 4655 if (!sUserManager.exists(userId)) return null; 4656 final int callingUid = Binder.getCallingUid(); 4657 flags = updateFlagsForComponent(flags, userId, component); 4658 enforceCrossUserPermission(callingUid, userId, 4659 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 4660 synchronized (mPackages) { 4661 PackageParser.Activity a = mReceivers.mActivities.get(component); 4662 if (DEBUG_PACKAGE_INFO) Log.v( 4663 TAG, "getReceiverInfo " + component + ": " + a); 4664 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 4665 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4666 if (ps == null) return null; 4667 if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) { 4668 return null; 4669 } 4670 return PackageParser.generateActivityInfo( 4671 a, flags, ps.readUserState(userId), userId); 4672 } 4673 } 4674 return null; 4675 } 4676 4677 @Override 4678 public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName, 4679 int flags, int userId) { 4680 if (!sUserManager.exists(userId)) return null; 4681 Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0"); 4682 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 4683 return null; 4684 } 4685 4686 flags = updateFlagsForPackage(flags, userId, null); 4687 4688 final boolean canSeeStaticLibraries = 4689 mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES) 4690 == PERMISSION_GRANTED 4691 || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES) 4692 == PERMISSION_GRANTED 4693 || canRequestPackageInstallsInternal(packageName, 4694 PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId, 4695 false /* throwIfPermNotDeclared*/) 4696 || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES) 4697 == PERMISSION_GRANTED; 4698 4699 synchronized (mPackages) { 4700 List<SharedLibraryInfo> result = null; 4701 4702 final int libCount = mSharedLibraries.size(); 4703 for (int i = 0; i < libCount; i++) { 4704 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 4705 if (versionedLib == null) { 4706 continue; 4707 } 4708 4709 final int versionCount = versionedLib.size(); 4710 for (int j = 0; j < versionCount; j++) { 4711 SharedLibraryInfo libInfo = versionedLib.valueAt(j).info; 4712 if (!canSeeStaticLibraries && libInfo.isStatic()) { 4713 break; 4714 } 4715 final long identity = Binder.clearCallingIdentity(); 4716 try { 4717 PackageInfo packageInfo = getPackageInfoVersioned( 4718 libInfo.getDeclaringPackage(), flags 4719 | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId); 4720 if (packageInfo == null) { 4721 continue; 4722 } 4723 } finally { 4724 Binder.restoreCallingIdentity(identity); 4725 } 4726 4727 SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(), 4728 libInfo.getVersion(), libInfo.getType(), 4729 libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo, 4730 flags, userId)); 4731 4732 if (result == null) { 4733 result = new ArrayList<>(); 4734 } 4735 result.add(resLibInfo); 4736 } 4737 } 4738 4739 return result != null ? new ParceledListSlice<>(result) : null; 4740 } 4741 } 4742 4743 private List<VersionedPackage> getPackagesUsingSharedLibraryLPr( 4744 SharedLibraryInfo libInfo, int flags, int userId) { 4745 List<VersionedPackage> versionedPackages = null; 4746 final int packageCount = mSettings.mPackages.size(); 4747 for (int i = 0; i < packageCount; i++) { 4748 PackageSetting ps = mSettings.mPackages.valueAt(i); 4749 4750 if (ps == null) { 4751 continue; 4752 } 4753 4754 if (!ps.getUserState().get(userId).isAvailable(flags)) { 4755 continue; 4756 } 4757 4758 final String libName = libInfo.getName(); 4759 if (libInfo.isStatic()) { 4760 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 4761 if (libIdx < 0) { 4762 continue; 4763 } 4764 if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) { 4765 continue; 4766 } 4767 if (versionedPackages == null) { 4768 versionedPackages = new ArrayList<>(); 4769 } 4770 // If the dependent is a static shared lib, use the public package name 4771 String dependentPackageName = ps.name; 4772 if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) { 4773 dependentPackageName = ps.pkg.manifestPackageName; 4774 } 4775 versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode)); 4776 } else if (ps.pkg != null) { 4777 if (ArrayUtils.contains(ps.pkg.usesLibraries, libName) 4778 || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) { 4779 if (versionedPackages == null) { 4780 versionedPackages = new ArrayList<>(); 4781 } 4782 versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode)); 4783 } 4784 } 4785 } 4786 4787 return versionedPackages; 4788 } 4789 4790 @Override 4791 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 4792 if (!sUserManager.exists(userId)) return null; 4793 final int callingUid = Binder.getCallingUid(); 4794 flags = updateFlagsForComponent(flags, userId, component); 4795 enforceCrossUserPermission(callingUid, userId, 4796 false /* requireFullPermission */, false /* checkShell */, "get service info"); 4797 synchronized (mPackages) { 4798 PackageParser.Service s = mServices.mServices.get(component); 4799 if (DEBUG_PACKAGE_INFO) Log.v( 4800 TAG, "getServiceInfo " + component + ": " + s); 4801 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 4802 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4803 if (ps == null) return null; 4804 if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) { 4805 return null; 4806 } 4807 return PackageParser.generateServiceInfo( 4808 s, flags, ps.readUserState(userId), userId); 4809 } 4810 } 4811 return null; 4812 } 4813 4814 @Override 4815 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 4816 if (!sUserManager.exists(userId)) return null; 4817 final int callingUid = Binder.getCallingUid(); 4818 flags = updateFlagsForComponent(flags, userId, component); 4819 enforceCrossUserPermission(callingUid, userId, 4820 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 4821 synchronized (mPackages) { 4822 PackageParser.Provider p = mProviders.mProviders.get(component); 4823 if (DEBUG_PACKAGE_INFO) Log.v( 4824 TAG, "getProviderInfo " + component + ": " + p); 4825 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 4826 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4827 if (ps == null) return null; 4828 if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) { 4829 return null; 4830 } 4831 return PackageParser.generateProviderInfo( 4832 p, flags, ps.readUserState(userId), userId); 4833 } 4834 } 4835 return null; 4836 } 4837 4838 @Override 4839 public String[] getSystemSharedLibraryNames() { 4840 // allow instant applications 4841 synchronized (mPackages) { 4842 Set<String> libs = null; 4843 final int libCount = mSharedLibraries.size(); 4844 for (int i = 0; i < libCount; i++) { 4845 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 4846 if (versionedLib == null) { 4847 continue; 4848 } 4849 final int versionCount = versionedLib.size(); 4850 for (int j = 0; j < versionCount; j++) { 4851 SharedLibraryEntry libEntry = versionedLib.valueAt(j); 4852 if (!libEntry.info.isStatic()) { 4853 if (libs == null) { 4854 libs = new ArraySet<>(); 4855 } 4856 libs.add(libEntry.info.getName()); 4857 break; 4858 } 4859 PackageSetting ps = mSettings.getPackageLPr(libEntry.apk); 4860 if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(), 4861 UserHandle.getUserId(Binder.getCallingUid()), 4862 PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) { 4863 if (libs == null) { 4864 libs = new ArraySet<>(); 4865 } 4866 libs.add(libEntry.info.getName()); 4867 break; 4868 } 4869 } 4870 } 4871 4872 if (libs != null) { 4873 String[] libsArray = new String[libs.size()]; 4874 libs.toArray(libsArray); 4875 return libsArray; 4876 } 4877 4878 return null; 4879 } 4880 } 4881 4882 @Override 4883 public @NonNull String getServicesSystemSharedLibraryPackageName() { 4884 // allow instant applications 4885 synchronized (mPackages) { 4886 return mServicesSystemSharedLibraryPackageName; 4887 } 4888 } 4889 4890 @Override 4891 public @NonNull String getSharedSystemSharedLibraryPackageName() { 4892 // allow instant applications 4893 synchronized (mPackages) { 4894 return mSharedSystemSharedLibraryPackageName; 4895 } 4896 } 4897 4898 private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) { 4899 for (int i = userList.length - 1; i >= 0; --i) { 4900 final int userId = userList[i]; 4901 // don't add instant app to the list of updates 4902 if (pkgSetting.getInstantApp(userId)) { 4903 continue; 4904 } 4905 SparseArray<String> changedPackages = mChangedPackages.get(userId); 4906 if (changedPackages == null) { 4907 changedPackages = new SparseArray<>(); 4908 mChangedPackages.put(userId, changedPackages); 4909 } 4910 Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId); 4911 if (sequenceNumbers == null) { 4912 sequenceNumbers = new HashMap<>(); 4913 mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers); 4914 } 4915 final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name); 4916 if (sequenceNumber != null) { 4917 changedPackages.remove(sequenceNumber); 4918 } 4919 changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name); 4920 sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber); 4921 } 4922 mChangedPackagesSequenceNumber++; 4923 } 4924 4925 @Override 4926 public ChangedPackages getChangedPackages(int sequenceNumber, int userId) { 4927 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 4928 return null; 4929 } 4930 synchronized (mPackages) { 4931 if (sequenceNumber >= mChangedPackagesSequenceNumber) { 4932 return null; 4933 } 4934 final SparseArray<String> changedPackages = mChangedPackages.get(userId); 4935 if (changedPackages == null) { 4936 return null; 4937 } 4938 final List<String> packageNames = 4939 new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber); 4940 for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) { 4941 final String packageName = changedPackages.get(i); 4942 if (packageName != null) { 4943 packageNames.add(packageName); 4944 } 4945 } 4946 return packageNames.isEmpty() 4947 ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames); 4948 } 4949 } 4950 4951 @Override 4952 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 4953 // allow instant applications 4954 ArrayList<FeatureInfo> res; 4955 synchronized (mAvailableFeatures) { 4956 res = new ArrayList<>(mAvailableFeatures.size() + 1); 4957 res.addAll(mAvailableFeatures.values()); 4958 } 4959 final FeatureInfo fi = new FeatureInfo(); 4960 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 4961 FeatureInfo.GL_ES_VERSION_UNDEFINED); 4962 res.add(fi); 4963 4964 return new ParceledListSlice<>(res); 4965 } 4966 4967 @Override 4968 public boolean hasSystemFeature(String name, int version) { 4969 // allow instant applications 4970 synchronized (mAvailableFeatures) { 4971 final FeatureInfo feat = mAvailableFeatures.get(name); 4972 if (feat == null) { 4973 return false; 4974 } else { 4975 return feat.version >= version; 4976 } 4977 } 4978 } 4979 4980 @Override 4981 public int checkPermission(String permName, String pkgName, int userId) { 4982 if (!sUserManager.exists(userId)) { 4983 return PackageManager.PERMISSION_DENIED; 4984 } 4985 final int callingUid = Binder.getCallingUid(); 4986 4987 synchronized (mPackages) { 4988 final PackageParser.Package p = mPackages.get(pkgName); 4989 if (p != null && p.mExtras != null) { 4990 final PackageSetting ps = (PackageSetting) p.mExtras; 4991 if (filterAppAccessLPr(ps, callingUid, userId)) { 4992 return PackageManager.PERMISSION_DENIED; 4993 } 4994 final boolean instantApp = ps.getInstantApp(userId); 4995 final PermissionsState permissionsState = ps.getPermissionsState(); 4996 if (permissionsState.hasPermission(permName, userId)) { 4997 if (instantApp) { 4998 BasePermission bp = mSettings.mPermissions.get(permName); 4999 if (bp != null && bp.isInstant()) { 5000 return PackageManager.PERMISSION_GRANTED; 5001 } 5002 } else { 5003 return PackageManager.PERMISSION_GRANTED; 5004 } 5005 } 5006 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 5007 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 5008 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 5009 return PackageManager.PERMISSION_GRANTED; 5010 } 5011 } 5012 } 5013 5014 return PackageManager.PERMISSION_DENIED; 5015 } 5016 5017 @Override 5018 public int checkUidPermission(String permName, int uid) { 5019 final int callingUid = Binder.getCallingUid(); 5020 final int callingUserId = UserHandle.getUserId(callingUid); 5021 final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null; 5022 final boolean isUidInstantApp = getInstantAppPackageName(uid) != null; 5023 final int userId = UserHandle.getUserId(uid); 5024 if (!sUserManager.exists(userId)) { 5025 return PackageManager.PERMISSION_DENIED; 5026 } 5027 5028 synchronized (mPackages) { 5029 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5030 if (obj != null) { 5031 if (obj instanceof SharedUserSetting) { 5032 if (isCallerInstantApp) { 5033 return PackageManager.PERMISSION_DENIED; 5034 } 5035 } else if (obj instanceof PackageSetting) { 5036 final PackageSetting ps = (PackageSetting) obj; 5037 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 5038 return PackageManager.PERMISSION_DENIED; 5039 } 5040 } 5041 final SettingBase settingBase = (SettingBase) obj; 5042 final PermissionsState permissionsState = settingBase.getPermissionsState(); 5043 if (permissionsState.hasPermission(permName, userId)) { 5044 if (isUidInstantApp) { 5045 BasePermission bp = mSettings.mPermissions.get(permName); 5046 if (bp != null && bp.isInstant()) { 5047 return PackageManager.PERMISSION_GRANTED; 5048 } 5049 } else { 5050 return PackageManager.PERMISSION_GRANTED; 5051 } 5052 } 5053 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 5054 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 5055 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 5056 return PackageManager.PERMISSION_GRANTED; 5057 } 5058 } else { 5059 ArraySet<String> perms = mSystemPermissions.get(uid); 5060 if (perms != null) { 5061 if (perms.contains(permName)) { 5062 return PackageManager.PERMISSION_GRANTED; 5063 } 5064 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 5065 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 5066 return PackageManager.PERMISSION_GRANTED; 5067 } 5068 } 5069 } 5070 } 5071 5072 return PackageManager.PERMISSION_DENIED; 5073 } 5074 5075 @Override 5076 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 5077 if (UserHandle.getCallingUserId() != userId) { 5078 mContext.enforceCallingPermission( 5079 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5080 "isPermissionRevokedByPolicy for user " + userId); 5081 } 5082 5083 if (checkPermission(permission, packageName, userId) 5084 == PackageManager.PERMISSION_GRANTED) { 5085 return false; 5086 } 5087 5088 final int callingUid = Binder.getCallingUid(); 5089 if (getInstantAppPackageName(callingUid) != null) { 5090 if (!isCallerSameApp(packageName, callingUid)) { 5091 return false; 5092 } 5093 } else { 5094 if (isInstantApp(packageName, userId)) { 5095 return false; 5096 } 5097 } 5098 5099 final long identity = Binder.clearCallingIdentity(); 5100 try { 5101 final int flags = getPermissionFlags(permission, packageName, userId); 5102 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 5103 } finally { 5104 Binder.restoreCallingIdentity(identity); 5105 } 5106 } 5107 5108 @Override 5109 public String getPermissionControllerPackageName() { 5110 synchronized (mPackages) { 5111 return mRequiredInstallerPackage; 5112 } 5113 } 5114 5115 /** 5116 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 5117 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 5118 * @param checkShell whether to prevent shell from access if there's a debugging restriction 5119 * @param message the message to log on security exception 5120 */ 5121 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 5122 boolean checkShell, String message) { 5123 if (userId < 0) { 5124 throw new IllegalArgumentException("Invalid userId " + userId); 5125 } 5126 if (checkShell) { 5127 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 5128 } 5129 if (userId == UserHandle.getUserId(callingUid)) return; 5130 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 5131 if (requireFullPermission) { 5132 mContext.enforceCallingOrSelfPermission( 5133 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 5134 } else { 5135 try { 5136 mContext.enforceCallingOrSelfPermission( 5137 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 5138 } catch (SecurityException se) { 5139 mContext.enforceCallingOrSelfPermission( 5140 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 5141 } 5142 } 5143 } 5144 } 5145 5146 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 5147 if (callingUid == Process.SHELL_UID) { 5148 if (userHandle >= 0 5149 && sUserManager.hasUserRestriction(restriction, userHandle)) { 5150 throw new SecurityException("Shell does not have permission to access user " 5151 + userHandle); 5152 } else if (userHandle < 0) { 5153 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 5154 + Debug.getCallers(3)); 5155 } 5156 } 5157 } 5158 5159 private BasePermission findPermissionTreeLP(String permName) { 5160 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 5161 if (permName.startsWith(bp.name) && 5162 permName.length() > bp.name.length() && 5163 permName.charAt(bp.name.length()) == '.') { 5164 return bp; 5165 } 5166 } 5167 return null; 5168 } 5169 5170 private BasePermission checkPermissionTreeLP(String permName) { 5171 if (permName != null) { 5172 BasePermission bp = findPermissionTreeLP(permName); 5173 if (bp != null) { 5174 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 5175 return bp; 5176 } 5177 throw new SecurityException("Calling uid " 5178 + Binder.getCallingUid() 5179 + " is not allowed to add to permission tree " 5180 + bp.name + " owned by uid " + bp.uid); 5181 } 5182 } 5183 throw new SecurityException("No permission tree found for " + permName); 5184 } 5185 5186 static boolean compareStrings(CharSequence s1, CharSequence s2) { 5187 if (s1 == null) { 5188 return s2 == null; 5189 } 5190 if (s2 == null) { 5191 return false; 5192 } 5193 if (s1.getClass() != s2.getClass()) { 5194 return false; 5195 } 5196 return s1.equals(s2); 5197 } 5198 5199 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 5200 if (pi1.icon != pi2.icon) return false; 5201 if (pi1.logo != pi2.logo) return false; 5202 if (pi1.protectionLevel != pi2.protectionLevel) return false; 5203 if (!compareStrings(pi1.name, pi2.name)) return false; 5204 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 5205 // We'll take care of setting this one. 5206 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 5207 // These are not currently stored in settings. 5208 //if (!compareStrings(pi1.group, pi2.group)) return false; 5209 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 5210 //if (pi1.labelRes != pi2.labelRes) return false; 5211 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 5212 return true; 5213 } 5214 5215 int permissionInfoFootprint(PermissionInfo info) { 5216 int size = info.name.length(); 5217 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 5218 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 5219 return size; 5220 } 5221 5222 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 5223 int size = 0; 5224 for (BasePermission perm : mSettings.mPermissions.values()) { 5225 if (perm.uid == tree.uid) { 5226 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 5227 } 5228 } 5229 return size; 5230 } 5231 5232 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 5233 // We calculate the max size of permissions defined by this uid and throw 5234 // if that plus the size of 'info' would exceed our stated maximum. 5235 if (tree.uid != Process.SYSTEM_UID) { 5236 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 5237 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 5238 throw new SecurityException("Permission tree size cap exceeded"); 5239 } 5240 } 5241 } 5242 5243 boolean addPermissionLocked(PermissionInfo info, boolean async) { 5244 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5245 throw new SecurityException("Instant apps can't add permissions"); 5246 } 5247 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 5248 throw new SecurityException("Label must be specified in permission"); 5249 } 5250 BasePermission tree = checkPermissionTreeLP(info.name); 5251 BasePermission bp = mSettings.mPermissions.get(info.name); 5252 boolean added = bp == null; 5253 boolean changed = true; 5254 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 5255 if (added) { 5256 enforcePermissionCapLocked(info, tree); 5257 bp = new BasePermission(info.name, tree.sourcePackage, 5258 BasePermission.TYPE_DYNAMIC); 5259 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 5260 throw new SecurityException( 5261 "Not allowed to modify non-dynamic permission " 5262 + info.name); 5263 } else { 5264 if (bp.protectionLevel == fixedLevel 5265 && bp.perm.owner.equals(tree.perm.owner) 5266 && bp.uid == tree.uid 5267 && comparePermissionInfos(bp.perm.info, info)) { 5268 changed = false; 5269 } 5270 } 5271 bp.protectionLevel = fixedLevel; 5272 info = new PermissionInfo(info); 5273 info.protectionLevel = fixedLevel; 5274 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 5275 bp.perm.info.packageName = tree.perm.info.packageName; 5276 bp.uid = tree.uid; 5277 if (added) { 5278 mSettings.mPermissions.put(info.name, bp); 5279 } 5280 if (changed) { 5281 if (!async) { 5282 mSettings.writeLPr(); 5283 } else { 5284 scheduleWriteSettingsLocked(); 5285 } 5286 } 5287 return added; 5288 } 5289 5290 @Override 5291 public boolean addPermission(PermissionInfo info) { 5292 synchronized (mPackages) { 5293 return addPermissionLocked(info, false); 5294 } 5295 } 5296 5297 @Override 5298 public boolean addPermissionAsync(PermissionInfo info) { 5299 synchronized (mPackages) { 5300 return addPermissionLocked(info, true); 5301 } 5302 } 5303 5304 @Override 5305 public void removePermission(String name) { 5306 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5307 throw new SecurityException("Instant applications don't have access to this method"); 5308 } 5309 synchronized (mPackages) { 5310 checkPermissionTreeLP(name); 5311 BasePermission bp = mSettings.mPermissions.get(name); 5312 if (bp != null) { 5313 if (bp.type != BasePermission.TYPE_DYNAMIC) { 5314 throw new SecurityException( 5315 "Not allowed to modify non-dynamic permission " 5316 + name); 5317 } 5318 mSettings.mPermissions.remove(name); 5319 mSettings.writeLPr(); 5320 } 5321 } 5322 } 5323 5324 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission( 5325 PackageParser.Package pkg, BasePermission bp) { 5326 int index = pkg.requestedPermissions.indexOf(bp.name); 5327 if (index == -1) { 5328 throw new SecurityException("Package " + pkg.packageName 5329 + " has not requested permission " + bp.name); 5330 } 5331 if (!bp.isRuntime() && !bp.isDevelopment()) { 5332 throw new SecurityException("Permission " + bp.name 5333 + " is not a changeable permission type"); 5334 } 5335 } 5336 5337 @Override 5338 public void grantRuntimePermission(String packageName, String name, final int userId) { 5339 grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */); 5340 } 5341 5342 private void grantRuntimePermission(String packageName, String name, final int userId, 5343 boolean overridePolicy) { 5344 if (!sUserManager.exists(userId)) { 5345 Log.e(TAG, "No such user:" + userId); 5346 return; 5347 } 5348 final int callingUid = Binder.getCallingUid(); 5349 5350 mContext.enforceCallingOrSelfPermission( 5351 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 5352 "grantRuntimePermission"); 5353 5354 enforceCrossUserPermission(callingUid, userId, 5355 true /* requireFullPermission */, true /* checkShell */, 5356 "grantRuntimePermission"); 5357 5358 final int uid; 5359 final PackageSetting ps; 5360 5361 synchronized (mPackages) { 5362 final PackageParser.Package pkg = mPackages.get(packageName); 5363 if (pkg == null) { 5364 throw new IllegalArgumentException("Unknown package: " + packageName); 5365 } 5366 final BasePermission bp = mSettings.mPermissions.get(name); 5367 if (bp == null) { 5368 throw new IllegalArgumentException("Unknown permission: " + name); 5369 } 5370 ps = (PackageSetting) pkg.mExtras; 5371 if (ps == null 5372 || filterAppAccessLPr(ps, callingUid, userId)) { 5373 throw new IllegalArgumentException("Unknown package: " + packageName); 5374 } 5375 5376 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 5377 5378 // If a permission review is required for legacy apps we represent 5379 // their permissions as always granted runtime ones since we need 5380 // to keep the review required permission flag per user while an 5381 // install permission's state is shared across all users. 5382 if (mPermissionReviewRequired 5383 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 5384 && bp.isRuntime()) { 5385 return; 5386 } 5387 5388 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 5389 5390 final PermissionsState permissionsState = ps.getPermissionsState(); 5391 5392 final int flags = permissionsState.getPermissionFlags(name, userId); 5393 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 5394 throw new SecurityException("Cannot grant system fixed permission " 5395 + name + " for package " + packageName); 5396 } 5397 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) { 5398 throw new SecurityException("Cannot grant policy fixed permission " 5399 + name + " for package " + packageName); 5400 } 5401 5402 if (bp.isDevelopment()) { 5403 // Development permissions must be handled specially, since they are not 5404 // normal runtime permissions. For now they apply to all users. 5405 if (permissionsState.grantInstallPermission(bp) != 5406 PermissionsState.PERMISSION_OPERATION_FAILURE) { 5407 scheduleWriteSettingsLocked(); 5408 } 5409 return; 5410 } 5411 5412 if (ps.getInstantApp(userId) && !bp.isInstant()) { 5413 throw new SecurityException("Cannot grant non-ephemeral permission" 5414 + name + " for package " + packageName); 5415 } 5416 5417 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 5418 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 5419 return; 5420 } 5421 5422 final int result = permissionsState.grantRuntimePermission(bp, userId); 5423 switch (result) { 5424 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 5425 return; 5426 } 5427 5428 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 5429 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 5430 mHandler.post(new Runnable() { 5431 @Override 5432 public void run() { 5433 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 5434 } 5435 }); 5436 } 5437 break; 5438 } 5439 5440 if (bp.isRuntime()) { 5441 logPermissionGranted(mContext, name, packageName); 5442 } 5443 5444 mOnPermissionChangeListeners.onPermissionsChanged(uid); 5445 5446 // Not critical if that is lost - app has to request again. 5447 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 5448 } 5449 5450 // Only need to do this if user is initialized. Otherwise it's a new user 5451 // and there are no processes running as the user yet and there's no need 5452 // to make an expensive call to remount processes for the changed permissions. 5453 if (READ_EXTERNAL_STORAGE.equals(name) 5454 || WRITE_EXTERNAL_STORAGE.equals(name)) { 5455 final long token = Binder.clearCallingIdentity(); 5456 try { 5457 if (sUserManager.isInitialized(userId)) { 5458 StorageManagerInternal storageManagerInternal = LocalServices.getService( 5459 StorageManagerInternal.class); 5460 storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName); 5461 } 5462 } finally { 5463 Binder.restoreCallingIdentity(token); 5464 } 5465 } 5466 } 5467 5468 @Override 5469 public void revokeRuntimePermission(String packageName, String name, int userId) { 5470 revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */); 5471 } 5472 5473 private void revokeRuntimePermission(String packageName, String name, int userId, 5474 boolean overridePolicy) { 5475 if (!sUserManager.exists(userId)) { 5476 Log.e(TAG, "No such user:" + userId); 5477 return; 5478 } 5479 5480 mContext.enforceCallingOrSelfPermission( 5481 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 5482 "revokeRuntimePermission"); 5483 5484 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5485 true /* requireFullPermission */, true /* checkShell */, 5486 "revokeRuntimePermission"); 5487 5488 final int appId; 5489 5490 synchronized (mPackages) { 5491 final PackageParser.Package pkg = mPackages.get(packageName); 5492 if (pkg == null) { 5493 throw new IllegalArgumentException("Unknown package: " + packageName); 5494 } 5495 final PackageSetting ps = (PackageSetting) pkg.mExtras; 5496 if (ps == null 5497 || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) { 5498 throw new IllegalArgumentException("Unknown package: " + packageName); 5499 } 5500 final BasePermission bp = mSettings.mPermissions.get(name); 5501 if (bp == null) { 5502 throw new IllegalArgumentException("Unknown permission: " + name); 5503 } 5504 5505 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 5506 5507 // If a permission review is required for legacy apps we represent 5508 // their permissions as always granted runtime ones since we need 5509 // to keep the review required permission flag per user while an 5510 // install permission's state is shared across all users. 5511 if (mPermissionReviewRequired 5512 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 5513 && bp.isRuntime()) { 5514 return; 5515 } 5516 5517 final PermissionsState permissionsState = ps.getPermissionsState(); 5518 5519 final int flags = permissionsState.getPermissionFlags(name, userId); 5520 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 5521 throw new SecurityException("Cannot revoke system fixed permission " 5522 + name + " for package " + packageName); 5523 } 5524 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) { 5525 throw new SecurityException("Cannot revoke policy fixed permission " 5526 + name + " for package " + packageName); 5527 } 5528 5529 if (bp.isDevelopment()) { 5530 // Development permissions must be handled specially, since they are not 5531 // normal runtime permissions. For now they apply to all users. 5532 if (permissionsState.revokeInstallPermission(bp) != 5533 PermissionsState.PERMISSION_OPERATION_FAILURE) { 5534 scheduleWriteSettingsLocked(); 5535 } 5536 return; 5537 } 5538 5539 if (permissionsState.revokeRuntimePermission(bp, userId) == 5540 PermissionsState.PERMISSION_OPERATION_FAILURE) { 5541 return; 5542 } 5543 5544 if (bp.isRuntime()) { 5545 logPermissionRevoked(mContext, name, packageName); 5546 } 5547 5548 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 5549 5550 // Critical, after this call app should never have the permission. 5551 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 5552 5553 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 5554 } 5555 5556 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 5557 } 5558 5559 /** 5560 * Get the first event id for the permission. 5561 * 5562 * <p>There are four events for each permission: <ul> 5563 * <li>Request permission: first id + 0</li> 5564 * <li>Grant permission: first id + 1</li> 5565 * <li>Request for permission denied: first id + 2</li> 5566 * <li>Revoke permission: first id + 3</li> 5567 * </ul></p> 5568 * 5569 * @param name name of the permission 5570 * 5571 * @return The first event id for the permission 5572 */ 5573 private static int getBaseEventId(@NonNull String name) { 5574 int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name); 5575 5576 if (eventIdIndex == -1) { 5577 if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE 5578 || "user".equals(Build.TYPE)) { 5579 Log.i(TAG, "Unknown permission " + name); 5580 5581 return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN; 5582 } else { 5583 // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated. 5584 // 5585 // Also update 5586 // - EventLogger#ALL_DANGEROUS_PERMISSIONS 5587 // - metrics_constants.proto 5588 throw new IllegalStateException("Unknown permission " + name); 5589 } 5590 } 5591 5592 return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4; 5593 } 5594 5595 /** 5596 * Log that a permission was revoked. 5597 * 5598 * @param context Context of the caller 5599 * @param name name of the permission 5600 * @param packageName package permission if for 5601 */ 5602 private static void logPermissionRevoked(@NonNull Context context, @NonNull String name, 5603 @NonNull String packageName) { 5604 MetricsLogger.action(context, getBaseEventId(name) + 3, packageName); 5605 } 5606 5607 /** 5608 * Log that a permission request was granted. 5609 * 5610 * @param context Context of the caller 5611 * @param name name of the permission 5612 * @param packageName package permission if for 5613 */ 5614 private static void logPermissionGranted(@NonNull Context context, @NonNull String name, 5615 @NonNull String packageName) { 5616 MetricsLogger.action(context, getBaseEventId(name) + 1, packageName); 5617 } 5618 5619 @Override 5620 public void resetRuntimePermissions() { 5621 mContext.enforceCallingOrSelfPermission( 5622 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 5623 "revokeRuntimePermission"); 5624 5625 int callingUid = Binder.getCallingUid(); 5626 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 5627 mContext.enforceCallingOrSelfPermission( 5628 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5629 "resetRuntimePermissions"); 5630 } 5631 5632 synchronized (mPackages) { 5633 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 5634 for (int userId : UserManagerService.getInstance().getUserIds()) { 5635 final int packageCount = mPackages.size(); 5636 for (int i = 0; i < packageCount; i++) { 5637 PackageParser.Package pkg = mPackages.valueAt(i); 5638 if (!(pkg.mExtras instanceof PackageSetting)) { 5639 continue; 5640 } 5641 PackageSetting ps = (PackageSetting) pkg.mExtras; 5642 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 5643 } 5644 } 5645 } 5646 } 5647 5648 @Override 5649 public int getPermissionFlags(String name, String packageName, int userId) { 5650 if (!sUserManager.exists(userId)) { 5651 return 0; 5652 } 5653 5654 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 5655 5656 final int callingUid = Binder.getCallingUid(); 5657 enforceCrossUserPermission(callingUid, userId, 5658 true /* requireFullPermission */, false /* checkShell */, 5659 "getPermissionFlags"); 5660 5661 synchronized (mPackages) { 5662 final PackageParser.Package pkg = mPackages.get(packageName); 5663 if (pkg == null) { 5664 return 0; 5665 } 5666 final BasePermission bp = mSettings.mPermissions.get(name); 5667 if (bp == null) { 5668 return 0; 5669 } 5670 final PackageSetting ps = (PackageSetting) pkg.mExtras; 5671 if (ps == null 5672 || filterAppAccessLPr(ps, callingUid, userId)) { 5673 return 0; 5674 } 5675 PermissionsState permissionsState = ps.getPermissionsState(); 5676 return permissionsState.getPermissionFlags(name, userId); 5677 } 5678 } 5679 5680 @Override 5681 public void updatePermissionFlags(String name, String packageName, int flagMask, 5682 int flagValues, int userId) { 5683 if (!sUserManager.exists(userId)) { 5684 return; 5685 } 5686 5687 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 5688 5689 final int callingUid = Binder.getCallingUid(); 5690 enforceCrossUserPermission(callingUid, userId, 5691 true /* requireFullPermission */, true /* checkShell */, 5692 "updatePermissionFlags"); 5693 5694 // Only the system can change these flags and nothing else. 5695 if (getCallingUid() != Process.SYSTEM_UID) { 5696 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5697 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5698 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 5699 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 5700 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 5701 } 5702 5703 synchronized (mPackages) { 5704 final PackageParser.Package pkg = mPackages.get(packageName); 5705 if (pkg == null) { 5706 throw new IllegalArgumentException("Unknown package: " + packageName); 5707 } 5708 final PackageSetting ps = (PackageSetting) pkg.mExtras; 5709 if (ps == null 5710 || filterAppAccessLPr(ps, callingUid, userId)) { 5711 throw new IllegalArgumentException("Unknown package: " + packageName); 5712 } 5713 5714 final BasePermission bp = mSettings.mPermissions.get(name); 5715 if (bp == null) { 5716 throw new IllegalArgumentException("Unknown permission: " + name); 5717 } 5718 5719 PermissionsState permissionsState = ps.getPermissionsState(); 5720 5721 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 5722 5723 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 5724 // Install and runtime permissions are stored in different places, 5725 // so figure out what permission changed and persist the change. 5726 if (permissionsState.getInstallPermissionState(name) != null) { 5727 scheduleWriteSettingsLocked(); 5728 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 5729 || hadState) { 5730 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 5731 } 5732 } 5733 } 5734 } 5735 5736 /** 5737 * Update the permission flags for all packages and runtime permissions of a user in order 5738 * to allow device or profile owner to remove POLICY_FIXED. 5739 */ 5740 @Override 5741 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 5742 if (!sUserManager.exists(userId)) { 5743 return; 5744 } 5745 5746 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 5747 5748 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5749 true /* requireFullPermission */, true /* checkShell */, 5750 "updatePermissionFlagsForAllApps"); 5751 5752 // Only the system can change system fixed flags. 5753 if (getCallingUid() != Process.SYSTEM_UID) { 5754 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5755 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5756 } 5757 5758 synchronized (mPackages) { 5759 boolean changed = false; 5760 final int packageCount = mPackages.size(); 5761 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 5762 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 5763 final PackageSetting ps = (PackageSetting) pkg.mExtras; 5764 if (ps == null) { 5765 continue; 5766 } 5767 PermissionsState permissionsState = ps.getPermissionsState(); 5768 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 5769 userId, flagMask, flagValues); 5770 } 5771 if (changed) { 5772 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 5773 } 5774 } 5775 } 5776 5777 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 5778 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 5779 != PackageManager.PERMISSION_GRANTED 5780 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 5781 != PackageManager.PERMISSION_GRANTED) { 5782 throw new SecurityException(message + " requires " 5783 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 5784 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 5785 } 5786 } 5787 5788 @Override 5789 public boolean shouldShowRequestPermissionRationale(String permissionName, 5790 String packageName, int userId) { 5791 if (UserHandle.getCallingUserId() != userId) { 5792 mContext.enforceCallingPermission( 5793 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5794 "canShowRequestPermissionRationale for user " + userId); 5795 } 5796 5797 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 5798 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 5799 return false; 5800 } 5801 5802 if (checkPermission(permissionName, packageName, userId) 5803 == PackageManager.PERMISSION_GRANTED) { 5804 return false; 5805 } 5806 5807 final int flags; 5808 5809 final long identity = Binder.clearCallingIdentity(); 5810 try { 5811 flags = getPermissionFlags(permissionName, 5812 packageName, userId); 5813 } finally { 5814 Binder.restoreCallingIdentity(identity); 5815 } 5816 5817 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 5818 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 5819 | PackageManager.FLAG_PERMISSION_USER_FIXED; 5820 5821 if ((flags & fixedFlags) != 0) { 5822 return false; 5823 } 5824 5825 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 5826 } 5827 5828 @Override 5829 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 5830 mContext.enforceCallingOrSelfPermission( 5831 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 5832 "addOnPermissionsChangeListener"); 5833 5834 synchronized (mPackages) { 5835 mOnPermissionChangeListeners.addListenerLocked(listener); 5836 } 5837 } 5838 5839 @Override 5840 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 5841 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5842 throw new SecurityException("Instant applications don't have access to this method"); 5843 } 5844 synchronized (mPackages) { 5845 mOnPermissionChangeListeners.removeListenerLocked(listener); 5846 } 5847 } 5848 5849 @Override 5850 public boolean isProtectedBroadcast(String actionName) { 5851 // allow instant applications 5852 synchronized (mPackages) { 5853 if (mProtectedBroadcasts.contains(actionName)) { 5854 return true; 5855 } else if (actionName != null) { 5856 // TODO: remove these terrible hacks 5857 if (actionName.startsWith("android.net.netmon.lingerExpired") 5858 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 5859 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 5860 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 5861 return true; 5862 } 5863 } 5864 } 5865 return false; 5866 } 5867 5868 @Override 5869 public int checkSignatures(String pkg1, String pkg2) { 5870 synchronized (mPackages) { 5871 final PackageParser.Package p1 = mPackages.get(pkg1); 5872 final PackageParser.Package p2 = mPackages.get(pkg2); 5873 if (p1 == null || p1.mExtras == null 5874 || p2 == null || p2.mExtras == null) { 5875 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5876 } 5877 final int callingUid = Binder.getCallingUid(); 5878 final int callingUserId = UserHandle.getUserId(callingUid); 5879 final PackageSetting ps1 = (PackageSetting) p1.mExtras; 5880 final PackageSetting ps2 = (PackageSetting) p2.mExtras; 5881 if (filterAppAccessLPr(ps1, callingUid, callingUserId) 5882 || filterAppAccessLPr(ps2, callingUid, callingUserId)) { 5883 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5884 } 5885 return compareSignatures(p1.mSignatures, p2.mSignatures); 5886 } 5887 } 5888 5889 @Override 5890 public int checkUidSignatures(int uid1, int uid2) { 5891 final int callingUid = Binder.getCallingUid(); 5892 final int callingUserId = UserHandle.getUserId(callingUid); 5893 final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null; 5894 // Map to base uids. 5895 uid1 = UserHandle.getAppId(uid1); 5896 uid2 = UserHandle.getAppId(uid2); 5897 // reader 5898 synchronized (mPackages) { 5899 Signature[] s1; 5900 Signature[] s2; 5901 Object obj = mSettings.getUserIdLPr(uid1); 5902 if (obj != null) { 5903 if (obj instanceof SharedUserSetting) { 5904 if (isCallerInstantApp) { 5905 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5906 } 5907 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 5908 } else if (obj instanceof PackageSetting) { 5909 final PackageSetting ps = (PackageSetting) obj; 5910 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 5911 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5912 } 5913 s1 = ps.signatures.mSignatures; 5914 } else { 5915 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5916 } 5917 } else { 5918 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5919 } 5920 obj = mSettings.getUserIdLPr(uid2); 5921 if (obj != null) { 5922 if (obj instanceof SharedUserSetting) { 5923 if (isCallerInstantApp) { 5924 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5925 } 5926 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 5927 } else if (obj instanceof PackageSetting) { 5928 final PackageSetting ps = (PackageSetting) obj; 5929 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 5930 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5931 } 5932 s2 = ps.signatures.mSignatures; 5933 } else { 5934 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5935 } 5936 } else { 5937 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5938 } 5939 return compareSignatures(s1, s2); 5940 } 5941 } 5942 5943 /** 5944 * This method should typically only be used when granting or revoking 5945 * permissions, since the app may immediately restart after this call. 5946 * <p> 5947 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 5948 * guard your work against the app being relaunched. 5949 */ 5950 private void killUid(int appId, int userId, String reason) { 5951 final long identity = Binder.clearCallingIdentity(); 5952 try { 5953 IActivityManager am = ActivityManager.getService(); 5954 if (am != null) { 5955 try { 5956 am.killUid(appId, userId, reason); 5957 } catch (RemoteException e) { 5958 /* ignore - same process */ 5959 } 5960 } 5961 } finally { 5962 Binder.restoreCallingIdentity(identity); 5963 } 5964 } 5965 5966 /** 5967 * Compares two sets of signatures. Returns: 5968 * <br /> 5969 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 5970 * <br /> 5971 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 5972 * <br /> 5973 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 5974 * <br /> 5975 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 5976 * <br /> 5977 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 5978 */ 5979 static int compareSignatures(Signature[] s1, Signature[] s2) { 5980 if (s1 == null) { 5981 return s2 == null 5982 ? PackageManager.SIGNATURE_NEITHER_SIGNED 5983 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 5984 } 5985 5986 if (s2 == null) { 5987 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 5988 } 5989 5990 if (s1.length != s2.length) { 5991 return PackageManager.SIGNATURE_NO_MATCH; 5992 } 5993 5994 // Since both signature sets are of size 1, we can compare without HashSets. 5995 if (s1.length == 1) { 5996 return s1[0].equals(s2[0]) ? 5997 PackageManager.SIGNATURE_MATCH : 5998 PackageManager.SIGNATURE_NO_MATCH; 5999 } 6000 6001 ArraySet<Signature> set1 = new ArraySet<Signature>(); 6002 for (Signature sig : s1) { 6003 set1.add(sig); 6004 } 6005 ArraySet<Signature> set2 = new ArraySet<Signature>(); 6006 for (Signature sig : s2) { 6007 set2.add(sig); 6008 } 6009 // Make sure s2 contains all signatures in s1. 6010 if (set1.equals(set2)) { 6011 return PackageManager.SIGNATURE_MATCH; 6012 } 6013 return PackageManager.SIGNATURE_NO_MATCH; 6014 } 6015 6016 /** 6017 * If the database version for this type of package (internal storage or 6018 * external storage) is less than the version where package signatures 6019 * were updated, return true. 6020 */ 6021 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 6022 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 6023 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 6024 } 6025 6026 /** 6027 * Used for backward compatibility to make sure any packages with 6028 * certificate chains get upgraded to the new style. {@code existingSigs} 6029 * will be in the old format (since they were stored on disk from before the 6030 * system upgrade) and {@code scannedSigs} will be in the newer format. 6031 */ 6032 private int compareSignaturesCompat(PackageSignatures existingSigs, 6033 PackageParser.Package scannedPkg) { 6034 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 6035 return PackageManager.SIGNATURE_NO_MATCH; 6036 } 6037 6038 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 6039 for (Signature sig : existingSigs.mSignatures) { 6040 existingSet.add(sig); 6041 } 6042 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 6043 for (Signature sig : scannedPkg.mSignatures) { 6044 try { 6045 Signature[] chainSignatures = sig.getChainSignatures(); 6046 for (Signature chainSig : chainSignatures) { 6047 scannedCompatSet.add(chainSig); 6048 } 6049 } catch (CertificateEncodingException e) { 6050 scannedCompatSet.add(sig); 6051 } 6052 } 6053 /* 6054 * Make sure the expanded scanned set contains all signatures in the 6055 * existing one. 6056 */ 6057 if (scannedCompatSet.equals(existingSet)) { 6058 // Migrate the old signatures to the new scheme. 6059 existingSigs.assignSignatures(scannedPkg.mSignatures); 6060 // The new KeySets will be re-added later in the scanning process. 6061 synchronized (mPackages) { 6062 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 6063 } 6064 return PackageManager.SIGNATURE_MATCH; 6065 } 6066 return PackageManager.SIGNATURE_NO_MATCH; 6067 } 6068 6069 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 6070 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 6071 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 6072 } 6073 6074 private int compareSignaturesRecover(PackageSignatures existingSigs, 6075 PackageParser.Package scannedPkg) { 6076 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 6077 return PackageManager.SIGNATURE_NO_MATCH; 6078 } 6079 6080 String msg = null; 6081 try { 6082 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 6083 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 6084 + scannedPkg.packageName); 6085 return PackageManager.SIGNATURE_MATCH; 6086 } 6087 } catch (CertificateException e) { 6088 msg = e.getMessage(); 6089 } 6090 6091 logCriticalInfo(Log.INFO, 6092 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 6093 return PackageManager.SIGNATURE_NO_MATCH; 6094 } 6095 6096 @Override 6097 public List<String> getAllPackages() { 6098 final int callingUid = Binder.getCallingUid(); 6099 final int callingUserId = UserHandle.getUserId(callingUid); 6100 synchronized (mPackages) { 6101 if (canViewInstantApps(callingUid, callingUserId)) { 6102 return new ArrayList<String>(mPackages.keySet()); 6103 } 6104 final String instantAppPkgName = getInstantAppPackageName(callingUid); 6105 final List<String> result = new ArrayList<>(); 6106 if (instantAppPkgName != null) { 6107 // caller is an instant application; filter unexposed applications 6108 for (PackageParser.Package pkg : mPackages.values()) { 6109 if (!pkg.visibleToInstantApps) { 6110 continue; 6111 } 6112 result.add(pkg.packageName); 6113 } 6114 } else { 6115 // caller is a normal application; filter instant applications 6116 for (PackageParser.Package pkg : mPackages.values()) { 6117 final PackageSetting ps = 6118 pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null; 6119 if (ps != null 6120 && ps.getInstantApp(callingUserId) 6121 && !mInstantAppRegistry.isInstantAccessGranted( 6122 callingUserId, UserHandle.getAppId(callingUid), ps.appId)) { 6123 continue; 6124 } 6125 result.add(pkg.packageName); 6126 } 6127 } 6128 return result; 6129 } 6130 } 6131 6132 @Override 6133 public String[] getPackagesForUid(int uid) { 6134 final int callingUid = Binder.getCallingUid(); 6135 final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null; 6136 final int userId = UserHandle.getUserId(uid); 6137 uid = UserHandle.getAppId(uid); 6138 // reader 6139 synchronized (mPackages) { 6140 Object obj = mSettings.getUserIdLPr(uid); 6141 if (obj instanceof SharedUserSetting) { 6142 if (isCallerInstantApp) { 6143 return null; 6144 } 6145 final SharedUserSetting sus = (SharedUserSetting) obj; 6146 final int N = sus.packages.size(); 6147 String[] res = new String[N]; 6148 final Iterator<PackageSetting> it = sus.packages.iterator(); 6149 int i = 0; 6150 while (it.hasNext()) { 6151 PackageSetting ps = it.next(); 6152 if (ps.getInstalled(userId)) { 6153 res[i++] = ps.name; 6154 } else { 6155 res = ArrayUtils.removeElement(String.class, res, res[i]); 6156 } 6157 } 6158 return res; 6159 } else if (obj instanceof PackageSetting) { 6160 final PackageSetting ps = (PackageSetting) obj; 6161 if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) { 6162 return new String[]{ps.name}; 6163 } 6164 } 6165 } 6166 return null; 6167 } 6168 6169 @Override 6170 public String getNameForUid(int uid) { 6171 final int callingUid = Binder.getCallingUid(); 6172 if (getInstantAppPackageName(callingUid) != null) { 6173 return null; 6174 } 6175 synchronized (mPackages) { 6176 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 6177 if (obj instanceof SharedUserSetting) { 6178 final SharedUserSetting sus = (SharedUserSetting) obj; 6179 return sus.name + ":" + sus.userId; 6180 } else if (obj instanceof PackageSetting) { 6181 final PackageSetting ps = (PackageSetting) obj; 6182 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 6183 return null; 6184 } 6185 return ps.name; 6186 } 6187 } 6188 return null; 6189 } 6190 6191 @Override 6192 public int getUidForSharedUser(String sharedUserName) { 6193 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 6194 return -1; 6195 } 6196 if (sharedUserName == null) { 6197 return -1; 6198 } 6199 // reader 6200 synchronized (mPackages) { 6201 SharedUserSetting suid; 6202 try { 6203 suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 6204 if (suid != null) { 6205 return suid.userId; 6206 } 6207 } catch (PackageManagerException ignore) { 6208 // can't happen, but, still need to catch it 6209 } 6210 return -1; 6211 } 6212 } 6213 6214 @Override 6215 public int getFlagsForUid(int uid) { 6216 final int callingUid = Binder.getCallingUid(); 6217 if (getInstantAppPackageName(callingUid) != null) { 6218 return 0; 6219 } 6220 synchronized (mPackages) { 6221 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 6222 if (obj instanceof SharedUserSetting) { 6223 final SharedUserSetting sus = (SharedUserSetting) obj; 6224 return sus.pkgFlags; 6225 } else if (obj instanceof PackageSetting) { 6226 final PackageSetting ps = (PackageSetting) obj; 6227 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 6228 return 0; 6229 } 6230 return ps.pkgFlags; 6231 } 6232 } 6233 return 0; 6234 } 6235 6236 @Override 6237 public int getPrivateFlagsForUid(int uid) { 6238 final int callingUid = Binder.getCallingUid(); 6239 if (getInstantAppPackageName(callingUid) != null) { 6240 return 0; 6241 } 6242 synchronized (mPackages) { 6243 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 6244 if (obj instanceof SharedUserSetting) { 6245 final SharedUserSetting sus = (SharedUserSetting) obj; 6246 return sus.pkgPrivateFlags; 6247 } else if (obj instanceof PackageSetting) { 6248 final PackageSetting ps = (PackageSetting) obj; 6249 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 6250 return 0; 6251 } 6252 return ps.pkgPrivateFlags; 6253 } 6254 } 6255 return 0; 6256 } 6257 6258 @Override 6259 public boolean isUidPrivileged(int uid) { 6260 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 6261 return false; 6262 } 6263 uid = UserHandle.getAppId(uid); 6264 // reader 6265 synchronized (mPackages) { 6266 Object obj = mSettings.getUserIdLPr(uid); 6267 if (obj instanceof SharedUserSetting) { 6268 final SharedUserSetting sus = (SharedUserSetting) obj; 6269 final Iterator<PackageSetting> it = sus.packages.iterator(); 6270 while (it.hasNext()) { 6271 if (it.next().isPrivileged()) { 6272 return true; 6273 } 6274 } 6275 } else if (obj instanceof PackageSetting) { 6276 final PackageSetting ps = (PackageSetting) obj; 6277 return ps.isPrivileged(); 6278 } 6279 } 6280 return false; 6281 } 6282 6283 @Override 6284 public String[] getAppOpPermissionPackages(String permissionName) { 6285 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 6286 return null; 6287 } 6288 synchronized (mPackages) { 6289 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 6290 if (pkgs == null) { 6291 return null; 6292 } 6293 return pkgs.toArray(new String[pkgs.size()]); 6294 } 6295 } 6296 6297 @Override 6298 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 6299 int flags, int userId) { 6300 return resolveIntentInternal( 6301 intent, resolvedType, flags, userId, false /*includeInstantApps*/); 6302 } 6303 6304 private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType, 6305 int flags, int userId, boolean resolveForStart) { 6306 try { 6307 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 6308 6309 if (!sUserManager.exists(userId)) return null; 6310 final int callingUid = Binder.getCallingUid(); 6311 flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart); 6312 enforceCrossUserPermission(callingUid, userId, 6313 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 6314 6315 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 6316 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 6317 flags, callingUid, userId, resolveForStart); 6318 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6319 6320 final ResolveInfo bestChoice = 6321 chooseBestActivity(intent, resolvedType, flags, query, userId); 6322 return bestChoice; 6323 } finally { 6324 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6325 } 6326 } 6327 6328 @Override 6329 public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) { 6330 if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) { 6331 throw new SecurityException( 6332 "findPersistentPreferredActivity can only be run by the system"); 6333 } 6334 if (!sUserManager.exists(userId)) { 6335 return null; 6336 } 6337 final int callingUid = Binder.getCallingUid(); 6338 intent = updateIntentForResolve(intent); 6339 final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver()); 6340 final int flags = updateFlagsForResolve( 6341 0, userId, intent, callingUid, false /*includeInstantApps*/); 6342 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 6343 userId); 6344 synchronized (mPackages) { 6345 return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false, 6346 userId); 6347 } 6348 } 6349 6350 @Override 6351 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 6352 IntentFilter filter, int match, ComponentName activity) { 6353 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 6354 return; 6355 } 6356 final int userId = UserHandle.getCallingUserId(); 6357 if (DEBUG_PREFERRED) { 6358 Log.v(TAG, "setLastChosenActivity intent=" + intent 6359 + " resolvedType=" + resolvedType 6360 + " flags=" + flags 6361 + " filter=" + filter 6362 + " match=" + match 6363 + " activity=" + activity); 6364 filter.dump(new PrintStreamPrinter(System.out), " "); 6365 } 6366 intent.setComponent(null); 6367 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 6368 userId); 6369 // Find any earlier preferred or last chosen entries and nuke them 6370 findPreferredActivity(intent, resolvedType, 6371 flags, query, 0, false, true, false, userId); 6372 // Add the new activity as the last chosen for this filter 6373 addPreferredActivityInternal(filter, match, null, activity, false, userId, 6374 "Setting last chosen"); 6375 } 6376 6377 @Override 6378 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 6379 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 6380 return null; 6381 } 6382 final int userId = UserHandle.getCallingUserId(); 6383 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 6384 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 6385 userId); 6386 return findPreferredActivity(intent, resolvedType, flags, query, 0, 6387 false, false, false, userId); 6388 } 6389 6390 /** 6391 * Returns whether or not instant apps have been disabled remotely. 6392 */ 6393 private boolean isEphemeralDisabled() { 6394 return mEphemeralAppsDisabled; 6395 } 6396 6397 private boolean isInstantAppAllowed( 6398 Intent intent, List<ResolveInfo> resolvedActivities, int userId, 6399 boolean skipPackageCheck) { 6400 if (mInstantAppResolverConnection == null) { 6401 return false; 6402 } 6403 if (mInstantAppInstallerActivity == null) { 6404 return false; 6405 } 6406 if (intent.getComponent() != null) { 6407 return false; 6408 } 6409 if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) { 6410 return false; 6411 } 6412 if (!skipPackageCheck && intent.getPackage() != null) { 6413 return false; 6414 } 6415 final boolean isWebUri = hasWebURI(intent); 6416 if (!isWebUri || intent.getData().getHost() == null) { 6417 return false; 6418 } 6419 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 6420 // Or if there's already an ephemeral app installed that handles the action 6421 synchronized (mPackages) { 6422 final int count = (resolvedActivities == null ? 0 : resolvedActivities.size()); 6423 for (int n = 0; n < count; n++) { 6424 final ResolveInfo info = resolvedActivities.get(n); 6425 final String packageName = info.activityInfo.packageName; 6426 final PackageSetting ps = mSettings.mPackages.get(packageName); 6427 if (ps != null) { 6428 // only check domain verification status if the app is not a browser 6429 if (!info.handleAllWebDataURI) { 6430 // Try to get the status from User settings first 6431 final long packedStatus = getDomainVerificationStatusLPr(ps, userId); 6432 final int status = (int) (packedStatus >> 32); 6433 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 6434 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 6435 if (DEBUG_EPHEMERAL) { 6436 Slog.v(TAG, "DENY instant app;" 6437 + " pkg: " + packageName + ", status: " + status); 6438 } 6439 return false; 6440 } 6441 } 6442 if (ps.getInstantApp(userId)) { 6443 if (DEBUG_EPHEMERAL) { 6444 Slog.v(TAG, "DENY instant app installed;" 6445 + " pkg: " + packageName); 6446 } 6447 return false; 6448 } 6449 } 6450 } 6451 } 6452 // We've exhausted all ways to deny ephemeral application; let the system look for them. 6453 return true; 6454 } 6455 6456 private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj, 6457 Intent origIntent, String resolvedType, String callingPackage, 6458 Bundle verificationBundle, int userId) { 6459 final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO, 6460 new InstantAppRequest(responseObj, origIntent, resolvedType, 6461 callingPackage, userId, verificationBundle)); 6462 mHandler.sendMessage(msg); 6463 } 6464 6465 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 6466 int flags, List<ResolveInfo> query, int userId) { 6467 if (query != null) { 6468 final int N = query.size(); 6469 if (N == 1) { 6470 return query.get(0); 6471 } else if (N > 1) { 6472 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 6473 // If there is more than one activity with the same priority, 6474 // then let the user decide between them. 6475 ResolveInfo r0 = query.get(0); 6476 ResolveInfo r1 = query.get(1); 6477 if (DEBUG_INTENT_MATCHING || debug) { 6478 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 6479 + r1.activityInfo.name + "=" + r1.priority); 6480 } 6481 // If the first activity has a higher priority, or a different 6482 // default, then it is always desirable to pick it. 6483 if (r0.priority != r1.priority 6484 || r0.preferredOrder != r1.preferredOrder 6485 || r0.isDefault != r1.isDefault) { 6486 return query.get(0); 6487 } 6488 // If we have saved a preference for a preferred activity for 6489 // this Intent, use that. 6490 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 6491 flags, query, r0.priority, true, false, debug, userId); 6492 if (ri != null) { 6493 return ri; 6494 } 6495 // If we have an ephemeral app, use it 6496 for (int i = 0; i < N; i++) { 6497 ri = query.get(i); 6498 if (ri.activityInfo.applicationInfo.isInstantApp()) { 6499 final String packageName = ri.activityInfo.packageName; 6500 final PackageSetting ps = mSettings.mPackages.get(packageName); 6501 final long packedStatus = getDomainVerificationStatusLPr(ps, userId); 6502 final int status = (int)(packedStatus >> 32); 6503 if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 6504 return ri; 6505 } 6506 } 6507 } 6508 ri = new ResolveInfo(mResolveInfo); 6509 ri.activityInfo = new ActivityInfo(ri.activityInfo); 6510 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 6511 // If all of the options come from the same package, show the application's 6512 // label and icon instead of the generic resolver's. 6513 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 6514 // and then throw away the ResolveInfo itself, meaning that the caller loses 6515 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 6516 // a fallback for this case; we only set the target package's resources on 6517 // the ResolveInfo, not the ActivityInfo. 6518 final String intentPackage = intent.getPackage(); 6519 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 6520 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 6521 ri.resolvePackageName = intentPackage; 6522 if (userNeedsBadging(userId)) { 6523 ri.noResourceId = true; 6524 } else { 6525 ri.icon = appi.icon; 6526 } 6527 ri.iconResourceId = appi.icon; 6528 ri.labelRes = appi.labelRes; 6529 } 6530 ri.activityInfo.applicationInfo = new ApplicationInfo( 6531 ri.activityInfo.applicationInfo); 6532 if (userId != 0) { 6533 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 6534 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 6535 } 6536 // Make sure that the resolver is displayable in car mode 6537 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 6538 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 6539 return ri; 6540 } 6541 } 6542 return null; 6543 } 6544 6545 /** 6546 * Return true if the given list is not empty and all of its contents have 6547 * an activityInfo with the given package name. 6548 */ 6549 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 6550 if (ArrayUtils.isEmpty(list)) { 6551 return false; 6552 } 6553 for (int i = 0, N = list.size(); i < N; i++) { 6554 final ResolveInfo ri = list.get(i); 6555 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 6556 if (ai == null || !packageName.equals(ai.packageName)) { 6557 return false; 6558 } 6559 } 6560 return true; 6561 } 6562 6563 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 6564 int flags, List<ResolveInfo> query, boolean debug, int userId) { 6565 final int N = query.size(); 6566 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 6567 .get(userId); 6568 // Get the list of persistent preferred activities that handle the intent 6569 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 6570 List<PersistentPreferredActivity> pprefs = ppir != null 6571 ? ppir.queryIntent(intent, resolvedType, 6572 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 6573 userId) 6574 : null; 6575 if (pprefs != null && pprefs.size() > 0) { 6576 final int M = pprefs.size(); 6577 for (int i=0; i<M; i++) { 6578 final PersistentPreferredActivity ppa = pprefs.get(i); 6579 if (DEBUG_PREFERRED || debug) { 6580 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 6581 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 6582 + "\n component=" + ppa.mComponent); 6583 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6584 } 6585 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 6586 flags | MATCH_DISABLED_COMPONENTS, userId); 6587 if (DEBUG_PREFERRED || debug) { 6588 Slog.v(TAG, "Found persistent preferred activity:"); 6589 if (ai != null) { 6590 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6591 } else { 6592 Slog.v(TAG, " null"); 6593 } 6594 } 6595 if (ai == null) { 6596 // This previously registered persistent preferred activity 6597 // component is no longer known. Ignore it and do NOT remove it. 6598 continue; 6599 } 6600 for (int j=0; j<N; j++) { 6601 final ResolveInfo ri = query.get(j); 6602 if (!ri.activityInfo.applicationInfo.packageName 6603 .equals(ai.applicationInfo.packageName)) { 6604 continue; 6605 } 6606 if (!ri.activityInfo.name.equals(ai.name)) { 6607 continue; 6608 } 6609 // Found a persistent preference that can handle the intent. 6610 if (DEBUG_PREFERRED || debug) { 6611 Slog.v(TAG, "Returning persistent preferred activity: " + 6612 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 6613 } 6614 return ri; 6615 } 6616 } 6617 } 6618 return null; 6619 } 6620 6621 // TODO: handle preferred activities missing while user has amnesia 6622 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 6623 List<ResolveInfo> query, int priority, boolean always, 6624 boolean removeMatches, boolean debug, int userId) { 6625 if (!sUserManager.exists(userId)) return null; 6626 final int callingUid = Binder.getCallingUid(); 6627 flags = updateFlagsForResolve( 6628 flags, userId, intent, callingUid, false /*includeInstantApps*/); 6629 intent = updateIntentForResolve(intent); 6630 // writer 6631 synchronized (mPackages) { 6632 // Try to find a matching persistent preferred activity. 6633 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 6634 debug, userId); 6635 6636 // If a persistent preferred activity matched, use it. 6637 if (pri != null) { 6638 return pri; 6639 } 6640 6641 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 6642 // Get the list of preferred activities that handle the intent 6643 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 6644 List<PreferredActivity> prefs = pir != null 6645 ? pir.queryIntent(intent, resolvedType, 6646 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 6647 userId) 6648 : null; 6649 if (prefs != null && prefs.size() > 0) { 6650 boolean changed = false; 6651 try { 6652 // First figure out how good the original match set is. 6653 // We will only allow preferred activities that came 6654 // from the same match quality. 6655 int match = 0; 6656 6657 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 6658 6659 final int N = query.size(); 6660 for (int j=0; j<N; j++) { 6661 final ResolveInfo ri = query.get(j); 6662 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 6663 + ": 0x" + Integer.toHexString(match)); 6664 if (ri.match > match) { 6665 match = ri.match; 6666 } 6667 } 6668 6669 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 6670 + Integer.toHexString(match)); 6671 6672 match &= IntentFilter.MATCH_CATEGORY_MASK; 6673 final int M = prefs.size(); 6674 for (int i=0; i<M; i++) { 6675 final PreferredActivity pa = prefs.get(i); 6676 if (DEBUG_PREFERRED || debug) { 6677 Slog.v(TAG, "Checking PreferredActivity ds=" 6678 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 6679 + "\n component=" + pa.mPref.mComponent); 6680 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6681 } 6682 if (pa.mPref.mMatch != match) { 6683 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 6684 + Integer.toHexString(pa.mPref.mMatch)); 6685 continue; 6686 } 6687 // If it's not an "always" type preferred activity and that's what we're 6688 // looking for, skip it. 6689 if (always && !pa.mPref.mAlways) { 6690 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 6691 continue; 6692 } 6693 final ActivityInfo ai = getActivityInfo( 6694 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 6695 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 6696 userId); 6697 if (DEBUG_PREFERRED || debug) { 6698 Slog.v(TAG, "Found preferred activity:"); 6699 if (ai != null) { 6700 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6701 } else { 6702 Slog.v(TAG, " null"); 6703 } 6704 } 6705 if (ai == null) { 6706 // This previously registered preferred activity 6707 // component is no longer known. Most likely an update 6708 // to the app was installed and in the new version this 6709 // component no longer exists. Clean it up by removing 6710 // it from the preferred activities list, and skip it. 6711 Slog.w(TAG, "Removing dangling preferred activity: " 6712 + pa.mPref.mComponent); 6713 pir.removeFilter(pa); 6714 changed = true; 6715 continue; 6716 } 6717 for (int j=0; j<N; j++) { 6718 final ResolveInfo ri = query.get(j); 6719 if (!ri.activityInfo.applicationInfo.packageName 6720 .equals(ai.applicationInfo.packageName)) { 6721 continue; 6722 } 6723 if (!ri.activityInfo.name.equals(ai.name)) { 6724 continue; 6725 } 6726 6727 if (removeMatches) { 6728 pir.removeFilter(pa); 6729 changed = true; 6730 if (DEBUG_PREFERRED) { 6731 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 6732 } 6733 break; 6734 } 6735 6736 // Okay we found a previously set preferred or last chosen app. 6737 // If the result set is different from when this 6738 // was created, we need to clear it and re-ask the 6739 // user their preference, if we're looking for an "always" type entry. 6740 if (always && !pa.mPref.sameSet(query)) { 6741 Slog.i(TAG, "Result set changed, dropping preferred activity for " 6742 + intent + " type " + resolvedType); 6743 if (DEBUG_PREFERRED) { 6744 Slog.v(TAG, "Removing preferred activity since set changed " 6745 + pa.mPref.mComponent); 6746 } 6747 pir.removeFilter(pa); 6748 // Re-add the filter as a "last chosen" entry (!always) 6749 PreferredActivity lastChosen = new PreferredActivity( 6750 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 6751 pir.addFilter(lastChosen); 6752 changed = true; 6753 return null; 6754 } 6755 6756 // Yay! Either the set matched or we're looking for the last chosen 6757 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 6758 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 6759 return ri; 6760 } 6761 } 6762 } finally { 6763 if (changed) { 6764 if (DEBUG_PREFERRED) { 6765 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 6766 } 6767 scheduleWritePackageRestrictionsLocked(userId); 6768 } 6769 } 6770 } 6771 } 6772 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 6773 return null; 6774 } 6775 6776 /* 6777 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 6778 */ 6779 @Override 6780 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 6781 int targetUserId) { 6782 mContext.enforceCallingOrSelfPermission( 6783 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 6784 List<CrossProfileIntentFilter> matches = 6785 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 6786 if (matches != null) { 6787 int size = matches.size(); 6788 for (int i = 0; i < size; i++) { 6789 if (matches.get(i).getTargetUserId() == targetUserId) return true; 6790 } 6791 } 6792 if (hasWebURI(intent)) { 6793 // cross-profile app linking works only towards the parent. 6794 final int callingUid = Binder.getCallingUid(); 6795 final UserInfo parent = getProfileParent(sourceUserId); 6796 synchronized(mPackages) { 6797 int flags = updateFlagsForResolve(0, parent.id, intent, callingUid, 6798 false /*includeInstantApps*/); 6799 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 6800 intent, resolvedType, flags, sourceUserId, parent.id); 6801 return xpDomainInfo != null; 6802 } 6803 } 6804 return false; 6805 } 6806 6807 private UserInfo getProfileParent(int userId) { 6808 final long identity = Binder.clearCallingIdentity(); 6809 try { 6810 return sUserManager.getProfileParent(userId); 6811 } finally { 6812 Binder.restoreCallingIdentity(identity); 6813 } 6814 } 6815 6816 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 6817 String resolvedType, int userId) { 6818 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 6819 if (resolver != null) { 6820 return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId); 6821 } 6822 return null; 6823 } 6824 6825 @Override 6826 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 6827 String resolvedType, int flags, int userId) { 6828 try { 6829 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 6830 6831 return new ParceledListSlice<>( 6832 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 6833 } finally { 6834 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6835 } 6836 } 6837 6838 /** 6839 * Returns the package name of the calling Uid if it's an instant app. If it isn't 6840 * instant, returns {@code null}. 6841 */ 6842 private String getInstantAppPackageName(int callingUid) { 6843 synchronized (mPackages) { 6844 // If the caller is an isolated app use the owner's uid for the lookup. 6845 if (Process.isIsolated(callingUid)) { 6846 callingUid = mIsolatedOwners.get(callingUid); 6847 } 6848 final int appId = UserHandle.getAppId(callingUid); 6849 final Object obj = mSettings.getUserIdLPr(appId); 6850 if (obj instanceof PackageSetting) { 6851 final PackageSetting ps = (PackageSetting) obj; 6852 final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid)); 6853 return isInstantApp ? ps.pkg.packageName : null; 6854 } 6855 } 6856 return null; 6857 } 6858 6859 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 6860 String resolvedType, int flags, int userId) { 6861 return queryIntentActivitiesInternal( 6862 intent, resolvedType, flags, Binder.getCallingUid(), userId, false); 6863 } 6864 6865 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 6866 String resolvedType, int flags, int filterCallingUid, int userId, 6867 boolean resolveForStart) { 6868 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6869 final String instantAppPkgName = getInstantAppPackageName(filterCallingUid); 6870 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6871 false /* requireFullPermission */, false /* checkShell */, 6872 "query intent activities"); 6873 final String pkgName = intent.getPackage(); 6874 ComponentName comp = intent.getComponent(); 6875 if (comp == null) { 6876 if (intent.getSelector() != null) { 6877 intent = intent.getSelector(); 6878 comp = intent.getComponent(); 6879 } 6880 } 6881 6882 flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart, 6883 comp != null || pkgName != null /*onlyExposedExplicitly*/); 6884 if (comp != null) { 6885 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6886 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 6887 if (ai != null) { 6888 // When specifying an explicit component, we prevent the activity from being 6889 // used when either 1) the calling package is normal and the activity is within 6890 // an ephemeral application or 2) the calling package is ephemeral and the 6891 // activity is not visible to ephemeral applications. 6892 final boolean matchInstantApp = 6893 (flags & PackageManager.MATCH_INSTANT) != 0; 6894 final boolean matchVisibleToInstantAppOnly = 6895 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 6896 final boolean matchExplicitlyVisibleOnly = 6897 (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0; 6898 final boolean isCallerInstantApp = 6899 instantAppPkgName != null; 6900 final boolean isTargetSameInstantApp = 6901 comp.getPackageName().equals(instantAppPkgName); 6902 final boolean isTargetInstantApp = 6903 (ai.applicationInfo.privateFlags 6904 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 6905 final boolean isTargetVisibleToInstantApp = 6906 (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0; 6907 final boolean isTargetExplicitlyVisibleToInstantApp = 6908 isTargetVisibleToInstantApp 6909 && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0; 6910 final boolean isTargetHiddenFromInstantApp = 6911 !isTargetVisibleToInstantApp 6912 || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp); 6913 final boolean blockResolution = 6914 !isTargetSameInstantApp 6915 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 6916 || (matchVisibleToInstantAppOnly && isCallerInstantApp 6917 && isTargetHiddenFromInstantApp)); 6918 if (!blockResolution) { 6919 final ResolveInfo ri = new ResolveInfo(); 6920 ri.activityInfo = ai; 6921 list.add(ri); 6922 } 6923 } 6924 return applyPostResolutionFilter(list, instantAppPkgName); 6925 } 6926 6927 // reader 6928 boolean sortResult = false; 6929 boolean addEphemeral = false; 6930 List<ResolveInfo> result; 6931 final boolean ephemeralDisabled = isEphemeralDisabled(); 6932 synchronized (mPackages) { 6933 if (pkgName == null) { 6934 List<CrossProfileIntentFilter> matchingFilters = 6935 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 6936 // Check for results that need to skip the current profile. 6937 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 6938 resolvedType, flags, userId); 6939 if (xpResolveInfo != null) { 6940 List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1); 6941 xpResult.add(xpResolveInfo); 6942 return applyPostResolutionFilter( 6943 filterIfNotSystemUser(xpResult, userId), instantAppPkgName); 6944 } 6945 6946 // Check for results in the current profile. 6947 result = filterIfNotSystemUser(mActivities.queryIntent( 6948 intent, resolvedType, flags, userId), userId); 6949 addEphemeral = !ephemeralDisabled 6950 && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/); 6951 // Check for cross profile results. 6952 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 6953 xpResolveInfo = queryCrossProfileIntents( 6954 matchingFilters, intent, resolvedType, flags, userId, 6955 hasNonNegativePriorityResult); 6956 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 6957 boolean isVisibleToUser = filterIfNotSystemUser( 6958 Collections.singletonList(xpResolveInfo), userId).size() > 0; 6959 if (isVisibleToUser) { 6960 result.add(xpResolveInfo); 6961 sortResult = true; 6962 } 6963 } 6964 if (hasWebURI(intent)) { 6965 CrossProfileDomainInfo xpDomainInfo = null; 6966 final UserInfo parent = getProfileParent(userId); 6967 if (parent != null) { 6968 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 6969 flags, userId, parent.id); 6970 } 6971 if (xpDomainInfo != null) { 6972 if (xpResolveInfo != null) { 6973 // If we didn't remove it, the cross-profile ResolveInfo would be twice 6974 // in the result. 6975 result.remove(xpResolveInfo); 6976 } 6977 if (result.size() == 0 && !addEphemeral) { 6978 // No result in current profile, but found candidate in parent user. 6979 // And we are not going to add emphemeral app, so we can return the 6980 // result straight away. 6981 result.add(xpDomainInfo.resolveInfo); 6982 return applyPostResolutionFilter(result, instantAppPkgName); 6983 } 6984 } else if (result.size() <= 1 && !addEphemeral) { 6985 // No result in parent user and <= 1 result in current profile, and we 6986 // are not going to add emphemeral app, so we can return the result without 6987 // further processing. 6988 return applyPostResolutionFilter(result, instantAppPkgName); 6989 } 6990 // We have more than one candidate (combining results from current and parent 6991 // profile), so we need filtering and sorting. 6992 result = filterCandidatesWithDomainPreferredActivitiesLPr( 6993 intent, flags, result, xpDomainInfo, userId); 6994 sortResult = true; 6995 } 6996 } else { 6997 final PackageParser.Package pkg = mPackages.get(pkgName); 6998 result = null; 6999 if (pkg != null) { 7000 result = filterIfNotSystemUser( 7001 mActivities.queryIntentForPackage( 7002 intent, resolvedType, flags, pkg.activities, userId), 7003 userId); 7004 } 7005 if (result == null || result.size() == 0) { 7006 // the caller wants to resolve for a particular package; however, there 7007 // were no installed results, so, try to find an ephemeral result 7008 addEphemeral = !ephemeralDisabled 7009 && isInstantAppAllowed( 7010 intent, null /*result*/, userId, true /*skipPackageCheck*/); 7011 if (result == null) { 7012 result = new ArrayList<>(); 7013 } 7014 } 7015 } 7016 } 7017 if (addEphemeral) { 7018 result = maybeAddInstantAppInstaller(result, intent, resolvedType, flags, userId); 7019 } 7020 if (sortResult) { 7021 Collections.sort(result, mResolvePrioritySorter); 7022 } 7023 return applyPostResolutionFilter(result, instantAppPkgName); 7024 } 7025 7026 private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent, 7027 String resolvedType, int flags, int userId) { 7028 // first, check to see if we've got an instant app already installed 7029 final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0; 7030 ResolveInfo localInstantApp = null; 7031 boolean blockResolution = false; 7032 if (!alreadyResolvedLocally) { 7033 final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType, 7034 flags 7035 | PackageManager.GET_RESOLVED_FILTER 7036 | PackageManager.MATCH_INSTANT 7037 | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY, 7038 userId); 7039 for (int i = instantApps.size() - 1; i >= 0; --i) { 7040 final ResolveInfo info = instantApps.get(i); 7041 final String packageName = info.activityInfo.packageName; 7042 final PackageSetting ps = mSettings.mPackages.get(packageName); 7043 if (ps.getInstantApp(userId)) { 7044 final long packedStatus = getDomainVerificationStatusLPr(ps, userId); 7045 final int status = (int)(packedStatus >> 32); 7046 final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 7047 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 7048 // there's a local instant application installed, but, the user has 7049 // chosen to never use it; skip resolution and don't acknowledge 7050 // an instant application is even available 7051 if (DEBUG_EPHEMERAL) { 7052 Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName); 7053 } 7054 blockResolution = true; 7055 break; 7056 } else { 7057 // we have a locally installed instant application; skip resolution 7058 // but acknowledge there's an instant application available 7059 if (DEBUG_EPHEMERAL) { 7060 Slog.v(TAG, "Found installed instant app; pkg: " + packageName); 7061 } 7062 localInstantApp = info; 7063 break; 7064 } 7065 } 7066 } 7067 } 7068 // no app installed, let's see if one's available 7069 AuxiliaryResolveInfo auxiliaryResponse = null; 7070 if (!blockResolution) { 7071 if (localInstantApp == null) { 7072 // we don't have an instant app locally, resolve externally 7073 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 7074 final InstantAppRequest requestObject = new InstantAppRequest( 7075 null /*responseObj*/, intent /*origIntent*/, resolvedType, 7076 null /*callingPackage*/, userId, null /*verificationBundle*/); 7077 auxiliaryResponse = 7078 InstantAppResolver.doInstantAppResolutionPhaseOne( 7079 mContext, mInstantAppResolverConnection, requestObject); 7080 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7081 } else { 7082 // we have an instant application locally, but, we can't admit that since 7083 // callers shouldn't be able to determine prior browsing. create a dummy 7084 // auxiliary response so the downstream code behaves as if there's an 7085 // instant application available externally. when it comes time to start 7086 // the instant application, we'll do the right thing. 7087 final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo; 7088 auxiliaryResponse = new AuxiliaryResolveInfo( 7089 ai.packageName, null /*splitName*/, ai.versionCode, null /*failureIntent*/); 7090 } 7091 } 7092 if (auxiliaryResponse != null) { 7093 if (DEBUG_EPHEMERAL) { 7094 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 7095 } 7096 final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo); 7097 final PackageSetting ps = 7098 mSettings.mPackages.get(mInstantAppInstallerActivity.packageName); 7099 if (ps != null) { 7100 ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo( 7101 mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId); 7102 ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token; 7103 ephemeralInstaller.auxiliaryInfo = auxiliaryResponse; 7104 // make sure this resolver is the default 7105 ephemeralInstaller.isDefault = true; 7106 ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 7107 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 7108 // add a non-generic filter 7109 ephemeralInstaller.filter = new IntentFilter(intent.getAction()); 7110 ephemeralInstaller.filter.addDataPath( 7111 intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL); 7112 ephemeralInstaller.isInstantAppAvailable = true; 7113 result.add(ephemeralInstaller); 7114 } 7115 } 7116 return result; 7117 } 7118 7119 private static class CrossProfileDomainInfo { 7120 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 7121 ResolveInfo resolveInfo; 7122 /* Best domain verification status of the activities found in the other profile */ 7123 int bestDomainVerificationStatus; 7124 } 7125 7126 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 7127 String resolvedType, int flags, int sourceUserId, int parentUserId) { 7128 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 7129 sourceUserId)) { 7130 return null; 7131 } 7132 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 7133 resolvedType, flags, parentUserId); 7134 7135 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 7136 return null; 7137 } 7138 CrossProfileDomainInfo result = null; 7139 int size = resultTargetUser.size(); 7140 for (int i = 0; i < size; i++) { 7141 ResolveInfo riTargetUser = resultTargetUser.get(i); 7142 // Intent filter verification is only for filters that specify a host. So don't return 7143 // those that handle all web uris. 7144 if (riTargetUser.handleAllWebDataURI) { 7145 continue; 7146 } 7147 String packageName = riTargetUser.activityInfo.packageName; 7148 PackageSetting ps = mSettings.mPackages.get(packageName); 7149 if (ps == null) { 7150 continue; 7151 } 7152 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 7153 int status = (int)(verificationState >> 32); 7154 if (result == null) { 7155 result = new CrossProfileDomainInfo(); 7156 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 7157 sourceUserId, parentUserId); 7158 result.bestDomainVerificationStatus = status; 7159 } else { 7160 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 7161 result.bestDomainVerificationStatus); 7162 } 7163 } 7164 // Don't consider matches with status NEVER across profiles. 7165 if (result != null && result.bestDomainVerificationStatus 7166 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 7167 return null; 7168 } 7169 return result; 7170 } 7171 7172 /** 7173 * Verification statuses are ordered from the worse to the best, except for 7174 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 7175 */ 7176 private int bestDomainVerificationStatus(int status1, int status2) { 7177 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 7178 return status2; 7179 } 7180 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 7181 return status1; 7182 } 7183 return (int) MathUtils.max(status1, status2); 7184 } 7185 7186 private boolean isUserEnabled(int userId) { 7187 long callingId = Binder.clearCallingIdentity(); 7188 try { 7189 UserInfo userInfo = sUserManager.getUserInfo(userId); 7190 return userInfo != null && userInfo.isEnabled(); 7191 } finally { 7192 Binder.restoreCallingIdentity(callingId); 7193 } 7194 } 7195 7196 /** 7197 * Filter out activities with systemUserOnly flag set, when current user is not System. 7198 * 7199 * @return filtered list 7200 */ 7201 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 7202 if (userId == UserHandle.USER_SYSTEM) { 7203 return resolveInfos; 7204 } 7205 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 7206 ResolveInfo info = resolveInfos.get(i); 7207 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 7208 resolveInfos.remove(i); 7209 } 7210 } 7211 return resolveInfos; 7212 } 7213 7214 /** 7215 * Filters out ephemeral activities. 7216 * <p>When resolving for an ephemeral app, only activities that 1) are defined in the 7217 * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned. 7218 * 7219 * @param resolveInfos The pre-filtered list of resolved activities 7220 * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering 7221 * is performed. 7222 * @return A filtered list of resolved activities. 7223 */ 7224 private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos, 7225 String ephemeralPkgName) { 7226 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 7227 final ResolveInfo info = resolveInfos.get(i); 7228 final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp(); 7229 // TODO: When adding on-demand split support for non-instant apps, remove this check 7230 // and always apply post filtering 7231 // allow activities that are defined in the provided package 7232 if (isEphemeralApp) { 7233 if (info.activityInfo.splitName != null 7234 && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames, 7235 info.activityInfo.splitName)) { 7236 // requested activity is defined in a split that hasn't been installed yet. 7237 // add the installer to the resolve list 7238 if (DEBUG_EPHEMERAL) { 7239 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 7240 } 7241 final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo); 7242 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 7243 info.activityInfo.packageName, info.activityInfo.splitName, 7244 info.activityInfo.applicationInfo.versionCode, null /*failureIntent*/); 7245 // make sure this resolver is the default 7246 installerInfo.isDefault = true; 7247 installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 7248 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 7249 // add a non-generic filter 7250 installerInfo.filter = new IntentFilter(); 7251 // load resources from the correct package 7252 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 7253 resolveInfos.set(i, installerInfo); 7254 continue; 7255 } 7256 } 7257 // caller is a full app, don't need to apply any other filtering 7258 if (ephemeralPkgName == null) { 7259 continue; 7260 } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) { 7261 // caller is same app; don't need to apply any other filtering 7262 continue; 7263 } 7264 // allow activities that have been explicitly exposed to ephemeral apps 7265 if (!isEphemeralApp 7266 && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) { 7267 continue; 7268 } 7269 resolveInfos.remove(i); 7270 } 7271 return resolveInfos; 7272 } 7273 7274 /** 7275 * @param resolveInfos list of resolve infos in descending priority order 7276 * @return if the list contains a resolve info with non-negative priority 7277 */ 7278 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 7279 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 7280 } 7281 7282 private static boolean hasWebURI(Intent intent) { 7283 if (intent.getData() == null) { 7284 return false; 7285 } 7286 final String scheme = intent.getScheme(); 7287 if (TextUtils.isEmpty(scheme)) { 7288 return false; 7289 } 7290 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 7291 } 7292 7293 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 7294 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 7295 int userId) { 7296 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 7297 7298 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 7299 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 7300 candidates.size()); 7301 } 7302 7303 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 7304 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 7305 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 7306 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 7307 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 7308 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 7309 7310 synchronized (mPackages) { 7311 final int count = candidates.size(); 7312 // First, try to use linked apps. Partition the candidates into four lists: 7313 // one for the final results, one for the "do not use ever", one for "undefined status" 7314 // and finally one for "browser app type". 7315 for (int n=0; n<count; n++) { 7316 ResolveInfo info = candidates.get(n); 7317 String packageName = info.activityInfo.packageName; 7318 PackageSetting ps = mSettings.mPackages.get(packageName); 7319 if (ps != null) { 7320 // Add to the special match all list (Browser use case) 7321 if (info.handleAllWebDataURI) { 7322 matchAllList.add(info); 7323 continue; 7324 } 7325 // Try to get the status from User settings first 7326 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 7327 int status = (int)(packedStatus >> 32); 7328 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 7329 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 7330 if (DEBUG_DOMAIN_VERIFICATION || debug) { 7331 Slog.i(TAG, " + always: " + info.activityInfo.packageName 7332 + " : linkgen=" + linkGeneration); 7333 } 7334 // Use link-enabled generation as preferredOrder, i.e. 7335 // prefer newly-enabled over earlier-enabled. 7336 info.preferredOrder = linkGeneration; 7337 alwaysList.add(info); 7338 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 7339 if (DEBUG_DOMAIN_VERIFICATION || debug) { 7340 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 7341 } 7342 neverList.add(info); 7343 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 7344 if (DEBUG_DOMAIN_VERIFICATION || debug) { 7345 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 7346 } 7347 alwaysAskList.add(info); 7348 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 7349 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 7350 if (DEBUG_DOMAIN_VERIFICATION || debug) { 7351 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 7352 } 7353 undefinedList.add(info); 7354 } 7355 } 7356 } 7357 7358 // We'll want to include browser possibilities in a few cases 7359 boolean includeBrowser = false; 7360 7361 // First try to add the "always" resolution(s) for the current user, if any 7362 if (alwaysList.size() > 0) { 7363 result.addAll(alwaysList); 7364 } else { 7365 // Add all undefined apps as we want them to appear in the disambiguation dialog. 7366 result.addAll(undefinedList); 7367 // Maybe add one for the other profile. 7368 if (xpDomainInfo != null && ( 7369 xpDomainInfo.bestDomainVerificationStatus 7370 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 7371 result.add(xpDomainInfo.resolveInfo); 7372 } 7373 includeBrowser = true; 7374 } 7375 7376 // The presence of any 'always ask' alternatives means we'll also offer browsers. 7377 // If there were 'always' entries their preferred order has been set, so we also 7378 // back that off to make the alternatives equivalent 7379 if (alwaysAskList.size() > 0) { 7380 for (ResolveInfo i : result) { 7381 i.preferredOrder = 0; 7382 } 7383 result.addAll(alwaysAskList); 7384 includeBrowser = true; 7385 } 7386 7387 if (includeBrowser) { 7388 // Also add browsers (all of them or only the default one) 7389 if (DEBUG_DOMAIN_VERIFICATION) { 7390 Slog.v(TAG, " ...including browsers in candidate set"); 7391 } 7392 if ((matchFlags & MATCH_ALL) != 0) { 7393 result.addAll(matchAllList); 7394 } else { 7395 // Browser/generic handling case. If there's a default browser, go straight 7396 // to that (but only if there is no other higher-priority match). 7397 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 7398 int maxMatchPrio = 0; 7399 ResolveInfo defaultBrowserMatch = null; 7400 final int numCandidates = matchAllList.size(); 7401 for (int n = 0; n < numCandidates; n++) { 7402 ResolveInfo info = matchAllList.get(n); 7403 // track the highest overall match priority... 7404 if (info.priority > maxMatchPrio) { 7405 maxMatchPrio = info.priority; 7406 } 7407 // ...and the highest-priority default browser match 7408 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 7409 if (defaultBrowserMatch == null 7410 || (defaultBrowserMatch.priority < info.priority)) { 7411 if (debug) { 7412 Slog.v(TAG, "Considering default browser match " + info); 7413 } 7414 defaultBrowserMatch = info; 7415 } 7416 } 7417 } 7418 if (defaultBrowserMatch != null 7419 && defaultBrowserMatch.priority >= maxMatchPrio 7420 && !TextUtils.isEmpty(defaultBrowserPackageName)) 7421 { 7422 if (debug) { 7423 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 7424 } 7425 result.add(defaultBrowserMatch); 7426 } else { 7427 result.addAll(matchAllList); 7428 } 7429 } 7430 7431 // If there is nothing selected, add all candidates and remove the ones that the user 7432 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 7433 if (result.size() == 0) { 7434 result.addAll(candidates); 7435 result.removeAll(neverList); 7436 } 7437 } 7438 } 7439 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 7440 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 7441 result.size()); 7442 for (ResolveInfo info : result) { 7443 Slog.v(TAG, " + " + info.activityInfo); 7444 } 7445 } 7446 return result; 7447 } 7448 7449 // Returns a packed value as a long: 7450 // 7451 // high 'int'-sized word: link status: undefined/ask/never/always. 7452 // low 'int'-sized word: relative priority among 'always' results. 7453 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 7454 long result = ps.getDomainVerificationStatusForUser(userId); 7455 // if none available, get the master status 7456 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 7457 if (ps.getIntentFilterVerificationInfo() != null) { 7458 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 7459 } 7460 } 7461 return result; 7462 } 7463 7464 private ResolveInfo querySkipCurrentProfileIntents( 7465 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 7466 int flags, int sourceUserId) { 7467 if (matchingFilters != null) { 7468 int size = matchingFilters.size(); 7469 for (int i = 0; i < size; i ++) { 7470 CrossProfileIntentFilter filter = matchingFilters.get(i); 7471 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 7472 // Checking if there are activities in the target user that can handle the 7473 // intent. 7474 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 7475 resolvedType, flags, sourceUserId); 7476 if (resolveInfo != null) { 7477 return resolveInfo; 7478 } 7479 } 7480 } 7481 } 7482 return null; 7483 } 7484 7485 // Return matching ResolveInfo in target user if any. 7486 private ResolveInfo queryCrossProfileIntents( 7487 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 7488 int flags, int sourceUserId, boolean matchInCurrentProfile) { 7489 if (matchingFilters != null) { 7490 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 7491 // match the same intent. For performance reasons, it is better not to 7492 // run queryIntent twice for the same userId 7493 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 7494 int size = matchingFilters.size(); 7495 for (int i = 0; i < size; i++) { 7496 CrossProfileIntentFilter filter = matchingFilters.get(i); 7497 int targetUserId = filter.getTargetUserId(); 7498 boolean skipCurrentProfile = 7499 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 7500 boolean skipCurrentProfileIfNoMatchFound = 7501 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 7502 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 7503 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 7504 // Checking if there are activities in the target user that can handle the 7505 // intent. 7506 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 7507 resolvedType, flags, sourceUserId); 7508 if (resolveInfo != null) return resolveInfo; 7509 alreadyTriedUserIds.put(targetUserId, true); 7510 } 7511 } 7512 } 7513 return null; 7514 } 7515 7516 /** 7517 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 7518 * will forward the intent to the filter's target user. 7519 * Otherwise, returns null. 7520 */ 7521 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 7522 String resolvedType, int flags, int sourceUserId) { 7523 int targetUserId = filter.getTargetUserId(); 7524 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 7525 resolvedType, flags, targetUserId); 7526 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 7527 // If all the matches in the target profile are suspended, return null. 7528 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 7529 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 7530 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 7531 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 7532 targetUserId); 7533 } 7534 } 7535 } 7536 return null; 7537 } 7538 7539 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 7540 int sourceUserId, int targetUserId) { 7541 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 7542 long ident = Binder.clearCallingIdentity(); 7543 boolean targetIsProfile; 7544 try { 7545 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 7546 } finally { 7547 Binder.restoreCallingIdentity(ident); 7548 } 7549 String className; 7550 if (targetIsProfile) { 7551 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 7552 } else { 7553 className = FORWARD_INTENT_TO_PARENT; 7554 } 7555 ComponentName forwardingActivityComponentName = new ComponentName( 7556 mAndroidApplication.packageName, className); 7557 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 7558 sourceUserId); 7559 if (!targetIsProfile) { 7560 forwardingActivityInfo.showUserIcon = targetUserId; 7561 forwardingResolveInfo.noResourceId = true; 7562 } 7563 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 7564 forwardingResolveInfo.priority = 0; 7565 forwardingResolveInfo.preferredOrder = 0; 7566 forwardingResolveInfo.match = 0; 7567 forwardingResolveInfo.isDefault = true; 7568 forwardingResolveInfo.filter = filter; 7569 forwardingResolveInfo.targetUserId = targetUserId; 7570 return forwardingResolveInfo; 7571 } 7572 7573 @Override 7574 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 7575 Intent[] specifics, String[] specificTypes, Intent intent, 7576 String resolvedType, int flags, int userId) { 7577 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 7578 specificTypes, intent, resolvedType, flags, userId)); 7579 } 7580 7581 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 7582 Intent[] specifics, String[] specificTypes, Intent intent, 7583 String resolvedType, int flags, int userId) { 7584 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7585 final int callingUid = Binder.getCallingUid(); 7586 flags = updateFlagsForResolve(flags, userId, intent, callingUid, 7587 false /*includeInstantApps*/); 7588 enforceCrossUserPermission(callingUid, userId, 7589 false /*requireFullPermission*/, false /*checkShell*/, 7590 "query intent activity options"); 7591 final String resultsAction = intent.getAction(); 7592 7593 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 7594 | PackageManager.GET_RESOLVED_FILTER, userId); 7595 7596 if (DEBUG_INTENT_MATCHING) { 7597 Log.v(TAG, "Query " + intent + ": " + results); 7598 } 7599 7600 int specificsPos = 0; 7601 int N; 7602 7603 // todo: note that the algorithm used here is O(N^2). This 7604 // isn't a problem in our current environment, but if we start running 7605 // into situations where we have more than 5 or 10 matches then this 7606 // should probably be changed to something smarter... 7607 7608 // First we go through and resolve each of the specific items 7609 // that were supplied, taking care of removing any corresponding 7610 // duplicate items in the generic resolve list. 7611 if (specifics != null) { 7612 for (int i=0; i<specifics.length; i++) { 7613 final Intent sintent = specifics[i]; 7614 if (sintent == null) { 7615 continue; 7616 } 7617 7618 if (DEBUG_INTENT_MATCHING) { 7619 Log.v(TAG, "Specific #" + i + ": " + sintent); 7620 } 7621 7622 String action = sintent.getAction(); 7623 if (resultsAction != null && resultsAction.equals(action)) { 7624 // If this action was explicitly requested, then don't 7625 // remove things that have it. 7626 action = null; 7627 } 7628 7629 ResolveInfo ri = null; 7630 ActivityInfo ai = null; 7631 7632 ComponentName comp = sintent.getComponent(); 7633 if (comp == null) { 7634 ri = resolveIntent( 7635 sintent, 7636 specificTypes != null ? specificTypes[i] : null, 7637 flags, userId); 7638 if (ri == null) { 7639 continue; 7640 } 7641 if (ri == mResolveInfo) { 7642 // ACK! Must do something better with this. 7643 } 7644 ai = ri.activityInfo; 7645 comp = new ComponentName(ai.applicationInfo.packageName, 7646 ai.name); 7647 } else { 7648 ai = getActivityInfo(comp, flags, userId); 7649 if (ai == null) { 7650 continue; 7651 } 7652 } 7653 7654 // Look for any generic query activities that are duplicates 7655 // of this specific one, and remove them from the results. 7656 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 7657 N = results.size(); 7658 int j; 7659 for (j=specificsPos; j<N; j++) { 7660 ResolveInfo sri = results.get(j); 7661 if ((sri.activityInfo.name.equals(comp.getClassName()) 7662 && sri.activityInfo.applicationInfo.packageName.equals( 7663 comp.getPackageName())) 7664 || (action != null && sri.filter.matchAction(action))) { 7665 results.remove(j); 7666 if (DEBUG_INTENT_MATCHING) Log.v( 7667 TAG, "Removing duplicate item from " + j 7668 + " due to specific " + specificsPos); 7669 if (ri == null) { 7670 ri = sri; 7671 } 7672 j--; 7673 N--; 7674 } 7675 } 7676 7677 // Add this specific item to its proper place. 7678 if (ri == null) { 7679 ri = new ResolveInfo(); 7680 ri.activityInfo = ai; 7681 } 7682 results.add(specificsPos, ri); 7683 ri.specificIndex = i; 7684 specificsPos++; 7685 } 7686 } 7687 7688 // Now we go through the remaining generic results and remove any 7689 // duplicate actions that are found here. 7690 N = results.size(); 7691 for (int i=specificsPos; i<N-1; i++) { 7692 final ResolveInfo rii = results.get(i); 7693 if (rii.filter == null) { 7694 continue; 7695 } 7696 7697 // Iterate over all of the actions of this result's intent 7698 // filter... typically this should be just one. 7699 final Iterator<String> it = rii.filter.actionsIterator(); 7700 if (it == null) { 7701 continue; 7702 } 7703 while (it.hasNext()) { 7704 final String action = it.next(); 7705 if (resultsAction != null && resultsAction.equals(action)) { 7706 // If this action was explicitly requested, then don't 7707 // remove things that have it. 7708 continue; 7709 } 7710 for (int j=i+1; j<N; j++) { 7711 final ResolveInfo rij = results.get(j); 7712 if (rij.filter != null && rij.filter.hasAction(action)) { 7713 results.remove(j); 7714 if (DEBUG_INTENT_MATCHING) Log.v( 7715 TAG, "Removing duplicate item from " + j 7716 + " due to action " + action + " at " + i); 7717 j--; 7718 N--; 7719 } 7720 } 7721 } 7722 7723 // If the caller didn't request filter information, drop it now 7724 // so we don't have to marshall/unmarshall it. 7725 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 7726 rii.filter = null; 7727 } 7728 } 7729 7730 // Filter out the caller activity if so requested. 7731 if (caller != null) { 7732 N = results.size(); 7733 for (int i=0; i<N; i++) { 7734 ActivityInfo ainfo = results.get(i).activityInfo; 7735 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 7736 && caller.getClassName().equals(ainfo.name)) { 7737 results.remove(i); 7738 break; 7739 } 7740 } 7741 } 7742 7743 // If the caller didn't request filter information, 7744 // drop them now so we don't have to 7745 // marshall/unmarshall it. 7746 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 7747 N = results.size(); 7748 for (int i=0; i<N; i++) { 7749 results.get(i).filter = null; 7750 } 7751 } 7752 7753 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 7754 return results; 7755 } 7756 7757 @Override 7758 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 7759 String resolvedType, int flags, int userId) { 7760 return new ParceledListSlice<>( 7761 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 7762 } 7763 7764 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 7765 String resolvedType, int flags, int userId) { 7766 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7767 final int callingUid = Binder.getCallingUid(); 7768 final String instantAppPkgName = getInstantAppPackageName(callingUid); 7769 flags = updateFlagsForResolve(flags, userId, intent, callingUid, 7770 false /*includeInstantApps*/); 7771 ComponentName comp = intent.getComponent(); 7772 if (comp == null) { 7773 if (intent.getSelector() != null) { 7774 intent = intent.getSelector(); 7775 comp = intent.getComponent(); 7776 } 7777 } 7778 if (comp != null) { 7779 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7780 final ActivityInfo ai = getReceiverInfo(comp, flags, userId); 7781 if (ai != null) { 7782 // When specifying an explicit component, we prevent the activity from being 7783 // used when either 1) the calling package is normal and the activity is within 7784 // an instant application or 2) the calling package is ephemeral and the 7785 // activity is not visible to instant applications. 7786 final boolean matchInstantApp = 7787 (flags & PackageManager.MATCH_INSTANT) != 0; 7788 final boolean matchVisibleToInstantAppOnly = 7789 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 7790 final boolean matchExplicitlyVisibleOnly = 7791 (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0; 7792 final boolean isCallerInstantApp = 7793 instantAppPkgName != null; 7794 final boolean isTargetSameInstantApp = 7795 comp.getPackageName().equals(instantAppPkgName); 7796 final boolean isTargetInstantApp = 7797 (ai.applicationInfo.privateFlags 7798 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 7799 final boolean isTargetVisibleToInstantApp = 7800 (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0; 7801 final boolean isTargetExplicitlyVisibleToInstantApp = 7802 isTargetVisibleToInstantApp 7803 && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0; 7804 final boolean isTargetHiddenFromInstantApp = 7805 !isTargetVisibleToInstantApp 7806 || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp); 7807 final boolean blockResolution = 7808 !isTargetSameInstantApp 7809 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 7810 || (matchVisibleToInstantAppOnly && isCallerInstantApp 7811 && isTargetHiddenFromInstantApp)); 7812 if (!blockResolution) { 7813 ResolveInfo ri = new ResolveInfo(); 7814 ri.activityInfo = ai; 7815 list.add(ri); 7816 } 7817 } 7818 return applyPostResolutionFilter(list, instantAppPkgName); 7819 } 7820 7821 // reader 7822 synchronized (mPackages) { 7823 String pkgName = intent.getPackage(); 7824 if (pkgName == null) { 7825 final List<ResolveInfo> result = 7826 mReceivers.queryIntent(intent, resolvedType, flags, userId); 7827 return applyPostResolutionFilter(result, instantAppPkgName); 7828 } 7829 final PackageParser.Package pkg = mPackages.get(pkgName); 7830 if (pkg != null) { 7831 final List<ResolveInfo> result = mReceivers.queryIntentForPackage( 7832 intent, resolvedType, flags, pkg.receivers, userId); 7833 return applyPostResolutionFilter(result, instantAppPkgName); 7834 } 7835 return Collections.emptyList(); 7836 } 7837 } 7838 7839 @Override 7840 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 7841 final int callingUid = Binder.getCallingUid(); 7842 return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid); 7843 } 7844 7845 private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags, 7846 int userId, int callingUid) { 7847 if (!sUserManager.exists(userId)) return null; 7848 flags = updateFlagsForResolve( 7849 flags, userId, intent, callingUid, false /*includeInstantApps*/); 7850 List<ResolveInfo> query = queryIntentServicesInternal( 7851 intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/); 7852 if (query != null) { 7853 if (query.size() >= 1) { 7854 // If there is more than one service with the same priority, 7855 // just arbitrarily pick the first one. 7856 return query.get(0); 7857 } 7858 } 7859 return null; 7860 } 7861 7862 @Override 7863 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 7864 String resolvedType, int flags, int userId) { 7865 final int callingUid = Binder.getCallingUid(); 7866 return new ParceledListSlice<>(queryIntentServicesInternal( 7867 intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/)); 7868 } 7869 7870 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 7871 String resolvedType, int flags, int userId, int callingUid, 7872 boolean includeInstantApps) { 7873 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7874 final String instantAppPkgName = getInstantAppPackageName(callingUid); 7875 flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps); 7876 ComponentName comp = intent.getComponent(); 7877 if (comp == null) { 7878 if (intent.getSelector() != null) { 7879 intent = intent.getSelector(); 7880 comp = intent.getComponent(); 7881 } 7882 } 7883 if (comp != null) { 7884 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7885 final ServiceInfo si = getServiceInfo(comp, flags, userId); 7886 if (si != null) { 7887 // When specifying an explicit component, we prevent the service from being 7888 // used when either 1) the service is in an instant application and the 7889 // caller is not the same instant application or 2) the calling package is 7890 // ephemeral and the activity is not visible to ephemeral applications. 7891 final boolean matchInstantApp = 7892 (flags & PackageManager.MATCH_INSTANT) != 0; 7893 final boolean matchVisibleToInstantAppOnly = 7894 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 7895 final boolean isCallerInstantApp = 7896 instantAppPkgName != null; 7897 final boolean isTargetSameInstantApp = 7898 comp.getPackageName().equals(instantAppPkgName); 7899 final boolean isTargetInstantApp = 7900 (si.applicationInfo.privateFlags 7901 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 7902 final boolean isTargetHiddenFromInstantApp = 7903 (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0; 7904 final boolean blockResolution = 7905 !isTargetSameInstantApp 7906 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 7907 || (matchVisibleToInstantAppOnly && isCallerInstantApp 7908 && isTargetHiddenFromInstantApp)); 7909 if (!blockResolution) { 7910 final ResolveInfo ri = new ResolveInfo(); 7911 ri.serviceInfo = si; 7912 list.add(ri); 7913 } 7914 } 7915 return list; 7916 } 7917 7918 // reader 7919 synchronized (mPackages) { 7920 String pkgName = intent.getPackage(); 7921 if (pkgName == null) { 7922 return applyPostServiceResolutionFilter( 7923 mServices.queryIntent(intent, resolvedType, flags, userId), 7924 instantAppPkgName); 7925 } 7926 final PackageParser.Package pkg = mPackages.get(pkgName); 7927 if (pkg != null) { 7928 return applyPostServiceResolutionFilter( 7929 mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 7930 userId), 7931 instantAppPkgName); 7932 } 7933 return Collections.emptyList(); 7934 } 7935 } 7936 7937 private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos, 7938 String instantAppPkgName) { 7939 // TODO: When adding on-demand split support for non-instant apps, remove this check 7940 // and always apply post filtering 7941 if (instantAppPkgName == null) { 7942 return resolveInfos; 7943 } 7944 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 7945 final ResolveInfo info = resolveInfos.get(i); 7946 final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp(); 7947 // allow services that are defined in the provided package 7948 if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) { 7949 if (info.serviceInfo.splitName != null 7950 && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames, 7951 info.serviceInfo.splitName)) { 7952 // requested service is defined in a split that hasn't been installed yet. 7953 // add the installer to the resolve list 7954 if (DEBUG_EPHEMERAL) { 7955 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 7956 } 7957 final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo); 7958 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 7959 info.serviceInfo.packageName, info.serviceInfo.splitName, 7960 info.serviceInfo.applicationInfo.versionCode, null /*failureIntent*/); 7961 // make sure this resolver is the default 7962 installerInfo.isDefault = true; 7963 installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 7964 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 7965 // add a non-generic filter 7966 installerInfo.filter = new IntentFilter(); 7967 // load resources from the correct package 7968 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 7969 resolveInfos.set(i, installerInfo); 7970 } 7971 continue; 7972 } 7973 // allow services that have been explicitly exposed to ephemeral apps 7974 if (!isEphemeralApp 7975 && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) { 7976 continue; 7977 } 7978 resolveInfos.remove(i); 7979 } 7980 return resolveInfos; 7981 } 7982 7983 @Override 7984 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 7985 String resolvedType, int flags, int userId) { 7986 return new ParceledListSlice<>( 7987 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 7988 } 7989 7990 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 7991 Intent intent, String resolvedType, int flags, int userId) { 7992 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7993 final int callingUid = Binder.getCallingUid(); 7994 final String instantAppPkgName = getInstantAppPackageName(callingUid); 7995 flags = updateFlagsForResolve(flags, userId, intent, callingUid, 7996 false /*includeInstantApps*/); 7997 ComponentName comp = intent.getComponent(); 7998 if (comp == null) { 7999 if (intent.getSelector() != null) { 8000 intent = intent.getSelector(); 8001 comp = intent.getComponent(); 8002 } 8003 } 8004 if (comp != null) { 8005 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 8006 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 8007 if (pi != null) { 8008 // When specifying an explicit component, we prevent the provider from being 8009 // used when either 1) the provider is in an instant application and the 8010 // caller is not the same instant application or 2) the calling package is an 8011 // instant application and the provider is not visible to instant applications. 8012 final boolean matchInstantApp = 8013 (flags & PackageManager.MATCH_INSTANT) != 0; 8014 final boolean matchVisibleToInstantAppOnly = 8015 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 8016 final boolean isCallerInstantApp = 8017 instantAppPkgName != null; 8018 final boolean isTargetSameInstantApp = 8019 comp.getPackageName().equals(instantAppPkgName); 8020 final boolean isTargetInstantApp = 8021 (pi.applicationInfo.privateFlags 8022 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 8023 final boolean isTargetHiddenFromInstantApp = 8024 (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0; 8025 final boolean blockResolution = 8026 !isTargetSameInstantApp 8027 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 8028 || (matchVisibleToInstantAppOnly && isCallerInstantApp 8029 && isTargetHiddenFromInstantApp)); 8030 if (!blockResolution) { 8031 final ResolveInfo ri = new ResolveInfo(); 8032 ri.providerInfo = pi; 8033 list.add(ri); 8034 } 8035 } 8036 return list; 8037 } 8038 8039 // reader 8040 synchronized (mPackages) { 8041 String pkgName = intent.getPackage(); 8042 if (pkgName == null) { 8043 return applyPostContentProviderResolutionFilter( 8044 mProviders.queryIntent(intent, resolvedType, flags, userId), 8045 instantAppPkgName); 8046 } 8047 final PackageParser.Package pkg = mPackages.get(pkgName); 8048 if (pkg != null) { 8049 return applyPostContentProviderResolutionFilter( 8050 mProviders.queryIntentForPackage( 8051 intent, resolvedType, flags, pkg.providers, userId), 8052 instantAppPkgName); 8053 } 8054 return Collections.emptyList(); 8055 } 8056 } 8057 8058 private List<ResolveInfo> applyPostContentProviderResolutionFilter( 8059 List<ResolveInfo> resolveInfos, String instantAppPkgName) { 8060 // TODO: When adding on-demand split support for non-instant applications, remove 8061 // this check and always apply post filtering 8062 if (instantAppPkgName == null) { 8063 return resolveInfos; 8064 } 8065 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 8066 final ResolveInfo info = resolveInfos.get(i); 8067 final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp(); 8068 // allow providers that are defined in the provided package 8069 if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) { 8070 if (info.providerInfo.splitName != null 8071 && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames, 8072 info.providerInfo.splitName)) { 8073 // requested provider is defined in a split that hasn't been installed yet. 8074 // add the installer to the resolve list 8075 if (DEBUG_EPHEMERAL) { 8076 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 8077 } 8078 final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo); 8079 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 8080 info.providerInfo.packageName, info.providerInfo.splitName, 8081 info.providerInfo.applicationInfo.versionCode, null /*failureIntent*/); 8082 // make sure this resolver is the default 8083 installerInfo.isDefault = true; 8084 installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 8085 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 8086 // add a non-generic filter 8087 installerInfo.filter = new IntentFilter(); 8088 // load resources from the correct package 8089 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 8090 resolveInfos.set(i, installerInfo); 8091 } 8092 continue; 8093 } 8094 // allow providers that have been explicitly exposed to instant applications 8095 if (!isEphemeralApp 8096 && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) { 8097 continue; 8098 } 8099 resolveInfos.remove(i); 8100 } 8101 return resolveInfos; 8102 } 8103 8104 @Override 8105 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 8106 final int callingUid = Binder.getCallingUid(); 8107 if (getInstantAppPackageName(callingUid) != null) { 8108 return ParceledListSlice.emptyList(); 8109 } 8110 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 8111 flags = updateFlagsForPackage(flags, userId, null); 8112 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 8113 enforceCrossUserPermission(callingUid, userId, 8114 true /* requireFullPermission */, false /* checkShell */, 8115 "get installed packages"); 8116 8117 // writer 8118 synchronized (mPackages) { 8119 ArrayList<PackageInfo> list; 8120 if (listUninstalled) { 8121 list = new ArrayList<>(mSettings.mPackages.size()); 8122 for (PackageSetting ps : mSettings.mPackages.values()) { 8123 if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) { 8124 continue; 8125 } 8126 if (filterAppAccessLPr(ps, callingUid, userId)) { 8127 return null; 8128 } 8129 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 8130 if (pi != null) { 8131 list.add(pi); 8132 } 8133 } 8134 } else { 8135 list = new ArrayList<>(mPackages.size()); 8136 for (PackageParser.Package p : mPackages.values()) { 8137 final PackageSetting ps = (PackageSetting) p.mExtras; 8138 if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) { 8139 continue; 8140 } 8141 if (filterAppAccessLPr(ps, callingUid, userId)) { 8142 return null; 8143 } 8144 final PackageInfo pi = generatePackageInfo((PackageSetting) 8145 p.mExtras, flags, userId); 8146 if (pi != null) { 8147 list.add(pi); 8148 } 8149 } 8150 } 8151 8152 return new ParceledListSlice<>(list); 8153 } 8154 } 8155 8156 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 8157 String[] permissions, boolean[] tmp, int flags, int userId) { 8158 int numMatch = 0; 8159 final PermissionsState permissionsState = ps.getPermissionsState(); 8160 for (int i=0; i<permissions.length; i++) { 8161 final String permission = permissions[i]; 8162 if (permissionsState.hasPermission(permission, userId)) { 8163 tmp[i] = true; 8164 numMatch++; 8165 } else { 8166 tmp[i] = false; 8167 } 8168 } 8169 if (numMatch == 0) { 8170 return; 8171 } 8172 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 8173 8174 // The above might return null in cases of uninstalled apps or install-state 8175 // skew across users/profiles. 8176 if (pi != null) { 8177 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 8178 if (numMatch == permissions.length) { 8179 pi.requestedPermissions = permissions; 8180 } else { 8181 pi.requestedPermissions = new String[numMatch]; 8182 numMatch = 0; 8183 for (int i=0; i<permissions.length; i++) { 8184 if (tmp[i]) { 8185 pi.requestedPermissions[numMatch] = permissions[i]; 8186 numMatch++; 8187 } 8188 } 8189 } 8190 } 8191 list.add(pi); 8192 } 8193 } 8194 8195 @Override 8196 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 8197 String[] permissions, int flags, int userId) { 8198 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 8199 flags = updateFlagsForPackage(flags, userId, permissions); 8200 enforceCrossUserPermission(Binder.getCallingUid(), userId, 8201 true /* requireFullPermission */, false /* checkShell */, 8202 "get packages holding permissions"); 8203 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 8204 8205 // writer 8206 synchronized (mPackages) { 8207 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 8208 boolean[] tmpBools = new boolean[permissions.length]; 8209 if (listUninstalled) { 8210 for (PackageSetting ps : mSettings.mPackages.values()) { 8211 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 8212 userId); 8213 } 8214 } else { 8215 for (PackageParser.Package pkg : mPackages.values()) { 8216 PackageSetting ps = (PackageSetting)pkg.mExtras; 8217 if (ps != null) { 8218 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 8219 userId); 8220 } 8221 } 8222 } 8223 8224 return new ParceledListSlice<PackageInfo>(list); 8225 } 8226 } 8227 8228 @Override 8229 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 8230 final int callingUid = Binder.getCallingUid(); 8231 if (getInstantAppPackageName(callingUid) != null) { 8232 return ParceledListSlice.emptyList(); 8233 } 8234 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 8235 flags = updateFlagsForApplication(flags, userId, null); 8236 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 8237 8238 // writer 8239 synchronized (mPackages) { 8240 ArrayList<ApplicationInfo> list; 8241 if (listUninstalled) { 8242 list = new ArrayList<>(mSettings.mPackages.size()); 8243 for (PackageSetting ps : mSettings.mPackages.values()) { 8244 ApplicationInfo ai; 8245 int effectiveFlags = flags; 8246 if (ps.isSystem()) { 8247 effectiveFlags |= PackageManager.MATCH_ANY_USER; 8248 } 8249 if (ps.pkg != null) { 8250 if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) { 8251 continue; 8252 } 8253 if (filterAppAccessLPr(ps, callingUid, userId)) { 8254 return null; 8255 } 8256 ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags, 8257 ps.readUserState(userId), userId); 8258 if (ai != null) { 8259 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 8260 } 8261 } else { 8262 // Shared lib filtering done in generateApplicationInfoFromSettingsLPw 8263 // and already converts to externally visible package name 8264 ai = generateApplicationInfoFromSettingsLPw(ps.name, 8265 callingUid, effectiveFlags, userId); 8266 } 8267 if (ai != null) { 8268 list.add(ai); 8269 } 8270 } 8271 } else { 8272 list = new ArrayList<>(mPackages.size()); 8273 for (PackageParser.Package p : mPackages.values()) { 8274 if (p.mExtras != null) { 8275 PackageSetting ps = (PackageSetting) p.mExtras; 8276 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) { 8277 continue; 8278 } 8279 if (filterAppAccessLPr(ps, callingUid, userId)) { 8280 return null; 8281 } 8282 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 8283 ps.readUserState(userId), userId); 8284 if (ai != null) { 8285 ai.packageName = resolveExternalPackageNameLPr(p); 8286 list.add(ai); 8287 } 8288 } 8289 } 8290 } 8291 8292 return new ParceledListSlice<>(list); 8293 } 8294 } 8295 8296 @Override 8297 public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) { 8298 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 8299 return null; 8300 } 8301 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS, 8302 "getEphemeralApplications"); 8303 enforceCrossUserPermission(Binder.getCallingUid(), userId, 8304 true /* requireFullPermission */, false /* checkShell */, 8305 "getEphemeralApplications"); 8306 synchronized (mPackages) { 8307 List<InstantAppInfo> instantApps = mInstantAppRegistry 8308 .getInstantAppsLPr(userId); 8309 if (instantApps != null) { 8310 return new ParceledListSlice<>(instantApps); 8311 } 8312 } 8313 return null; 8314 } 8315 8316 @Override 8317 public boolean isInstantApp(String packageName, int userId) { 8318 enforceCrossUserPermission(Binder.getCallingUid(), userId, 8319 true /* requireFullPermission */, false /* checkShell */, 8320 "isInstantApp"); 8321 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 8322 return false; 8323 } 8324 int callingUid = Binder.getCallingUid(); 8325 if (Process.isIsolated(callingUid)) { 8326 callingUid = mIsolatedOwners.get(callingUid); 8327 } 8328 8329 synchronized (mPackages) { 8330 final PackageSetting ps = mSettings.mPackages.get(packageName); 8331 PackageParser.Package pkg = mPackages.get(packageName); 8332 final boolean returnAllowed = 8333 ps != null 8334 && (isCallerSameApp(packageName, callingUid) 8335 || canViewInstantApps(callingUid, userId) 8336 || mInstantAppRegistry.isInstantAccessGranted( 8337 userId, UserHandle.getAppId(callingUid), ps.appId)); 8338 if (returnAllowed) { 8339 return ps.getInstantApp(userId); 8340 } 8341 } 8342 return false; 8343 } 8344 8345 @Override 8346 public byte[] getInstantAppCookie(String packageName, int userId) { 8347 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 8348 return null; 8349 } 8350 8351 enforceCrossUserPermission(Binder.getCallingUid(), userId, 8352 true /* requireFullPermission */, false /* checkShell */, 8353 "getInstantAppCookie"); 8354 if (!isCallerSameApp(packageName, Binder.getCallingUid())) { 8355 return null; 8356 } 8357 synchronized (mPackages) { 8358 return mInstantAppRegistry.getInstantAppCookieLPw( 8359 packageName, userId); 8360 } 8361 } 8362 8363 @Override 8364 public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) { 8365 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 8366 return true; 8367 } 8368 8369 enforceCrossUserPermission(Binder.getCallingUid(), userId, 8370 true /* requireFullPermission */, true /* checkShell */, 8371 "setInstantAppCookie"); 8372 if (!isCallerSameApp(packageName, Binder.getCallingUid())) { 8373 return false; 8374 } 8375 synchronized (mPackages) { 8376 return mInstantAppRegistry.setInstantAppCookieLPw( 8377 packageName, cookie, userId); 8378 } 8379 } 8380 8381 @Override 8382 public Bitmap getInstantAppIcon(String packageName, int userId) { 8383 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 8384 return null; 8385 } 8386 8387 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS, 8388 "getInstantAppIcon"); 8389 8390 enforceCrossUserPermission(Binder.getCallingUid(), userId, 8391 true /* requireFullPermission */, false /* checkShell */, 8392 "getInstantAppIcon"); 8393 8394 synchronized (mPackages) { 8395 return mInstantAppRegistry.getInstantAppIconLPw( 8396 packageName, userId); 8397 } 8398 } 8399 8400 private boolean isCallerSameApp(String packageName, int uid) { 8401 PackageParser.Package pkg = mPackages.get(packageName); 8402 return pkg != null 8403 && UserHandle.getAppId(uid) == pkg.applicationInfo.uid; 8404 } 8405 8406 @Override 8407 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 8408 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 8409 return ParceledListSlice.emptyList(); 8410 } 8411 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 8412 } 8413 8414 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 8415 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 8416 8417 // reader 8418 synchronized (mPackages) { 8419 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 8420 final int userId = UserHandle.getCallingUserId(); 8421 while (i.hasNext()) { 8422 final PackageParser.Package p = i.next(); 8423 if (p.applicationInfo == null) continue; 8424 8425 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 8426 && !p.applicationInfo.isDirectBootAware(); 8427 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 8428 && p.applicationInfo.isDirectBootAware(); 8429 8430 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 8431 && (!mSafeMode || isSystemApp(p)) 8432 && (matchesUnaware || matchesAware)) { 8433 PackageSetting ps = mSettings.mPackages.get(p.packageName); 8434 if (ps != null) { 8435 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 8436 ps.readUserState(userId), userId); 8437 if (ai != null) { 8438 finalList.add(ai); 8439 } 8440 } 8441 } 8442 } 8443 } 8444 8445 return finalList; 8446 } 8447 8448 @Override 8449 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 8450 if (!sUserManager.exists(userId)) return null; 8451 flags = updateFlagsForComponent(flags, userId, name); 8452 final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid()); 8453 // reader 8454 synchronized (mPackages) { 8455 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 8456 PackageSetting ps = provider != null 8457 ? mSettings.mPackages.get(provider.owner.packageName) 8458 : null; 8459 if (ps != null) { 8460 final boolean isInstantApp = ps.getInstantApp(userId); 8461 // normal application; filter out instant application provider 8462 if (instantAppPkgName == null && isInstantApp) { 8463 return null; 8464 } 8465 // instant application; filter out other instant applications 8466 if (instantAppPkgName != null 8467 && isInstantApp 8468 && !provider.owner.packageName.equals(instantAppPkgName)) { 8469 return null; 8470 } 8471 // instant application; filter out non-exposed provider 8472 if (instantAppPkgName != null 8473 && !isInstantApp 8474 && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) { 8475 return null; 8476 } 8477 // provider not enabled 8478 if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) { 8479 return null; 8480 } 8481 return PackageParser.generateProviderInfo( 8482 provider, flags, ps.readUserState(userId), userId); 8483 } 8484 return null; 8485 } 8486 } 8487 8488 /** 8489 * @deprecated 8490 */ 8491 @Deprecated 8492 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 8493 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 8494 return; 8495 } 8496 // reader 8497 synchronized (mPackages) { 8498 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 8499 .entrySet().iterator(); 8500 final int userId = UserHandle.getCallingUserId(); 8501 while (i.hasNext()) { 8502 Map.Entry<String, PackageParser.Provider> entry = i.next(); 8503 PackageParser.Provider p = entry.getValue(); 8504 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 8505 8506 if (ps != null && p.syncable 8507 && (!mSafeMode || (p.info.applicationInfo.flags 8508 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 8509 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 8510 ps.readUserState(userId), userId); 8511 if (info != null) { 8512 outNames.add(entry.getKey()); 8513 outInfo.add(info); 8514 } 8515 } 8516 } 8517 } 8518 } 8519 8520 @Override 8521 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 8522 int uid, int flags, String metaDataKey) { 8523 final int callingUid = Binder.getCallingUid(); 8524 final int userId = processName != null ? UserHandle.getUserId(uid) 8525 : UserHandle.getCallingUserId(); 8526 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 8527 flags = updateFlagsForComponent(flags, userId, processName); 8528 ArrayList<ProviderInfo> finalList = null; 8529 // reader 8530 synchronized (mPackages) { 8531 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 8532 while (i.hasNext()) { 8533 final PackageParser.Provider p = i.next(); 8534 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 8535 if (ps != null && p.info.authority != null 8536 && (processName == null 8537 || (p.info.processName.equals(processName) 8538 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 8539 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 8540 8541 // See PM.queryContentProviders()'s javadoc for why we have the metaData 8542 // parameter. 8543 if (metaDataKey != null 8544 && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) { 8545 continue; 8546 } 8547 final ComponentName component = 8548 new ComponentName(p.info.packageName, p.info.name); 8549 if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) { 8550 continue; 8551 } 8552 if (finalList == null) { 8553 finalList = new ArrayList<ProviderInfo>(3); 8554 } 8555 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 8556 ps.readUserState(userId), userId); 8557 if (info != null) { 8558 finalList.add(info); 8559 } 8560 } 8561 } 8562 } 8563 8564 if (finalList != null) { 8565 Collections.sort(finalList, mProviderInitOrderSorter); 8566 return new ParceledListSlice<ProviderInfo>(finalList); 8567 } 8568 8569 return ParceledListSlice.emptyList(); 8570 } 8571 8572 @Override 8573 public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) { 8574 // reader 8575 synchronized (mPackages) { 8576 final int callingUid = Binder.getCallingUid(); 8577 final int callingUserId = UserHandle.getUserId(callingUid); 8578 final PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 8579 if (ps == null) return null; 8580 if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) { 8581 return null; 8582 } 8583 final PackageParser.Instrumentation i = mInstrumentation.get(component); 8584 return PackageParser.generateInstrumentationInfo(i, flags); 8585 } 8586 } 8587 8588 @Override 8589 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 8590 String targetPackage, int flags) { 8591 final int callingUid = Binder.getCallingUid(); 8592 final int callingUserId = UserHandle.getUserId(callingUid); 8593 final PackageSetting ps = mSettings.mPackages.get(targetPackage); 8594 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 8595 return ParceledListSlice.emptyList(); 8596 } 8597 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 8598 } 8599 8600 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 8601 int flags) { 8602 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 8603 8604 // reader 8605 synchronized (mPackages) { 8606 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 8607 while (i.hasNext()) { 8608 final PackageParser.Instrumentation p = i.next(); 8609 if (targetPackage == null 8610 || targetPackage.equals(p.info.targetPackage)) { 8611 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 8612 flags); 8613 if (ii != null) { 8614 finalList.add(ii); 8615 } 8616 } 8617 } 8618 } 8619 8620 return finalList; 8621 } 8622 8623 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 8624 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]"); 8625 try { 8626 scanDirLI(dir, parseFlags, scanFlags, currentTime); 8627 } finally { 8628 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8629 } 8630 } 8631 8632 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 8633 final File[] files = dir.listFiles(); 8634 if (ArrayUtils.isEmpty(files)) { 8635 Log.d(TAG, "No files in app dir " + dir); 8636 return; 8637 } 8638 8639 if (DEBUG_PACKAGE_SCANNING) { 8640 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 8641 + " flags=0x" + Integer.toHexString(parseFlags)); 8642 } 8643 ParallelPackageParser parallelPackageParser = new ParallelPackageParser( 8644 mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir, 8645 mParallelPackageParserCallback); 8646 8647 // Submit files for parsing in parallel 8648 int fileCount = 0; 8649 for (File file : files) { 8650 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 8651 && !PackageInstallerService.isStageName(file.getName()); 8652 if (!isPackage) { 8653 // Ignore entries which are not packages 8654 continue; 8655 } 8656 parallelPackageParser.submit(file, parseFlags); 8657 fileCount++; 8658 } 8659 8660 // Process results one by one 8661 for (; fileCount > 0; fileCount--) { 8662 ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take(); 8663 Throwable throwable = parseResult.throwable; 8664 int errorCode = PackageManager.INSTALL_SUCCEEDED; 8665 8666 if (throwable == null) { 8667 // Static shared libraries have synthetic package names 8668 if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) { 8669 renameStaticSharedLibraryPackage(parseResult.pkg); 8670 } 8671 try { 8672 if (errorCode == PackageManager.INSTALL_SUCCEEDED) { 8673 scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags, 8674 currentTime, null); 8675 } 8676 } catch (PackageManagerException e) { 8677 errorCode = e.error; 8678 Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage()); 8679 } 8680 } else if (throwable instanceof PackageParser.PackageParserException) { 8681 PackageParser.PackageParserException e = (PackageParser.PackageParserException) 8682 throwable; 8683 errorCode = e.error; 8684 Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage()); 8685 } else { 8686 throw new IllegalStateException("Unexpected exception occurred while parsing " 8687 + parseResult.scanFile, throwable); 8688 } 8689 8690 // Delete invalid userdata apps 8691 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 8692 errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) { 8693 logCriticalInfo(Log.WARN, 8694 "Deleting invalid package at " + parseResult.scanFile); 8695 removeCodePathLI(parseResult.scanFile); 8696 } 8697 } 8698 parallelPackageParser.close(); 8699 } 8700 8701 private static File getSettingsProblemFile() { 8702 File dataDir = Environment.getDataDirectory(); 8703 File systemDir = new File(dataDir, "system"); 8704 File fname = new File(systemDir, "uiderrors.txt"); 8705 return fname; 8706 } 8707 8708 static void reportSettingsProblem(int priority, String msg) { 8709 logCriticalInfo(priority, msg); 8710 } 8711 8712 public static void logCriticalInfo(int priority, String msg) { 8713 Slog.println(priority, TAG, msg); 8714 EventLogTags.writePmCriticalInfo(msg); 8715 try { 8716 File fname = getSettingsProblemFile(); 8717 FileOutputStream out = new FileOutputStream(fname, true); 8718 PrintWriter pw = new FastPrintWriter(out); 8719 SimpleDateFormat formatter = new SimpleDateFormat(); 8720 String dateString = formatter.format(new Date(System.currentTimeMillis())); 8721 pw.println(dateString + ": " + msg); 8722 pw.close(); 8723 FileUtils.setPermissions( 8724 fname.toString(), 8725 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 8726 -1, -1); 8727 } catch (java.io.IOException e) { 8728 } 8729 } 8730 8731 private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) { 8732 if (srcFile.isDirectory()) { 8733 final File baseFile = new File(pkg.baseCodePath); 8734 long maxModifiedTime = baseFile.lastModified(); 8735 if (pkg.splitCodePaths != null) { 8736 for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) { 8737 final File splitFile = new File(pkg.splitCodePaths[i]); 8738 maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified()); 8739 } 8740 } 8741 return maxModifiedTime; 8742 } 8743 return srcFile.lastModified(); 8744 } 8745 8746 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 8747 final int policyFlags) throws PackageManagerException { 8748 // When upgrading from pre-N MR1, verify the package time stamp using the package 8749 // directory and not the APK file. 8750 final long lastModifiedTime = mIsPreNMR1Upgrade 8751 ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile); 8752 if (ps != null 8753 && ps.codePath.equals(srcFile) 8754 && ps.timeStamp == lastModifiedTime 8755 && !isCompatSignatureUpdateNeeded(pkg) 8756 && !isRecoverSignatureUpdateNeeded(pkg)) { 8757 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 8758 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8759 ArraySet<PublicKey> signingKs; 8760 synchronized (mPackages) { 8761 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 8762 } 8763 if (ps.signatures.mSignatures != null 8764 && ps.signatures.mSignatures.length != 0 8765 && signingKs != null) { 8766 // Optimization: reuse the existing cached certificates 8767 // if the package appears to be unchanged. 8768 pkg.mSignatures = ps.signatures.mSignatures; 8769 pkg.mSigningKeys = signingKs; 8770 return; 8771 } 8772 8773 Slog.w(TAG, "PackageSetting for " + ps.name 8774 + " is missing signatures. Collecting certs again to recover them."); 8775 } else { 8776 Slog.i(TAG, srcFile.toString() + " changed; collecting certs"); 8777 } 8778 8779 try { 8780 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 8781 PackageParser.collectCertificates(pkg, policyFlags); 8782 } catch (PackageParserException e) { 8783 throw PackageManagerException.from(e); 8784 } finally { 8785 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8786 } 8787 } 8788 8789 /** 8790 * Traces a package scan. 8791 * @see #scanPackageLI(File, int, int, long, UserHandle) 8792 */ 8793 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 8794 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 8795 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]"); 8796 try { 8797 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 8798 } finally { 8799 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8800 } 8801 } 8802 8803 /** 8804 * Scans a package and returns the newly parsed package. 8805 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 8806 */ 8807 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 8808 long currentTime, UserHandle user) throws PackageManagerException { 8809 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 8810 PackageParser pp = new PackageParser(); 8811 pp.setSeparateProcesses(mSeparateProcesses); 8812 pp.setOnlyCoreApps(mOnlyCore); 8813 pp.setDisplayMetrics(mMetrics); 8814 pp.setCallback(mPackageParserCallback); 8815 8816 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 8817 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 8818 } 8819 8820 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 8821 final PackageParser.Package pkg; 8822 try { 8823 pkg = pp.parsePackage(scanFile, parseFlags); 8824 } catch (PackageParserException e) { 8825 throw PackageManagerException.from(e); 8826 } finally { 8827 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8828 } 8829 8830 // Static shared libraries have synthetic package names 8831 if (pkg.applicationInfo.isStaticSharedLibrary()) { 8832 renameStaticSharedLibraryPackage(pkg); 8833 } 8834 8835 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 8836 } 8837 8838 /** 8839 * Scans a package and returns the newly parsed package. 8840 * @throws PackageManagerException on a parse error. 8841 */ 8842 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 8843 final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user) 8844 throws PackageManagerException { 8845 // If the package has children and this is the first dive in the function 8846 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 8847 // packages (parent and children) would be successfully scanned before the 8848 // actual scan since scanning mutates internal state and we want to atomically 8849 // install the package and its children. 8850 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8851 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 8852 scanFlags |= SCAN_CHECK_ONLY; 8853 } 8854 } else { 8855 scanFlags &= ~SCAN_CHECK_ONLY; 8856 } 8857 8858 // Scan the parent 8859 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 8860 scanFlags, currentTime, user); 8861 8862 // Scan the children 8863 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8864 for (int i = 0; i < childCount; i++) { 8865 PackageParser.Package childPackage = pkg.childPackages.get(i); 8866 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 8867 currentTime, user); 8868 } 8869 8870 8871 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8872 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 8873 } 8874 8875 return scannedPkg; 8876 } 8877 8878 /** 8879 * Scans a package and returns the newly parsed package. 8880 * @throws PackageManagerException on a parse error. 8881 */ 8882 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 8883 int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user) 8884 throws PackageManagerException { 8885 PackageSetting ps = null; 8886 PackageSetting updatedPkg; 8887 // reader 8888 synchronized (mPackages) { 8889 // Look to see if we already know about this package. 8890 String oldName = mSettings.getRenamedPackageLPr(pkg.packageName); 8891 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 8892 // This package has been renamed to its original name. Let's 8893 // use that. 8894 ps = mSettings.getPackageLPr(oldName); 8895 } 8896 // If there was no original package, see one for the real package name. 8897 if (ps == null) { 8898 ps = mSettings.getPackageLPr(pkg.packageName); 8899 } 8900 // Check to see if this package could be hiding/updating a system 8901 // package. Must look for it either under the original or real 8902 // package name depending on our state. 8903 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 8904 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 8905 8906 // If this is a package we don't know about on the system partition, we 8907 // may need to remove disabled child packages on the system partition 8908 // or may need to not add child packages if the parent apk is updated 8909 // on the data partition and no longer defines this child package. 8910 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 8911 // If this is a parent package for an updated system app and this system 8912 // app got an OTA update which no longer defines some of the child packages 8913 // we have to prune them from the disabled system packages. 8914 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 8915 if (disabledPs != null) { 8916 final int scannedChildCount = (pkg.childPackages != null) 8917 ? pkg.childPackages.size() : 0; 8918 final int disabledChildCount = disabledPs.childPackageNames != null 8919 ? disabledPs.childPackageNames.size() : 0; 8920 for (int i = 0; i < disabledChildCount; i++) { 8921 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 8922 boolean disabledPackageAvailable = false; 8923 for (int j = 0; j < scannedChildCount; j++) { 8924 PackageParser.Package childPkg = pkg.childPackages.get(j); 8925 if (childPkg.packageName.equals(disabledChildPackageName)) { 8926 disabledPackageAvailable = true; 8927 break; 8928 } 8929 } 8930 if (!disabledPackageAvailable) { 8931 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 8932 } 8933 } 8934 } 8935 } 8936 } 8937 8938 boolean updatedPkgBetter = false; 8939 // First check if this is a system package that may involve an update 8940 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 8941 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 8942 // it needs to drop FLAG_PRIVILEGED. 8943 if (locationIsPrivileged(scanFile)) { 8944 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 8945 } else { 8946 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 8947 } 8948 8949 if (ps != null && !ps.codePath.equals(scanFile)) { 8950 // The path has changed from what was last scanned... check the 8951 // version of the new path against what we have stored to determine 8952 // what to do. 8953 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 8954 if (pkg.mVersionCode <= ps.versionCode) { 8955 // The system package has been updated and the code path does not match 8956 // Ignore entry. Skip it. 8957 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 8958 + " ignored: updated version " + ps.versionCode 8959 + " better than this " + pkg.mVersionCode); 8960 if (!updatedPkg.codePath.equals(scanFile)) { 8961 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 8962 + ps.name + " changing from " + updatedPkg.codePathString 8963 + " to " + scanFile); 8964 updatedPkg.codePath = scanFile; 8965 updatedPkg.codePathString = scanFile.toString(); 8966 updatedPkg.resourcePath = scanFile; 8967 updatedPkg.resourcePathString = scanFile.toString(); 8968 } 8969 updatedPkg.pkg = pkg; 8970 updatedPkg.versionCode = pkg.mVersionCode; 8971 8972 // Update the disabled system child packages to point to the package too. 8973 final int childCount = updatedPkg.childPackageNames != null 8974 ? updatedPkg.childPackageNames.size() : 0; 8975 for (int i = 0; i < childCount; i++) { 8976 String childPackageName = updatedPkg.childPackageNames.get(i); 8977 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 8978 childPackageName); 8979 if (updatedChildPkg != null) { 8980 updatedChildPkg.pkg = pkg; 8981 updatedChildPkg.versionCode = pkg.mVersionCode; 8982 } 8983 } 8984 8985 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 8986 + scanFile + " ignored: updated version " + ps.versionCode 8987 + " better than this " + pkg.mVersionCode); 8988 } else { 8989 // The current app on the system partition is better than 8990 // what we have updated to on the data partition; switch 8991 // back to the system partition version. 8992 // At this point, its safely assumed that package installation for 8993 // apps in system partition will go through. If not there won't be a working 8994 // version of the app 8995 // writer 8996 synchronized (mPackages) { 8997 // Just remove the loaded entries from package lists. 8998 mPackages.remove(ps.name); 8999 } 9000 9001 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 9002 + " reverting from " + ps.codePathString 9003 + ": new version " + pkg.mVersionCode 9004 + " better than installed " + ps.versionCode); 9005 9006 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 9007 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 9008 synchronized (mInstallLock) { 9009 args.cleanUpResourcesLI(); 9010 } 9011 synchronized (mPackages) { 9012 mSettings.enableSystemPackageLPw(ps.name); 9013 } 9014 updatedPkgBetter = true; 9015 } 9016 } 9017 } 9018 9019 if (updatedPkg != null) { 9020 // An updated system app will not have the PARSE_IS_SYSTEM flag set 9021 // initially 9022 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 9023 9024 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 9025 // flag set initially 9026 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 9027 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 9028 } 9029 } 9030 9031 // Verify certificates against what was last scanned 9032 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 9033 9034 /* 9035 * A new system app appeared, but we already had a non-system one of the 9036 * same name installed earlier. 9037 */ 9038 boolean shouldHideSystemApp = false; 9039 if (updatedPkg == null && ps != null 9040 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 9041 /* 9042 * Check to make sure the signatures match first. If they don't, 9043 * wipe the installed application and its data. 9044 */ 9045 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 9046 != PackageManager.SIGNATURE_MATCH) { 9047 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 9048 + " signatures don't match existing userdata copy; removing"); 9049 try (PackageFreezer freezer = freezePackage(pkg.packageName, 9050 "scanPackageInternalLI")) { 9051 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 9052 } 9053 ps = null; 9054 } else { 9055 /* 9056 * If the newly-added system app is an older version than the 9057 * already installed version, hide it. It will be scanned later 9058 * and re-added like an update. 9059 */ 9060 if (pkg.mVersionCode <= ps.versionCode) { 9061 shouldHideSystemApp = true; 9062 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 9063 + " but new version " + pkg.mVersionCode + " better than installed " 9064 + ps.versionCode + "; hiding system"); 9065 } else { 9066 /* 9067 * The newly found system app is a newer version that the 9068 * one previously installed. Simply remove the 9069 * already-installed application and replace it with our own 9070 * while keeping the application data. 9071 */ 9072 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 9073 + " reverting from " + ps.codePathString + ": new version " 9074 + pkg.mVersionCode + " better than installed " + ps.versionCode); 9075 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 9076 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 9077 synchronized (mInstallLock) { 9078 args.cleanUpResourcesLI(); 9079 } 9080 } 9081 } 9082 } 9083 9084 // The apk is forward locked (not public) if its code and resources 9085 // are kept in different files. (except for app in either system or 9086 // vendor path). 9087 // TODO grab this value from PackageSettings 9088 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 9089 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 9090 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 9091 } 9092 } 9093 9094 // TODO: extend to support forward-locked splits 9095 String resourcePath = null; 9096 String baseResourcePath = null; 9097 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 9098 if (ps != null && ps.resourcePathString != null) { 9099 resourcePath = ps.resourcePathString; 9100 baseResourcePath = ps.resourcePathString; 9101 } else { 9102 // Should not happen at all. Just log an error. 9103 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 9104 } 9105 } else { 9106 resourcePath = pkg.codePath; 9107 baseResourcePath = pkg.baseCodePath; 9108 } 9109 9110 // Set application objects path explicitly. 9111 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 9112 pkg.setApplicationInfoCodePath(pkg.codePath); 9113 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 9114 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 9115 pkg.setApplicationInfoResourcePath(resourcePath); 9116 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 9117 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 9118 9119 final int userId = ((user == null) ? 0 : user.getIdentifier()); 9120 if (ps != null && ps.getInstantApp(userId)) { 9121 scanFlags |= SCAN_AS_INSTANT_APP; 9122 } 9123 9124 // Note that we invoke the following method only if we are about to unpack an application 9125 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 9126 | SCAN_UPDATE_SIGNATURE, currentTime, user); 9127 9128 /* 9129 * If the system app should be overridden by a previously installed 9130 * data, hide the system app now and let the /data/app scan pick it up 9131 * again. 9132 */ 9133 if (shouldHideSystemApp) { 9134 synchronized (mPackages) { 9135 mSettings.disableSystemPackageLPw(pkg.packageName, true); 9136 } 9137 } 9138 9139 return scannedPkg; 9140 } 9141 9142 private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) { 9143 // Derive the new package synthetic package name 9144 pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER 9145 + pkg.staticSharedLibVersion); 9146 } 9147 9148 private static String fixProcessName(String defProcessName, 9149 String processName) { 9150 if (processName == null) { 9151 return defProcessName; 9152 } 9153 return processName; 9154 } 9155 9156 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 9157 throws PackageManagerException { 9158 if (pkgSetting.signatures.mSignatures != null) { 9159 // Already existing package. Make sure signatures match 9160 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 9161 == PackageManager.SIGNATURE_MATCH; 9162 if (!match) { 9163 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 9164 == PackageManager.SIGNATURE_MATCH; 9165 } 9166 if (!match) { 9167 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 9168 == PackageManager.SIGNATURE_MATCH; 9169 } 9170 if (!match) { 9171 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 9172 + pkg.packageName + " signatures do not match the " 9173 + "previously installed version; ignoring!"); 9174 } 9175 } 9176 9177 // Check for shared user signatures 9178 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 9179 // Already existing package. Make sure signatures match 9180 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 9181 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 9182 if (!match) { 9183 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 9184 == PackageManager.SIGNATURE_MATCH; 9185 } 9186 if (!match) { 9187 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 9188 == PackageManager.SIGNATURE_MATCH; 9189 } 9190 if (!match) { 9191 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 9192 "Package " + pkg.packageName 9193 + " has no signatures that match those in shared user " 9194 + pkgSetting.sharedUser.name + "; ignoring!"); 9195 } 9196 } 9197 } 9198 9199 /** 9200 * Enforces that only the system UID or root's UID can call a method exposed 9201 * via Binder. 9202 * 9203 * @param message used as message if SecurityException is thrown 9204 * @throws SecurityException if the caller is not system or root 9205 */ 9206 private static final void enforceSystemOrRoot(String message) { 9207 final int uid = Binder.getCallingUid(); 9208 if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) { 9209 throw new SecurityException(message); 9210 } 9211 } 9212 9213 @Override 9214 public void performFstrimIfNeeded() { 9215 enforceSystemOrRoot("Only the system can request fstrim"); 9216 9217 // Before everything else, see whether we need to fstrim. 9218 try { 9219 IStorageManager sm = PackageHelper.getStorageManager(); 9220 if (sm != null) { 9221 boolean doTrim = false; 9222 final long interval = android.provider.Settings.Global.getLong( 9223 mContext.getContentResolver(), 9224 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 9225 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 9226 if (interval > 0) { 9227 final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance(); 9228 if (timeSinceLast > interval) { 9229 doTrim = true; 9230 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 9231 + "; running immediately"); 9232 } 9233 } 9234 if (doTrim) { 9235 final boolean dexOptDialogShown; 9236 synchronized (mPackages) { 9237 dexOptDialogShown = mDexOptDialogShown; 9238 } 9239 if (!isFirstBoot() && dexOptDialogShown) { 9240 try { 9241 ActivityManager.getService().showBootMessage( 9242 mContext.getResources().getString( 9243 R.string.android_upgrading_fstrim), true); 9244 } catch (RemoteException e) { 9245 } 9246 } 9247 sm.runMaintenance(); 9248 } 9249 } else { 9250 Slog.e(TAG, "storageManager service unavailable!"); 9251 } 9252 } catch (RemoteException e) { 9253 // Can't happen; StorageManagerService is local 9254 } 9255 } 9256 9257 @Override 9258 public void updatePackagesIfNeeded() { 9259 enforceSystemOrRoot("Only the system can request package update"); 9260 9261 // We need to re-extract after an OTA. 9262 boolean causeUpgrade = isUpgrade(); 9263 9264 // First boot or factory reset. 9265 // Note: we also handle devices that are upgrading to N right now as if it is their 9266 // first boot, as they do not have profile data. 9267 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 9268 9269 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 9270 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 9271 9272 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 9273 return; 9274 } 9275 9276 List<PackageParser.Package> pkgs; 9277 synchronized (mPackages) { 9278 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 9279 } 9280 9281 final long startTime = System.nanoTime(); 9282 final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */, 9283 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT)); 9284 9285 final int elapsedTimeSeconds = 9286 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 9287 9288 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]); 9289 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]); 9290 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]); 9291 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 9292 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 9293 } 9294 9295 /** 9296 * Performs dexopt on the set of packages in {@code packages} and returns an int array 9297 * containing statistics about the invocation. The array consists of three elements, 9298 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped} 9299 * and {@code numberOfPackagesFailed}. 9300 */ 9301 private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog, 9302 String compilerFilter) { 9303 9304 int numberOfPackagesVisited = 0; 9305 int numberOfPackagesOptimized = 0; 9306 int numberOfPackagesSkipped = 0; 9307 int numberOfPackagesFailed = 0; 9308 final int numberOfPackagesToDexopt = pkgs.size(); 9309 9310 for (PackageParser.Package pkg : pkgs) { 9311 numberOfPackagesVisited++; 9312 9313 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 9314 if (DEBUG_DEXOPT) { 9315 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 9316 } 9317 numberOfPackagesSkipped++; 9318 continue; 9319 } 9320 9321 if (DEBUG_DEXOPT) { 9322 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 9323 numberOfPackagesToDexopt + ": " + pkg.packageName); 9324 } 9325 9326 if (showDialog) { 9327 try { 9328 ActivityManager.getService().showBootMessage( 9329 mContext.getResources().getString(R.string.android_upgrading_apk, 9330 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 9331 } catch (RemoteException e) { 9332 } 9333 synchronized (mPackages) { 9334 mDexOptDialogShown = true; 9335 } 9336 } 9337 9338 // If the OTA updates a system app which was previously preopted to a non-preopted state 9339 // the app might end up being verified at runtime. That's because by default the apps 9340 // are verify-profile but for preopted apps there's no profile. 9341 // Do a hacky check to ensure that if we have no profiles (a reasonable indication 9342 // that before the OTA the app was preopted) the app gets compiled with a non-profile 9343 // filter (by default 'quicken'). 9344 // Note that at this stage unused apps are already filtered. 9345 if (isSystemApp(pkg) && 9346 DexFile.isProfileGuidedCompilerFilter(compilerFilter) && 9347 !Environment.getReferenceProfile(pkg.packageName).exists()) { 9348 compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter); 9349 } 9350 9351 // checkProfiles is false to avoid merging profiles during boot which 9352 // might interfere with background compilation (b/28612421). 9353 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 9354 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 9355 // trade-off worth doing to save boot time work. 9356 int dexOptStatus = performDexOptTraced(pkg.packageName, 9357 false /* checkProfiles */, 9358 compilerFilter, 9359 false /* force */); 9360 switch (dexOptStatus) { 9361 case PackageDexOptimizer.DEX_OPT_PERFORMED: 9362 numberOfPackagesOptimized++; 9363 break; 9364 case PackageDexOptimizer.DEX_OPT_SKIPPED: 9365 numberOfPackagesSkipped++; 9366 break; 9367 case PackageDexOptimizer.DEX_OPT_FAILED: 9368 numberOfPackagesFailed++; 9369 break; 9370 default: 9371 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus); 9372 break; 9373 } 9374 } 9375 9376 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped, 9377 numberOfPackagesFailed }; 9378 } 9379 9380 @Override 9381 public void notifyPackageUse(String packageName, int reason) { 9382 synchronized (mPackages) { 9383 final int callingUid = Binder.getCallingUid(); 9384 final int callingUserId = UserHandle.getUserId(callingUid); 9385 if (getInstantAppPackageName(callingUid) != null) { 9386 if (!isCallerSameApp(packageName, callingUid)) { 9387 return; 9388 } 9389 } else { 9390 if (isInstantApp(packageName, callingUserId)) { 9391 return; 9392 } 9393 } 9394 final PackageParser.Package p = mPackages.get(packageName); 9395 if (p == null) { 9396 return; 9397 } 9398 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 9399 } 9400 } 9401 9402 @Override 9403 public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) { 9404 int userId = UserHandle.getCallingUserId(); 9405 ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId); 9406 if (ai == null) { 9407 Slog.w(TAG, "Loading a package that does not exist for the calling user. package=" 9408 + loadingPackageName + ", user=" + userId); 9409 return; 9410 } 9411 mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId); 9412 } 9413 9414 @Override 9415 public boolean performDexOpt(String packageName, 9416 boolean checkProfiles, int compileReason, boolean force) { 9417 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 9418 return false; 9419 } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) { 9420 return false; 9421 } 9422 return performDexOptWithStatus(packageName, checkProfiles, compileReason, force) != 9423 PackageDexOptimizer.DEX_OPT_FAILED; 9424 } 9425 9426 /** 9427 * Perform dexopt on the given package and return one of following result: 9428 * {@link PackageDexOptimizer#DEX_OPT_SKIPPED} 9429 * {@link PackageDexOptimizer#DEX_OPT_PERFORMED} 9430 * {@link PackageDexOptimizer#DEX_OPT_FAILED} 9431 */ 9432 /* package */ int performDexOptWithStatus(String packageName, 9433 boolean checkProfiles, int compileReason, boolean force) { 9434 return performDexOptTraced(packageName, checkProfiles, 9435 getCompilerFilterForReason(compileReason), force); 9436 } 9437 9438 @Override 9439 public boolean performDexOptMode(String packageName, 9440 boolean checkProfiles, String targetCompilerFilter, boolean force) { 9441 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 9442 return false; 9443 } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) { 9444 return false; 9445 } 9446 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 9447 targetCompilerFilter, force); 9448 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 9449 } 9450 9451 private int performDexOptTraced(String packageName, 9452 boolean checkProfiles, String targetCompilerFilter, boolean force) { 9453 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 9454 try { 9455 return performDexOptInternal(packageName, checkProfiles, 9456 targetCompilerFilter, force); 9457 } finally { 9458 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9459 } 9460 } 9461 9462 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 9463 // if the package can now be considered up to date for the given filter. 9464 private int performDexOptInternal(String packageName, 9465 boolean checkProfiles, String targetCompilerFilter, boolean force) { 9466 PackageParser.Package p; 9467 synchronized (mPackages) { 9468 p = mPackages.get(packageName); 9469 if (p == null) { 9470 // Package could not be found. Report failure. 9471 return PackageDexOptimizer.DEX_OPT_FAILED; 9472 } 9473 mPackageUsage.maybeWriteAsync(mPackages); 9474 mCompilerStats.maybeWriteAsync(); 9475 } 9476 long callingId = Binder.clearCallingIdentity(); 9477 try { 9478 synchronized (mInstallLock) { 9479 return performDexOptInternalWithDependenciesLI(p, checkProfiles, 9480 targetCompilerFilter, force); 9481 } 9482 } finally { 9483 Binder.restoreCallingIdentity(callingId); 9484 } 9485 } 9486 9487 public ArraySet<String> getOptimizablePackages() { 9488 ArraySet<String> pkgs = new ArraySet<String>(); 9489 synchronized (mPackages) { 9490 for (PackageParser.Package p : mPackages.values()) { 9491 if (PackageDexOptimizer.canOptimizePackage(p)) { 9492 pkgs.add(p.packageName); 9493 } 9494 } 9495 } 9496 return pkgs; 9497 } 9498 9499 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 9500 boolean checkProfiles, String targetCompilerFilter, 9501 boolean force) { 9502 // Select the dex optimizer based on the force parameter. 9503 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 9504 // allocate an object here. 9505 PackageDexOptimizer pdo = force 9506 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 9507 : mPackageDexOptimizer; 9508 9509 // Dexopt all dependencies first. Note: we ignore the return value and march on 9510 // on errors. 9511 // Note that we are going to call performDexOpt on those libraries as many times as 9512 // they are referenced in packages. When we do a batch of performDexOpt (for example 9513 // at boot, or background job), the passed 'targetCompilerFilter' stays the same, 9514 // and the first package that uses the library will dexopt it. The 9515 // others will see that the compiled code for the library is up to date. 9516 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 9517 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 9518 if (!deps.isEmpty()) { 9519 for (PackageParser.Package depPackage : deps) { 9520 // TODO: Analyze and investigate if we (should) profile libraries. 9521 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 9522 false /* checkProfiles */, 9523 targetCompilerFilter, 9524 getOrCreateCompilerPackageStats(depPackage), 9525 true /* isUsedByOtherApps */); 9526 } 9527 } 9528 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 9529 targetCompilerFilter, getOrCreateCompilerPackageStats(p), 9530 mDexManager.isUsedByOtherApps(p.packageName)); 9531 } 9532 9533 // Performs dexopt on the used secondary dex files belonging to the given package. 9534 // Returns true if all dex files were process successfully (which could mean either dexopt or 9535 // skip). Returns false if any of the files caused errors. 9536 @Override 9537 public boolean performDexOptSecondary(String packageName, String compilerFilter, 9538 boolean force) { 9539 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 9540 return false; 9541 } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) { 9542 return false; 9543 } 9544 mDexManager.reconcileSecondaryDexFiles(packageName); 9545 return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force); 9546 } 9547 9548 public boolean performDexOptSecondary(String packageName, int compileReason, 9549 boolean force) { 9550 return mDexManager.dexoptSecondaryDex(packageName, compileReason, force); 9551 } 9552 9553 /** 9554 * Reconcile the information we have about the secondary dex files belonging to 9555 * {@code packagName} and the actual dex files. For all dex files that were 9556 * deleted, update the internal records and delete the generated oat files. 9557 */ 9558 @Override 9559 public void reconcileSecondaryDexFiles(String packageName) { 9560 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 9561 return; 9562 } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) { 9563 return; 9564 } 9565 mDexManager.reconcileSecondaryDexFiles(packageName); 9566 } 9567 9568 // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject 9569 // a reference there. 9570 /*package*/ DexManager getDexManager() { 9571 return mDexManager; 9572 } 9573 9574 /** 9575 * Execute the background dexopt job immediately. 9576 */ 9577 @Override 9578 public boolean runBackgroundDexoptJob() { 9579 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 9580 return false; 9581 } 9582 return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext); 9583 } 9584 9585 List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 9586 if (p.usesLibraries != null || p.usesOptionalLibraries != null 9587 || p.usesStaticLibraries != null) { 9588 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 9589 Set<String> collectedNames = new HashSet<>(); 9590 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 9591 9592 retValue.remove(p); 9593 9594 return retValue; 9595 } else { 9596 return Collections.emptyList(); 9597 } 9598 } 9599 9600 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 9601 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) { 9602 if (!collectedNames.contains(p.packageName)) { 9603 collectedNames.add(p.packageName); 9604 collected.add(p); 9605 9606 if (p.usesLibraries != null) { 9607 findSharedNonSystemLibrariesRecursive(p.usesLibraries, 9608 null, collected, collectedNames); 9609 } 9610 if (p.usesOptionalLibraries != null) { 9611 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, 9612 null, collected, collectedNames); 9613 } 9614 if (p.usesStaticLibraries != null) { 9615 findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries, 9616 p.usesStaticLibrariesVersions, collected, collectedNames); 9617 } 9618 } 9619 } 9620 9621 private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions, 9622 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) { 9623 final int libNameCount = libs.size(); 9624 for (int i = 0; i < libNameCount; i++) { 9625 String libName = libs.get(i); 9626 int version = (versions != null && versions.length == libNameCount) 9627 ? versions[i] : PackageManager.VERSION_CODE_HIGHEST; 9628 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version); 9629 if (libPkg != null) { 9630 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 9631 } 9632 } 9633 } 9634 9635 private PackageParser.Package findSharedNonSystemLibrary(String name, int version) { 9636 synchronized (mPackages) { 9637 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version); 9638 if (libEntry != null) { 9639 return mPackages.get(libEntry.apk); 9640 } 9641 return null; 9642 } 9643 } 9644 9645 private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) { 9646 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 9647 if (versionedLib == null) { 9648 return null; 9649 } 9650 return versionedLib.get(version); 9651 } 9652 9653 private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) { 9654 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get( 9655 pkg.staticSharedLibName); 9656 if (versionedLib == null) { 9657 return null; 9658 } 9659 int previousLibVersion = -1; 9660 final int versionCount = versionedLib.size(); 9661 for (int i = 0; i < versionCount; i++) { 9662 final int libVersion = versionedLib.keyAt(i); 9663 if (libVersion < pkg.staticSharedLibVersion) { 9664 previousLibVersion = Math.max(previousLibVersion, libVersion); 9665 } 9666 } 9667 if (previousLibVersion >= 0) { 9668 return versionedLib.get(previousLibVersion); 9669 } 9670 return null; 9671 } 9672 9673 public void shutdown() { 9674 mPackageUsage.writeNow(mPackages); 9675 mCompilerStats.writeNow(); 9676 } 9677 9678 @Override 9679 public void dumpProfiles(String packageName) { 9680 PackageParser.Package pkg; 9681 synchronized (mPackages) { 9682 pkg = mPackages.get(packageName); 9683 if (pkg == null) { 9684 throw new IllegalArgumentException("Unknown package: " + packageName); 9685 } 9686 } 9687 /* Only the shell, root, or the app user should be able to dump profiles. */ 9688 int callingUid = Binder.getCallingUid(); 9689 if (callingUid != Process.SHELL_UID && 9690 callingUid != Process.ROOT_UID && 9691 callingUid != pkg.applicationInfo.uid) { 9692 throw new SecurityException("dumpProfiles"); 9693 } 9694 9695 synchronized (mInstallLock) { 9696 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles"); 9697 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 9698 try { 9699 List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly(); 9700 String codePaths = TextUtils.join(";", allCodePaths); 9701 mInstaller.dumpProfiles(sharedGid, packageName, codePaths); 9702 } catch (InstallerException e) { 9703 Slog.w(TAG, "Failed to dump profiles", e); 9704 } 9705 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9706 } 9707 } 9708 9709 @Override 9710 public void forceDexOpt(String packageName) { 9711 enforceSystemOrRoot("forceDexOpt"); 9712 9713 PackageParser.Package pkg; 9714 synchronized (mPackages) { 9715 pkg = mPackages.get(packageName); 9716 if (pkg == null) { 9717 throw new IllegalArgumentException("Unknown package: " + packageName); 9718 } 9719 } 9720 9721 synchronized (mInstallLock) { 9722 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 9723 9724 // Whoever is calling forceDexOpt wants a compiled package. 9725 // Don't use profiles since that may cause compilation to be skipped. 9726 final int res = performDexOptInternalWithDependenciesLI(pkg, 9727 false /* checkProfiles */, getDefaultCompilerFilter(), 9728 true /* force */); 9729 9730 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9731 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 9732 throw new IllegalStateException("Failed to dexopt: " + res); 9733 } 9734 } 9735 } 9736 9737 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 9738 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 9739 Slog.w(TAG, "Unable to update from " + oldPkg.name 9740 + " to " + newPkg.packageName 9741 + ": old package not in system partition"); 9742 return false; 9743 } else if (mPackages.get(oldPkg.name) != null) { 9744 Slog.w(TAG, "Unable to update from " + oldPkg.name 9745 + " to " + newPkg.packageName 9746 + ": old package still exists"); 9747 return false; 9748 } 9749 return true; 9750 } 9751 9752 void removeCodePathLI(File codePath) { 9753 if (codePath.isDirectory()) { 9754 try { 9755 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 9756 } catch (InstallerException e) { 9757 Slog.w(TAG, "Failed to remove code path", e); 9758 } 9759 } else { 9760 codePath.delete(); 9761 } 9762 } 9763 9764 private int[] resolveUserIds(int userId) { 9765 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 9766 } 9767 9768 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 9769 if (pkg == null) { 9770 Slog.wtf(TAG, "Package was null!", new Throwable()); 9771 return; 9772 } 9773 clearAppDataLeafLIF(pkg, userId, flags); 9774 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9775 for (int i = 0; i < childCount; i++) { 9776 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 9777 } 9778 } 9779 9780 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 9781 final PackageSetting ps; 9782 synchronized (mPackages) { 9783 ps = mSettings.mPackages.get(pkg.packageName); 9784 } 9785 for (int realUserId : resolveUserIds(userId)) { 9786 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 9787 try { 9788 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 9789 ceDataInode); 9790 } catch (InstallerException e) { 9791 Slog.w(TAG, String.valueOf(e)); 9792 } 9793 } 9794 } 9795 9796 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 9797 if (pkg == null) { 9798 Slog.wtf(TAG, "Package was null!", new Throwable()); 9799 return; 9800 } 9801 destroyAppDataLeafLIF(pkg, userId, flags); 9802 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9803 for (int i = 0; i < childCount; i++) { 9804 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 9805 } 9806 } 9807 9808 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 9809 final PackageSetting ps; 9810 synchronized (mPackages) { 9811 ps = mSettings.mPackages.get(pkg.packageName); 9812 } 9813 for (int realUserId : resolveUserIds(userId)) { 9814 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 9815 try { 9816 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 9817 ceDataInode); 9818 } catch (InstallerException e) { 9819 Slog.w(TAG, String.valueOf(e)); 9820 } 9821 mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId); 9822 } 9823 } 9824 9825 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 9826 if (pkg == null) { 9827 Slog.wtf(TAG, "Package was null!", new Throwable()); 9828 return; 9829 } 9830 destroyAppProfilesLeafLIF(pkg); 9831 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9832 for (int i = 0; i < childCount; i++) { 9833 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 9834 } 9835 } 9836 9837 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 9838 try { 9839 mInstaller.destroyAppProfiles(pkg.packageName); 9840 } catch (InstallerException e) { 9841 Slog.w(TAG, String.valueOf(e)); 9842 } 9843 } 9844 9845 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 9846 if (pkg == null) { 9847 Slog.wtf(TAG, "Package was null!", new Throwable()); 9848 return; 9849 } 9850 clearAppProfilesLeafLIF(pkg); 9851 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9852 for (int i = 0; i < childCount; i++) { 9853 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 9854 } 9855 } 9856 9857 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 9858 try { 9859 mInstaller.clearAppProfiles(pkg.packageName); 9860 } catch (InstallerException e) { 9861 Slog.w(TAG, String.valueOf(e)); 9862 } 9863 } 9864 9865 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 9866 long lastUpdateTime) { 9867 // Set parent install/update time 9868 PackageSetting ps = (PackageSetting) pkg.mExtras; 9869 if (ps != null) { 9870 ps.firstInstallTime = firstInstallTime; 9871 ps.lastUpdateTime = lastUpdateTime; 9872 } 9873 // Set children install/update time 9874 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9875 for (int i = 0; i < childCount; i++) { 9876 PackageParser.Package childPkg = pkg.childPackages.get(i); 9877 ps = (PackageSetting) childPkg.mExtras; 9878 if (ps != null) { 9879 ps.firstInstallTime = firstInstallTime; 9880 ps.lastUpdateTime = lastUpdateTime; 9881 } 9882 } 9883 } 9884 9885 private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 9886 PackageParser.Package changingLib) { 9887 if (file.path != null) { 9888 usesLibraryFiles.add(file.path); 9889 return; 9890 } 9891 PackageParser.Package p = mPackages.get(file.apk); 9892 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 9893 // If we are doing this while in the middle of updating a library apk, 9894 // then we need to make sure to use that new apk for determining the 9895 // dependencies here. (We haven't yet finished committing the new apk 9896 // to the package manager state.) 9897 if (p == null || p.packageName.equals(changingLib.packageName)) { 9898 p = changingLib; 9899 } 9900 } 9901 if (p != null) { 9902 usesLibraryFiles.addAll(p.getAllCodePaths()); 9903 if (p.usesLibraryFiles != null) { 9904 Collections.addAll(usesLibraryFiles, p.usesLibraryFiles); 9905 } 9906 } 9907 } 9908 9909 private void updateSharedLibrariesLPr(PackageParser.Package pkg, 9910 PackageParser.Package changingLib) throws PackageManagerException { 9911 if (pkg == null) { 9912 return; 9913 } 9914 ArraySet<String> usesLibraryFiles = null; 9915 if (pkg.usesLibraries != null) { 9916 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries, 9917 null, null, pkg.packageName, changingLib, true, null); 9918 } 9919 if (pkg.usesStaticLibraries != null) { 9920 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries, 9921 pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests, 9922 pkg.packageName, changingLib, true, usesLibraryFiles); 9923 } 9924 if (pkg.usesOptionalLibraries != null) { 9925 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries, 9926 null, null, pkg.packageName, changingLib, false, usesLibraryFiles); 9927 } 9928 if (!ArrayUtils.isEmpty(usesLibraryFiles)) { 9929 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]); 9930 } else { 9931 pkg.usesLibraryFiles = null; 9932 } 9933 } 9934 9935 private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries, 9936 @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests, 9937 @NonNull String packageName, @Nullable PackageParser.Package changingLib, 9938 boolean required, @Nullable ArraySet<String> outUsedLibraries) 9939 throws PackageManagerException { 9940 final int libCount = requestedLibraries.size(); 9941 for (int i = 0; i < libCount; i++) { 9942 final String libName = requestedLibraries.get(i); 9943 final int libVersion = requiredVersions != null ? requiredVersions[i] 9944 : SharedLibraryInfo.VERSION_UNDEFINED; 9945 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion); 9946 if (libEntry == null) { 9947 if (required) { 9948 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9949 "Package " + packageName + " requires unavailable shared library " 9950 + libName + "; failing!"); 9951 } else if (DEBUG_SHARED_LIBRARIES) { 9952 Slog.i(TAG, "Package " + packageName 9953 + " desires unavailable shared library " 9954 + libName + "; ignoring!"); 9955 } 9956 } else { 9957 if (requiredVersions != null && requiredCertDigests != null) { 9958 if (libEntry.info.getVersion() != requiredVersions[i]) { 9959 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9960 "Package " + packageName + " requires unavailable static shared" 9961 + " library " + libName + " version " 9962 + libEntry.info.getVersion() + "; failing!"); 9963 } 9964 9965 PackageParser.Package libPkg = mPackages.get(libEntry.apk); 9966 if (libPkg == null) { 9967 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9968 "Package " + packageName + " requires unavailable static shared" 9969 + " library; failing!"); 9970 } 9971 9972 String expectedCertDigest = requiredCertDigests[i]; 9973 String libCertDigest = PackageUtils.computeCertSha256Digest( 9974 libPkg.mSignatures[0]); 9975 if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) { 9976 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9977 "Package " + packageName + " requires differently signed" + 9978 " static shared library; failing!"); 9979 } 9980 } 9981 9982 if (outUsedLibraries == null) { 9983 outUsedLibraries = new ArraySet<>(); 9984 } 9985 addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib); 9986 } 9987 } 9988 return outUsedLibraries; 9989 } 9990 9991 private static boolean hasString(List<String> list, List<String> which) { 9992 if (list == null) { 9993 return false; 9994 } 9995 for (int i=list.size()-1; i>=0; i--) { 9996 for (int j=which.size()-1; j>=0; j--) { 9997 if (which.get(j).equals(list.get(i))) { 9998 return true; 9999 } 10000 } 10001 } 10002 return false; 10003 } 10004 10005 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 10006 PackageParser.Package changingPkg) { 10007 ArrayList<PackageParser.Package> res = null; 10008 for (PackageParser.Package pkg : mPackages.values()) { 10009 if (changingPkg != null 10010 && !hasString(pkg.usesLibraries, changingPkg.libraryNames) 10011 && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames) 10012 && !ArrayUtils.contains(pkg.usesStaticLibraries, 10013 changingPkg.staticSharedLibName)) { 10014 return null; 10015 } 10016 if (res == null) { 10017 res = new ArrayList<>(); 10018 } 10019 res.add(pkg); 10020 try { 10021 updateSharedLibrariesLPr(pkg, changingPkg); 10022 } catch (PackageManagerException e) { 10023 // If a system app update or an app and a required lib missing we 10024 // delete the package and for updated system apps keep the data as 10025 // it is better for the user to reinstall than to be in an limbo 10026 // state. Also libs disappearing under an app should never happen 10027 // - just in case. 10028 if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) { 10029 final int flags = pkg.isUpdatedSystemApp() 10030 ? PackageManager.DELETE_KEEP_DATA : 0; 10031 deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(), 10032 flags , null, true, null); 10033 } 10034 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 10035 } 10036 } 10037 return res; 10038 } 10039 10040 /** 10041 * Derive the value of the {@code cpuAbiOverride} based on the provided 10042 * value and an optional stored value from the package settings. 10043 */ 10044 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 10045 String cpuAbiOverride = null; 10046 10047 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 10048 cpuAbiOverride = null; 10049 } else if (abiOverride != null) { 10050 cpuAbiOverride = abiOverride; 10051 } else if (settings != null) { 10052 cpuAbiOverride = settings.cpuAbiOverrideString; 10053 } 10054 10055 return cpuAbiOverride; 10056 } 10057 10058 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 10059 final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user) 10060 throws PackageManagerException { 10061 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 10062 // If the package has children and this is the first dive in the function 10063 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 10064 // whether all packages (parent and children) would be successfully scanned 10065 // before the actual scan since scanning mutates internal state and we want 10066 // to atomically install the package and its children. 10067 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 10068 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 10069 scanFlags |= SCAN_CHECK_ONLY; 10070 } 10071 } else { 10072 scanFlags &= ~SCAN_CHECK_ONLY; 10073 } 10074 10075 final PackageParser.Package scannedPkg; 10076 try { 10077 // Scan the parent 10078 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 10079 // Scan the children 10080 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 10081 for (int i = 0; i < childCount; i++) { 10082 PackageParser.Package childPkg = pkg.childPackages.get(i); 10083 scanPackageLI(childPkg, policyFlags, 10084 scanFlags, currentTime, user); 10085 } 10086 } finally { 10087 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10088 } 10089 10090 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 10091 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 10092 } 10093 10094 return scannedPkg; 10095 } 10096 10097 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 10098 int scanFlags, long currentTime, @Nullable UserHandle user) 10099 throws PackageManagerException { 10100 boolean success = false; 10101 try { 10102 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 10103 currentTime, user); 10104 success = true; 10105 return res; 10106 } finally { 10107 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 10108 // DELETE_DATA_ON_FAILURES is only used by frozen paths 10109 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 10110 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 10111 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 10112 } 10113 } 10114 } 10115 10116 /** 10117 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 10118 */ 10119 private static boolean apkHasCode(String fileName) { 10120 StrictJarFile jarFile = null; 10121 try { 10122 jarFile = new StrictJarFile(fileName, 10123 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 10124 return jarFile.findEntry("classes.dex") != null; 10125 } catch (IOException ignore) { 10126 } finally { 10127 try { 10128 if (jarFile != null) { 10129 jarFile.close(); 10130 } 10131 } catch (IOException ignore) {} 10132 } 10133 return false; 10134 } 10135 10136 /** 10137 * Enforces code policy for the package. This ensures that if an APK has 10138 * declared hasCode="true" in its manifest that the APK actually contains 10139 * code. 10140 * 10141 * @throws PackageManagerException If bytecode could not be found when it should exist 10142 */ 10143 private static void assertCodePolicy(PackageParser.Package pkg) 10144 throws PackageManagerException { 10145 final boolean shouldHaveCode = 10146 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 10147 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 10148 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 10149 "Package " + pkg.baseCodePath + " code is missing"); 10150 } 10151 10152 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 10153 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 10154 final boolean splitShouldHaveCode = 10155 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 10156 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 10157 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 10158 "Package " + pkg.splitCodePaths[i] + " code is missing"); 10159 } 10160 } 10161 } 10162 } 10163 10164 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 10165 final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user) 10166 throws PackageManagerException { 10167 if (DEBUG_PACKAGE_SCANNING) { 10168 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 10169 Log.d(TAG, "Scanning package " + pkg.packageName); 10170 } 10171 10172 applyPolicy(pkg, policyFlags); 10173 10174 assertPackageIsValid(pkg, policyFlags, scanFlags); 10175 10176 // Initialize package source and resource directories 10177 final File scanFile = new File(pkg.codePath); 10178 final File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 10179 final File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 10180 10181 SharedUserSetting suid = null; 10182 PackageSetting pkgSetting = null; 10183 10184 // Getting the package setting may have a side-effect, so if we 10185 // are only checking if scan would succeed, stash a copy of the 10186 // old setting to restore at the end. 10187 PackageSetting nonMutatedPs = null; 10188 10189 // We keep references to the derived CPU Abis from settings in oder to reuse 10190 // them in the case where we're not upgrading or booting for the first time. 10191 String primaryCpuAbiFromSettings = null; 10192 String secondaryCpuAbiFromSettings = null; 10193 10194 // writer 10195 synchronized (mPackages) { 10196 if (pkg.mSharedUserId != null) { 10197 // SIDE EFFECTS; may potentially allocate a new shared user 10198 suid = mSettings.getSharedUserLPw( 10199 pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/); 10200 if (DEBUG_PACKAGE_SCANNING) { 10201 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 10202 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 10203 + "): packages=" + suid.packages); 10204 } 10205 } 10206 10207 // Check if we are renaming from an original package name. 10208 PackageSetting origPackage = null; 10209 String realName = null; 10210 if (pkg.mOriginalPackages != null) { 10211 // This package may need to be renamed to a previously 10212 // installed name. Let's check on that... 10213 final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage); 10214 if (pkg.mOriginalPackages.contains(renamed)) { 10215 // This package had originally been installed as the 10216 // original name, and we have already taken care of 10217 // transitioning to the new one. Just update the new 10218 // one to continue using the old name. 10219 realName = pkg.mRealPackage; 10220 if (!pkg.packageName.equals(renamed)) { 10221 // Callers into this function may have already taken 10222 // care of renaming the package; only do it here if 10223 // it is not already done. 10224 pkg.setPackageName(renamed); 10225 } 10226 } else { 10227 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 10228 if ((origPackage = mSettings.getPackageLPr( 10229 pkg.mOriginalPackages.get(i))) != null) { 10230 // We do have the package already installed under its 10231 // original name... should we use it? 10232 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 10233 // New package is not compatible with original. 10234 origPackage = null; 10235 continue; 10236 } else if (origPackage.sharedUser != null) { 10237 // Make sure uid is compatible between packages. 10238 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 10239 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 10240 + " to " + pkg.packageName + ": old uid " 10241 + origPackage.sharedUser.name 10242 + " differs from " + pkg.mSharedUserId); 10243 origPackage = null; 10244 continue; 10245 } 10246 // TODO: Add case when shared user id is added [b/28144775] 10247 } else { 10248 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 10249 + pkg.packageName + " to old name " + origPackage.name); 10250 } 10251 break; 10252 } 10253 } 10254 } 10255 } 10256 10257 if (mTransferedPackages.contains(pkg.packageName)) { 10258 Slog.w(TAG, "Package " + pkg.packageName 10259 + " was transferred to another, but its .apk remains"); 10260 } 10261 10262 // See comments in nonMutatedPs declaration 10263 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 10264 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName); 10265 if (foundPs != null) { 10266 nonMutatedPs = new PackageSetting(foundPs); 10267 } 10268 } 10269 10270 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) { 10271 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName); 10272 if (foundPs != null) { 10273 primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString; 10274 secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString; 10275 } 10276 } 10277 10278 pkgSetting = mSettings.getPackageLPr(pkg.packageName); 10279 if (pkgSetting != null && pkgSetting.sharedUser != suid) { 10280 PackageManagerService.reportSettingsProblem(Log.WARN, 10281 "Package " + pkg.packageName + " shared user changed from " 10282 + (pkgSetting.sharedUser != null 10283 ? pkgSetting.sharedUser.name : "<nothing>") 10284 + " to " 10285 + (suid != null ? suid.name : "<nothing>") 10286 + "; replacing with new"); 10287 pkgSetting = null; 10288 } 10289 final PackageSetting oldPkgSetting = 10290 pkgSetting == null ? null : new PackageSetting(pkgSetting); 10291 final PackageSetting disabledPkgSetting = 10292 mSettings.getDisabledSystemPkgLPr(pkg.packageName); 10293 10294 String[] usesStaticLibraries = null; 10295 if (pkg.usesStaticLibraries != null) { 10296 usesStaticLibraries = new String[pkg.usesStaticLibraries.size()]; 10297 pkg.usesStaticLibraries.toArray(usesStaticLibraries); 10298 } 10299 10300 if (pkgSetting == null) { 10301 final String parentPackageName = (pkg.parentPackage != null) 10302 ? pkg.parentPackage.packageName : null; 10303 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 10304 // REMOVE SharedUserSetting from method; update in a separate call 10305 pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage, 10306 disabledPkgSetting, realName, suid, destCodeFile, destResourceFile, 10307 pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi, 10308 pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode, 10309 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user, 10310 true /*allowInstall*/, instantApp, parentPackageName, 10311 pkg.getChildPackageNames(), UserManagerService.getInstance(), 10312 usesStaticLibraries, pkg.usesStaticLibrariesVersions); 10313 // SIDE EFFECTS; updates system state; move elsewhere 10314 if (origPackage != null) { 10315 mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name); 10316 } 10317 mSettings.addUserToSettingLPw(pkgSetting); 10318 } else { 10319 // REMOVE SharedUserSetting from method; update in a separate call. 10320 // 10321 // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi, 10322 // secondaryCpuAbi are not known at this point so we always update them 10323 // to null here, only to reset them at a later point. 10324 Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile, 10325 pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi, 10326 pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags, 10327 pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(), 10328 UserManagerService.getInstance(), usesStaticLibraries, 10329 pkg.usesStaticLibrariesVersions); 10330 } 10331 // SIDE EFFECTS; persists system state to files on disk; move elsewhere 10332 mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting); 10333 10334 // SIDE EFFECTS; modifies system state; move elsewhere 10335 if (pkgSetting.origPackage != null) { 10336 // If we are first transitioning from an original package, 10337 // fix up the new package's name now. We need to do this after 10338 // looking up the package under its new name, so getPackageLP 10339 // can take care of fiddling things correctly. 10340 pkg.setPackageName(origPackage.name); 10341 10342 // File a report about this. 10343 String msg = "New package " + pkgSetting.realName 10344 + " renamed to replace old package " + pkgSetting.name; 10345 reportSettingsProblem(Log.WARN, msg); 10346 10347 // Make a note of it. 10348 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 10349 mTransferedPackages.add(origPackage.name); 10350 } 10351 10352 // No longer need to retain this. 10353 pkgSetting.origPackage = null; 10354 } 10355 10356 // SIDE EFFECTS; modifies system state; move elsewhere 10357 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 10358 // Make a note of it. 10359 mTransferedPackages.add(pkg.packageName); 10360 } 10361 10362 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 10363 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 10364 } 10365 10366 if ((scanFlags & SCAN_BOOTING) == 0 10367 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 10368 // Check all shared libraries and map to their actual file path. 10369 // We only do this here for apps not on a system dir, because those 10370 // are the only ones that can fail an install due to this. We 10371 // will take care of the system apps by updating all of their 10372 // library paths after the scan is done. Also during the initial 10373 // scan don't update any libs as we do this wholesale after all 10374 // apps are scanned to avoid dependency based scanning. 10375 updateSharedLibrariesLPr(pkg, null); 10376 } 10377 10378 if (mFoundPolicyFile) { 10379 SELinuxMMAC.assignSeInfoValue(pkg); 10380 } 10381 pkg.applicationInfo.uid = pkgSetting.appId; 10382 pkg.mExtras = pkgSetting; 10383 10384 10385 // Static shared libs have same package with different versions where 10386 // we internally use a synthetic package name to allow multiple versions 10387 // of the same package, therefore we need to compare signatures against 10388 // the package setting for the latest library version. 10389 PackageSetting signatureCheckPs = pkgSetting; 10390 if (pkg.applicationInfo.isStaticSharedLibrary()) { 10391 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg); 10392 if (libraryEntry != null) { 10393 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk); 10394 } 10395 } 10396 10397 if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) { 10398 if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) { 10399 // We just determined the app is signed correctly, so bring 10400 // over the latest parsed certs. 10401 pkgSetting.signatures.mSignatures = pkg.mSignatures; 10402 } else { 10403 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 10404 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 10405 "Package " + pkg.packageName + " upgrade keys do not match the " 10406 + "previously installed version"); 10407 } else { 10408 pkgSetting.signatures.mSignatures = pkg.mSignatures; 10409 String msg = "System package " + pkg.packageName 10410 + " signature changed; retaining data."; 10411 reportSettingsProblem(Log.WARN, msg); 10412 } 10413 } 10414 } else { 10415 try { 10416 // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService 10417 verifySignaturesLP(signatureCheckPs, pkg); 10418 // We just determined the app is signed correctly, so bring 10419 // over the latest parsed certs. 10420 pkgSetting.signatures.mSignatures = pkg.mSignatures; 10421 } catch (PackageManagerException e) { 10422 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 10423 throw e; 10424 } 10425 // The signature has changed, but this package is in the system 10426 // image... let's recover! 10427 pkgSetting.signatures.mSignatures = pkg.mSignatures; 10428 // However... if this package is part of a shared user, but it 10429 // doesn't match the signature of the shared user, let's fail. 10430 // What this means is that you can't change the signatures 10431 // associated with an overall shared user, which doesn't seem all 10432 // that unreasonable. 10433 if (signatureCheckPs.sharedUser != null) { 10434 if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures, 10435 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 10436 throw new PackageManagerException( 10437 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 10438 "Signature mismatch for shared user: " 10439 + pkgSetting.sharedUser); 10440 } 10441 } 10442 // File a report about this. 10443 String msg = "System package " + pkg.packageName 10444 + " signature changed; retaining data."; 10445 reportSettingsProblem(Log.WARN, msg); 10446 } 10447 } 10448 10449 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 10450 // This package wants to adopt ownership of permissions from 10451 // another package. 10452 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 10453 final String origName = pkg.mAdoptPermissions.get(i); 10454 final PackageSetting orig = mSettings.getPackageLPr(origName); 10455 if (orig != null) { 10456 if (verifyPackageUpdateLPr(orig, pkg)) { 10457 Slog.i(TAG, "Adopting permissions from " + origName + " to " 10458 + pkg.packageName); 10459 // SIDE EFFECTS; updates permissions system state; move elsewhere 10460 mSettings.transferPermissionsLPw(origName, pkg.packageName); 10461 } 10462 } 10463 } 10464 } 10465 } 10466 10467 pkg.applicationInfo.processName = fixProcessName( 10468 pkg.applicationInfo.packageName, 10469 pkg.applicationInfo.processName); 10470 10471 if (pkg != mPlatformPackage) { 10472 // Get all of our default paths setup 10473 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 10474 } 10475 10476 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 10477 10478 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 10479 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) { 10480 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi"); 10481 final boolean extractNativeLibs = !pkg.isLibrary(); 10482 derivePackageAbi(pkg, scanFile, cpuAbiOverride, extractNativeLibs, 10483 mAppLib32InstallDir); 10484 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10485 10486 // Some system apps still use directory structure for native libraries 10487 // in which case we might end up not detecting abi solely based on apk 10488 // structure. Try to detect abi based on directory structure. 10489 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 10490 pkg.applicationInfo.primaryCpuAbi == null) { 10491 setBundledAppAbisAndRoots(pkg, pkgSetting); 10492 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 10493 } 10494 } else { 10495 // This is not a first boot or an upgrade, don't bother deriving the 10496 // ABI during the scan. Instead, trust the value that was stored in the 10497 // package setting. 10498 pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings; 10499 pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings; 10500 10501 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 10502 10503 if (DEBUG_ABI_SELECTION) { 10504 Slog.i(TAG, "Using ABIS and native lib paths from settings : " + 10505 pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " + 10506 pkg.applicationInfo.secondaryCpuAbi); 10507 } 10508 } 10509 } else { 10510 if ((scanFlags & SCAN_MOVE) != 0) { 10511 // We haven't run dex-opt for this move (since we've moved the compiled output too) 10512 // but we already have this packages package info in the PackageSetting. We just 10513 // use that and derive the native library path based on the new codepath. 10514 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 10515 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 10516 } 10517 10518 // Set native library paths again. For moves, the path will be updated based on the 10519 // ABIs we've determined above. For non-moves, the path will be updated based on the 10520 // ABIs we determined during compilation, but the path will depend on the final 10521 // package path (after the rename away from the stage path). 10522 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 10523 } 10524 10525 // This is a special case for the "system" package, where the ABI is 10526 // dictated by the zygote configuration (and init.rc). We should keep track 10527 // of this ABI so that we can deal with "normal" applications that run under 10528 // the same UID correctly. 10529 if (mPlatformPackage == pkg) { 10530 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 10531 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 10532 } 10533 10534 // If there's a mismatch between the abi-override in the package setting 10535 // and the abiOverride specified for the install. Warn about this because we 10536 // would've already compiled the app without taking the package setting into 10537 // account. 10538 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 10539 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 10540 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 10541 " for package " + pkg.packageName); 10542 } 10543 } 10544 10545 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 10546 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 10547 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 10548 10549 // Copy the derived override back to the parsed package, so that we can 10550 // update the package settings accordingly. 10551 pkg.cpuAbiOverride = cpuAbiOverride; 10552 10553 if (DEBUG_ABI_SELECTION) { 10554 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 10555 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 10556 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 10557 } 10558 10559 // Push the derived path down into PackageSettings so we know what to 10560 // clean up at uninstall time. 10561 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 10562 10563 if (DEBUG_ABI_SELECTION) { 10564 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 10565 " primary=" + pkg.applicationInfo.primaryCpuAbi + 10566 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 10567 } 10568 10569 // SIDE EFFECTS; removes DEX files from disk; move elsewhere 10570 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 10571 // We don't do this here during boot because we can do it all 10572 // at once after scanning all existing packages. 10573 // 10574 // We also do this *before* we perform dexopt on this package, so that 10575 // we can avoid redundant dexopts, and also to make sure we've got the 10576 // code and package path correct. 10577 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg); 10578 } 10579 10580 if (mFactoryTest && pkg.requestedPermissions.contains( 10581 android.Manifest.permission.FACTORY_TEST)) { 10582 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 10583 } 10584 10585 if (isSystemApp(pkg)) { 10586 pkgSetting.isOrphaned = true; 10587 } 10588 10589 // Take care of first install / last update times. 10590 final long scanFileTime = getLastModifiedTime(pkg, scanFile); 10591 if (currentTime != 0) { 10592 if (pkgSetting.firstInstallTime == 0) { 10593 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 10594 } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) { 10595 pkgSetting.lastUpdateTime = currentTime; 10596 } 10597 } else if (pkgSetting.firstInstallTime == 0) { 10598 // We need *something*. Take time time stamp of the file. 10599 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 10600 } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 10601 if (scanFileTime != pkgSetting.timeStamp) { 10602 // A package on the system image has changed; consider this 10603 // to be an update. 10604 pkgSetting.lastUpdateTime = scanFileTime; 10605 } 10606 } 10607 pkgSetting.setTimeStamp(scanFileTime); 10608 10609 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 10610 if (nonMutatedPs != null) { 10611 synchronized (mPackages) { 10612 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 10613 } 10614 } 10615 } else { 10616 final int userId = user == null ? 0 : user.getIdentifier(); 10617 // Modify state for the given package setting 10618 commitPackageSettings(pkg, pkgSetting, user, scanFlags, 10619 (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/); 10620 if (pkgSetting.getInstantApp(userId)) { 10621 mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId); 10622 } 10623 } 10624 return pkg; 10625 } 10626 10627 /** 10628 * Applies policy to the parsed package based upon the given policy flags. 10629 * Ensures the package is in a good state. 10630 * <p> 10631 * Implementation detail: This method must NOT have any side effect. It would 10632 * ideally be static, but, it requires locks to read system state. 10633 */ 10634 private void applyPolicy(PackageParser.Package pkg, int policyFlags) { 10635 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 10636 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 10637 if (pkg.applicationInfo.isDirectBootAware()) { 10638 // we're direct boot aware; set for all components 10639 for (PackageParser.Service s : pkg.services) { 10640 s.info.encryptionAware = s.info.directBootAware = true; 10641 } 10642 for (PackageParser.Provider p : pkg.providers) { 10643 p.info.encryptionAware = p.info.directBootAware = true; 10644 } 10645 for (PackageParser.Activity a : pkg.activities) { 10646 a.info.encryptionAware = a.info.directBootAware = true; 10647 } 10648 for (PackageParser.Activity r : pkg.receivers) { 10649 r.info.encryptionAware = r.info.directBootAware = true; 10650 } 10651 } 10652 } else { 10653 // Only allow system apps to be flagged as core apps. 10654 pkg.coreApp = false; 10655 // clear flags not applicable to regular apps 10656 pkg.applicationInfo.privateFlags &= 10657 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 10658 pkg.applicationInfo.privateFlags &= 10659 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 10660 } 10661 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 10662 10663 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 10664 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 10665 } 10666 10667 if (!isSystemApp(pkg)) { 10668 // Only system apps can use these features. 10669 pkg.mOriginalPackages = null; 10670 pkg.mRealPackage = null; 10671 pkg.mAdoptPermissions = null; 10672 } 10673 } 10674 10675 /** 10676 * Asserts the parsed package is valid according to the given policy. If the 10677 * package is invalid, for whatever reason, throws {@link PackageManagerException}. 10678 * <p> 10679 * Implementation detail: This method must NOT have any side effects. It would 10680 * ideally be static, but, it requires locks to read system state. 10681 * 10682 * @throws PackageManagerException If the package fails any of the validation checks 10683 */ 10684 private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags) 10685 throws PackageManagerException { 10686 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 10687 assertCodePolicy(pkg); 10688 } 10689 10690 if (pkg.applicationInfo.getCodePath() == null || 10691 pkg.applicationInfo.getResourcePath() == null) { 10692 // Bail out. The resource and code paths haven't been set. 10693 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 10694 "Code and resource paths haven't been set correctly"); 10695 } 10696 10697 // Make sure we're not adding any bogus keyset info 10698 KeySetManagerService ksms = mSettings.mKeySetManagerService; 10699 ksms.assertScannedPackageValid(pkg); 10700 10701 synchronized (mPackages) { 10702 // The special "android" package can only be defined once 10703 if (pkg.packageName.equals("android")) { 10704 if (mAndroidApplication != null) { 10705 Slog.w(TAG, "*************************************************"); 10706 Slog.w(TAG, "Core android package being redefined. Skipping."); 10707 Slog.w(TAG, " codePath=" + pkg.codePath); 10708 Slog.w(TAG, "*************************************************"); 10709 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 10710 "Core android package being redefined. Skipping."); 10711 } 10712 } 10713 10714 // A package name must be unique; don't allow duplicates 10715 if (mPackages.containsKey(pkg.packageName)) { 10716 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 10717 "Application package " + pkg.packageName 10718 + " already installed. Skipping duplicate."); 10719 } 10720 10721 if (pkg.applicationInfo.isStaticSharedLibrary()) { 10722 // Static libs have a synthetic package name containing the version 10723 // but we still want the base name to be unique. 10724 if (mPackages.containsKey(pkg.manifestPackageName)) { 10725 throw new PackageManagerException( 10726 "Duplicate static shared lib provider package"); 10727 } 10728 10729 // Static shared libraries should have at least O target SDK 10730 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) { 10731 throw new PackageManagerException( 10732 "Packages declaring static-shared libs must target O SDK or higher"); 10733 } 10734 10735 // Package declaring static a shared lib cannot be instant apps 10736 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 10737 throw new PackageManagerException( 10738 "Packages declaring static-shared libs cannot be instant apps"); 10739 } 10740 10741 // Package declaring static a shared lib cannot be renamed since the package 10742 // name is synthetic and apps can't code around package manager internals. 10743 if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) { 10744 throw new PackageManagerException( 10745 "Packages declaring static-shared libs cannot be renamed"); 10746 } 10747 10748 // Package declaring static a shared lib cannot declare child packages 10749 if (!ArrayUtils.isEmpty(pkg.childPackages)) { 10750 throw new PackageManagerException( 10751 "Packages declaring static-shared libs cannot have child packages"); 10752 } 10753 10754 // Package declaring static a shared lib cannot declare dynamic libs 10755 if (!ArrayUtils.isEmpty(pkg.libraryNames)) { 10756 throw new PackageManagerException( 10757 "Packages declaring static-shared libs cannot declare dynamic libs"); 10758 } 10759 10760 // Package declaring static a shared lib cannot declare shared users 10761 if (pkg.mSharedUserId != null) { 10762 throw new PackageManagerException( 10763 "Packages declaring static-shared libs cannot declare shared users"); 10764 } 10765 10766 // Static shared libs cannot declare activities 10767 if (!pkg.activities.isEmpty()) { 10768 throw new PackageManagerException( 10769 "Static shared libs cannot declare activities"); 10770 } 10771 10772 // Static shared libs cannot declare services 10773 if (!pkg.services.isEmpty()) { 10774 throw new PackageManagerException( 10775 "Static shared libs cannot declare services"); 10776 } 10777 10778 // Static shared libs cannot declare providers 10779 if (!pkg.providers.isEmpty()) { 10780 throw new PackageManagerException( 10781 "Static shared libs cannot declare content providers"); 10782 } 10783 10784 // Static shared libs cannot declare receivers 10785 if (!pkg.receivers.isEmpty()) { 10786 throw new PackageManagerException( 10787 "Static shared libs cannot declare broadcast receivers"); 10788 } 10789 10790 // Static shared libs cannot declare permission groups 10791 if (!pkg.permissionGroups.isEmpty()) { 10792 throw new PackageManagerException( 10793 "Static shared libs cannot declare permission groups"); 10794 } 10795 10796 // Static shared libs cannot declare permissions 10797 if (!pkg.permissions.isEmpty()) { 10798 throw new PackageManagerException( 10799 "Static shared libs cannot declare permissions"); 10800 } 10801 10802 // Static shared libs cannot declare protected broadcasts 10803 if (pkg.protectedBroadcasts != null) { 10804 throw new PackageManagerException( 10805 "Static shared libs cannot declare protected broadcasts"); 10806 } 10807 10808 // Static shared libs cannot be overlay targets 10809 if (pkg.mOverlayTarget != null) { 10810 throw new PackageManagerException( 10811 "Static shared libs cannot be overlay targets"); 10812 } 10813 10814 // The version codes must be ordered as lib versions 10815 int minVersionCode = Integer.MIN_VALUE; 10816 int maxVersionCode = Integer.MAX_VALUE; 10817 10818 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get( 10819 pkg.staticSharedLibName); 10820 if (versionedLib != null) { 10821 final int versionCount = versionedLib.size(); 10822 for (int i = 0; i < versionCount; i++) { 10823 SharedLibraryInfo libInfo = versionedLib.valueAt(i).info; 10824 final int libVersionCode = libInfo.getDeclaringPackage() 10825 .getVersionCode(); 10826 if (libInfo.getVersion() < pkg.staticSharedLibVersion) { 10827 minVersionCode = Math.max(minVersionCode, libVersionCode + 1); 10828 } else if (libInfo.getVersion() > pkg.staticSharedLibVersion) { 10829 maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1); 10830 } else { 10831 minVersionCode = maxVersionCode = libVersionCode; 10832 break; 10833 } 10834 } 10835 } 10836 if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) { 10837 throw new PackageManagerException("Static shared" 10838 + " lib version codes must be ordered as lib versions"); 10839 } 10840 } 10841 10842 // Only privileged apps and updated privileged apps can add child packages. 10843 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 10844 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 10845 throw new PackageManagerException("Only privileged apps can add child " 10846 + "packages. Ignoring package " + pkg.packageName); 10847 } 10848 final int childCount = pkg.childPackages.size(); 10849 for (int i = 0; i < childCount; i++) { 10850 PackageParser.Package childPkg = pkg.childPackages.get(i); 10851 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 10852 childPkg.packageName)) { 10853 throw new PackageManagerException("Can't override child of " 10854 + "another disabled app. Ignoring package " + pkg.packageName); 10855 } 10856 } 10857 } 10858 10859 // If we're only installing presumed-existing packages, require that the 10860 // scanned APK is both already known and at the path previously established 10861 // for it. Previously unknown packages we pick up normally, but if we have an 10862 // a priori expectation about this package's install presence, enforce it. 10863 // With a singular exception for new system packages. When an OTA contains 10864 // a new system package, we allow the codepath to change from a system location 10865 // to the user-installed location. If we don't allow this change, any newer, 10866 // user-installed version of the application will be ignored. 10867 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 10868 if (mExpectingBetter.containsKey(pkg.packageName)) { 10869 logCriticalInfo(Log.WARN, 10870 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 10871 } else { 10872 PackageSetting known = mSettings.getPackageLPr(pkg.packageName); 10873 if (known != null) { 10874 if (DEBUG_PACKAGE_SCANNING) { 10875 Log.d(TAG, "Examining " + pkg.codePath 10876 + " and requiring known paths " + known.codePathString 10877 + " & " + known.resourcePathString); 10878 } 10879 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 10880 || !pkg.applicationInfo.getResourcePath().equals( 10881 known.resourcePathString)) { 10882 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 10883 "Application package " + pkg.packageName 10884 + " found at " + pkg.applicationInfo.getCodePath() 10885 + " but expected at " + known.codePathString 10886 + "; ignoring."); 10887 } 10888 } 10889 } 10890 } 10891 10892 // Verify that this new package doesn't have any content providers 10893 // that conflict with existing packages. Only do this if the 10894 // package isn't already installed, since we don't want to break 10895 // things that are installed. 10896 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 10897 final int N = pkg.providers.size(); 10898 int i; 10899 for (i=0; i<N; i++) { 10900 PackageParser.Provider p = pkg.providers.get(i); 10901 if (p.info.authority != null) { 10902 String names[] = p.info.authority.split(";"); 10903 for (int j = 0; j < names.length; j++) { 10904 if (mProvidersByAuthority.containsKey(names[j])) { 10905 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 10906 final String otherPackageName = 10907 ((other != null && other.getComponentName() != null) ? 10908 other.getComponentName().getPackageName() : "?"); 10909 throw new PackageManagerException( 10910 INSTALL_FAILED_CONFLICTING_PROVIDER, 10911 "Can't install because provider name " + names[j] 10912 + " (in package " + pkg.applicationInfo.packageName 10913 + ") is already used by " + otherPackageName); 10914 } 10915 } 10916 } 10917 } 10918 } 10919 } 10920 } 10921 10922 private boolean addSharedLibraryLPw(String path, String apk, String name, int version, 10923 int type, String declaringPackageName, int declaringVersionCode) { 10924 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 10925 if (versionedLib == null) { 10926 versionedLib = new SparseArray<>(); 10927 mSharedLibraries.put(name, versionedLib); 10928 if (type == SharedLibraryInfo.TYPE_STATIC) { 10929 mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib); 10930 } 10931 } else if (versionedLib.indexOfKey(version) >= 0) { 10932 return false; 10933 } 10934 SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name, 10935 version, type, declaringPackageName, declaringVersionCode); 10936 versionedLib.put(version, libEntry); 10937 return true; 10938 } 10939 10940 private boolean removeSharedLibraryLPw(String name, int version) { 10941 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 10942 if (versionedLib == null) { 10943 return false; 10944 } 10945 final int libIdx = versionedLib.indexOfKey(version); 10946 if (libIdx < 0) { 10947 return false; 10948 } 10949 SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx); 10950 versionedLib.remove(version); 10951 if (versionedLib.size() <= 0) { 10952 mSharedLibraries.remove(name); 10953 if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) { 10954 mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage() 10955 .getPackageName()); 10956 } 10957 } 10958 return true; 10959 } 10960 10961 /** 10962 * Adds a scanned package to the system. When this method is finished, the package will 10963 * be available for query, resolution, etc... 10964 */ 10965 private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting, 10966 UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException { 10967 final String pkgName = pkg.packageName; 10968 if (mCustomResolverComponentName != null && 10969 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 10970 setUpCustomResolverActivity(pkg); 10971 } 10972 10973 if (pkg.packageName.equals("android")) { 10974 synchronized (mPackages) { 10975 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 10976 // Set up information for our fall-back user intent resolution activity. 10977 mPlatformPackage = pkg; 10978 pkg.mVersionCode = mSdkVersion; 10979 mAndroidApplication = pkg.applicationInfo; 10980 if (!mResolverReplaced) { 10981 mResolveActivity.applicationInfo = mAndroidApplication; 10982 mResolveActivity.name = ResolverActivity.class.getName(); 10983 mResolveActivity.packageName = mAndroidApplication.packageName; 10984 mResolveActivity.processName = "system:ui"; 10985 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 10986 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 10987 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 10988 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 10989 mResolveActivity.exported = true; 10990 mResolveActivity.enabled = true; 10991 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 10992 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 10993 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 10994 | ActivityInfo.CONFIG_SCREEN_LAYOUT 10995 | ActivityInfo.CONFIG_ORIENTATION 10996 | ActivityInfo.CONFIG_KEYBOARD 10997 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 10998 mResolveInfo.activityInfo = mResolveActivity; 10999 mResolveInfo.priority = 0; 11000 mResolveInfo.preferredOrder = 0; 11001 mResolveInfo.match = 0; 11002 mResolveComponentName = new ComponentName( 11003 mAndroidApplication.packageName, mResolveActivity.name); 11004 } 11005 } 11006 } 11007 } 11008 11009 ArrayList<PackageParser.Package> clientLibPkgs = null; 11010 // writer 11011 synchronized (mPackages) { 11012 boolean hasStaticSharedLibs = false; 11013 11014 // Any app can add new static shared libraries 11015 if (pkg.staticSharedLibName != null) { 11016 // Static shared libs don't allow renaming as they have synthetic package 11017 // names to allow install of multiple versions, so use name from manifest. 11018 if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName, 11019 pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC, 11020 pkg.manifestPackageName, pkg.mVersionCode)) { 11021 hasStaticSharedLibs = true; 11022 } else { 11023 Slog.w(TAG, "Package " + pkg.packageName + " library " 11024 + pkg.staticSharedLibName + " already exists; skipping"); 11025 } 11026 // Static shared libs cannot be updated once installed since they 11027 // use synthetic package name which includes the version code, so 11028 // not need to update other packages's shared lib dependencies. 11029 } 11030 11031 if (!hasStaticSharedLibs 11032 && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 11033 // Only system apps can add new dynamic shared libraries. 11034 if (pkg.libraryNames != null) { 11035 for (int i = 0; i < pkg.libraryNames.size(); i++) { 11036 String name = pkg.libraryNames.get(i); 11037 boolean allowed = false; 11038 if (pkg.isUpdatedSystemApp()) { 11039 // New library entries can only be added through the 11040 // system image. This is important to get rid of a lot 11041 // of nasty edge cases: for example if we allowed a non- 11042 // system update of the app to add a library, then uninstalling 11043 // the update would make the library go away, and assumptions 11044 // we made such as through app install filtering would now 11045 // have allowed apps on the device which aren't compatible 11046 // with it. Better to just have the restriction here, be 11047 // conservative, and create many fewer cases that can negatively 11048 // impact the user experience. 11049 final PackageSetting sysPs = mSettings 11050 .getDisabledSystemPkgLPr(pkg.packageName); 11051 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 11052 for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) { 11053 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 11054 allowed = true; 11055 break; 11056 } 11057 } 11058 } 11059 } else { 11060 allowed = true; 11061 } 11062 if (allowed) { 11063 if (!addSharedLibraryLPw(null, pkg.packageName, name, 11064 SharedLibraryInfo.VERSION_UNDEFINED, 11065 SharedLibraryInfo.TYPE_DYNAMIC, 11066 pkg.packageName, pkg.mVersionCode)) { 11067 Slog.w(TAG, "Package " + pkg.packageName + " library " 11068 + name + " already exists; skipping"); 11069 } 11070 } else { 11071 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 11072 + name + " that is not declared on system image; skipping"); 11073 } 11074 } 11075 11076 if ((scanFlags & SCAN_BOOTING) == 0) { 11077 // If we are not booting, we need to update any applications 11078 // that are clients of our shared library. If we are booting, 11079 // this will all be done once the scan is complete. 11080 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 11081 } 11082 } 11083 } 11084 } 11085 11086 if ((scanFlags & SCAN_BOOTING) != 0) { 11087 // No apps can run during boot scan, so they don't need to be frozen 11088 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 11089 // Caller asked to not kill app, so it's probably not frozen 11090 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 11091 // Caller asked us to ignore frozen check for some reason; they 11092 // probably didn't know the package name 11093 } else { 11094 // We're doing major surgery on this package, so it better be frozen 11095 // right now to keep it from launching 11096 checkPackageFrozen(pkgName); 11097 } 11098 11099 // Also need to kill any apps that are dependent on the library. 11100 if (clientLibPkgs != null) { 11101 for (int i=0; i<clientLibPkgs.size(); i++) { 11102 PackageParser.Package clientPkg = clientLibPkgs.get(i); 11103 killApplication(clientPkg.applicationInfo.packageName, 11104 clientPkg.applicationInfo.uid, "update lib"); 11105 } 11106 } 11107 11108 // writer 11109 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 11110 11111 synchronized (mPackages) { 11112 // We don't expect installation to fail beyond this point 11113 11114 // Add the new setting to mSettings 11115 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 11116 // Add the new setting to mPackages 11117 mPackages.put(pkg.applicationInfo.packageName, pkg); 11118 // Make sure we don't accidentally delete its data. 11119 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 11120 while (iter.hasNext()) { 11121 PackageCleanItem item = iter.next(); 11122 if (pkgName.equals(item.packageName)) { 11123 iter.remove(); 11124 } 11125 } 11126 11127 // Add the package's KeySets to the global KeySetManagerService 11128 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11129 ksms.addScannedPackageLPw(pkg); 11130 11131 int N = pkg.providers.size(); 11132 StringBuilder r = null; 11133 int i; 11134 for (i=0; i<N; i++) { 11135 PackageParser.Provider p = pkg.providers.get(i); 11136 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 11137 p.info.processName); 11138 mProviders.addProvider(p); 11139 p.syncable = p.info.isSyncable; 11140 if (p.info.authority != null) { 11141 String names[] = p.info.authority.split(";"); 11142 p.info.authority = null; 11143 for (int j = 0; j < names.length; j++) { 11144 if (j == 1 && p.syncable) { 11145 // We only want the first authority for a provider to possibly be 11146 // syncable, so if we already added this provider using a different 11147 // authority clear the syncable flag. We copy the provider before 11148 // changing it because the mProviders object contains a reference 11149 // to a provider that we don't want to change. 11150 // Only do this for the second authority since the resulting provider 11151 // object can be the same for all future authorities for this provider. 11152 p = new PackageParser.Provider(p); 11153 p.syncable = false; 11154 } 11155 if (!mProvidersByAuthority.containsKey(names[j])) { 11156 mProvidersByAuthority.put(names[j], p); 11157 if (p.info.authority == null) { 11158 p.info.authority = names[j]; 11159 } else { 11160 p.info.authority = p.info.authority + ";" + names[j]; 11161 } 11162 if (DEBUG_PACKAGE_SCANNING) { 11163 if (chatty) 11164 Log.d(TAG, "Registered content provider: " + names[j] 11165 + ", className = " + p.info.name + ", isSyncable = " 11166 + p.info.isSyncable); 11167 } 11168 } else { 11169 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 11170 Slog.w(TAG, "Skipping provider name " + names[j] + 11171 " (in package " + pkg.applicationInfo.packageName + 11172 "): name already used by " 11173 + ((other != null && other.getComponentName() != null) 11174 ? other.getComponentName().getPackageName() : "?")); 11175 } 11176 } 11177 } 11178 if (chatty) { 11179 if (r == null) { 11180 r = new StringBuilder(256); 11181 } else { 11182 r.append(' '); 11183 } 11184 r.append(p.info.name); 11185 } 11186 } 11187 if (r != null) { 11188 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 11189 } 11190 11191 N = pkg.services.size(); 11192 r = null; 11193 for (i=0; i<N; i++) { 11194 PackageParser.Service s = pkg.services.get(i); 11195 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 11196 s.info.processName); 11197 mServices.addService(s); 11198 if (chatty) { 11199 if (r == null) { 11200 r = new StringBuilder(256); 11201 } else { 11202 r.append(' '); 11203 } 11204 r.append(s.info.name); 11205 } 11206 } 11207 if (r != null) { 11208 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 11209 } 11210 11211 N = pkg.receivers.size(); 11212 r = null; 11213 for (i=0; i<N; i++) { 11214 PackageParser.Activity a = pkg.receivers.get(i); 11215 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 11216 a.info.processName); 11217 mReceivers.addActivity(a, "receiver"); 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, " Receivers: " + r); 11229 } 11230 11231 N = pkg.activities.size(); 11232 r = null; 11233 for (i=0; i<N; i++) { 11234 PackageParser.Activity a = pkg.activities.get(i); 11235 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 11236 a.info.processName); 11237 mActivities.addActivity(a, "activity"); 11238 if (chatty) { 11239 if (r == null) { 11240 r = new StringBuilder(256); 11241 } else { 11242 r.append(' '); 11243 } 11244 r.append(a.info.name); 11245 } 11246 } 11247 if (r != null) { 11248 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 11249 } 11250 11251 N = pkg.permissionGroups.size(); 11252 r = null; 11253 for (i=0; i<N; i++) { 11254 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 11255 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 11256 final String curPackageName = cur == null ? null : cur.info.packageName; 11257 // Dont allow ephemeral apps to define new permission groups. 11258 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 11259 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 11260 + pg.info.packageName 11261 + " ignored: instant apps cannot define new permission groups."); 11262 continue; 11263 } 11264 final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName); 11265 if (cur == null || isPackageUpdate) { 11266 mPermissionGroups.put(pg.info.name, pg); 11267 if (chatty) { 11268 if (r == null) { 11269 r = new StringBuilder(256); 11270 } else { 11271 r.append(' '); 11272 } 11273 if (isPackageUpdate) { 11274 r.append("UPD:"); 11275 } 11276 r.append(pg.info.name); 11277 } 11278 } else { 11279 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 11280 + pg.info.packageName + " ignored: original from " 11281 + cur.info.packageName); 11282 if (chatty) { 11283 if (r == null) { 11284 r = new StringBuilder(256); 11285 } else { 11286 r.append(' '); 11287 } 11288 r.append("DUP:"); 11289 r.append(pg.info.name); 11290 } 11291 } 11292 } 11293 if (r != null) { 11294 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 11295 } 11296 11297 N = pkg.permissions.size(); 11298 r = null; 11299 for (i=0; i<N; i++) { 11300 PackageParser.Permission p = pkg.permissions.get(i); 11301 11302 // Dont allow ephemeral apps to define new permissions. 11303 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 11304 Slog.w(TAG, "Permission " + p.info.name + " from package " 11305 + p.info.packageName 11306 + " ignored: instant apps cannot define new permissions."); 11307 continue; 11308 } 11309 11310 // Assume by default that we did not install this permission into the system. 11311 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 11312 11313 // Now that permission groups have a special meaning, we ignore permission 11314 // groups for legacy apps to prevent unexpected behavior. In particular, 11315 // permissions for one app being granted to someone just because they happen 11316 // to be in a group defined by another app (before this had no implications). 11317 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 11318 p.group = mPermissionGroups.get(p.info.group); 11319 // Warn for a permission in an unknown group. 11320 if (DEBUG_PERMISSIONS && p.info.group != null && p.group == null) { 11321 Slog.i(TAG, "Permission " + p.info.name + " from package " 11322 + p.info.packageName + " in an unknown group " + p.info.group); 11323 } 11324 } 11325 11326 ArrayMap<String, BasePermission> permissionMap = 11327 p.tree ? mSettings.mPermissionTrees 11328 : mSettings.mPermissions; 11329 BasePermission bp = permissionMap.get(p.info.name); 11330 11331 // Allow system apps to redefine non-system permissions 11332 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 11333 final boolean currentOwnerIsSystem = (bp.perm != null 11334 && isSystemApp(bp.perm.owner)); 11335 if (isSystemApp(p.owner)) { 11336 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 11337 // It's a built-in permission and no owner, take ownership now 11338 bp.packageSetting = pkgSetting; 11339 bp.perm = p; 11340 bp.uid = pkg.applicationInfo.uid; 11341 bp.sourcePackage = p.info.packageName; 11342 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 11343 } else if (!currentOwnerIsSystem) { 11344 String msg = "New decl " + p.owner + " of permission " 11345 + p.info.name + " is system; overriding " + bp.sourcePackage; 11346 reportSettingsProblem(Log.WARN, msg); 11347 bp = null; 11348 } 11349 } 11350 } 11351 11352 if (bp == null) { 11353 bp = new BasePermission(p.info.name, p.info.packageName, 11354 BasePermission.TYPE_NORMAL); 11355 permissionMap.put(p.info.name, bp); 11356 } 11357 11358 if (bp.perm == null) { 11359 if (bp.sourcePackage == null 11360 || bp.sourcePackage.equals(p.info.packageName)) { 11361 BasePermission tree = findPermissionTreeLP(p.info.name); 11362 if (tree == null 11363 || tree.sourcePackage.equals(p.info.packageName)) { 11364 bp.packageSetting = pkgSetting; 11365 bp.perm = p; 11366 bp.uid = pkg.applicationInfo.uid; 11367 bp.sourcePackage = p.info.packageName; 11368 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 11369 if (chatty) { 11370 if (r == null) { 11371 r = new StringBuilder(256); 11372 } else { 11373 r.append(' '); 11374 } 11375 r.append(p.info.name); 11376 } 11377 } else { 11378 Slog.w(TAG, "Permission " + p.info.name + " from package " 11379 + p.info.packageName + " ignored: base tree " 11380 + tree.name + " is from package " 11381 + tree.sourcePackage); 11382 } 11383 } else { 11384 Slog.w(TAG, "Permission " + p.info.name + " from package " 11385 + p.info.packageName + " ignored: original from " 11386 + bp.sourcePackage); 11387 } 11388 } else if (chatty) { 11389 if (r == null) { 11390 r = new StringBuilder(256); 11391 } else { 11392 r.append(' '); 11393 } 11394 r.append("DUP:"); 11395 r.append(p.info.name); 11396 } 11397 if (bp.perm == p) { 11398 bp.protectionLevel = p.info.protectionLevel; 11399 } 11400 } 11401 11402 if (r != null) { 11403 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 11404 } 11405 11406 N = pkg.instrumentation.size(); 11407 r = null; 11408 for (i=0; i<N; i++) { 11409 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 11410 a.info.packageName = pkg.applicationInfo.packageName; 11411 a.info.sourceDir = pkg.applicationInfo.sourceDir; 11412 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 11413 a.info.splitNames = pkg.splitNames; 11414 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 11415 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 11416 a.info.splitDependencies = pkg.applicationInfo.splitDependencies; 11417 a.info.dataDir = pkg.applicationInfo.dataDir; 11418 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 11419 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 11420 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 11421 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 11422 mInstrumentation.put(a.getComponentName(), a); 11423 if (chatty) { 11424 if (r == null) { 11425 r = new StringBuilder(256); 11426 } else { 11427 r.append(' '); 11428 } 11429 r.append(a.info.name); 11430 } 11431 } 11432 if (r != null) { 11433 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 11434 } 11435 11436 if (pkg.protectedBroadcasts != null) { 11437 N = pkg.protectedBroadcasts.size(); 11438 for (i=0; i<N; i++) { 11439 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 11440 } 11441 } 11442 } 11443 11444 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11445 } 11446 11447 /** 11448 * Derive the ABI of a non-system package located at {@code scanFile}. This information 11449 * is derived purely on the basis of the contents of {@code scanFile} and 11450 * {@code cpuAbiOverride}. 11451 * 11452 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 11453 */ 11454 private static void derivePackageAbi(PackageParser.Package pkg, File scanFile, 11455 String cpuAbiOverride, boolean extractLibs, 11456 File appLib32InstallDir) 11457 throws PackageManagerException { 11458 // Give ourselves some initial paths; we'll come back for another 11459 // pass once we've determined ABI below. 11460 setNativeLibraryPaths(pkg, appLib32InstallDir); 11461 11462 // We would never need to extract libs for forward-locked and external packages, 11463 // since the container service will do it for us. We shouldn't attempt to 11464 // extract libs from system app when it was not updated. 11465 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 11466 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 11467 extractLibs = false; 11468 } 11469 11470 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 11471 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 11472 11473 NativeLibraryHelper.Handle handle = null; 11474 try { 11475 handle = NativeLibraryHelper.Handle.create(pkg); 11476 // TODO(multiArch): This can be null for apps that didn't go through the 11477 // usual installation process. We can calculate it again, like we 11478 // do during install time. 11479 // 11480 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 11481 // unnecessary. 11482 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 11483 11484 // Null out the abis so that they can be recalculated. 11485 pkg.applicationInfo.primaryCpuAbi = null; 11486 pkg.applicationInfo.secondaryCpuAbi = null; 11487 if (isMultiArch(pkg.applicationInfo)) { 11488 // Warn if we've set an abiOverride for multi-lib packages.. 11489 // By definition, we need to copy both 32 and 64 bit libraries for 11490 // such packages. 11491 if (pkg.cpuAbiOverride != null 11492 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 11493 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 11494 } 11495 11496 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 11497 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 11498 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 11499 if (extractLibs) { 11500 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 11501 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 11502 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 11503 useIsaSpecificSubdirs); 11504 } else { 11505 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 11506 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 11507 } 11508 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11509 } 11510 11511 // Shared library native code should be in the APK zip aligned 11512 if (abi32 >= 0 && pkg.isLibrary() && extractLibs) { 11513 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 11514 "Shared library native lib extraction not supported"); 11515 } 11516 11517 maybeThrowExceptionForMultiArchCopy( 11518 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 11519 11520 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 11521 if (extractLibs) { 11522 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 11523 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 11524 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 11525 useIsaSpecificSubdirs); 11526 } else { 11527 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 11528 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 11529 } 11530 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11531 } 11532 11533 maybeThrowExceptionForMultiArchCopy( 11534 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 11535 11536 if (abi64 >= 0) { 11537 // Shared library native libs should be in the APK zip aligned 11538 if (extractLibs && pkg.isLibrary()) { 11539 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 11540 "Shared library native lib extraction not supported"); 11541 } 11542 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 11543 } 11544 11545 if (abi32 >= 0) { 11546 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 11547 if (abi64 >= 0) { 11548 if (pkg.use32bitAbi) { 11549 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 11550 pkg.applicationInfo.primaryCpuAbi = abi; 11551 } else { 11552 pkg.applicationInfo.secondaryCpuAbi = abi; 11553 } 11554 } else { 11555 pkg.applicationInfo.primaryCpuAbi = abi; 11556 } 11557 } 11558 } else { 11559 String[] abiList = (cpuAbiOverride != null) ? 11560 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 11561 11562 // Enable gross and lame hacks for apps that are built with old 11563 // SDK tools. We must scan their APKs for renderscript bitcode and 11564 // not launch them if it's present. Don't bother checking on devices 11565 // that don't have 64 bit support. 11566 boolean needsRenderScriptOverride = false; 11567 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 11568 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 11569 abiList = Build.SUPPORTED_32_BIT_ABIS; 11570 needsRenderScriptOverride = true; 11571 } 11572 11573 final int copyRet; 11574 if (extractLibs) { 11575 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 11576 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 11577 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 11578 } else { 11579 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 11580 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 11581 } 11582 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11583 11584 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 11585 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 11586 "Error unpackaging native libs for app, errorCode=" + copyRet); 11587 } 11588 11589 if (copyRet >= 0) { 11590 // Shared libraries that have native libs must be multi-architecture 11591 if (pkg.isLibrary()) { 11592 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 11593 "Shared library with native libs must be multiarch"); 11594 } 11595 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 11596 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 11597 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 11598 } else if (needsRenderScriptOverride) { 11599 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 11600 } 11601 } 11602 } catch (IOException ioe) { 11603 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 11604 } finally { 11605 IoUtils.closeQuietly(handle); 11606 } 11607 11608 // Now that we've calculated the ABIs and determined if it's an internal app, 11609 // we will go ahead and populate the nativeLibraryPath. 11610 setNativeLibraryPaths(pkg, appLib32InstallDir); 11611 } 11612 11613 /** 11614 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 11615 * i.e, so that all packages can be run inside a single process if required. 11616 * 11617 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 11618 * this function will either try and make the ABI for all packages in {@code packagesForUser} 11619 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 11620 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 11621 * updating a package that belongs to a shared user. 11622 * 11623 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 11624 * adds unnecessary complexity. 11625 */ 11626 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 11627 PackageParser.Package scannedPackage) { 11628 String requiredInstructionSet = null; 11629 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 11630 requiredInstructionSet = VMRuntime.getInstructionSet( 11631 scannedPackage.applicationInfo.primaryCpuAbi); 11632 } 11633 11634 PackageSetting requirer = null; 11635 for (PackageSetting ps : packagesForUser) { 11636 // If packagesForUser contains scannedPackage, we skip it. This will happen 11637 // when scannedPackage is an update of an existing package. Without this check, 11638 // we will never be able to change the ABI of any package belonging to a shared 11639 // user, even if it's compatible with other packages. 11640 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 11641 if (ps.primaryCpuAbiString == null) { 11642 continue; 11643 } 11644 11645 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 11646 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 11647 // We have a mismatch between instruction sets (say arm vs arm64) warn about 11648 // this but there's not much we can do. 11649 String errorMessage = "Instruction set mismatch, " 11650 + ((requirer == null) ? "[caller]" : requirer) 11651 + " requires " + requiredInstructionSet + " whereas " + ps 11652 + " requires " + instructionSet; 11653 Slog.w(TAG, errorMessage); 11654 } 11655 11656 if (requiredInstructionSet == null) { 11657 requiredInstructionSet = instructionSet; 11658 requirer = ps; 11659 } 11660 } 11661 } 11662 11663 if (requiredInstructionSet != null) { 11664 String adjustedAbi; 11665 if (requirer != null) { 11666 // requirer != null implies that either scannedPackage was null or that scannedPackage 11667 // did not require an ABI, in which case we have to adjust scannedPackage to match 11668 // the ABI of the set (which is the same as requirer's ABI) 11669 adjustedAbi = requirer.primaryCpuAbiString; 11670 if (scannedPackage != null) { 11671 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 11672 } 11673 } else { 11674 // requirer == null implies that we're updating all ABIs in the set to 11675 // match scannedPackage. 11676 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 11677 } 11678 11679 for (PackageSetting ps : packagesForUser) { 11680 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 11681 if (ps.primaryCpuAbiString != null) { 11682 continue; 11683 } 11684 11685 ps.primaryCpuAbiString = adjustedAbi; 11686 if (ps.pkg != null && ps.pkg.applicationInfo != null && 11687 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 11688 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 11689 if (DEBUG_ABI_SELECTION) { 11690 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 11691 + " (requirer=" 11692 + (requirer != null ? requirer.pkg : "null") 11693 + ", scannedPackage=" 11694 + (scannedPackage != null ? scannedPackage : "null") 11695 + ")"); 11696 } 11697 try { 11698 mInstaller.rmdex(ps.codePathString, 11699 getDexCodeInstructionSet(getPreferredInstructionSet())); 11700 } catch (InstallerException ignored) { 11701 } 11702 } 11703 } 11704 } 11705 } 11706 } 11707 11708 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 11709 synchronized (mPackages) { 11710 mResolverReplaced = true; 11711 // Set up information for custom user intent resolution activity. 11712 mResolveActivity.applicationInfo = pkg.applicationInfo; 11713 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 11714 mResolveActivity.packageName = pkg.applicationInfo.packageName; 11715 mResolveActivity.processName = pkg.applicationInfo.packageName; 11716 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 11717 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 11718 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 11719 mResolveActivity.theme = 0; 11720 mResolveActivity.exported = true; 11721 mResolveActivity.enabled = true; 11722 mResolveInfo.activityInfo = mResolveActivity; 11723 mResolveInfo.priority = 0; 11724 mResolveInfo.preferredOrder = 0; 11725 mResolveInfo.match = 0; 11726 mResolveComponentName = mCustomResolverComponentName; 11727 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 11728 mResolveComponentName); 11729 } 11730 } 11731 11732 private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) { 11733 if (installerActivity == null) { 11734 if (DEBUG_EPHEMERAL) { 11735 Slog.d(TAG, "Clear ephemeral installer activity"); 11736 } 11737 mInstantAppInstallerActivity = null; 11738 return; 11739 } 11740 11741 if (DEBUG_EPHEMERAL) { 11742 Slog.d(TAG, "Set ephemeral installer activity: " 11743 + installerActivity.getComponentName()); 11744 } 11745 // Set up information for ephemeral installer activity 11746 mInstantAppInstallerActivity = installerActivity; 11747 mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS 11748 | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 11749 mInstantAppInstallerActivity.exported = true; 11750 mInstantAppInstallerActivity.enabled = true; 11751 mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity; 11752 mInstantAppInstallerInfo.priority = 0; 11753 mInstantAppInstallerInfo.preferredOrder = 1; 11754 mInstantAppInstallerInfo.isDefault = true; 11755 mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 11756 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 11757 } 11758 11759 private static String calculateBundledApkRoot(final String codePathString) { 11760 final File codePath = new File(codePathString); 11761 final File codeRoot; 11762 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 11763 codeRoot = Environment.getRootDirectory(); 11764 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 11765 codeRoot = Environment.getOemDirectory(); 11766 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 11767 codeRoot = Environment.getVendorDirectory(); 11768 } else { 11769 // Unrecognized code path; take its top real segment as the apk root: 11770 // e.g. /something/app/blah.apk => /something 11771 try { 11772 File f = codePath.getCanonicalFile(); 11773 File parent = f.getParentFile(); // non-null because codePath is a file 11774 File tmp; 11775 while ((tmp = parent.getParentFile()) != null) { 11776 f = parent; 11777 parent = tmp; 11778 } 11779 codeRoot = f; 11780 Slog.w(TAG, "Unrecognized code path " 11781 + codePath + " - using " + codeRoot); 11782 } catch (IOException e) { 11783 // Can't canonicalize the code path -- shenanigans? 11784 Slog.w(TAG, "Can't canonicalize code path " + codePath); 11785 return Environment.getRootDirectory().getPath(); 11786 } 11787 } 11788 return codeRoot.getPath(); 11789 } 11790 11791 /** 11792 * Derive and set the location of native libraries for the given package, 11793 * which varies depending on where and how the package was installed. 11794 */ 11795 private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) { 11796 final ApplicationInfo info = pkg.applicationInfo; 11797 final String codePath = pkg.codePath; 11798 final File codeFile = new File(codePath); 11799 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 11800 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 11801 11802 info.nativeLibraryRootDir = null; 11803 info.nativeLibraryRootRequiresIsa = false; 11804 info.nativeLibraryDir = null; 11805 info.secondaryNativeLibraryDir = null; 11806 11807 if (isApkFile(codeFile)) { 11808 // Monolithic install 11809 if (bundledApp) { 11810 // If "/system/lib64/apkname" exists, assume that is the per-package 11811 // native library directory to use; otherwise use "/system/lib/apkname". 11812 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 11813 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 11814 getPrimaryInstructionSet(info)); 11815 11816 // This is a bundled system app so choose the path based on the ABI. 11817 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 11818 // is just the default path. 11819 final String apkName = deriveCodePathName(codePath); 11820 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 11821 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 11822 apkName).getAbsolutePath(); 11823 11824 if (info.secondaryCpuAbi != null) { 11825 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 11826 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 11827 secondaryLibDir, apkName).getAbsolutePath(); 11828 } 11829 } else if (asecApp) { 11830 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 11831 .getAbsolutePath(); 11832 } else { 11833 final String apkName = deriveCodePathName(codePath); 11834 info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName) 11835 .getAbsolutePath(); 11836 } 11837 11838 info.nativeLibraryRootRequiresIsa = false; 11839 info.nativeLibraryDir = info.nativeLibraryRootDir; 11840 } else { 11841 // Cluster install 11842 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 11843 info.nativeLibraryRootRequiresIsa = true; 11844 11845 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 11846 getPrimaryInstructionSet(info)).getAbsolutePath(); 11847 11848 if (info.secondaryCpuAbi != null) { 11849 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 11850 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 11851 } 11852 } 11853 } 11854 11855 /** 11856 * Calculate the abis and roots for a bundled app. These can uniquely 11857 * be determined from the contents of the system partition, i.e whether 11858 * it contains 64 or 32 bit shared libraries etc. We do not validate any 11859 * of this information, and instead assume that the system was built 11860 * sensibly. 11861 */ 11862 private static void setBundledAppAbisAndRoots(PackageParser.Package pkg, 11863 PackageSetting pkgSetting) { 11864 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 11865 11866 // If "/system/lib64/apkname" exists, assume that is the per-package 11867 // native library directory to use; otherwise use "/system/lib/apkname". 11868 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 11869 setBundledAppAbi(pkg, apkRoot, apkName); 11870 // pkgSetting might be null during rescan following uninstall of updates 11871 // to a bundled app, so accommodate that possibility. The settings in 11872 // that case will be established later from the parsed package. 11873 // 11874 // If the settings aren't null, sync them up with what we've just derived. 11875 // note that apkRoot isn't stored in the package settings. 11876 if (pkgSetting != null) { 11877 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 11878 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 11879 } 11880 } 11881 11882 /** 11883 * Deduces the ABI of a bundled app and sets the relevant fields on the 11884 * parsed pkg object. 11885 * 11886 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 11887 * under which system libraries are installed. 11888 * @param apkName the name of the installed package. 11889 */ 11890 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 11891 final File codeFile = new File(pkg.codePath); 11892 11893 final boolean has64BitLibs; 11894 final boolean has32BitLibs; 11895 if (isApkFile(codeFile)) { 11896 // Monolithic install 11897 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 11898 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 11899 } else { 11900 // Cluster install 11901 final File rootDir = new File(codeFile, LIB_DIR_NAME); 11902 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 11903 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 11904 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 11905 has64BitLibs = (new File(rootDir, isa)).exists(); 11906 } else { 11907 has64BitLibs = false; 11908 } 11909 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 11910 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 11911 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 11912 has32BitLibs = (new File(rootDir, isa)).exists(); 11913 } else { 11914 has32BitLibs = false; 11915 } 11916 } 11917 11918 if (has64BitLibs && !has32BitLibs) { 11919 // The package has 64 bit libs, but not 32 bit libs. Its primary 11920 // ABI should be 64 bit. We can safely assume here that the bundled 11921 // native libraries correspond to the most preferred ABI in the list. 11922 11923 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 11924 pkg.applicationInfo.secondaryCpuAbi = null; 11925 } else if (has32BitLibs && !has64BitLibs) { 11926 // The package has 32 bit libs but not 64 bit libs. Its primary 11927 // ABI should be 32 bit. 11928 11929 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 11930 pkg.applicationInfo.secondaryCpuAbi = null; 11931 } else if (has32BitLibs && has64BitLibs) { 11932 // The application has both 64 and 32 bit bundled libraries. We check 11933 // here that the app declares multiArch support, and warn if it doesn't. 11934 // 11935 // We will be lenient here and record both ABIs. The primary will be the 11936 // ABI that's higher on the list, i.e, a device that's configured to prefer 11937 // 64 bit apps will see a 64 bit primary ABI, 11938 11939 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 11940 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 11941 } 11942 11943 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 11944 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 11945 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 11946 } else { 11947 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 11948 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 11949 } 11950 } else { 11951 pkg.applicationInfo.primaryCpuAbi = null; 11952 pkg.applicationInfo.secondaryCpuAbi = null; 11953 } 11954 } 11955 11956 private void killApplication(String pkgName, int appId, String reason) { 11957 killApplication(pkgName, appId, UserHandle.USER_ALL, reason); 11958 } 11959 11960 private void killApplication(String pkgName, int appId, int userId, String reason) { 11961 // Request the ActivityManager to kill the process(only for existing packages) 11962 // so that we do not end up in a confused state while the user is still using the older 11963 // version of the application while the new one gets installed. 11964 final long token = Binder.clearCallingIdentity(); 11965 try { 11966 IActivityManager am = ActivityManager.getService(); 11967 if (am != null) { 11968 try { 11969 am.killApplication(pkgName, appId, userId, reason); 11970 } catch (RemoteException e) { 11971 } 11972 } 11973 } finally { 11974 Binder.restoreCallingIdentity(token); 11975 } 11976 } 11977 11978 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 11979 // Remove the parent package setting 11980 PackageSetting ps = (PackageSetting) pkg.mExtras; 11981 if (ps != null) { 11982 removePackageLI(ps, chatty); 11983 } 11984 // Remove the child package setting 11985 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 11986 for (int i = 0; i < childCount; i++) { 11987 PackageParser.Package childPkg = pkg.childPackages.get(i); 11988 ps = (PackageSetting) childPkg.mExtras; 11989 if (ps != null) { 11990 removePackageLI(ps, chatty); 11991 } 11992 } 11993 } 11994 11995 void removePackageLI(PackageSetting ps, boolean chatty) { 11996 if (DEBUG_INSTALL) { 11997 if (chatty) 11998 Log.d(TAG, "Removing package " + ps.name); 11999 } 12000 12001 // writer 12002 synchronized (mPackages) { 12003 mPackages.remove(ps.name); 12004 final PackageParser.Package pkg = ps.pkg; 12005 if (pkg != null) { 12006 cleanPackageDataStructuresLILPw(pkg, chatty); 12007 } 12008 } 12009 } 12010 12011 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 12012 if (DEBUG_INSTALL) { 12013 if (chatty) 12014 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 12015 } 12016 12017 // writer 12018 synchronized (mPackages) { 12019 // Remove the parent package 12020 mPackages.remove(pkg.applicationInfo.packageName); 12021 cleanPackageDataStructuresLILPw(pkg, chatty); 12022 12023 // Remove the child packages 12024 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 12025 for (int i = 0; i < childCount; i++) { 12026 PackageParser.Package childPkg = pkg.childPackages.get(i); 12027 mPackages.remove(childPkg.applicationInfo.packageName); 12028 cleanPackageDataStructuresLILPw(childPkg, chatty); 12029 } 12030 } 12031 } 12032 12033 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 12034 int N = pkg.providers.size(); 12035 StringBuilder r = null; 12036 int i; 12037 for (i=0; i<N; i++) { 12038 PackageParser.Provider p = pkg.providers.get(i); 12039 mProviders.removeProvider(p); 12040 if (p.info.authority == null) { 12041 12042 /* There was another ContentProvider with this authority when 12043 * this app was installed so this authority is null, 12044 * Ignore it as we don't have to unregister the provider. 12045 */ 12046 continue; 12047 } 12048 String names[] = p.info.authority.split(";"); 12049 for (int j = 0; j < names.length; j++) { 12050 if (mProvidersByAuthority.get(names[j]) == p) { 12051 mProvidersByAuthority.remove(names[j]); 12052 if (DEBUG_REMOVE) { 12053 if (chatty) 12054 Log.d(TAG, "Unregistered content provider: " + names[j] 12055 + ", className = " + p.info.name + ", isSyncable = " 12056 + p.info.isSyncable); 12057 } 12058 } 12059 } 12060 if (DEBUG_REMOVE && chatty) { 12061 if (r == null) { 12062 r = new StringBuilder(256); 12063 } else { 12064 r.append(' '); 12065 } 12066 r.append(p.info.name); 12067 } 12068 } 12069 if (r != null) { 12070 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 12071 } 12072 12073 N = pkg.services.size(); 12074 r = null; 12075 for (i=0; i<N; i++) { 12076 PackageParser.Service s = pkg.services.get(i); 12077 mServices.removeService(s); 12078 if (chatty) { 12079 if (r == null) { 12080 r = new StringBuilder(256); 12081 } else { 12082 r.append(' '); 12083 } 12084 r.append(s.info.name); 12085 } 12086 } 12087 if (r != null) { 12088 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 12089 } 12090 12091 N = pkg.receivers.size(); 12092 r = null; 12093 for (i=0; i<N; i++) { 12094 PackageParser.Activity a = pkg.receivers.get(i); 12095 mReceivers.removeActivity(a, "receiver"); 12096 if (DEBUG_REMOVE && chatty) { 12097 if (r == null) { 12098 r = new StringBuilder(256); 12099 } else { 12100 r.append(' '); 12101 } 12102 r.append(a.info.name); 12103 } 12104 } 12105 if (r != null) { 12106 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 12107 } 12108 12109 N = pkg.activities.size(); 12110 r = null; 12111 for (i=0; i<N; i++) { 12112 PackageParser.Activity a = pkg.activities.get(i); 12113 mActivities.removeActivity(a, "activity"); 12114 if (DEBUG_REMOVE && chatty) { 12115 if (r == null) { 12116 r = new StringBuilder(256); 12117 } else { 12118 r.append(' '); 12119 } 12120 r.append(a.info.name); 12121 } 12122 } 12123 if (r != null) { 12124 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 12125 } 12126 12127 N = pkg.permissions.size(); 12128 r = null; 12129 for (i=0; i<N; i++) { 12130 PackageParser.Permission p = pkg.permissions.get(i); 12131 BasePermission bp = mSettings.mPermissions.get(p.info.name); 12132 if (bp == null) { 12133 bp = mSettings.mPermissionTrees.get(p.info.name); 12134 } 12135 if (bp != null && bp.perm == p) { 12136 bp.perm = null; 12137 if (DEBUG_REMOVE && chatty) { 12138 if (r == null) { 12139 r = new StringBuilder(256); 12140 } else { 12141 r.append(' '); 12142 } 12143 r.append(p.info.name); 12144 } 12145 } 12146 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 12147 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 12148 if (appOpPkgs != null) { 12149 appOpPkgs.remove(pkg.packageName); 12150 } 12151 } 12152 } 12153 if (r != null) { 12154 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 12155 } 12156 12157 N = pkg.requestedPermissions.size(); 12158 r = null; 12159 for (i=0; i<N; i++) { 12160 String perm = pkg.requestedPermissions.get(i); 12161 BasePermission bp = mSettings.mPermissions.get(perm); 12162 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 12163 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 12164 if (appOpPkgs != null) { 12165 appOpPkgs.remove(pkg.packageName); 12166 if (appOpPkgs.isEmpty()) { 12167 mAppOpPermissionPackages.remove(perm); 12168 } 12169 } 12170 } 12171 } 12172 if (r != null) { 12173 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 12174 } 12175 12176 N = pkg.instrumentation.size(); 12177 r = null; 12178 for (i=0; i<N; i++) { 12179 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 12180 mInstrumentation.remove(a.getComponentName()); 12181 if (DEBUG_REMOVE && chatty) { 12182 if (r == null) { 12183 r = new StringBuilder(256); 12184 } else { 12185 r.append(' '); 12186 } 12187 r.append(a.info.name); 12188 } 12189 } 12190 if (r != null) { 12191 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 12192 } 12193 12194 r = null; 12195 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 12196 // Only system apps can hold shared libraries. 12197 if (pkg.libraryNames != null) { 12198 for (i = 0; i < pkg.libraryNames.size(); i++) { 12199 String name = pkg.libraryNames.get(i); 12200 if (removeSharedLibraryLPw(name, 0)) { 12201 if (DEBUG_REMOVE && chatty) { 12202 if (r == null) { 12203 r = new StringBuilder(256); 12204 } else { 12205 r.append(' '); 12206 } 12207 r.append(name); 12208 } 12209 } 12210 } 12211 } 12212 } 12213 12214 r = null; 12215 12216 // Any package can hold static shared libraries. 12217 if (pkg.staticSharedLibName != null) { 12218 if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) { 12219 if (DEBUG_REMOVE && chatty) { 12220 if (r == null) { 12221 r = new StringBuilder(256); 12222 } else { 12223 r.append(' '); 12224 } 12225 r.append(pkg.staticSharedLibName); 12226 } 12227 } 12228 } 12229 12230 if (r != null) { 12231 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 12232 } 12233 } 12234 12235 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 12236 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 12237 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 12238 return true; 12239 } 12240 } 12241 return false; 12242 } 12243 12244 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 12245 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 12246 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 12247 12248 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 12249 // Update the parent permissions 12250 updatePermissionsLPw(pkg.packageName, pkg, flags); 12251 // Update the child permissions 12252 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 12253 for (int i = 0; i < childCount; i++) { 12254 PackageParser.Package childPkg = pkg.childPackages.get(i); 12255 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 12256 } 12257 } 12258 12259 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 12260 int flags) { 12261 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 12262 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 12263 } 12264 12265 private void updatePermissionsLPw(String changingPkg, 12266 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 12267 // Make sure there are no dangling permission trees. 12268 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 12269 while (it.hasNext()) { 12270 final BasePermission bp = it.next(); 12271 if (bp.packageSetting == null) { 12272 // We may not yet have parsed the package, so just see if 12273 // we still know about its settings. 12274 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 12275 } 12276 if (bp.packageSetting == null) { 12277 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 12278 + " from package " + bp.sourcePackage); 12279 it.remove(); 12280 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 12281 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 12282 Slog.i(TAG, "Removing old permission tree: " + bp.name 12283 + " from package " + bp.sourcePackage); 12284 flags |= UPDATE_PERMISSIONS_ALL; 12285 it.remove(); 12286 } 12287 } 12288 } 12289 12290 // Make sure all dynamic permissions have been assigned to a package, 12291 // and make sure there are no dangling permissions. 12292 it = mSettings.mPermissions.values().iterator(); 12293 while (it.hasNext()) { 12294 final BasePermission bp = it.next(); 12295 if (bp.type == BasePermission.TYPE_DYNAMIC) { 12296 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 12297 + bp.name + " pkg=" + bp.sourcePackage 12298 + " info=" + bp.pendingInfo); 12299 if (bp.packageSetting == null && bp.pendingInfo != null) { 12300 final BasePermission tree = findPermissionTreeLP(bp.name); 12301 if (tree != null && tree.perm != null) { 12302 bp.packageSetting = tree.packageSetting; 12303 bp.perm = new PackageParser.Permission(tree.perm.owner, 12304 new PermissionInfo(bp.pendingInfo)); 12305 bp.perm.info.packageName = tree.perm.info.packageName; 12306 bp.perm.info.name = bp.name; 12307 bp.uid = tree.uid; 12308 } 12309 } 12310 } 12311 if (bp.packageSetting == null) { 12312 // We may not yet have parsed the package, so just see if 12313 // we still know about its settings. 12314 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 12315 } 12316 if (bp.packageSetting == null) { 12317 Slog.w(TAG, "Removing dangling permission: " + bp.name 12318 + " from package " + bp.sourcePackage); 12319 it.remove(); 12320 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 12321 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 12322 Slog.i(TAG, "Removing old permission: " + bp.name 12323 + " from package " + bp.sourcePackage); 12324 flags |= UPDATE_PERMISSIONS_ALL; 12325 it.remove(); 12326 } 12327 } 12328 } 12329 12330 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 12331 // Now update the permissions for all packages, in particular 12332 // replace the granted permissions of the system packages. 12333 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 12334 for (PackageParser.Package pkg : mPackages.values()) { 12335 if (pkg != pkgInfo) { 12336 // Only replace for packages on requested volume 12337 final String volumeUuid = getVolumeUuidForPackage(pkg); 12338 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 12339 && Objects.equals(replaceVolumeUuid, volumeUuid); 12340 grantPermissionsLPw(pkg, replace, changingPkg); 12341 } 12342 } 12343 } 12344 12345 if (pkgInfo != null) { 12346 // Only replace for packages on requested volume 12347 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 12348 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 12349 && Objects.equals(replaceVolumeUuid, volumeUuid); 12350 grantPermissionsLPw(pkgInfo, replace, changingPkg); 12351 } 12352 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12353 } 12354 12355 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 12356 String packageOfInterest) { 12357 // IMPORTANT: There are two types of permissions: install and runtime. 12358 // Install time permissions are granted when the app is installed to 12359 // all device users and users added in the future. Runtime permissions 12360 // are granted at runtime explicitly to specific users. Normal and signature 12361 // protected permissions are install time permissions. Dangerous permissions 12362 // are install permissions if the app's target SDK is Lollipop MR1 or older, 12363 // otherwise they are runtime permissions. This function does not manage 12364 // runtime permissions except for the case an app targeting Lollipop MR1 12365 // being upgraded to target a newer SDK, in which case dangerous permissions 12366 // are transformed from install time to runtime ones. 12367 12368 final PackageSetting ps = (PackageSetting) pkg.mExtras; 12369 if (ps == null) { 12370 return; 12371 } 12372 12373 PermissionsState permissionsState = ps.getPermissionsState(); 12374 PermissionsState origPermissions = permissionsState; 12375 12376 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 12377 12378 boolean runtimePermissionsRevoked = false; 12379 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 12380 12381 boolean changedInstallPermission = false; 12382 12383 if (replace) { 12384 ps.installPermissionsFixed = false; 12385 if (!ps.isSharedUser()) { 12386 origPermissions = new PermissionsState(permissionsState); 12387 permissionsState.reset(); 12388 } else { 12389 // We need to know only about runtime permission changes since the 12390 // calling code always writes the install permissions state but 12391 // the runtime ones are written only if changed. The only cases of 12392 // changed runtime permissions here are promotion of an install to 12393 // runtime and revocation of a runtime from a shared user. 12394 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 12395 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 12396 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 12397 runtimePermissionsRevoked = true; 12398 } 12399 } 12400 } 12401 12402 permissionsState.setGlobalGids(mGlobalGids); 12403 12404 final int N = pkg.requestedPermissions.size(); 12405 for (int i=0; i<N; i++) { 12406 final String name = pkg.requestedPermissions.get(i); 12407 final BasePermission bp = mSettings.mPermissions.get(name); 12408 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 12409 >= Build.VERSION_CODES.M; 12410 12411 if (DEBUG_INSTALL) { 12412 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 12413 } 12414 12415 if (bp == null || bp.packageSetting == null) { 12416 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 12417 if (DEBUG_PERMISSIONS) { 12418 Slog.i(TAG, "Unknown permission " + name 12419 + " in package " + pkg.packageName); 12420 } 12421 } 12422 continue; 12423 } 12424 12425 12426 // Limit ephemeral apps to ephemeral allowed permissions. 12427 if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) { 12428 if (DEBUG_PERMISSIONS) { 12429 Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package " 12430 + pkg.packageName); 12431 } 12432 continue; 12433 } 12434 12435 if (bp.isRuntimeOnly() && !appSupportsRuntimePermissions) { 12436 if (DEBUG_PERMISSIONS) { 12437 Log.i(TAG, "Denying runtime-only permission " + bp.name + " for package " 12438 + pkg.packageName); 12439 } 12440 continue; 12441 } 12442 12443 final String perm = bp.name; 12444 boolean allowedSig = false; 12445 int grant = GRANT_DENIED; 12446 12447 // Keep track of app op permissions. 12448 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 12449 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 12450 if (pkgs == null) { 12451 pkgs = new ArraySet<>(); 12452 mAppOpPermissionPackages.put(bp.name, pkgs); 12453 } 12454 pkgs.add(pkg.packageName); 12455 } 12456 12457 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 12458 switch (level) { 12459 case PermissionInfo.PROTECTION_NORMAL: { 12460 // For all apps normal permissions are install time ones. 12461 grant = GRANT_INSTALL; 12462 } break; 12463 12464 case PermissionInfo.PROTECTION_DANGEROUS: { 12465 // If a permission review is required for legacy apps we represent 12466 // their permissions as always granted runtime ones since we need 12467 // to keep the review required permission flag per user while an 12468 // install permission's state is shared across all users. 12469 if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) { 12470 // For legacy apps dangerous permissions are install time ones. 12471 grant = GRANT_INSTALL; 12472 } else if (origPermissions.hasInstallPermission(bp.name)) { 12473 // For legacy apps that became modern, install becomes runtime. 12474 grant = GRANT_UPGRADE; 12475 } else if (mPromoteSystemApps 12476 && isSystemApp(ps) 12477 && mExistingSystemPackages.contains(ps.name)) { 12478 // For legacy system apps, install becomes runtime. 12479 // We cannot check hasInstallPermission() for system apps since those 12480 // permissions were granted implicitly and not persisted pre-M. 12481 grant = GRANT_UPGRADE; 12482 } else { 12483 // For modern apps keep runtime permissions unchanged. 12484 grant = GRANT_RUNTIME; 12485 } 12486 } break; 12487 12488 case PermissionInfo.PROTECTION_SIGNATURE: { 12489 // For all apps signature permissions are install time ones. 12490 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 12491 if (allowedSig) { 12492 grant = GRANT_INSTALL; 12493 } 12494 } break; 12495 } 12496 12497 if (DEBUG_PERMISSIONS) { 12498 Slog.i(TAG, "Granting permission " + perm + " to package " + pkg.packageName); 12499 } 12500 12501 if (grant != GRANT_DENIED) { 12502 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 12503 // If this is an existing, non-system package, then 12504 // we can't add any new permissions to it. 12505 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 12506 // Except... if this is a permission that was added 12507 // to the platform (note: need to only do this when 12508 // updating the platform). 12509 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 12510 grant = GRANT_DENIED; 12511 } 12512 } 12513 } 12514 12515 switch (grant) { 12516 case GRANT_INSTALL: { 12517 // Revoke this as runtime permission to handle the case of 12518 // a runtime permission being downgraded to an install one. 12519 // Also in permission review mode we keep dangerous permissions 12520 // for legacy apps 12521 for (int userId : UserManagerService.getInstance().getUserIds()) { 12522 if (origPermissions.getRuntimePermissionState( 12523 bp.name, userId) != null) { 12524 // Revoke the runtime permission and clear the flags. 12525 origPermissions.revokeRuntimePermission(bp, userId); 12526 origPermissions.updatePermissionFlags(bp, userId, 12527 PackageManager.MASK_PERMISSION_FLAGS, 0); 12528 // If we revoked a permission permission, we have to write. 12529 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 12530 changedRuntimePermissionUserIds, userId); 12531 } 12532 } 12533 // Grant an install permission. 12534 if (permissionsState.grantInstallPermission(bp) != 12535 PermissionsState.PERMISSION_OPERATION_FAILURE) { 12536 changedInstallPermission = true; 12537 } 12538 } break; 12539 12540 case GRANT_RUNTIME: { 12541 // Grant previously granted runtime permissions. 12542 for (int userId : UserManagerService.getInstance().getUserIds()) { 12543 PermissionState permissionState = origPermissions 12544 .getRuntimePermissionState(bp.name, userId); 12545 int flags = permissionState != null 12546 ? permissionState.getFlags() : 0; 12547 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 12548 // Don't propagate the permission in a permission review mode if 12549 // the former was revoked, i.e. marked to not propagate on upgrade. 12550 // Note that in a permission review mode install permissions are 12551 // represented as constantly granted runtime ones since we need to 12552 // keep a per user state associated with the permission. Also the 12553 // revoke on upgrade flag is no longer applicable and is reset. 12554 final boolean revokeOnUpgrade = (flags & PackageManager 12555 .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 12556 if (revokeOnUpgrade) { 12557 flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 12558 // Since we changed the flags, we have to write. 12559 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 12560 changedRuntimePermissionUserIds, userId); 12561 } 12562 if (!mPermissionReviewRequired || !revokeOnUpgrade) { 12563 if (permissionsState.grantRuntimePermission(bp, userId) == 12564 PermissionsState.PERMISSION_OPERATION_FAILURE) { 12565 // If we cannot put the permission as it was, 12566 // we have to write. 12567 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 12568 changedRuntimePermissionUserIds, userId); 12569 } 12570 } 12571 12572 // If the app supports runtime permissions no need for a review. 12573 if (mPermissionReviewRequired 12574 && appSupportsRuntimePermissions 12575 && (flags & PackageManager 12576 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 12577 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 12578 // Since we changed the flags, we have to write. 12579 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 12580 changedRuntimePermissionUserIds, userId); 12581 } 12582 } else if (mPermissionReviewRequired 12583 && !appSupportsRuntimePermissions) { 12584 // For legacy apps that need a permission review, every new 12585 // runtime permission is granted but it is pending a review. 12586 // We also need to review only platform defined runtime 12587 // permissions as these are the only ones the platform knows 12588 // how to disable the API to simulate revocation as legacy 12589 // apps don't expect to run with revoked permissions. 12590 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 12591 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 12592 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 12593 // We changed the flags, hence have to write. 12594 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 12595 changedRuntimePermissionUserIds, userId); 12596 } 12597 } 12598 if (permissionsState.grantRuntimePermission(bp, userId) 12599 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 12600 // We changed the permission, hence have to write. 12601 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 12602 changedRuntimePermissionUserIds, userId); 12603 } 12604 } 12605 // Propagate the permission flags. 12606 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 12607 } 12608 } break; 12609 12610 case GRANT_UPGRADE: { 12611 // Grant runtime permissions for a previously held install permission. 12612 PermissionState permissionState = origPermissions 12613 .getInstallPermissionState(bp.name); 12614 final int flags = permissionState != null ? permissionState.getFlags() : 0; 12615 12616 if (origPermissions.revokeInstallPermission(bp) 12617 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 12618 // We will be transferring the permission flags, so clear them. 12619 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 12620 PackageManager.MASK_PERMISSION_FLAGS, 0); 12621 changedInstallPermission = true; 12622 } 12623 12624 // If the permission is not to be promoted to runtime we ignore it and 12625 // also its other flags as they are not applicable to install permissions. 12626 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 12627 for (int userId : currentUserIds) { 12628 if (permissionsState.grantRuntimePermission(bp, userId) != 12629 PermissionsState.PERMISSION_OPERATION_FAILURE) { 12630 // Transfer the permission flags. 12631 permissionsState.updatePermissionFlags(bp, userId, 12632 flags, flags); 12633 // If we granted the permission, we have to write. 12634 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 12635 changedRuntimePermissionUserIds, userId); 12636 } 12637 } 12638 } 12639 } break; 12640 12641 default: { 12642 if (packageOfInterest == null 12643 || packageOfInterest.equals(pkg.packageName)) { 12644 if (DEBUG_PERMISSIONS) { 12645 Slog.i(TAG, "Not granting permission " + perm 12646 + " to package " + pkg.packageName 12647 + " because it was previously installed without"); 12648 } 12649 } 12650 } break; 12651 } 12652 } else { 12653 if (permissionsState.revokeInstallPermission(bp) != 12654 PermissionsState.PERMISSION_OPERATION_FAILURE) { 12655 // Also drop the permission flags. 12656 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 12657 PackageManager.MASK_PERMISSION_FLAGS, 0); 12658 changedInstallPermission = true; 12659 Slog.i(TAG, "Un-granting permission " + perm 12660 + " from package " + pkg.packageName 12661 + " (protectionLevel=" + bp.protectionLevel 12662 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 12663 + ")"); 12664 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 12665 // Don't print warning for app op permissions, since it is fine for them 12666 // not to be granted, there is a UI for the user to decide. 12667 if (DEBUG_PERMISSIONS 12668 && (packageOfInterest == null 12669 || packageOfInterest.equals(pkg.packageName))) { 12670 Slog.i(TAG, "Not granting permission " + perm 12671 + " to package " + pkg.packageName 12672 + " (protectionLevel=" + bp.protectionLevel 12673 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 12674 + ")"); 12675 } 12676 } 12677 } 12678 } 12679 12680 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 12681 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 12682 // This is the first that we have heard about this package, so the 12683 // permissions we have now selected are fixed until explicitly 12684 // changed. 12685 ps.installPermissionsFixed = true; 12686 } 12687 12688 // Persist the runtime permissions state for users with changes. If permissions 12689 // were revoked because no app in the shared user declares them we have to 12690 // write synchronously to avoid losing runtime permissions state. 12691 for (int userId : changedRuntimePermissionUserIds) { 12692 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 12693 } 12694 } 12695 12696 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 12697 boolean allowed = false; 12698 final int NP = PackageParser.NEW_PERMISSIONS.length; 12699 for (int ip=0; ip<NP; ip++) { 12700 final PackageParser.NewPermissionInfo npi 12701 = PackageParser.NEW_PERMISSIONS[ip]; 12702 if (npi.name.equals(perm) 12703 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 12704 allowed = true; 12705 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 12706 + pkg.packageName); 12707 break; 12708 } 12709 } 12710 return allowed; 12711 } 12712 12713 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 12714 BasePermission bp, PermissionsState origPermissions) { 12715 boolean privilegedPermission = (bp.protectionLevel 12716 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0; 12717 boolean privappPermissionsDisable = 12718 RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE; 12719 boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage); 12720 boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName); 12721 if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp() 12722 && !platformPackage && platformPermission) { 12723 ArraySet<String> wlPermissions = SystemConfig.getInstance() 12724 .getPrivAppPermissions(pkg.packageName); 12725 boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm); 12726 if (!whitelisted) { 12727 Slog.w(TAG, "Privileged permission " + perm + " for package " 12728 + pkg.packageName + " - not in privapp-permissions whitelist"); 12729 // Only report violations for apps on system image 12730 if (!mSystemReady && !pkg.isUpdatedSystemApp()) { 12731 if (mPrivappPermissionsViolations == null) { 12732 mPrivappPermissionsViolations = new ArraySet<>(); 12733 } 12734 mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm); 12735 } 12736 if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) { 12737 return false; 12738 } 12739 } 12740 } 12741 boolean allowed = (compareSignatures( 12742 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 12743 == PackageManager.SIGNATURE_MATCH) 12744 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 12745 == PackageManager.SIGNATURE_MATCH); 12746 if (!allowed && privilegedPermission) { 12747 if (isSystemApp(pkg)) { 12748 // For updated system applications, a system permission 12749 // is granted only if it had been defined by the original application. 12750 if (pkg.isUpdatedSystemApp()) { 12751 final PackageSetting sysPs = mSettings 12752 .getDisabledSystemPkgLPr(pkg.packageName); 12753 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 12754 // If the original was granted this permission, we take 12755 // that grant decision as read and propagate it to the 12756 // update. 12757 if (sysPs.isPrivileged()) { 12758 allowed = true; 12759 } 12760 } else { 12761 // The system apk may have been updated with an older 12762 // version of the one on the data partition, but which 12763 // granted a new system permission that it didn't have 12764 // before. In this case we do want to allow the app to 12765 // now get the new permission if the ancestral apk is 12766 // privileged to get it. 12767 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 12768 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 12769 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 12770 allowed = true; 12771 break; 12772 } 12773 } 12774 } 12775 // Also if a privileged parent package on the system image or any of 12776 // its children requested a privileged permission, the updated child 12777 // packages can also get the permission. 12778 if (pkg.parentPackage != null) { 12779 final PackageSetting disabledSysParentPs = mSettings 12780 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 12781 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 12782 && disabledSysParentPs.isPrivileged()) { 12783 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 12784 allowed = true; 12785 } else if (disabledSysParentPs.pkg.childPackages != null) { 12786 final int count = disabledSysParentPs.pkg.childPackages.size(); 12787 for (int i = 0; i < count; i++) { 12788 PackageParser.Package disabledSysChildPkg = 12789 disabledSysParentPs.pkg.childPackages.get(i); 12790 if (isPackageRequestingPermission(disabledSysChildPkg, 12791 perm)) { 12792 allowed = true; 12793 break; 12794 } 12795 } 12796 } 12797 } 12798 } 12799 } 12800 } else { 12801 allowed = isPrivilegedApp(pkg); 12802 } 12803 } 12804 } 12805 if (!allowed) { 12806 if (!allowed && (bp.protectionLevel 12807 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 12808 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 12809 // If this was a previously normal/dangerous permission that got moved 12810 // to a system permission as part of the runtime permission redesign, then 12811 // we still want to blindly grant it to old apps. 12812 allowed = true; 12813 } 12814 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 12815 && pkg.packageName.equals(mRequiredInstallerPackage)) { 12816 // If this permission is to be granted to the system installer and 12817 // this app is an installer, then it gets the permission. 12818 allowed = true; 12819 } 12820 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 12821 && pkg.packageName.equals(mRequiredVerifierPackage)) { 12822 // If this permission is to be granted to the system verifier and 12823 // this app is a verifier, then it gets the permission. 12824 allowed = true; 12825 } 12826 if (!allowed && (bp.protectionLevel 12827 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 12828 && isSystemApp(pkg)) { 12829 // Any pre-installed system app is allowed to get this permission. 12830 allowed = true; 12831 } 12832 if (!allowed && (bp.protectionLevel 12833 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 12834 // For development permissions, a development permission 12835 // is granted only if it was already granted. 12836 allowed = origPermissions.hasInstallPermission(perm); 12837 } 12838 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 12839 && pkg.packageName.equals(mSetupWizardPackage)) { 12840 // If this permission is to be granted to the system setup wizard and 12841 // this app is a setup wizard, then it gets the permission. 12842 allowed = true; 12843 } 12844 } 12845 return allowed; 12846 } 12847 12848 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 12849 final int permCount = pkg.requestedPermissions.size(); 12850 for (int j = 0; j < permCount; j++) { 12851 String requestedPermission = pkg.requestedPermissions.get(j); 12852 if (permission.equals(requestedPermission)) { 12853 return true; 12854 } 12855 } 12856 return false; 12857 } 12858 12859 final class ActivityIntentResolver 12860 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 12861 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12862 boolean defaultOnly, int userId) { 12863 if (!sUserManager.exists(userId)) return null; 12864 mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0); 12865 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 12866 } 12867 12868 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12869 int userId) { 12870 if (!sUserManager.exists(userId)) return null; 12871 mFlags = flags; 12872 return super.queryIntent(intent, resolvedType, 12873 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12874 userId); 12875 } 12876 12877 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12878 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 12879 if (!sUserManager.exists(userId)) return null; 12880 if (packageActivities == null) { 12881 return null; 12882 } 12883 mFlags = flags; 12884 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 12885 final int N = packageActivities.size(); 12886 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 12887 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 12888 12889 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 12890 for (int i = 0; i < N; ++i) { 12891 intentFilters = packageActivities.get(i).intents; 12892 if (intentFilters != null && intentFilters.size() > 0) { 12893 PackageParser.ActivityIntentInfo[] array = 12894 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 12895 intentFilters.toArray(array); 12896 listCut.add(array); 12897 } 12898 } 12899 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 12900 } 12901 12902 /** 12903 * Finds a privileged activity that matches the specified activity names. 12904 */ 12905 private PackageParser.Activity findMatchingActivity( 12906 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 12907 for (PackageParser.Activity sysActivity : activityList) { 12908 if (sysActivity.info.name.equals(activityInfo.name)) { 12909 return sysActivity; 12910 } 12911 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 12912 return sysActivity; 12913 } 12914 if (sysActivity.info.targetActivity != null) { 12915 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 12916 return sysActivity; 12917 } 12918 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 12919 return sysActivity; 12920 } 12921 } 12922 } 12923 return null; 12924 } 12925 12926 public class IterGenerator<E> { 12927 public Iterator<E> generate(ActivityIntentInfo info) { 12928 return null; 12929 } 12930 } 12931 12932 public class ActionIterGenerator extends IterGenerator<String> { 12933 @Override 12934 public Iterator<String> generate(ActivityIntentInfo info) { 12935 return info.actionsIterator(); 12936 } 12937 } 12938 12939 public class CategoriesIterGenerator extends IterGenerator<String> { 12940 @Override 12941 public Iterator<String> generate(ActivityIntentInfo info) { 12942 return info.categoriesIterator(); 12943 } 12944 } 12945 12946 public class SchemesIterGenerator extends IterGenerator<String> { 12947 @Override 12948 public Iterator<String> generate(ActivityIntentInfo info) { 12949 return info.schemesIterator(); 12950 } 12951 } 12952 12953 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 12954 @Override 12955 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 12956 return info.authoritiesIterator(); 12957 } 12958 } 12959 12960 /** 12961 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 12962 * MODIFIED. Do not pass in a list that should not be changed. 12963 */ 12964 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 12965 IterGenerator<T> generator, Iterator<T> searchIterator) { 12966 // loop through the set of actions; every one must be found in the intent filter 12967 while (searchIterator.hasNext()) { 12968 // we must have at least one filter in the list to consider a match 12969 if (intentList.size() == 0) { 12970 break; 12971 } 12972 12973 final T searchAction = searchIterator.next(); 12974 12975 // loop through the set of intent filters 12976 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 12977 while (intentIter.hasNext()) { 12978 final ActivityIntentInfo intentInfo = intentIter.next(); 12979 boolean selectionFound = false; 12980 12981 // loop through the intent filter's selection criteria; at least one 12982 // of them must match the searched criteria 12983 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 12984 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 12985 final T intentSelection = intentSelectionIter.next(); 12986 if (intentSelection != null && intentSelection.equals(searchAction)) { 12987 selectionFound = true; 12988 break; 12989 } 12990 } 12991 12992 // the selection criteria wasn't found in this filter's set; this filter 12993 // is not a potential match 12994 if (!selectionFound) { 12995 intentIter.remove(); 12996 } 12997 } 12998 } 12999 } 13000 13001 private boolean isProtectedAction(ActivityIntentInfo filter) { 13002 final Iterator<String> actionsIter = filter.actionsIterator(); 13003 while (actionsIter != null && actionsIter.hasNext()) { 13004 final String filterAction = actionsIter.next(); 13005 if (PROTECTED_ACTIONS.contains(filterAction)) { 13006 return true; 13007 } 13008 } 13009 return false; 13010 } 13011 13012 /** 13013 * Adjusts the priority of the given intent filter according to policy. 13014 * <p> 13015 * <ul> 13016 * <li>The priority for non privileged applications is capped to '0'</li> 13017 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 13018 * <li>The priority for unbundled updates to privileged applications is capped to the 13019 * priority defined on the system partition</li> 13020 * </ul> 13021 * <p> 13022 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 13023 * allowed to obtain any priority on any action. 13024 */ 13025 private void adjustPriority( 13026 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 13027 // nothing to do; priority is fine as-is 13028 if (intent.getPriority() <= 0) { 13029 return; 13030 } 13031 13032 final ActivityInfo activityInfo = intent.activity.info; 13033 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 13034 13035 final boolean privilegedApp = 13036 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 13037 if (!privilegedApp) { 13038 // non-privileged applications can never define a priority >0 13039 if (DEBUG_FILTERS) { 13040 Slog.i(TAG, "Non-privileged app; cap priority to 0;" 13041 + " package: " + applicationInfo.packageName 13042 + " activity: " + intent.activity.className 13043 + " origPrio: " + intent.getPriority()); 13044 } 13045 intent.setPriority(0); 13046 return; 13047 } 13048 13049 if (systemActivities == null) { 13050 // the system package is not disabled; we're parsing the system partition 13051 if (isProtectedAction(intent)) { 13052 if (mDeferProtectedFilters) { 13053 // We can't deal with these just yet. No component should ever obtain a 13054 // >0 priority for a protected actions, with ONE exception -- the setup 13055 // wizard. The setup wizard, however, cannot be known until we're able to 13056 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 13057 // until all intent filters have been processed. Chicken, meet egg. 13058 // Let the filter temporarily have a high priority and rectify the 13059 // priorities after all system packages have been scanned. 13060 mProtectedFilters.add(intent); 13061 if (DEBUG_FILTERS) { 13062 Slog.i(TAG, "Protected action; save for later;" 13063 + " package: " + applicationInfo.packageName 13064 + " activity: " + intent.activity.className 13065 + " origPrio: " + intent.getPriority()); 13066 } 13067 return; 13068 } else { 13069 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 13070 Slog.i(TAG, "No setup wizard;" 13071 + " All protected intents capped to priority 0"); 13072 } 13073 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 13074 if (DEBUG_FILTERS) { 13075 Slog.i(TAG, "Found setup wizard;" 13076 + " allow priority " + intent.getPriority() + ";" 13077 + " package: " + intent.activity.info.packageName 13078 + " activity: " + intent.activity.className 13079 + " priority: " + intent.getPriority()); 13080 } 13081 // setup wizard gets whatever it wants 13082 return; 13083 } 13084 if (DEBUG_FILTERS) { 13085 Slog.i(TAG, "Protected action; cap priority to 0;" 13086 + " package: " + intent.activity.info.packageName 13087 + " activity: " + intent.activity.className 13088 + " origPrio: " + intent.getPriority()); 13089 } 13090 intent.setPriority(0); 13091 return; 13092 } 13093 } 13094 // privileged apps on the system image get whatever priority they request 13095 return; 13096 } 13097 13098 // privileged app unbundled update ... try to find the same activity 13099 final PackageParser.Activity foundActivity = 13100 findMatchingActivity(systemActivities, activityInfo); 13101 if (foundActivity == null) { 13102 // this is a new activity; it cannot obtain >0 priority 13103 if (DEBUG_FILTERS) { 13104 Slog.i(TAG, "New activity; cap priority to 0;" 13105 + " package: " + applicationInfo.packageName 13106 + " activity: " + intent.activity.className 13107 + " origPrio: " + intent.getPriority()); 13108 } 13109 intent.setPriority(0); 13110 return; 13111 } 13112 13113 // found activity, now check for filter equivalence 13114 13115 // a shallow copy is enough; we modify the list, not its contents 13116 final List<ActivityIntentInfo> intentListCopy = 13117 new ArrayList<>(foundActivity.intents); 13118 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 13119 13120 // find matching action subsets 13121 final Iterator<String> actionsIterator = intent.actionsIterator(); 13122 if (actionsIterator != null) { 13123 getIntentListSubset( 13124 intentListCopy, new ActionIterGenerator(), actionsIterator); 13125 if (intentListCopy.size() == 0) { 13126 // no more intents to match; we're not equivalent 13127 if (DEBUG_FILTERS) { 13128 Slog.i(TAG, "Mismatched action; cap priority to 0;" 13129 + " package: " + applicationInfo.packageName 13130 + " activity: " + intent.activity.className 13131 + " origPrio: " + intent.getPriority()); 13132 } 13133 intent.setPriority(0); 13134 return; 13135 } 13136 } 13137 13138 // find matching category subsets 13139 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 13140 if (categoriesIterator != null) { 13141 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 13142 categoriesIterator); 13143 if (intentListCopy.size() == 0) { 13144 // no more intents to match; we're not equivalent 13145 if (DEBUG_FILTERS) { 13146 Slog.i(TAG, "Mismatched category; cap priority to 0;" 13147 + " package: " + applicationInfo.packageName 13148 + " activity: " + intent.activity.className 13149 + " origPrio: " + intent.getPriority()); 13150 } 13151 intent.setPriority(0); 13152 return; 13153 } 13154 } 13155 13156 // find matching schemes subsets 13157 final Iterator<String> schemesIterator = intent.schemesIterator(); 13158 if (schemesIterator != null) { 13159 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 13160 schemesIterator); 13161 if (intentListCopy.size() == 0) { 13162 // no more intents to match; we're not equivalent 13163 if (DEBUG_FILTERS) { 13164 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 13165 + " package: " + applicationInfo.packageName 13166 + " activity: " + intent.activity.className 13167 + " origPrio: " + intent.getPriority()); 13168 } 13169 intent.setPriority(0); 13170 return; 13171 } 13172 } 13173 13174 // find matching authorities subsets 13175 final Iterator<IntentFilter.AuthorityEntry> 13176 authoritiesIterator = intent.authoritiesIterator(); 13177 if (authoritiesIterator != null) { 13178 getIntentListSubset(intentListCopy, 13179 new AuthoritiesIterGenerator(), 13180 authoritiesIterator); 13181 if (intentListCopy.size() == 0) { 13182 // no more intents to match; we're not equivalent 13183 if (DEBUG_FILTERS) { 13184 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 13185 + " package: " + applicationInfo.packageName 13186 + " activity: " + intent.activity.className 13187 + " origPrio: " + intent.getPriority()); 13188 } 13189 intent.setPriority(0); 13190 return; 13191 } 13192 } 13193 13194 // we found matching filter(s); app gets the max priority of all intents 13195 int cappedPriority = 0; 13196 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 13197 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 13198 } 13199 if (intent.getPriority() > cappedPriority) { 13200 if (DEBUG_FILTERS) { 13201 Slog.i(TAG, "Found matching filter(s);" 13202 + " cap priority to " + cappedPriority + ";" 13203 + " package: " + applicationInfo.packageName 13204 + " activity: " + intent.activity.className 13205 + " origPrio: " + intent.getPriority()); 13206 } 13207 intent.setPriority(cappedPriority); 13208 return; 13209 } 13210 // all this for nothing; the requested priority was <= what was on the system 13211 } 13212 13213 public final void addActivity(PackageParser.Activity a, String type) { 13214 mActivities.put(a.getComponentName(), a); 13215 if (DEBUG_SHOW_INFO) 13216 Log.v( 13217 TAG, " " + type + " " + 13218 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 13219 if (DEBUG_SHOW_INFO) 13220 Log.v(TAG, " Class=" + a.info.name); 13221 final int NI = a.intents.size(); 13222 for (int j=0; j<NI; j++) { 13223 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 13224 if ("activity".equals(type)) { 13225 final PackageSetting ps = 13226 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 13227 final List<PackageParser.Activity> systemActivities = 13228 ps != null && ps.pkg != null ? ps.pkg.activities : null; 13229 adjustPriority(systemActivities, intent); 13230 } 13231 if (DEBUG_SHOW_INFO) { 13232 Log.v(TAG, " IntentFilter:"); 13233 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 13234 } 13235 if (!intent.debugCheck()) { 13236 Log.w(TAG, "==> For Activity " + a.info.name); 13237 } 13238 addFilter(intent); 13239 } 13240 } 13241 13242 public final void removeActivity(PackageParser.Activity a, String type) { 13243 mActivities.remove(a.getComponentName()); 13244 if (DEBUG_SHOW_INFO) { 13245 Log.v(TAG, " " + type + " " 13246 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 13247 : a.info.name) + ":"); 13248 Log.v(TAG, " Class=" + a.info.name); 13249 } 13250 final int NI = a.intents.size(); 13251 for (int j=0; j<NI; j++) { 13252 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 13253 if (DEBUG_SHOW_INFO) { 13254 Log.v(TAG, " IntentFilter:"); 13255 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 13256 } 13257 removeFilter(intent); 13258 } 13259 } 13260 13261 @Override 13262 protected boolean allowFilterResult( 13263 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 13264 ActivityInfo filterAi = filter.activity.info; 13265 for (int i=dest.size()-1; i>=0; i--) { 13266 ActivityInfo destAi = dest.get(i).activityInfo; 13267 if (destAi.name == filterAi.name 13268 && destAi.packageName == filterAi.packageName) { 13269 return false; 13270 } 13271 } 13272 return true; 13273 } 13274 13275 @Override 13276 protected ActivityIntentInfo[] newArray(int size) { 13277 return new ActivityIntentInfo[size]; 13278 } 13279 13280 @Override 13281 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 13282 if (!sUserManager.exists(userId)) return true; 13283 PackageParser.Package p = filter.activity.owner; 13284 if (p != null) { 13285 PackageSetting ps = (PackageSetting)p.mExtras; 13286 if (ps != null) { 13287 // System apps are never considered stopped for purposes of 13288 // filtering, because there may be no way for the user to 13289 // actually re-launch them. 13290 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 13291 && ps.getStopped(userId); 13292 } 13293 } 13294 return false; 13295 } 13296 13297 @Override 13298 protected boolean isPackageForFilter(String packageName, 13299 PackageParser.ActivityIntentInfo info) { 13300 return packageName.equals(info.activity.owner.packageName); 13301 } 13302 13303 @Override 13304 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 13305 int match, int userId) { 13306 if (!sUserManager.exists(userId)) return null; 13307 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 13308 return null; 13309 } 13310 final PackageParser.Activity activity = info.activity; 13311 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 13312 if (ps == null) { 13313 return null; 13314 } 13315 final PackageUserState userState = ps.readUserState(userId); 13316 ActivityInfo ai = 13317 PackageParser.generateActivityInfo(activity, mFlags, userState, userId); 13318 if (ai == null) { 13319 return null; 13320 } 13321 final boolean matchExplicitlyVisibleOnly = 13322 (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0; 13323 final boolean matchVisibleToInstantApp = 13324 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 13325 final boolean componentVisible = 13326 matchVisibleToInstantApp 13327 && info.isVisibleToInstantApp() 13328 && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp()); 13329 final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 13330 // throw out filters that aren't visible to ephemeral apps 13331 if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) { 13332 return null; 13333 } 13334 // throw out instant app filters if we're not explicitly requesting them 13335 if (!matchInstantApp && userState.instantApp) { 13336 return null; 13337 } 13338 // throw out instant app filters if updates are available; will trigger 13339 // instant app resolution 13340 if (userState.instantApp && ps.isUpdateAvailable()) { 13341 return null; 13342 } 13343 final ResolveInfo res = new ResolveInfo(); 13344 res.activityInfo = ai; 13345 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 13346 res.filter = info; 13347 } 13348 if (info != null) { 13349 res.handleAllWebDataURI = info.handleAllWebDataURI(); 13350 } 13351 res.priority = info.getPriority(); 13352 res.preferredOrder = activity.owner.mPreferredOrder; 13353 //System.out.println("Result: " + res.activityInfo.className + 13354 // " = " + res.priority); 13355 res.match = match; 13356 res.isDefault = info.hasDefault; 13357 res.labelRes = info.labelRes; 13358 res.nonLocalizedLabel = info.nonLocalizedLabel; 13359 if (userNeedsBadging(userId)) { 13360 res.noResourceId = true; 13361 } else { 13362 res.icon = info.icon; 13363 } 13364 res.iconResourceId = info.icon; 13365 res.system = res.activityInfo.applicationInfo.isSystemApp(); 13366 res.isInstantAppAvailable = userState.instantApp; 13367 return res; 13368 } 13369 13370 @Override 13371 protected void sortResults(List<ResolveInfo> results) { 13372 Collections.sort(results, mResolvePrioritySorter); 13373 } 13374 13375 @Override 13376 protected void dumpFilter(PrintWriter out, String prefix, 13377 PackageParser.ActivityIntentInfo filter) { 13378 out.print(prefix); out.print( 13379 Integer.toHexString(System.identityHashCode(filter.activity))); 13380 out.print(' '); 13381 filter.activity.printComponentShortName(out); 13382 out.print(" filter "); 13383 out.println(Integer.toHexString(System.identityHashCode(filter))); 13384 } 13385 13386 @Override 13387 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 13388 return filter.activity; 13389 } 13390 13391 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 13392 PackageParser.Activity activity = (PackageParser.Activity)label; 13393 out.print(prefix); out.print( 13394 Integer.toHexString(System.identityHashCode(activity))); 13395 out.print(' '); 13396 activity.printComponentShortName(out); 13397 if (count > 1) { 13398 out.print(" ("); out.print(count); out.print(" filters)"); 13399 } 13400 out.println(); 13401 } 13402 13403 // Keys are String (activity class name), values are Activity. 13404 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 13405 = new ArrayMap<ComponentName, PackageParser.Activity>(); 13406 private int mFlags; 13407 } 13408 13409 private final class ServiceIntentResolver 13410 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 13411 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 13412 boolean defaultOnly, int userId) { 13413 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 13414 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 13415 } 13416 13417 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 13418 int userId) { 13419 if (!sUserManager.exists(userId)) return null; 13420 mFlags = flags; 13421 return super.queryIntent(intent, resolvedType, 13422 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 13423 userId); 13424 } 13425 13426 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 13427 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 13428 if (!sUserManager.exists(userId)) return null; 13429 if (packageServices == null) { 13430 return null; 13431 } 13432 mFlags = flags; 13433 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 13434 final int N = packageServices.size(); 13435 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 13436 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 13437 13438 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 13439 for (int i = 0; i < N; ++i) { 13440 intentFilters = packageServices.get(i).intents; 13441 if (intentFilters != null && intentFilters.size() > 0) { 13442 PackageParser.ServiceIntentInfo[] array = 13443 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 13444 intentFilters.toArray(array); 13445 listCut.add(array); 13446 } 13447 } 13448 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 13449 } 13450 13451 public final void addService(PackageParser.Service s) { 13452 mServices.put(s.getComponentName(), s); 13453 if (DEBUG_SHOW_INFO) { 13454 Log.v(TAG, " " 13455 + (s.info.nonLocalizedLabel != null 13456 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 13457 Log.v(TAG, " Class=" + s.info.name); 13458 } 13459 final int NI = s.intents.size(); 13460 int j; 13461 for (j=0; j<NI; j++) { 13462 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 13463 if (DEBUG_SHOW_INFO) { 13464 Log.v(TAG, " IntentFilter:"); 13465 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 13466 } 13467 if (!intent.debugCheck()) { 13468 Log.w(TAG, "==> For Service " + s.info.name); 13469 } 13470 addFilter(intent); 13471 } 13472 } 13473 13474 public final void removeService(PackageParser.Service s) { 13475 mServices.remove(s.getComponentName()); 13476 if (DEBUG_SHOW_INFO) { 13477 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 13478 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 13479 Log.v(TAG, " Class=" + s.info.name); 13480 } 13481 final int NI = s.intents.size(); 13482 int j; 13483 for (j=0; j<NI; j++) { 13484 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 13485 if (DEBUG_SHOW_INFO) { 13486 Log.v(TAG, " IntentFilter:"); 13487 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 13488 } 13489 removeFilter(intent); 13490 } 13491 } 13492 13493 @Override 13494 protected boolean allowFilterResult( 13495 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 13496 ServiceInfo filterSi = filter.service.info; 13497 for (int i=dest.size()-1; i>=0; i--) { 13498 ServiceInfo destAi = dest.get(i).serviceInfo; 13499 if (destAi.name == filterSi.name 13500 && destAi.packageName == filterSi.packageName) { 13501 return false; 13502 } 13503 } 13504 return true; 13505 } 13506 13507 @Override 13508 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 13509 return new PackageParser.ServiceIntentInfo[size]; 13510 } 13511 13512 @Override 13513 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 13514 if (!sUserManager.exists(userId)) return true; 13515 PackageParser.Package p = filter.service.owner; 13516 if (p != null) { 13517 PackageSetting ps = (PackageSetting)p.mExtras; 13518 if (ps != null) { 13519 // System apps are never considered stopped for purposes of 13520 // filtering, because there may be no way for the user to 13521 // actually re-launch them. 13522 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 13523 && ps.getStopped(userId); 13524 } 13525 } 13526 return false; 13527 } 13528 13529 @Override 13530 protected boolean isPackageForFilter(String packageName, 13531 PackageParser.ServiceIntentInfo info) { 13532 return packageName.equals(info.service.owner.packageName); 13533 } 13534 13535 @Override 13536 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 13537 int match, int userId) { 13538 if (!sUserManager.exists(userId)) return null; 13539 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 13540 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 13541 return null; 13542 } 13543 final PackageParser.Service service = info.service; 13544 PackageSetting ps = (PackageSetting) service.owner.mExtras; 13545 if (ps == null) { 13546 return null; 13547 } 13548 final PackageUserState userState = ps.readUserState(userId); 13549 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 13550 userState, userId); 13551 if (si == null) { 13552 return null; 13553 } 13554 final boolean matchVisibleToInstantApp = 13555 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 13556 final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 13557 // throw out filters that aren't visible to ephemeral apps 13558 if (matchVisibleToInstantApp 13559 && !(info.isVisibleToInstantApp() || userState.instantApp)) { 13560 return null; 13561 } 13562 // throw out ephemeral filters if we're not explicitly requesting them 13563 if (!isInstantApp && userState.instantApp) { 13564 return null; 13565 } 13566 // throw out instant app filters if updates are available; will trigger 13567 // instant app resolution 13568 if (userState.instantApp && ps.isUpdateAvailable()) { 13569 return null; 13570 } 13571 final ResolveInfo res = new ResolveInfo(); 13572 res.serviceInfo = si; 13573 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 13574 res.filter = filter; 13575 } 13576 res.priority = info.getPriority(); 13577 res.preferredOrder = service.owner.mPreferredOrder; 13578 res.match = match; 13579 res.isDefault = info.hasDefault; 13580 res.labelRes = info.labelRes; 13581 res.nonLocalizedLabel = info.nonLocalizedLabel; 13582 res.icon = info.icon; 13583 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 13584 return res; 13585 } 13586 13587 @Override 13588 protected void sortResults(List<ResolveInfo> results) { 13589 Collections.sort(results, mResolvePrioritySorter); 13590 } 13591 13592 @Override 13593 protected void dumpFilter(PrintWriter out, String prefix, 13594 PackageParser.ServiceIntentInfo filter) { 13595 out.print(prefix); out.print( 13596 Integer.toHexString(System.identityHashCode(filter.service))); 13597 out.print(' '); 13598 filter.service.printComponentShortName(out); 13599 out.print(" filter "); 13600 out.println(Integer.toHexString(System.identityHashCode(filter))); 13601 } 13602 13603 @Override 13604 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 13605 return filter.service; 13606 } 13607 13608 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 13609 PackageParser.Service service = (PackageParser.Service)label; 13610 out.print(prefix); out.print( 13611 Integer.toHexString(System.identityHashCode(service))); 13612 out.print(' '); 13613 service.printComponentShortName(out); 13614 if (count > 1) { 13615 out.print(" ("); out.print(count); out.print(" filters)"); 13616 } 13617 out.println(); 13618 } 13619 13620// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 13621// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 13622// final List<ResolveInfo> retList = Lists.newArrayList(); 13623// while (i.hasNext()) { 13624// final ResolveInfo resolveInfo = (ResolveInfo) i; 13625// if (isEnabledLP(resolveInfo.serviceInfo)) { 13626// retList.add(resolveInfo); 13627// } 13628// } 13629// return retList; 13630// } 13631 13632 // Keys are String (activity class name), values are Activity. 13633 private final ArrayMap<ComponentName, PackageParser.Service> mServices 13634 = new ArrayMap<ComponentName, PackageParser.Service>(); 13635 private int mFlags; 13636 } 13637 13638 private final class ProviderIntentResolver 13639 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 13640 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 13641 boolean defaultOnly, int userId) { 13642 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 13643 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 13644 } 13645 13646 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 13647 int userId) { 13648 if (!sUserManager.exists(userId)) 13649 return null; 13650 mFlags = flags; 13651 return super.queryIntent(intent, resolvedType, 13652 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 13653 userId); 13654 } 13655 13656 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 13657 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 13658 if (!sUserManager.exists(userId)) 13659 return null; 13660 if (packageProviders == null) { 13661 return null; 13662 } 13663 mFlags = flags; 13664 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 13665 final int N = packageProviders.size(); 13666 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 13667 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 13668 13669 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 13670 for (int i = 0; i < N; ++i) { 13671 intentFilters = packageProviders.get(i).intents; 13672 if (intentFilters != null && intentFilters.size() > 0) { 13673 PackageParser.ProviderIntentInfo[] array = 13674 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 13675 intentFilters.toArray(array); 13676 listCut.add(array); 13677 } 13678 } 13679 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 13680 } 13681 13682 public final void addProvider(PackageParser.Provider p) { 13683 if (mProviders.containsKey(p.getComponentName())) { 13684 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 13685 return; 13686 } 13687 13688 mProviders.put(p.getComponentName(), p); 13689 if (DEBUG_SHOW_INFO) { 13690 Log.v(TAG, " " 13691 + (p.info.nonLocalizedLabel != null 13692 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 13693 Log.v(TAG, " Class=" + p.info.name); 13694 } 13695 final int NI = p.intents.size(); 13696 int j; 13697 for (j = 0; j < NI; j++) { 13698 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 13699 if (DEBUG_SHOW_INFO) { 13700 Log.v(TAG, " IntentFilter:"); 13701 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 13702 } 13703 if (!intent.debugCheck()) { 13704 Log.w(TAG, "==> For Provider " + p.info.name); 13705 } 13706 addFilter(intent); 13707 } 13708 } 13709 13710 public final void removeProvider(PackageParser.Provider p) { 13711 mProviders.remove(p.getComponentName()); 13712 if (DEBUG_SHOW_INFO) { 13713 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 13714 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 13715 Log.v(TAG, " Class=" + p.info.name); 13716 } 13717 final int NI = p.intents.size(); 13718 int j; 13719 for (j = 0; j < NI; j++) { 13720 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 13721 if (DEBUG_SHOW_INFO) { 13722 Log.v(TAG, " IntentFilter:"); 13723 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 13724 } 13725 removeFilter(intent); 13726 } 13727 } 13728 13729 @Override 13730 protected boolean allowFilterResult( 13731 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 13732 ProviderInfo filterPi = filter.provider.info; 13733 for (int i = dest.size() - 1; i >= 0; i--) { 13734 ProviderInfo destPi = dest.get(i).providerInfo; 13735 if (destPi.name == filterPi.name 13736 && destPi.packageName == filterPi.packageName) { 13737 return false; 13738 } 13739 } 13740 return true; 13741 } 13742 13743 @Override 13744 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 13745 return new PackageParser.ProviderIntentInfo[size]; 13746 } 13747 13748 @Override 13749 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 13750 if (!sUserManager.exists(userId)) 13751 return true; 13752 PackageParser.Package p = filter.provider.owner; 13753 if (p != null) { 13754 PackageSetting ps = (PackageSetting) p.mExtras; 13755 if (ps != null) { 13756 // System apps are never considered stopped for purposes of 13757 // filtering, because there may be no way for the user to 13758 // actually re-launch them. 13759 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 13760 && ps.getStopped(userId); 13761 } 13762 } 13763 return false; 13764 } 13765 13766 @Override 13767 protected boolean isPackageForFilter(String packageName, 13768 PackageParser.ProviderIntentInfo info) { 13769 return packageName.equals(info.provider.owner.packageName); 13770 } 13771 13772 @Override 13773 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 13774 int match, int userId) { 13775 if (!sUserManager.exists(userId)) 13776 return null; 13777 final PackageParser.ProviderIntentInfo info = filter; 13778 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 13779 return null; 13780 } 13781 final PackageParser.Provider provider = info.provider; 13782 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 13783 if (ps == null) { 13784 return null; 13785 } 13786 final PackageUserState userState = ps.readUserState(userId); 13787 final boolean matchVisibleToInstantApp = 13788 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 13789 final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 13790 // throw out filters that aren't visible to instant applications 13791 if (matchVisibleToInstantApp 13792 && !(info.isVisibleToInstantApp() || userState.instantApp)) { 13793 return null; 13794 } 13795 // throw out instant application filters if we're not explicitly requesting them 13796 if (!isInstantApp && userState.instantApp) { 13797 return null; 13798 } 13799 // throw out instant application filters if updates are available; will trigger 13800 // instant application resolution 13801 if (userState.instantApp && ps.isUpdateAvailable()) { 13802 return null; 13803 } 13804 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 13805 userState, userId); 13806 if (pi == null) { 13807 return null; 13808 } 13809 final ResolveInfo res = new ResolveInfo(); 13810 res.providerInfo = pi; 13811 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 13812 res.filter = filter; 13813 } 13814 res.priority = info.getPriority(); 13815 res.preferredOrder = provider.owner.mPreferredOrder; 13816 res.match = match; 13817 res.isDefault = info.hasDefault; 13818 res.labelRes = info.labelRes; 13819 res.nonLocalizedLabel = info.nonLocalizedLabel; 13820 res.icon = info.icon; 13821 res.system = res.providerInfo.applicationInfo.isSystemApp(); 13822 return res; 13823 } 13824 13825 @Override 13826 protected void sortResults(List<ResolveInfo> results) { 13827 Collections.sort(results, mResolvePrioritySorter); 13828 } 13829 13830 @Override 13831 protected void dumpFilter(PrintWriter out, String prefix, 13832 PackageParser.ProviderIntentInfo filter) { 13833 out.print(prefix); 13834 out.print( 13835 Integer.toHexString(System.identityHashCode(filter.provider))); 13836 out.print(' '); 13837 filter.provider.printComponentShortName(out); 13838 out.print(" filter "); 13839 out.println(Integer.toHexString(System.identityHashCode(filter))); 13840 } 13841 13842 @Override 13843 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 13844 return filter.provider; 13845 } 13846 13847 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 13848 PackageParser.Provider provider = (PackageParser.Provider)label; 13849 out.print(prefix); out.print( 13850 Integer.toHexString(System.identityHashCode(provider))); 13851 out.print(' '); 13852 provider.printComponentShortName(out); 13853 if (count > 1) { 13854 out.print(" ("); out.print(count); out.print(" filters)"); 13855 } 13856 out.println(); 13857 } 13858 13859 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 13860 = new ArrayMap<ComponentName, PackageParser.Provider>(); 13861 private int mFlags; 13862 } 13863 13864 static final class EphemeralIntentResolver 13865 extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> { 13866 /** 13867 * The result that has the highest defined order. Ordering applies on a 13868 * per-package basis. Mapping is from package name to Pair of order and 13869 * EphemeralResolveInfo. 13870 * <p> 13871 * NOTE: This is implemented as a field variable for convenience and efficiency. 13872 * By having a field variable, we're able to track filter ordering as soon as 13873 * a non-zero order is defined. Otherwise, multiple loops across the result set 13874 * would be needed to apply ordering. If the intent resolver becomes re-entrant, 13875 * this needs to be contained entirely within {@link #filterResults}. 13876 */ 13877 final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>(); 13878 13879 @Override 13880 protected AuxiliaryResolveInfo[] newArray(int size) { 13881 return new AuxiliaryResolveInfo[size]; 13882 } 13883 13884 @Override 13885 protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) { 13886 return true; 13887 } 13888 13889 @Override 13890 protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match, 13891 int userId) { 13892 if (!sUserManager.exists(userId)) { 13893 return null; 13894 } 13895 final String packageName = responseObj.resolveInfo.getPackageName(); 13896 final Integer order = responseObj.getOrder(); 13897 final Pair<Integer, InstantAppResolveInfo> lastOrderResult = 13898 mOrderResult.get(packageName); 13899 // ordering is enabled and this item's order isn't high enough 13900 if (lastOrderResult != null && lastOrderResult.first >= order) { 13901 return null; 13902 } 13903 final InstantAppResolveInfo res = responseObj.resolveInfo; 13904 if (order > 0) { 13905 // non-zero order, enable ordering 13906 mOrderResult.put(packageName, new Pair<>(order, res)); 13907 } 13908 return responseObj; 13909 } 13910 13911 @Override 13912 protected void filterResults(List<AuxiliaryResolveInfo> results) { 13913 // only do work if ordering is enabled [most of the time it won't be] 13914 if (mOrderResult.size() == 0) { 13915 return; 13916 } 13917 int resultSize = results.size(); 13918 for (int i = 0; i < resultSize; i++) { 13919 final InstantAppResolveInfo info = results.get(i).resolveInfo; 13920 final String packageName = info.getPackageName(); 13921 final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName); 13922 if (savedInfo == null) { 13923 // package doesn't having ordering 13924 continue; 13925 } 13926 if (savedInfo.second == info) { 13927 // circled back to the highest ordered item; remove from order list 13928 mOrderResult.remove(savedInfo); 13929 if (mOrderResult.size() == 0) { 13930 // no more ordered items 13931 break; 13932 } 13933 continue; 13934 } 13935 // item has a worse order, remove it from the result list 13936 results.remove(i); 13937 resultSize--; 13938 i--; 13939 } 13940 } 13941 } 13942 13943 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 13944 new Comparator<ResolveInfo>() { 13945 public int compare(ResolveInfo r1, ResolveInfo r2) { 13946 int v1 = r1.priority; 13947 int v2 = r2.priority; 13948 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 13949 if (v1 != v2) { 13950 return (v1 > v2) ? -1 : 1; 13951 } 13952 v1 = r1.preferredOrder; 13953 v2 = r2.preferredOrder; 13954 if (v1 != v2) { 13955 return (v1 > v2) ? -1 : 1; 13956 } 13957 if (r1.isDefault != r2.isDefault) { 13958 return r1.isDefault ? -1 : 1; 13959 } 13960 v1 = r1.match; 13961 v2 = r2.match; 13962 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 13963 if (v1 != v2) { 13964 return (v1 > v2) ? -1 : 1; 13965 } 13966 if (r1.system != r2.system) { 13967 return r1.system ? -1 : 1; 13968 } 13969 if (r1.activityInfo != null) { 13970 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 13971 } 13972 if (r1.serviceInfo != null) { 13973 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 13974 } 13975 if (r1.providerInfo != null) { 13976 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 13977 } 13978 return 0; 13979 } 13980 }; 13981 13982 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 13983 new Comparator<ProviderInfo>() { 13984 public int compare(ProviderInfo p1, ProviderInfo p2) { 13985 final int v1 = p1.initOrder; 13986 final int v2 = p2.initOrder; 13987 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 13988 } 13989 }; 13990 13991 public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 13992 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 13993 final int[] userIds) { 13994 mHandler.post(new Runnable() { 13995 @Override 13996 public void run() { 13997 try { 13998 final IActivityManager am = ActivityManager.getService(); 13999 if (am == null) return; 14000 final int[] resolvedUserIds; 14001 if (userIds == null) { 14002 resolvedUserIds = am.getRunningUserIds(); 14003 } else { 14004 resolvedUserIds = userIds; 14005 } 14006 for (int id : resolvedUserIds) { 14007 final Intent intent = new Intent(action, 14008 pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null); 14009 if (extras != null) { 14010 intent.putExtras(extras); 14011 } 14012 if (targetPkg != null) { 14013 intent.setPackage(targetPkg); 14014 } 14015 // Modify the UID when posting to other users 14016 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 14017 if (uid > 0 && UserHandle.getUserId(uid) != id) { 14018 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 14019 intent.putExtra(Intent.EXTRA_UID, uid); 14020 } 14021 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 14022 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 14023 if (DEBUG_BROADCASTS) { 14024 RuntimeException here = new RuntimeException("here"); 14025 here.fillInStackTrace(); 14026 Slog.d(TAG, "Sending to user " + id + ": " 14027 + intent.toShortString(false, true, false, false) 14028 + " " + intent.getExtras(), here); 14029 } 14030 am.broadcastIntent(null, intent, null, finishedReceiver, 14031 0, null, null, null, android.app.AppOpsManager.OP_NONE, 14032 null, finishedReceiver != null, false, id); 14033 } 14034 } catch (RemoteException ex) { 14035 } 14036 } 14037 }); 14038 } 14039 14040 /** 14041 * Check if the external storage media is available. This is true if there 14042 * is a mounted external storage medium or if the external storage is 14043 * emulated. 14044 */ 14045 private boolean isExternalMediaAvailable() { 14046 return mMediaMounted || Environment.isExternalStorageEmulated(); 14047 } 14048 14049 @Override 14050 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 14051 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 14052 return null; 14053 } 14054 // writer 14055 synchronized (mPackages) { 14056 if (!isExternalMediaAvailable()) { 14057 // If the external storage is no longer mounted at this point, 14058 // the caller may not have been able to delete all of this 14059 // packages files and can not delete any more. Bail. 14060 return null; 14061 } 14062 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 14063 if (lastPackage != null) { 14064 pkgs.remove(lastPackage); 14065 } 14066 if (pkgs.size() > 0) { 14067 return pkgs.get(0); 14068 } 14069 } 14070 return null; 14071 } 14072 14073 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 14074 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 14075 userId, andCode ? 1 : 0, packageName); 14076 if (mSystemReady) { 14077 msg.sendToTarget(); 14078 } else { 14079 if (mPostSystemReadyMessages == null) { 14080 mPostSystemReadyMessages = new ArrayList<>(); 14081 } 14082 mPostSystemReadyMessages.add(msg); 14083 } 14084 } 14085 14086 void startCleaningPackages() { 14087 // reader 14088 if (!isExternalMediaAvailable()) { 14089 return; 14090 } 14091 synchronized (mPackages) { 14092 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 14093 return; 14094 } 14095 } 14096 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 14097 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 14098 IActivityManager am = ActivityManager.getService(); 14099 if (am != null) { 14100 int dcsUid = -1; 14101 synchronized (mPackages) { 14102 if (!mDefaultContainerWhitelisted) { 14103 mDefaultContainerWhitelisted = true; 14104 PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE); 14105 dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId); 14106 } 14107 } 14108 try { 14109 if (dcsUid > 0) { 14110 am.backgroundWhitelistUid(dcsUid); 14111 } 14112 am.startService(null, intent, null, false, mContext.getOpPackageName(), 14113 UserHandle.USER_SYSTEM); 14114 } catch (RemoteException e) { 14115 } 14116 } 14117 } 14118 14119 @Override 14120 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 14121 int installFlags, String installerPackageName, int userId) { 14122 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 14123 14124 final int callingUid = Binder.getCallingUid(); 14125 enforceCrossUserPermission(callingUid, userId, 14126 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 14127 14128 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 14129 try { 14130 if (observer != null) { 14131 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 14132 } 14133 } catch (RemoteException re) { 14134 } 14135 return; 14136 } 14137 14138 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 14139 installFlags |= PackageManager.INSTALL_FROM_ADB; 14140 14141 } else { 14142 // Caller holds INSTALL_PACKAGES permission, so we're less strict 14143 // about installerPackageName. 14144 14145 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 14146 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 14147 } 14148 14149 UserHandle user; 14150 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 14151 user = UserHandle.ALL; 14152 } else { 14153 user = new UserHandle(userId); 14154 } 14155 14156 // Only system components can circumvent runtime permissions when installing. 14157 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 14158 && mContext.checkCallingOrSelfPermission(Manifest.permission 14159 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 14160 throw new SecurityException("You need the " 14161 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 14162 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 14163 } 14164 14165 if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0 14166 || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 14167 throw new IllegalArgumentException( 14168 "New installs into ASEC containers no longer supported"); 14169 } 14170 14171 final File originFile = new File(originPath); 14172 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 14173 14174 final Message msg = mHandler.obtainMessage(INIT_COPY); 14175 final VerificationInfo verificationInfo = new VerificationInfo( 14176 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 14177 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 14178 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 14179 null /*packageAbiOverride*/, null /*grantedPermissions*/, 14180 null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN); 14181 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 14182 msg.obj = params; 14183 14184 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 14185 System.identityHashCode(msg.obj)); 14186 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 14187 System.identityHashCode(msg.obj)); 14188 14189 mHandler.sendMessage(msg); 14190 } 14191 14192 14193 /** 14194 * Ensure that the install reason matches what we know about the package installer (e.g. whether 14195 * it is acting on behalf on an enterprise or the user). 14196 * 14197 * Note that the ordering of the conditionals in this method is important. The checks we perform 14198 * are as follows, in this order: 14199 * 14200 * 1) If the install is being performed by a system app, we can trust the app to have set the 14201 * install reason correctly. Thus, we pass through the install reason unchanged, no matter 14202 * what it is. 14203 * 2) If the install is being performed by a device or profile owner app, the install reason 14204 * should be enterprise policy. However, we cannot be sure that the device or profile owner 14205 * set the install reason correctly. If the app targets an older SDK version where install 14206 * reasons did not exist yet, or if the app author simply forgot, the install reason may be 14207 * unset or wrong. Thus, we force the install reason to be enterprise policy. 14208 * 3) In all other cases, the install is being performed by a regular app that is neither part 14209 * of the system nor a device or profile owner. We have no reason to believe that this app is 14210 * acting on behalf of the enterprise admin. Thus, we check whether the install reason was 14211 * set to enterprise policy and if so, change it to unknown instead. 14212 */ 14213 private int fixUpInstallReason(String installerPackageName, int installerUid, 14214 int installReason) { 14215 if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid) 14216 == PERMISSION_GRANTED) { 14217 // If the install is being performed by a system app, we trust that app to have set the 14218 // install reason correctly. 14219 return installReason; 14220 } 14221 14222 final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 14223 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 14224 if (dpm != null) { 14225 ComponentName owner = null; 14226 try { 14227 owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */); 14228 if (owner == null) { 14229 owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid)); 14230 } 14231 } catch (RemoteException e) { 14232 } 14233 if (owner != null && owner.getPackageName().equals(installerPackageName)) { 14234 // If the install is being performed by a device or profile owner, the install 14235 // reason should be enterprise policy. 14236 return PackageManager.INSTALL_REASON_POLICY; 14237 } 14238 } 14239 14240 if (installReason == PackageManager.INSTALL_REASON_POLICY) { 14241 // If the install is being performed by a regular app (i.e. neither system app nor 14242 // device or profile owner), we have no reason to believe that the app is acting on 14243 // behalf of an enterprise. If the app set the install reason to enterprise policy, 14244 // change it to unknown instead. 14245 return PackageManager.INSTALL_REASON_UNKNOWN; 14246 } 14247 14248 // If the install is being performed by a regular app and the install reason was set to any 14249 // value but enterprise policy, leave the install reason unchanged. 14250 return installReason; 14251 } 14252 14253 void installStage(String packageName, File stagedDir, String stagedCid, 14254 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 14255 String installerPackageName, int installerUid, UserHandle user, 14256 Certificate[][] certificates) { 14257 if (DEBUG_EPHEMERAL) { 14258 if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) { 14259 Slog.d(TAG, "Ephemeral install of " + packageName); 14260 } 14261 } 14262 final VerificationInfo verificationInfo = new VerificationInfo( 14263 sessionParams.originatingUri, sessionParams.referrerUri, 14264 sessionParams.originatingUid, installerUid); 14265 14266 final OriginInfo origin; 14267 if (stagedDir != null) { 14268 origin = OriginInfo.fromStagedFile(stagedDir); 14269 } else { 14270 origin = OriginInfo.fromStagedContainer(stagedCid); 14271 } 14272 14273 final Message msg = mHandler.obtainMessage(INIT_COPY); 14274 final int installReason = fixUpInstallReason(installerPackageName, installerUid, 14275 sessionParams.installReason); 14276 final InstallParams params = new InstallParams(origin, null, observer, 14277 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 14278 verificationInfo, user, sessionParams.abiOverride, 14279 sessionParams.grantedRuntimePermissions, certificates, installReason); 14280 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 14281 msg.obj = params; 14282 14283 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 14284 System.identityHashCode(msg.obj)); 14285 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 14286 System.identityHashCode(msg.obj)); 14287 14288 mHandler.sendMessage(msg); 14289 } 14290 14291 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 14292 int userId) { 14293 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 14294 sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId); 14295 14296 // Send a session commit broadcast 14297 final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo(); 14298 info.installReason = pkgSetting.getInstallReason(userId); 14299 info.appPackageName = packageName; 14300 sendSessionCommitBroadcast(info, userId); 14301 } 14302 14303 public void sendPackageAddedForNewUsers(String packageName, boolean isSystem, int appId, int... userIds) { 14304 if (ArrayUtils.isEmpty(userIds)) { 14305 return; 14306 } 14307 Bundle extras = new Bundle(1); 14308 // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast 14309 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId)); 14310 14311 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 14312 packageName, extras, 0, null, null, userIds); 14313 if (isSystem) { 14314 mHandler.post(() -> { 14315 for (int userId : userIds) { 14316 sendBootCompletedBroadcastToSystemApp(packageName, userId); 14317 } 14318 } 14319 ); 14320 } 14321 } 14322 14323 /** 14324 * The just-installed/enabled app is bundled on the system, so presumed to be able to run 14325 * automatically without needing an explicit launch. 14326 * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones. 14327 */ 14328 private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) { 14329 // If user is not running, the app didn't miss any broadcast 14330 if (!mUserManagerInternal.isUserRunning(userId)) { 14331 return; 14332 } 14333 final IActivityManager am = ActivityManager.getService(); 14334 try { 14335 // Deliver LOCKED_BOOT_COMPLETED first 14336 Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED) 14337 .setPackage(packageName); 14338 final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED}; 14339 am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions, 14340 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 14341 14342 // Deliver BOOT_COMPLETED only if user is unlocked 14343 if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) { 14344 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName); 14345 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions, 14346 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 14347 } 14348 } catch (RemoteException e) { 14349 throw e.rethrowFromSystemServer(); 14350 } 14351 } 14352 14353 @Override 14354 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 14355 int userId) { 14356 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 14357 PackageSetting pkgSetting; 14358 final int callingUid = Binder.getCallingUid(); 14359 enforceCrossUserPermission(callingUid, userId, 14360 true /* requireFullPermission */, true /* checkShell */, 14361 "setApplicationHiddenSetting for user " + userId); 14362 14363 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 14364 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 14365 return false; 14366 } 14367 14368 long callingId = Binder.clearCallingIdentity(); 14369 try { 14370 boolean sendAdded = false; 14371 boolean sendRemoved = false; 14372 // writer 14373 synchronized (mPackages) { 14374 pkgSetting = mSettings.mPackages.get(packageName); 14375 if (pkgSetting == null) { 14376 return false; 14377 } 14378 if (filterAppAccessLPr(pkgSetting, callingUid, userId)) { 14379 return false; 14380 } 14381 // Do not allow "android" is being disabled 14382 if ("android".equals(packageName)) { 14383 Slog.w(TAG, "Cannot hide package: android"); 14384 return false; 14385 } 14386 // Cannot hide static shared libs as they are considered 14387 // a part of the using app (emulating static linking). Also 14388 // static libs are installed always on internal storage. 14389 PackageParser.Package pkg = mPackages.get(packageName); 14390 if (pkg != null && pkg.staticSharedLibName != null) { 14391 Slog.w(TAG, "Cannot hide package: " + packageName 14392 + " providing static shared library: " 14393 + pkg.staticSharedLibName); 14394 return false; 14395 } 14396 // Only allow protected packages to hide themselves. 14397 if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId) 14398 && mProtectedPackages.isPackageStateProtected(userId, packageName)) { 14399 Slog.w(TAG, "Not hiding protected package: " + packageName); 14400 return false; 14401 } 14402 14403 if (pkgSetting.getHidden(userId) != hidden) { 14404 pkgSetting.setHidden(hidden, userId); 14405 mSettings.writePackageRestrictionsLPr(userId); 14406 if (hidden) { 14407 sendRemoved = true; 14408 } else { 14409 sendAdded = true; 14410 } 14411 } 14412 } 14413 if (sendAdded) { 14414 sendPackageAddedForUser(packageName, pkgSetting, userId); 14415 return true; 14416 } 14417 if (sendRemoved) { 14418 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 14419 "hiding pkg"); 14420 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 14421 return true; 14422 } 14423 } finally { 14424 Binder.restoreCallingIdentity(callingId); 14425 } 14426 return false; 14427 } 14428 14429 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 14430 int userId) { 14431 final PackageRemovedInfo info = new PackageRemovedInfo(this); 14432 info.removedPackage = packageName; 14433 info.installerPackageName = pkgSetting.installerPackageName; 14434 info.removedUsers = new int[] {userId}; 14435 info.broadcastUsers = new int[] {userId}; 14436 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 14437 info.sendPackageRemovedBroadcasts(true /*killApp*/); 14438 } 14439 14440 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 14441 if (pkgList.length > 0) { 14442 Bundle extras = new Bundle(1); 14443 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 14444 14445 sendPackageBroadcast( 14446 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 14447 : Intent.ACTION_PACKAGES_UNSUSPENDED, 14448 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 14449 new int[] {userId}); 14450 } 14451 } 14452 14453 /** 14454 * Returns true if application is not found or there was an error. Otherwise it returns 14455 * the hidden state of the package for the given user. 14456 */ 14457 @Override 14458 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 14459 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 14460 final int callingUid = Binder.getCallingUid(); 14461 enforceCrossUserPermission(callingUid, userId, 14462 true /* requireFullPermission */, false /* checkShell */, 14463 "getApplicationHidden for user " + userId); 14464 PackageSetting ps; 14465 long callingId = Binder.clearCallingIdentity(); 14466 try { 14467 // writer 14468 synchronized (mPackages) { 14469 ps = mSettings.mPackages.get(packageName); 14470 if (ps == null) { 14471 return true; 14472 } 14473 if (filterAppAccessLPr(ps, callingUid, userId)) { 14474 return true; 14475 } 14476 return ps.getHidden(userId); 14477 } 14478 } finally { 14479 Binder.restoreCallingIdentity(callingId); 14480 } 14481 } 14482 14483 /** 14484 * @hide 14485 */ 14486 @Override 14487 public int installExistingPackageAsUser(String packageName, int userId, int installFlags, 14488 int installReason) { 14489 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 14490 null); 14491 PackageSetting pkgSetting; 14492 final int callingUid = Binder.getCallingUid(); 14493 enforceCrossUserPermission(callingUid, userId, 14494 true /* requireFullPermission */, true /* checkShell */, 14495 "installExistingPackage for user " + userId); 14496 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 14497 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 14498 } 14499 14500 long callingId = Binder.clearCallingIdentity(); 14501 try { 14502 boolean installed = false; 14503 final boolean instantApp = 14504 (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 14505 final boolean fullApp = 14506 (installFlags & PackageManager.INSTALL_FULL_APP) != 0; 14507 14508 // writer 14509 synchronized (mPackages) { 14510 pkgSetting = mSettings.mPackages.get(packageName); 14511 if (pkgSetting == null) { 14512 return PackageManager.INSTALL_FAILED_INVALID_URI; 14513 } 14514 if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) { 14515 // only allow the existing package to be used if it's installed as a full 14516 // application for at least one user 14517 boolean installAllowed = false; 14518 for (int checkUserId : sUserManager.getUserIds()) { 14519 installAllowed = !pkgSetting.getInstantApp(checkUserId); 14520 if (installAllowed) { 14521 break; 14522 } 14523 } 14524 if (!installAllowed) { 14525 return PackageManager.INSTALL_FAILED_INVALID_URI; 14526 } 14527 } 14528 if (!pkgSetting.getInstalled(userId)) { 14529 pkgSetting.setInstalled(true, userId); 14530 pkgSetting.setHidden(false, userId); 14531 pkgSetting.setInstallReason(installReason, userId); 14532 mSettings.writePackageRestrictionsLPr(userId); 14533 mSettings.writeKernelMappingLPr(pkgSetting); 14534 installed = true; 14535 } else if (fullApp && pkgSetting.getInstantApp(userId)) { 14536 // upgrade app from instant to full; we don't allow app downgrade 14537 installed = true; 14538 } 14539 setInstantAppForUser(pkgSetting, userId, instantApp, fullApp); 14540 } 14541 14542 if (installed) { 14543 if (pkgSetting.pkg != null) { 14544 synchronized (mInstallLock) { 14545 // We don't need to freeze for a brand new install 14546 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 14547 } 14548 } 14549 sendPackageAddedForUser(packageName, pkgSetting, userId); 14550 synchronized (mPackages) { 14551 updateSequenceNumberLP(pkgSetting, new int[]{ userId }); 14552 } 14553 } 14554 } finally { 14555 Binder.restoreCallingIdentity(callingId); 14556 } 14557 14558 return PackageManager.INSTALL_SUCCEEDED; 14559 } 14560 14561 void setInstantAppForUser(PackageSetting pkgSetting, int userId, 14562 boolean instantApp, boolean fullApp) { 14563 // no state specified; do nothing 14564 if (!instantApp && !fullApp) { 14565 return; 14566 } 14567 if (userId != UserHandle.USER_ALL) { 14568 if (instantApp && !pkgSetting.getInstantApp(userId)) { 14569 pkgSetting.setInstantApp(true /*instantApp*/, userId); 14570 } else if (fullApp && pkgSetting.getInstantApp(userId)) { 14571 pkgSetting.setInstantApp(false /*instantApp*/, userId); 14572 } 14573 } else { 14574 for (int currentUserId : sUserManager.getUserIds()) { 14575 if (instantApp && !pkgSetting.getInstantApp(currentUserId)) { 14576 pkgSetting.setInstantApp(true /*instantApp*/, currentUserId); 14577 } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) { 14578 pkgSetting.setInstantApp(false /*instantApp*/, currentUserId); 14579 } 14580 } 14581 } 14582 } 14583 14584 boolean isUserRestricted(int userId, String restrictionKey) { 14585 Bundle restrictions = sUserManager.getUserRestrictions(userId); 14586 if (restrictions.getBoolean(restrictionKey, false)) { 14587 Log.w(TAG, "User is restricted: " + restrictionKey); 14588 return true; 14589 } 14590 return false; 14591 } 14592 14593 @Override 14594 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 14595 int userId) { 14596 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 14597 final int callingUid = Binder.getCallingUid(); 14598 enforceCrossUserPermission(callingUid, userId, 14599 true /* requireFullPermission */, true /* checkShell */, 14600 "setPackagesSuspended for user " + userId); 14601 14602 if (ArrayUtils.isEmpty(packageNames)) { 14603 return packageNames; 14604 } 14605 14606 // List of package names for whom the suspended state has changed. 14607 List<String> changedPackages = new ArrayList<>(packageNames.length); 14608 // List of package names for whom the suspended state is not set as requested in this 14609 // method. 14610 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 14611 long callingId = Binder.clearCallingIdentity(); 14612 try { 14613 for (int i = 0; i < packageNames.length; i++) { 14614 String packageName = packageNames[i]; 14615 boolean changed = false; 14616 final int appId; 14617 synchronized (mPackages) { 14618 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 14619 if (pkgSetting == null 14620 || filterAppAccessLPr(pkgSetting, callingUid, userId)) { 14621 Slog.w(TAG, "Could not find package setting for package \"" + packageName 14622 + "\". Skipping suspending/un-suspending."); 14623 unactionedPackages.add(packageName); 14624 continue; 14625 } 14626 appId = pkgSetting.appId; 14627 if (pkgSetting.getSuspended(userId) != suspended) { 14628 if (!canSuspendPackageForUserLocked(packageName, userId)) { 14629 unactionedPackages.add(packageName); 14630 continue; 14631 } 14632 pkgSetting.setSuspended(suspended, userId); 14633 mSettings.writePackageRestrictionsLPr(userId); 14634 changed = true; 14635 changedPackages.add(packageName); 14636 } 14637 } 14638 14639 if (changed && suspended) { 14640 killApplication(packageName, UserHandle.getUid(userId, appId), 14641 "suspending package"); 14642 } 14643 } 14644 } finally { 14645 Binder.restoreCallingIdentity(callingId); 14646 } 14647 14648 if (!changedPackages.isEmpty()) { 14649 sendPackagesSuspendedForUser(changedPackages.toArray( 14650 new String[changedPackages.size()]), userId, suspended); 14651 } 14652 14653 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 14654 } 14655 14656 @Override 14657 public boolean isPackageSuspendedForUser(String packageName, int userId) { 14658 final int callingUid = Binder.getCallingUid(); 14659 enforceCrossUserPermission(callingUid, userId, 14660 true /* requireFullPermission */, false /* checkShell */, 14661 "isPackageSuspendedForUser for user " + userId); 14662 synchronized (mPackages) { 14663 final PackageSetting ps = mSettings.mPackages.get(packageName); 14664 if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) { 14665 throw new IllegalArgumentException("Unknown target package: " + packageName); 14666 } 14667 return ps.getSuspended(userId); 14668 } 14669 } 14670 14671 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 14672 if (isPackageDeviceAdmin(packageName, userId)) { 14673 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 14674 + "\": has an active device admin"); 14675 return false; 14676 } 14677 14678 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 14679 if (packageName.equals(activeLauncherPackageName)) { 14680 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 14681 + "\": contains the active launcher"); 14682 return false; 14683 } 14684 14685 if (packageName.equals(mRequiredInstallerPackage)) { 14686 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 14687 + "\": required for package installation"); 14688 return false; 14689 } 14690 14691 if (packageName.equals(mRequiredUninstallerPackage)) { 14692 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 14693 + "\": required for package uninstallation"); 14694 return false; 14695 } 14696 14697 if (packageName.equals(mRequiredVerifierPackage)) { 14698 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 14699 + "\": required for package verification"); 14700 return false; 14701 } 14702 14703 if (packageName.equals(getDefaultDialerPackageName(userId))) { 14704 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 14705 + "\": is the default dialer"); 14706 return false; 14707 } 14708 14709 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 14710 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 14711 + "\": protected package"); 14712 return false; 14713 } 14714 14715 // Cannot suspend static shared libs as they are considered 14716 // a part of the using app (emulating static linking). Also 14717 // static libs are installed always on internal storage. 14718 PackageParser.Package pkg = mPackages.get(packageName); 14719 if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) { 14720 Slog.w(TAG, "Cannot suspend package: " + packageName 14721 + " providing static shared library: " 14722 + pkg.staticSharedLibName); 14723 return false; 14724 } 14725 14726 return true; 14727 } 14728 14729 private String getActiveLauncherPackageName(int userId) { 14730 Intent intent = new Intent(Intent.ACTION_MAIN); 14731 intent.addCategory(Intent.CATEGORY_HOME); 14732 ResolveInfo resolveInfo = resolveIntent( 14733 intent, 14734 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 14735 PackageManager.MATCH_DEFAULT_ONLY, 14736 userId); 14737 14738 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 14739 } 14740 14741 private String getDefaultDialerPackageName(int userId) { 14742 synchronized (mPackages) { 14743 return mSettings.getDefaultDialerPackageNameLPw(userId); 14744 } 14745 } 14746 14747 @Override 14748 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 14749 mContext.enforceCallingOrSelfPermission( 14750 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 14751 "Only package verification agents can verify applications"); 14752 14753 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 14754 final PackageVerificationResponse response = new PackageVerificationResponse( 14755 verificationCode, Binder.getCallingUid()); 14756 msg.arg1 = id; 14757 msg.obj = response; 14758 mHandler.sendMessage(msg); 14759 } 14760 14761 @Override 14762 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 14763 long millisecondsToDelay) { 14764 mContext.enforceCallingOrSelfPermission( 14765 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 14766 "Only package verification agents can extend verification timeouts"); 14767 14768 final PackageVerificationState state = mPendingVerification.get(id); 14769 final PackageVerificationResponse response = new PackageVerificationResponse( 14770 verificationCodeAtTimeout, Binder.getCallingUid()); 14771 14772 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 14773 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 14774 } 14775 if (millisecondsToDelay < 0) { 14776 millisecondsToDelay = 0; 14777 } 14778 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 14779 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 14780 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 14781 } 14782 14783 if ((state != null) && !state.timeoutExtended()) { 14784 state.extendTimeout(); 14785 14786 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 14787 msg.arg1 = id; 14788 msg.obj = response; 14789 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 14790 } 14791 } 14792 14793 private void broadcastPackageVerified(int verificationId, Uri packageUri, 14794 int verificationCode, UserHandle user) { 14795 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 14796 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 14797 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 14798 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 14799 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 14800 14801 mContext.sendBroadcastAsUser(intent, user, 14802 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 14803 } 14804 14805 private ComponentName matchComponentForVerifier(String packageName, 14806 List<ResolveInfo> receivers) { 14807 ActivityInfo targetReceiver = null; 14808 14809 final int NR = receivers.size(); 14810 for (int i = 0; i < NR; i++) { 14811 final ResolveInfo info = receivers.get(i); 14812 if (info.activityInfo == null) { 14813 continue; 14814 } 14815 14816 if (packageName.equals(info.activityInfo.packageName)) { 14817 targetReceiver = info.activityInfo; 14818 break; 14819 } 14820 } 14821 14822 if (targetReceiver == null) { 14823 return null; 14824 } 14825 14826 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 14827 } 14828 14829 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 14830 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 14831 if (pkgInfo.verifiers.length == 0) { 14832 return null; 14833 } 14834 14835 final int N = pkgInfo.verifiers.length; 14836 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 14837 for (int i = 0; i < N; i++) { 14838 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 14839 14840 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 14841 receivers); 14842 if (comp == null) { 14843 continue; 14844 } 14845 14846 final int verifierUid = getUidForVerifier(verifierInfo); 14847 if (verifierUid == -1) { 14848 continue; 14849 } 14850 14851 if (DEBUG_VERIFY) { 14852 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 14853 + " with the correct signature"); 14854 } 14855 sufficientVerifiers.add(comp); 14856 verificationState.addSufficientVerifier(verifierUid); 14857 } 14858 14859 return sufficientVerifiers; 14860 } 14861 14862 private int getUidForVerifier(VerifierInfo verifierInfo) { 14863 synchronized (mPackages) { 14864 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 14865 if (pkg == null) { 14866 return -1; 14867 } else if (pkg.mSignatures.length != 1) { 14868 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 14869 + " has more than one signature; ignoring"); 14870 return -1; 14871 } 14872 14873 /* 14874 * If the public key of the package's signature does not match 14875 * our expected public key, then this is a different package and 14876 * we should skip. 14877 */ 14878 14879 final byte[] expectedPublicKey; 14880 try { 14881 final Signature verifierSig = pkg.mSignatures[0]; 14882 final PublicKey publicKey = verifierSig.getPublicKey(); 14883 expectedPublicKey = publicKey.getEncoded(); 14884 } catch (CertificateException e) { 14885 return -1; 14886 } 14887 14888 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 14889 14890 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 14891 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 14892 + " does not have the expected public key; ignoring"); 14893 return -1; 14894 } 14895 14896 return pkg.applicationInfo.uid; 14897 } 14898 } 14899 14900 @Override 14901 public void finishPackageInstall(int token, boolean didLaunch) { 14902 enforceSystemOrRoot("Only the system is allowed to finish installs"); 14903 14904 if (DEBUG_INSTALL) { 14905 Slog.v(TAG, "BM finishing package install for " + token); 14906 } 14907 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 14908 14909 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 14910 mHandler.sendMessage(msg); 14911 } 14912 14913 /** 14914 * Get the verification agent timeout. Used for both the APK verifier and the 14915 * intent filter verifier. 14916 * 14917 * @return verification timeout in milliseconds 14918 */ 14919 private long getVerificationTimeout() { 14920 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 14921 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 14922 DEFAULT_VERIFICATION_TIMEOUT); 14923 } 14924 14925 /** 14926 * Get the default verification agent response code. 14927 * 14928 * @return default verification response code 14929 */ 14930 private int getDefaultVerificationResponse(UserHandle user) { 14931 if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) { 14932 return PackageManager.VERIFICATION_REJECT; 14933 } 14934 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 14935 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 14936 DEFAULT_VERIFICATION_RESPONSE); 14937 } 14938 14939 /** 14940 * Check whether or not package verification has been enabled. 14941 * 14942 * @return true if verification should be performed 14943 */ 14944 private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) { 14945 if (!DEFAULT_VERIFY_ENABLE) { 14946 return false; 14947 } 14948 14949 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 14950 14951 // Check if installing from ADB 14952 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 14953 // Do not run verification in a test harness environment 14954 if (ActivityManager.isRunningInTestHarness()) { 14955 return false; 14956 } 14957 if (ensureVerifyAppsEnabled) { 14958 return true; 14959 } 14960 // Check if the developer does not want package verification for ADB installs 14961 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 14962 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 14963 return false; 14964 } 14965 } else { 14966 // only when not installed from ADB, skip verification for instant apps when 14967 // the installer and verifier are the same. 14968 if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) { 14969 if (mInstantAppInstallerActivity != null 14970 && mInstantAppInstallerActivity.packageName.equals( 14971 mRequiredVerifierPackage)) { 14972 try { 14973 mContext.getSystemService(AppOpsManager.class) 14974 .checkPackage(installerUid, mRequiredVerifierPackage); 14975 if (DEBUG_VERIFY) { 14976 Slog.i(TAG, "disable verification for instant app"); 14977 } 14978 return false; 14979 } catch (SecurityException ignore) { } 14980 } 14981 } 14982 } 14983 14984 if (ensureVerifyAppsEnabled) { 14985 return true; 14986 } 14987 14988 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 14989 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 14990 } 14991 14992 @Override 14993 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 14994 throws RemoteException { 14995 mContext.enforceCallingOrSelfPermission( 14996 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 14997 "Only intentfilter verification agents can verify applications"); 14998 14999 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 15000 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 15001 Binder.getCallingUid(), verificationCode, failedDomains); 15002 msg.arg1 = id; 15003 msg.obj = response; 15004 mHandler.sendMessage(msg); 15005 } 15006 15007 @Override 15008 public int getIntentVerificationStatus(String packageName, int userId) { 15009 final int callingUid = Binder.getCallingUid(); 15010 if (getInstantAppPackageName(callingUid) != null) { 15011 return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 15012 } 15013 synchronized (mPackages) { 15014 final PackageSetting ps = mSettings.mPackages.get(packageName); 15015 if (ps == null 15016 || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 15017 return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 15018 } 15019 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 15020 } 15021 } 15022 15023 @Override 15024 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 15025 mContext.enforceCallingOrSelfPermission( 15026 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 15027 15028 boolean result = false; 15029 synchronized (mPackages) { 15030 final PackageSetting ps = mSettings.mPackages.get(packageName); 15031 if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) { 15032 return false; 15033 } 15034 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 15035 } 15036 if (result) { 15037 scheduleWritePackageRestrictionsLocked(userId); 15038 } 15039 return result; 15040 } 15041 15042 @Override 15043 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 15044 String packageName) { 15045 final int callingUid = Binder.getCallingUid(); 15046 if (getInstantAppPackageName(callingUid) != null) { 15047 return ParceledListSlice.emptyList(); 15048 } 15049 synchronized (mPackages) { 15050 final PackageSetting ps = mSettings.mPackages.get(packageName); 15051 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 15052 return ParceledListSlice.emptyList(); 15053 } 15054 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 15055 } 15056 } 15057 15058 @Override 15059 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 15060 if (TextUtils.isEmpty(packageName)) { 15061 return ParceledListSlice.emptyList(); 15062 } 15063 final int callingUid = Binder.getCallingUid(); 15064 final int callingUserId = UserHandle.getUserId(callingUid); 15065 synchronized (mPackages) { 15066 PackageParser.Package pkg = mPackages.get(packageName); 15067 if (pkg == null || pkg.activities == null) { 15068 return ParceledListSlice.emptyList(); 15069 } 15070 if (pkg.mExtras == null) { 15071 return ParceledListSlice.emptyList(); 15072 } 15073 final PackageSetting ps = (PackageSetting) pkg.mExtras; 15074 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 15075 return ParceledListSlice.emptyList(); 15076 } 15077 final int count = pkg.activities.size(); 15078 ArrayList<IntentFilter> result = new ArrayList<>(); 15079 for (int n=0; n<count; n++) { 15080 PackageParser.Activity activity = pkg.activities.get(n); 15081 if (activity.intents != null && activity.intents.size() > 0) { 15082 result.addAll(activity.intents); 15083 } 15084 } 15085 return new ParceledListSlice<>(result); 15086 } 15087 } 15088 15089 @Override 15090 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 15091 mContext.enforceCallingOrSelfPermission( 15092 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 15093 15094 synchronized (mPackages) { 15095 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 15096 if (packageName != null) { 15097 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 15098 packageName, userId); 15099 } 15100 return result; 15101 } 15102 } 15103 15104 @Override 15105 public String getDefaultBrowserPackageName(int userId) { 15106 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 15107 return null; 15108 } 15109 synchronized (mPackages) { 15110 return mSettings.getDefaultBrowserPackageNameLPw(userId); 15111 } 15112 } 15113 15114 /** 15115 * Get the "allow unknown sources" setting. 15116 * 15117 * @return the current "allow unknown sources" setting 15118 */ 15119 private int getUnknownSourcesSettings() { 15120 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 15121 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 15122 -1); 15123 } 15124 15125 @Override 15126 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 15127 final int callingUid = Binder.getCallingUid(); 15128 if (getInstantAppPackageName(callingUid) != null) { 15129 return; 15130 } 15131 // writer 15132 synchronized (mPackages) { 15133 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 15134 if (targetPackageSetting == null 15135 || filterAppAccessLPr( 15136 targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) { 15137 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 15138 } 15139 15140 PackageSetting installerPackageSetting; 15141 if (installerPackageName != null) { 15142 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 15143 if (installerPackageSetting == null) { 15144 throw new IllegalArgumentException("Unknown installer package: " 15145 + installerPackageName); 15146 } 15147 } else { 15148 installerPackageSetting = null; 15149 } 15150 15151 Signature[] callerSignature; 15152 Object obj = mSettings.getUserIdLPr(callingUid); 15153 if (obj != null) { 15154 if (obj instanceof SharedUserSetting) { 15155 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 15156 } else if (obj instanceof PackageSetting) { 15157 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 15158 } else { 15159 throw new SecurityException("Bad object " + obj + " for uid " + callingUid); 15160 } 15161 } else { 15162 throw new SecurityException("Unknown calling UID: " + callingUid); 15163 } 15164 15165 // Verify: can't set installerPackageName to a package that is 15166 // not signed with the same cert as the caller. 15167 if (installerPackageSetting != null) { 15168 if (compareSignatures(callerSignature, 15169 installerPackageSetting.signatures.mSignatures) 15170 != PackageManager.SIGNATURE_MATCH) { 15171 throw new SecurityException( 15172 "Caller does not have same cert as new installer package " 15173 + installerPackageName); 15174 } 15175 } 15176 15177 // Verify: if target already has an installer package, it must 15178 // be signed with the same cert as the caller. 15179 if (targetPackageSetting.installerPackageName != null) { 15180 PackageSetting setting = mSettings.mPackages.get( 15181 targetPackageSetting.installerPackageName); 15182 // If the currently set package isn't valid, then it's always 15183 // okay to change it. 15184 if (setting != null) { 15185 if (compareSignatures(callerSignature, 15186 setting.signatures.mSignatures) 15187 != PackageManager.SIGNATURE_MATCH) { 15188 throw new SecurityException( 15189 "Caller does not have same cert as old installer package " 15190 + targetPackageSetting.installerPackageName); 15191 } 15192 } 15193 } 15194 15195 // Okay! 15196 targetPackageSetting.installerPackageName = installerPackageName; 15197 if (installerPackageName != null) { 15198 mSettings.mInstallerPackages.add(installerPackageName); 15199 } 15200 scheduleWriteSettingsLocked(); 15201 } 15202 } 15203 15204 @Override 15205 public void setApplicationCategoryHint(String packageName, int categoryHint, 15206 String callerPackageName) { 15207 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 15208 throw new SecurityException("Instant applications don't have access to this method"); 15209 } 15210 mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(), 15211 callerPackageName); 15212 synchronized (mPackages) { 15213 PackageSetting ps = mSettings.mPackages.get(packageName); 15214 if (ps == null) { 15215 throw new IllegalArgumentException("Unknown target package " + packageName); 15216 } 15217 if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) { 15218 throw new IllegalArgumentException("Unknown target package " + packageName); 15219 } 15220 if (!Objects.equals(callerPackageName, ps.installerPackageName)) { 15221 throw new IllegalArgumentException("Calling package " + callerPackageName 15222 + " is not installer for " + packageName); 15223 } 15224 15225 if (ps.categoryHint != categoryHint) { 15226 ps.categoryHint = categoryHint; 15227 scheduleWriteSettingsLocked(); 15228 } 15229 } 15230 } 15231 15232 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 15233 // Queue up an async operation since the package installation may take a little while. 15234 mHandler.post(new Runnable() { 15235 public void run() { 15236 mHandler.removeCallbacks(this); 15237 // Result object to be returned 15238 PackageInstalledInfo res = new PackageInstalledInfo(); 15239 res.setReturnCode(currentStatus); 15240 res.uid = -1; 15241 res.pkg = null; 15242 res.removedInfo = null; 15243 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 15244 args.doPreInstall(res.returnCode); 15245 synchronized (mInstallLock) { 15246 installPackageTracedLI(args, res); 15247 } 15248 args.doPostInstall(res.returnCode, res.uid); 15249 } 15250 15251 // A restore should be performed at this point if (a) the install 15252 // succeeded, (b) the operation is not an update, and (c) the new 15253 // package has not opted out of backup participation. 15254 final boolean update = res.removedInfo != null 15255 && res.removedInfo.removedPackage != null; 15256 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 15257 boolean doRestore = !update 15258 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 15259 15260 // Set up the post-install work request bookkeeping. This will be used 15261 // and cleaned up by the post-install event handling regardless of whether 15262 // there's a restore pass performed. Token values are >= 1. 15263 int token; 15264 if (mNextInstallToken < 0) mNextInstallToken = 1; 15265 token = mNextInstallToken++; 15266 15267 PostInstallData data = new PostInstallData(args, res); 15268 mRunningInstalls.put(token, data); 15269 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 15270 15271 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 15272 // Pass responsibility to the Backup Manager. It will perform a 15273 // restore if appropriate, then pass responsibility back to the 15274 // Package Manager to run the post-install observer callbacks 15275 // and broadcasts. 15276 IBackupManager bm = IBackupManager.Stub.asInterface( 15277 ServiceManager.getService(Context.BACKUP_SERVICE)); 15278 if (bm != null) { 15279 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 15280 + " to BM for possible restore"); 15281 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 15282 try { 15283 // TODO: http://b/22388012 15284 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 15285 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 15286 } else { 15287 doRestore = false; 15288 } 15289 } catch (RemoteException e) { 15290 // can't happen; the backup manager is local 15291 } catch (Exception e) { 15292 Slog.e(TAG, "Exception trying to enqueue restore", e); 15293 doRestore = false; 15294 } 15295 } else { 15296 Slog.e(TAG, "Backup Manager not found!"); 15297 doRestore = false; 15298 } 15299 } 15300 15301 if (!doRestore) { 15302 // No restore possible, or the Backup Manager was mysteriously not 15303 // available -- just fire the post-install work request directly. 15304 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 15305 15306 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 15307 15308 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 15309 mHandler.sendMessage(msg); 15310 } 15311 } 15312 }); 15313 } 15314 15315 /** 15316 * Callback from PackageSettings whenever an app is first transitioned out of the 15317 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 15318 * the app was "launched" for a restoreAtInstall operation. Therefore we check 15319 * here whether the app is the target of an ongoing install, and only send the 15320 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 15321 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 15322 * handling. 15323 */ 15324 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 15325 // Serialize this with the rest of the install-process message chain. In the 15326 // restore-at-install case, this Runnable will necessarily run before the 15327 // POST_INSTALL message is processed, so the contents of mRunningInstalls 15328 // are coherent. In the non-restore case, the app has already completed install 15329 // and been launched through some other means, so it is not in a problematic 15330 // state for observers to see the FIRST_LAUNCH signal. 15331 mHandler.post(new Runnable() { 15332 @Override 15333 public void run() { 15334 for (int i = 0; i < mRunningInstalls.size(); i++) { 15335 final PostInstallData data = mRunningInstalls.valueAt(i); 15336 if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 15337 continue; 15338 } 15339 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 15340 // right package; but is it for the right user? 15341 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 15342 if (userId == data.res.newUsers[uIndex]) { 15343 if (DEBUG_BACKUP) { 15344 Slog.i(TAG, "Package " + pkgName 15345 + " being restored so deferring FIRST_LAUNCH"); 15346 } 15347 return; 15348 } 15349 } 15350 } 15351 } 15352 // didn't find it, so not being restored 15353 if (DEBUG_BACKUP) { 15354 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 15355 } 15356 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 15357 } 15358 }); 15359 } 15360 15361 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 15362 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 15363 installerPkg, null, userIds); 15364 } 15365 15366 private abstract class HandlerParams { 15367 private static final int MAX_RETRIES = 4; 15368 15369 /** 15370 * Number of times startCopy() has been attempted and had a non-fatal 15371 * error. 15372 */ 15373 private int mRetries = 0; 15374 15375 /** User handle for the user requesting the information or installation. */ 15376 private final UserHandle mUser; 15377 String traceMethod; 15378 int traceCookie; 15379 15380 HandlerParams(UserHandle user) { 15381 mUser = user; 15382 } 15383 15384 UserHandle getUser() { 15385 return mUser; 15386 } 15387 15388 HandlerParams setTraceMethod(String traceMethod) { 15389 this.traceMethod = traceMethod; 15390 return this; 15391 } 15392 15393 HandlerParams setTraceCookie(int traceCookie) { 15394 this.traceCookie = traceCookie; 15395 return this; 15396 } 15397 15398 final boolean startCopy() { 15399 boolean res; 15400 try { 15401 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 15402 15403 if (++mRetries > MAX_RETRIES) { 15404 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 15405 mHandler.sendEmptyMessage(MCS_GIVE_UP); 15406 handleServiceError(); 15407 return false; 15408 } else { 15409 handleStartCopy(); 15410 res = true; 15411 } 15412 } catch (RemoteException e) { 15413 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 15414 mHandler.sendEmptyMessage(MCS_RECONNECT); 15415 res = false; 15416 } 15417 handleReturnCode(); 15418 return res; 15419 } 15420 15421 final void serviceError() { 15422 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 15423 handleServiceError(); 15424 handleReturnCode(); 15425 } 15426 15427 abstract void handleStartCopy() throws RemoteException; 15428 abstract void handleServiceError(); 15429 abstract void handleReturnCode(); 15430 } 15431 15432 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 15433 for (File path : paths) { 15434 try { 15435 mcs.clearDirectory(path.getAbsolutePath()); 15436 } catch (RemoteException e) { 15437 } 15438 } 15439 } 15440 15441 static class OriginInfo { 15442 /** 15443 * Location where install is coming from, before it has been 15444 * copied/renamed into place. This could be a single monolithic APK 15445 * file, or a cluster directory. This location may be untrusted. 15446 */ 15447 final File file; 15448 final String cid; 15449 15450 /** 15451 * Flag indicating that {@link #file} or {@link #cid} has already been 15452 * staged, meaning downstream users don't need to defensively copy the 15453 * contents. 15454 */ 15455 final boolean staged; 15456 15457 /** 15458 * Flag indicating that {@link #file} or {@link #cid} is an already 15459 * installed app that is being moved. 15460 */ 15461 final boolean existing; 15462 15463 final String resolvedPath; 15464 final File resolvedFile; 15465 15466 static OriginInfo fromNothing() { 15467 return new OriginInfo(null, null, false, false); 15468 } 15469 15470 static OriginInfo fromUntrustedFile(File file) { 15471 return new OriginInfo(file, null, false, false); 15472 } 15473 15474 static OriginInfo fromExistingFile(File file) { 15475 return new OriginInfo(file, null, false, true); 15476 } 15477 15478 static OriginInfo fromStagedFile(File file) { 15479 return new OriginInfo(file, null, true, false); 15480 } 15481 15482 static OriginInfo fromStagedContainer(String cid) { 15483 return new OriginInfo(null, cid, true, false); 15484 } 15485 15486 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 15487 this.file = file; 15488 this.cid = cid; 15489 this.staged = staged; 15490 this.existing = existing; 15491 15492 if (cid != null) { 15493 resolvedPath = PackageHelper.getSdDir(cid); 15494 resolvedFile = new File(resolvedPath); 15495 } else if (file != null) { 15496 resolvedPath = file.getAbsolutePath(); 15497 resolvedFile = file; 15498 } else { 15499 resolvedPath = null; 15500 resolvedFile = null; 15501 } 15502 } 15503 } 15504 15505 static class MoveInfo { 15506 final int moveId; 15507 final String fromUuid; 15508 final String toUuid; 15509 final String packageName; 15510 final String dataAppName; 15511 final int appId; 15512 final String seinfo; 15513 final int targetSdkVersion; 15514 15515 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 15516 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 15517 this.moveId = moveId; 15518 this.fromUuid = fromUuid; 15519 this.toUuid = toUuid; 15520 this.packageName = packageName; 15521 this.dataAppName = dataAppName; 15522 this.appId = appId; 15523 this.seinfo = seinfo; 15524 this.targetSdkVersion = targetSdkVersion; 15525 } 15526 } 15527 15528 static class VerificationInfo { 15529 /** A constant used to indicate that a uid value is not present. */ 15530 public static final int NO_UID = -1; 15531 15532 /** URI referencing where the package was downloaded from. */ 15533 final Uri originatingUri; 15534 15535 /** HTTP referrer URI associated with the originatingURI. */ 15536 final Uri referrer; 15537 15538 /** UID of the application that the install request originated from. */ 15539 final int originatingUid; 15540 15541 /** UID of application requesting the install */ 15542 final int installerUid; 15543 15544 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 15545 this.originatingUri = originatingUri; 15546 this.referrer = referrer; 15547 this.originatingUid = originatingUid; 15548 this.installerUid = installerUid; 15549 } 15550 } 15551 15552 class InstallParams extends HandlerParams { 15553 final OriginInfo origin; 15554 final MoveInfo move; 15555 final IPackageInstallObserver2 observer; 15556 int installFlags; 15557 final String installerPackageName; 15558 final String volumeUuid; 15559 private InstallArgs mArgs; 15560 private int mRet; 15561 final String packageAbiOverride; 15562 final String[] grantedRuntimePermissions; 15563 final VerificationInfo verificationInfo; 15564 final Certificate[][] certificates; 15565 final int installReason; 15566 15567 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 15568 int installFlags, String installerPackageName, String volumeUuid, 15569 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 15570 String[] grantedPermissions, Certificate[][] certificates, int installReason) { 15571 super(user); 15572 this.origin = origin; 15573 this.move = move; 15574 this.observer = observer; 15575 this.installFlags = installFlags; 15576 this.installerPackageName = installerPackageName; 15577 this.volumeUuid = volumeUuid; 15578 this.verificationInfo = verificationInfo; 15579 this.packageAbiOverride = packageAbiOverride; 15580 this.grantedRuntimePermissions = grantedPermissions; 15581 this.certificates = certificates; 15582 this.installReason = installReason; 15583 } 15584 15585 @Override 15586 public String toString() { 15587 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 15588 + " file=" + origin.file + " cid=" + origin.cid + "}"; 15589 } 15590 15591 private int installLocationPolicy(PackageInfoLite pkgLite) { 15592 String packageName = pkgLite.packageName; 15593 int installLocation = pkgLite.installLocation; 15594 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 15595 // reader 15596 synchronized (mPackages) { 15597 // Currently installed package which the new package is attempting to replace or 15598 // null if no such package is installed. 15599 PackageParser.Package installedPkg = mPackages.get(packageName); 15600 // Package which currently owns the data which the new package will own if installed. 15601 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 15602 // will be null whereas dataOwnerPkg will contain information about the package 15603 // which was uninstalled while keeping its data. 15604 PackageParser.Package dataOwnerPkg = installedPkg; 15605 if (dataOwnerPkg == null) { 15606 PackageSetting ps = mSettings.mPackages.get(packageName); 15607 if (ps != null) { 15608 dataOwnerPkg = ps.pkg; 15609 } 15610 } 15611 15612 if (dataOwnerPkg != null) { 15613 // If installed, the package will get access to data left on the device by its 15614 // predecessor. As a security measure, this is permited only if this is not a 15615 // version downgrade or if the predecessor package is marked as debuggable and 15616 // a downgrade is explicitly requested. 15617 // 15618 // On debuggable platform builds, downgrades are permitted even for 15619 // non-debuggable packages to make testing easier. Debuggable platform builds do 15620 // not offer security guarantees and thus it's OK to disable some security 15621 // mechanisms to make debugging/testing easier on those builds. However, even on 15622 // debuggable builds downgrades of packages are permitted only if requested via 15623 // installFlags. This is because we aim to keep the behavior of debuggable 15624 // platform builds as close as possible to the behavior of non-debuggable 15625 // platform builds. 15626 final boolean downgradeRequested = 15627 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 15628 final boolean packageDebuggable = 15629 (dataOwnerPkg.applicationInfo.flags 15630 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 15631 final boolean downgradePermitted = 15632 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 15633 if (!downgradePermitted) { 15634 try { 15635 checkDowngrade(dataOwnerPkg, pkgLite); 15636 } catch (PackageManagerException e) { 15637 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 15638 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 15639 } 15640 } 15641 } 15642 15643 if (installedPkg != null) { 15644 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 15645 // Check for updated system application. 15646 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 15647 if (onSd) { 15648 Slog.w(TAG, "Cannot install update to system app on sdcard"); 15649 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 15650 } 15651 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 15652 } else { 15653 if (onSd) { 15654 // Install flag overrides everything. 15655 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 15656 } 15657 // If current upgrade specifies particular preference 15658 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 15659 // Application explicitly specified internal. 15660 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 15661 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 15662 // App explictly prefers external. Let policy decide 15663 } else { 15664 // Prefer previous location 15665 if (isExternal(installedPkg)) { 15666 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 15667 } 15668 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 15669 } 15670 } 15671 } else { 15672 // Invalid install. Return error code 15673 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 15674 } 15675 } 15676 } 15677 // All the special cases have been taken care of. 15678 // Return result based on recommended install location. 15679 if (onSd) { 15680 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 15681 } 15682 return pkgLite.recommendedInstallLocation; 15683 } 15684 15685 /* 15686 * Invoke remote method to get package information and install 15687 * location values. Override install location based on default 15688 * policy if needed and then create install arguments based 15689 * on the install location. 15690 */ 15691 public void handleStartCopy() throws RemoteException { 15692 int ret = PackageManager.INSTALL_SUCCEEDED; 15693 15694 // If we're already staged, we've firmly committed to an install location 15695 if (origin.staged) { 15696 if (origin.file != null) { 15697 installFlags |= PackageManager.INSTALL_INTERNAL; 15698 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 15699 } else if (origin.cid != null) { 15700 installFlags |= PackageManager.INSTALL_EXTERNAL; 15701 installFlags &= ~PackageManager.INSTALL_INTERNAL; 15702 } else { 15703 throw new IllegalStateException("Invalid stage location"); 15704 } 15705 } 15706 15707 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 15708 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 15709 final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 15710 PackageInfoLite pkgLite = null; 15711 15712 if (onInt && onSd) { 15713 // Check if both bits are set. 15714 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 15715 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 15716 } else if (onSd && ephemeral) { 15717 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 15718 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 15719 } else { 15720 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 15721 packageAbiOverride); 15722 15723 if (DEBUG_EPHEMERAL && ephemeral) { 15724 Slog.v(TAG, "pkgLite for install: " + pkgLite); 15725 } 15726 15727 /* 15728 * If we have too little free space, try to free cache 15729 * before giving up. 15730 */ 15731 if (!origin.staged && pkgLite.recommendedInstallLocation 15732 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 15733 // TODO: focus freeing disk space on the target device 15734 final StorageManager storage = StorageManager.from(mContext); 15735 final long lowThreshold = storage.getStorageLowBytes( 15736 Environment.getDataDirectory()); 15737 15738 final long sizeBytes = mContainerService.calculateInstalledSize( 15739 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 15740 15741 try { 15742 mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0); 15743 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 15744 installFlags, packageAbiOverride); 15745 } catch (InstallerException e) { 15746 Slog.w(TAG, "Failed to free cache", e); 15747 } 15748 15749 /* 15750 * The cache free must have deleted the file we 15751 * downloaded to install. 15752 * 15753 * TODO: fix the "freeCache" call to not delete 15754 * the file we care about. 15755 */ 15756 if (pkgLite.recommendedInstallLocation 15757 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 15758 pkgLite.recommendedInstallLocation 15759 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 15760 } 15761 } 15762 } 15763 15764 if (ret == PackageManager.INSTALL_SUCCEEDED) { 15765 int loc = pkgLite.recommendedInstallLocation; 15766 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 15767 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 15768 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 15769 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 15770 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 15771 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 15772 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 15773 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 15774 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 15775 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 15776 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 15777 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 15778 } else { 15779 // Override with defaults if needed. 15780 loc = installLocationPolicy(pkgLite); 15781 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 15782 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 15783 } else if (!onSd && !onInt) { 15784 // Override install location with flags 15785 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 15786 // Set the flag to install on external media. 15787 installFlags |= PackageManager.INSTALL_EXTERNAL; 15788 installFlags &= ~PackageManager.INSTALL_INTERNAL; 15789 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 15790 if (DEBUG_EPHEMERAL) { 15791 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 15792 } 15793 installFlags |= PackageManager.INSTALL_INSTANT_APP; 15794 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 15795 |PackageManager.INSTALL_INTERNAL); 15796 } else { 15797 // Make sure the flag for installing on external 15798 // media is unset 15799 installFlags |= PackageManager.INSTALL_INTERNAL; 15800 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 15801 } 15802 } 15803 } 15804 } 15805 15806 final InstallArgs args = createInstallArgs(this); 15807 mArgs = args; 15808 15809 if (ret == PackageManager.INSTALL_SUCCEEDED) { 15810 // TODO: http://b/22976637 15811 // Apps installed for "all" users use the device owner to verify the app 15812 UserHandle verifierUser = getUser(); 15813 if (verifierUser == UserHandle.ALL) { 15814 verifierUser = UserHandle.SYSTEM; 15815 } 15816 15817 /* 15818 * Determine if we have any installed package verifiers. If we 15819 * do, then we'll defer to them to verify the packages. 15820 */ 15821 final int requiredUid = mRequiredVerifierPackage == null ? -1 15822 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 15823 verifierUser.getIdentifier()); 15824 final int installerUid = 15825 verificationInfo == null ? -1 : verificationInfo.installerUid; 15826 if (!origin.existing && requiredUid != -1 15827 && isVerificationEnabled( 15828 verifierUser.getIdentifier(), installFlags, installerUid)) { 15829 final Intent verification = new Intent( 15830 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 15831 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 15832 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 15833 PACKAGE_MIME_TYPE); 15834 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 15835 15836 // Query all live verifiers based on current user state 15837 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 15838 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 15839 15840 if (DEBUG_VERIFY) { 15841 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 15842 + verification.toString() + " with " + pkgLite.verifiers.length 15843 + " optional verifiers"); 15844 } 15845 15846 final int verificationId = mPendingVerificationToken++; 15847 15848 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 15849 15850 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 15851 installerPackageName); 15852 15853 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 15854 installFlags); 15855 15856 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 15857 pkgLite.packageName); 15858 15859 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 15860 pkgLite.versionCode); 15861 15862 if (verificationInfo != null) { 15863 if (verificationInfo.originatingUri != null) { 15864 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 15865 verificationInfo.originatingUri); 15866 } 15867 if (verificationInfo.referrer != null) { 15868 verification.putExtra(Intent.EXTRA_REFERRER, 15869 verificationInfo.referrer); 15870 } 15871 if (verificationInfo.originatingUid >= 0) { 15872 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 15873 verificationInfo.originatingUid); 15874 } 15875 if (verificationInfo.installerUid >= 0) { 15876 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 15877 verificationInfo.installerUid); 15878 } 15879 } 15880 15881 final PackageVerificationState verificationState = new PackageVerificationState( 15882 requiredUid, args); 15883 15884 mPendingVerification.append(verificationId, verificationState); 15885 15886 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 15887 receivers, verificationState); 15888 15889 DeviceIdleController.LocalService idleController = getDeviceIdleController(); 15890 final long idleDuration = getVerificationTimeout(); 15891 15892 /* 15893 * If any sufficient verifiers were listed in the package 15894 * manifest, attempt to ask them. 15895 */ 15896 if (sufficientVerifiers != null) { 15897 final int N = sufficientVerifiers.size(); 15898 if (N == 0) { 15899 Slog.i(TAG, "Additional verifiers required, but none installed."); 15900 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 15901 } else { 15902 for (int i = 0; i < N; i++) { 15903 final ComponentName verifierComponent = sufficientVerifiers.get(i); 15904 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 15905 verifierComponent.getPackageName(), idleDuration, 15906 verifierUser.getIdentifier(), false, "package verifier"); 15907 15908 final Intent sufficientIntent = new Intent(verification); 15909 sufficientIntent.setComponent(verifierComponent); 15910 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 15911 } 15912 } 15913 } 15914 15915 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 15916 mRequiredVerifierPackage, receivers); 15917 if (ret == PackageManager.INSTALL_SUCCEEDED 15918 && mRequiredVerifierPackage != null) { 15919 Trace.asyncTraceBegin( 15920 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 15921 /* 15922 * Send the intent to the required verification agent, 15923 * but only start the verification timeout after the 15924 * target BroadcastReceivers have run. 15925 */ 15926 verification.setComponent(requiredVerifierComponent); 15927 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 15928 mRequiredVerifierPackage, idleDuration, 15929 verifierUser.getIdentifier(), false, "package verifier"); 15930 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 15931 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 15932 new BroadcastReceiver() { 15933 @Override 15934 public void onReceive(Context context, Intent intent) { 15935 final Message msg = mHandler 15936 .obtainMessage(CHECK_PENDING_VERIFICATION); 15937 msg.arg1 = verificationId; 15938 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 15939 } 15940 }, null, 0, null, null); 15941 15942 /* 15943 * We don't want the copy to proceed until verification 15944 * succeeds, so null out this field. 15945 */ 15946 mArgs = null; 15947 } 15948 } else { 15949 /* 15950 * No package verification is enabled, so immediately start 15951 * the remote call to initiate copy using temporary file. 15952 */ 15953 ret = args.copyApk(mContainerService, true); 15954 } 15955 } 15956 15957 mRet = ret; 15958 } 15959 15960 @Override 15961 void handleReturnCode() { 15962 // If mArgs is null, then MCS couldn't be reached. When it 15963 // reconnects, it will try again to install. At that point, this 15964 // will succeed. 15965 if (mArgs != null) { 15966 processPendingInstall(mArgs, mRet); 15967 } 15968 } 15969 15970 @Override 15971 void handleServiceError() { 15972 mArgs = createInstallArgs(this); 15973 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15974 } 15975 15976 public boolean isForwardLocked() { 15977 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 15978 } 15979 } 15980 15981 /** 15982 * Used during creation of InstallArgs 15983 * 15984 * @param installFlags package installation flags 15985 * @return true if should be installed on external storage 15986 */ 15987 private static boolean installOnExternalAsec(int installFlags) { 15988 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 15989 return false; 15990 } 15991 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 15992 return true; 15993 } 15994 return false; 15995 } 15996 15997 /** 15998 * Used during creation of InstallArgs 15999 * 16000 * @param installFlags package installation flags 16001 * @return true if should be installed as forward locked 16002 */ 16003 private static boolean installForwardLocked(int installFlags) { 16004 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 16005 } 16006 16007 private InstallArgs createInstallArgs(InstallParams params) { 16008 if (params.move != null) { 16009 return new MoveInstallArgs(params); 16010 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 16011 return new AsecInstallArgs(params); 16012 } else { 16013 return new FileInstallArgs(params); 16014 } 16015 } 16016 16017 /** 16018 * Create args that describe an existing installed package. Typically used 16019 * when cleaning up old installs, or used as a move source. 16020 */ 16021 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 16022 String resourcePath, String[] instructionSets) { 16023 final boolean isInAsec; 16024 if (installOnExternalAsec(installFlags)) { 16025 /* Apps on SD card are always in ASEC containers. */ 16026 isInAsec = true; 16027 } else if (installForwardLocked(installFlags) 16028 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 16029 /* 16030 * Forward-locked apps are only in ASEC containers if they're the 16031 * new style 16032 */ 16033 isInAsec = true; 16034 } else { 16035 isInAsec = false; 16036 } 16037 16038 if (isInAsec) { 16039 return new AsecInstallArgs(codePath, instructionSets, 16040 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 16041 } else { 16042 return new FileInstallArgs(codePath, resourcePath, instructionSets); 16043 } 16044 } 16045 16046 static abstract class InstallArgs { 16047 /** @see InstallParams#origin */ 16048 final OriginInfo origin; 16049 /** @see InstallParams#move */ 16050 final MoveInfo move; 16051 16052 final IPackageInstallObserver2 observer; 16053 // Always refers to PackageManager flags only 16054 final int installFlags; 16055 final String installerPackageName; 16056 final String volumeUuid; 16057 final UserHandle user; 16058 final String abiOverride; 16059 final String[] installGrantPermissions; 16060 /** If non-null, drop an async trace when the install completes */ 16061 final String traceMethod; 16062 final int traceCookie; 16063 final Certificate[][] certificates; 16064 final int installReason; 16065 16066 // The list of instruction sets supported by this app. This is currently 16067 // only used during the rmdex() phase to clean up resources. We can get rid of this 16068 // if we move dex files under the common app path. 16069 /* nullable */ String[] instructionSets; 16070 16071 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 16072 int installFlags, String installerPackageName, String volumeUuid, 16073 UserHandle user, String[] instructionSets, 16074 String abiOverride, String[] installGrantPermissions, 16075 String traceMethod, int traceCookie, Certificate[][] certificates, 16076 int installReason) { 16077 this.origin = origin; 16078 this.move = move; 16079 this.installFlags = installFlags; 16080 this.observer = observer; 16081 this.installerPackageName = installerPackageName; 16082 this.volumeUuid = volumeUuid; 16083 this.user = user; 16084 this.instructionSets = instructionSets; 16085 this.abiOverride = abiOverride; 16086 this.installGrantPermissions = installGrantPermissions; 16087 this.traceMethod = traceMethod; 16088 this.traceCookie = traceCookie; 16089 this.certificates = certificates; 16090 this.installReason = installReason; 16091 } 16092 16093 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 16094 abstract int doPreInstall(int status); 16095 16096 /** 16097 * Rename package into final resting place. All paths on the given 16098 * scanned package should be updated to reflect the rename. 16099 */ 16100 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 16101 abstract int doPostInstall(int status, int uid); 16102 16103 /** @see PackageSettingBase#codePathString */ 16104 abstract String getCodePath(); 16105 /** @see PackageSettingBase#resourcePathString */ 16106 abstract String getResourcePath(); 16107 16108 // Need installer lock especially for dex file removal. 16109 abstract void cleanUpResourcesLI(); 16110 abstract boolean doPostDeleteLI(boolean delete); 16111 16112 /** 16113 * Called before the source arguments are copied. This is used mostly 16114 * for MoveParams when it needs to read the source file to put it in the 16115 * destination. 16116 */ 16117 int doPreCopy() { 16118 return PackageManager.INSTALL_SUCCEEDED; 16119 } 16120 16121 /** 16122 * Called after the source arguments are copied. This is used mostly for 16123 * MoveParams when it needs to read the source file to put it in the 16124 * destination. 16125 */ 16126 int doPostCopy(int uid) { 16127 return PackageManager.INSTALL_SUCCEEDED; 16128 } 16129 16130 protected boolean isFwdLocked() { 16131 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 16132 } 16133 16134 protected boolean isExternalAsec() { 16135 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 16136 } 16137 16138 protected boolean isEphemeral() { 16139 return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 16140 } 16141 16142 UserHandle getUser() { 16143 return user; 16144 } 16145 } 16146 16147 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 16148 if (!allCodePaths.isEmpty()) { 16149 if (instructionSets == null) { 16150 throw new IllegalStateException("instructionSet == null"); 16151 } 16152 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 16153 for (String codePath : allCodePaths) { 16154 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 16155 try { 16156 mInstaller.rmdex(codePath, dexCodeInstructionSet); 16157 } catch (InstallerException ignored) { 16158 } 16159 } 16160 } 16161 } 16162 } 16163 16164 /** 16165 * Logic to handle installation of non-ASEC applications, including copying 16166 * and renaming logic. 16167 */ 16168 class FileInstallArgs extends InstallArgs { 16169 private File codeFile; 16170 private File resourceFile; 16171 16172 // Example topology: 16173 // /data/app/com.example/base.apk 16174 // /data/app/com.example/split_foo.apk 16175 // /data/app/com.example/lib/arm/libfoo.so 16176 // /data/app/com.example/lib/arm64/libfoo.so 16177 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 16178 16179 /** New install */ 16180 FileInstallArgs(InstallParams params) { 16181 super(params.origin, params.move, params.observer, params.installFlags, 16182 params.installerPackageName, params.volumeUuid, 16183 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 16184 params.grantedRuntimePermissions, 16185 params.traceMethod, params.traceCookie, params.certificates, 16186 params.installReason); 16187 if (isFwdLocked()) { 16188 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 16189 } 16190 } 16191 16192 /** Existing install */ 16193 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 16194 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 16195 null, null, null, 0, null /*certificates*/, 16196 PackageManager.INSTALL_REASON_UNKNOWN); 16197 this.codeFile = (codePath != null) ? new File(codePath) : null; 16198 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 16199 } 16200 16201 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 16202 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 16203 try { 16204 return doCopyApk(imcs, temp); 16205 } finally { 16206 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16207 } 16208 } 16209 16210 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 16211 if (origin.staged) { 16212 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 16213 codeFile = origin.file; 16214 resourceFile = origin.file; 16215 return PackageManager.INSTALL_SUCCEEDED; 16216 } 16217 16218 try { 16219 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 16220 final File tempDir = 16221 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 16222 codeFile = tempDir; 16223 resourceFile = tempDir; 16224 } catch (IOException e) { 16225 Slog.w(TAG, "Failed to create copy file: " + e); 16226 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 16227 } 16228 16229 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 16230 @Override 16231 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 16232 if (!FileUtils.isValidExtFilename(name)) { 16233 throw new IllegalArgumentException("Invalid filename: " + name); 16234 } 16235 try { 16236 final File file = new File(codeFile, name); 16237 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 16238 O_RDWR | O_CREAT, 0644); 16239 Os.chmod(file.getAbsolutePath(), 0644); 16240 return new ParcelFileDescriptor(fd); 16241 } catch (ErrnoException e) { 16242 throw new RemoteException("Failed to open: " + e.getMessage()); 16243 } 16244 } 16245 }; 16246 16247 int ret = PackageManager.INSTALL_SUCCEEDED; 16248 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 16249 if (ret != PackageManager.INSTALL_SUCCEEDED) { 16250 Slog.e(TAG, "Failed to copy package"); 16251 return ret; 16252 } 16253 16254 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 16255 NativeLibraryHelper.Handle handle = null; 16256 try { 16257 handle = NativeLibraryHelper.Handle.create(codeFile); 16258 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 16259 abiOverride); 16260 } catch (IOException e) { 16261 Slog.e(TAG, "Copying native libraries failed", e); 16262 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 16263 } finally { 16264 IoUtils.closeQuietly(handle); 16265 } 16266 16267 return ret; 16268 } 16269 16270 int doPreInstall(int status) { 16271 if (status != PackageManager.INSTALL_SUCCEEDED) { 16272 cleanUp(); 16273 } 16274 return status; 16275 } 16276 16277 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 16278 if (status != PackageManager.INSTALL_SUCCEEDED) { 16279 cleanUp(); 16280 return false; 16281 } 16282 16283 final File targetDir = codeFile.getParentFile(); 16284 final File beforeCodeFile = codeFile; 16285 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 16286 16287 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 16288 try { 16289 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 16290 } catch (ErrnoException e) { 16291 Slog.w(TAG, "Failed to rename", e); 16292 return false; 16293 } 16294 16295 if (!SELinux.restoreconRecursive(afterCodeFile)) { 16296 Slog.w(TAG, "Failed to restorecon"); 16297 return false; 16298 } 16299 16300 // Reflect the rename internally 16301 codeFile = afterCodeFile; 16302 resourceFile = afterCodeFile; 16303 16304 // Reflect the rename in scanned details 16305 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 16306 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 16307 afterCodeFile, pkg.baseCodePath)); 16308 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 16309 afterCodeFile, pkg.splitCodePaths)); 16310 16311 // Reflect the rename in app info 16312 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 16313 pkg.setApplicationInfoCodePath(pkg.codePath); 16314 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 16315 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 16316 pkg.setApplicationInfoResourcePath(pkg.codePath); 16317 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 16318 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 16319 16320 return true; 16321 } 16322 16323 int doPostInstall(int status, int uid) { 16324 if (status != PackageManager.INSTALL_SUCCEEDED) { 16325 cleanUp(); 16326 } 16327 return status; 16328 } 16329 16330 @Override 16331 String getCodePath() { 16332 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 16333 } 16334 16335 @Override 16336 String getResourcePath() { 16337 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 16338 } 16339 16340 private boolean cleanUp() { 16341 if (codeFile == null || !codeFile.exists()) { 16342 return false; 16343 } 16344 16345 removeCodePathLI(codeFile); 16346 16347 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 16348 resourceFile.delete(); 16349 } 16350 16351 return true; 16352 } 16353 16354 void cleanUpResourcesLI() { 16355 // Try enumerating all code paths before deleting 16356 List<String> allCodePaths = Collections.EMPTY_LIST; 16357 if (codeFile != null && codeFile.exists()) { 16358 try { 16359 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 16360 allCodePaths = pkg.getAllCodePaths(); 16361 } catch (PackageParserException e) { 16362 // Ignored; we tried our best 16363 } 16364 } 16365 16366 cleanUp(); 16367 removeDexFiles(allCodePaths, instructionSets); 16368 } 16369 16370 boolean doPostDeleteLI(boolean delete) { 16371 // XXX err, shouldn't we respect the delete flag? 16372 cleanUpResourcesLI(); 16373 return true; 16374 } 16375 } 16376 16377 private boolean isAsecExternal(String cid) { 16378 final String asecPath = PackageHelper.getSdFilesystem(cid); 16379 return !asecPath.startsWith(mAsecInternalPath); 16380 } 16381 16382 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 16383 PackageManagerException { 16384 if (copyRet < 0) { 16385 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 16386 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 16387 throw new PackageManagerException(copyRet, message); 16388 } 16389 } 16390 } 16391 16392 /** 16393 * Extract the StorageManagerService "container ID" from the full code path of an 16394 * .apk. 16395 */ 16396 static String cidFromCodePath(String fullCodePath) { 16397 int eidx = fullCodePath.lastIndexOf("/"); 16398 String subStr1 = fullCodePath.substring(0, eidx); 16399 int sidx = subStr1.lastIndexOf("/"); 16400 return subStr1.substring(sidx+1, eidx); 16401 } 16402 16403 /** 16404 * Logic to handle installation of ASEC applications, including copying and 16405 * renaming logic. 16406 */ 16407 class AsecInstallArgs extends InstallArgs { 16408 static final String RES_FILE_NAME = "pkg.apk"; 16409 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 16410 16411 String cid; 16412 String packagePath; 16413 String resourcePath; 16414 16415 /** New install */ 16416 AsecInstallArgs(InstallParams params) { 16417 super(params.origin, params.move, params.observer, params.installFlags, 16418 params.installerPackageName, params.volumeUuid, 16419 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 16420 params.grantedRuntimePermissions, 16421 params.traceMethod, params.traceCookie, params.certificates, 16422 params.installReason); 16423 } 16424 16425 /** Existing install */ 16426 AsecInstallArgs(String fullCodePath, String[] instructionSets, 16427 boolean isExternal, boolean isForwardLocked) { 16428 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 16429 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 16430 instructionSets, null, null, null, 0, null /*certificates*/, 16431 PackageManager.INSTALL_REASON_UNKNOWN); 16432 // Hackily pretend we're still looking at a full code path 16433 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 16434 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 16435 } 16436 16437 // Extract cid from fullCodePath 16438 int eidx = fullCodePath.lastIndexOf("/"); 16439 String subStr1 = fullCodePath.substring(0, eidx); 16440 int sidx = subStr1.lastIndexOf("/"); 16441 cid = subStr1.substring(sidx+1, eidx); 16442 setMountPath(subStr1); 16443 } 16444 16445 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 16446 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 16447 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 16448 instructionSets, null, null, null, 0, null /*certificates*/, 16449 PackageManager.INSTALL_REASON_UNKNOWN); 16450 this.cid = cid; 16451 setMountPath(PackageHelper.getSdDir(cid)); 16452 } 16453 16454 void createCopyFile() { 16455 cid = mInstallerService.allocateExternalStageCidLegacy(); 16456 } 16457 16458 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 16459 if (origin.staged && origin.cid != null) { 16460 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 16461 cid = origin.cid; 16462 setMountPath(PackageHelper.getSdDir(cid)); 16463 return PackageManager.INSTALL_SUCCEEDED; 16464 } 16465 16466 if (temp) { 16467 createCopyFile(); 16468 } else { 16469 /* 16470 * Pre-emptively destroy the container since it's destroyed if 16471 * copying fails due to it existing anyway. 16472 */ 16473 PackageHelper.destroySdDir(cid); 16474 } 16475 16476 final String newMountPath = imcs.copyPackageToContainer( 16477 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 16478 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 16479 16480 if (newMountPath != null) { 16481 setMountPath(newMountPath); 16482 return PackageManager.INSTALL_SUCCEEDED; 16483 } else { 16484 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 16485 } 16486 } 16487 16488 @Override 16489 String getCodePath() { 16490 return packagePath; 16491 } 16492 16493 @Override 16494 String getResourcePath() { 16495 return resourcePath; 16496 } 16497 16498 int doPreInstall(int status) { 16499 if (status != PackageManager.INSTALL_SUCCEEDED) { 16500 // Destroy container 16501 PackageHelper.destroySdDir(cid); 16502 } else { 16503 boolean mounted = PackageHelper.isContainerMounted(cid); 16504 if (!mounted) { 16505 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 16506 Process.SYSTEM_UID); 16507 if (newMountPath != null) { 16508 setMountPath(newMountPath); 16509 } else { 16510 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 16511 } 16512 } 16513 } 16514 return status; 16515 } 16516 16517 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 16518 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 16519 String newMountPath = null; 16520 if (PackageHelper.isContainerMounted(cid)) { 16521 // Unmount the container 16522 if (!PackageHelper.unMountSdDir(cid)) { 16523 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 16524 return false; 16525 } 16526 } 16527 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 16528 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 16529 " which might be stale. Will try to clean up."); 16530 // Clean up the stale container and proceed to recreate. 16531 if (!PackageHelper.destroySdDir(newCacheId)) { 16532 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 16533 return false; 16534 } 16535 // Successfully cleaned up stale container. Try to rename again. 16536 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 16537 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 16538 + " inspite of cleaning it up."); 16539 return false; 16540 } 16541 } 16542 if (!PackageHelper.isContainerMounted(newCacheId)) { 16543 Slog.w(TAG, "Mounting container " + newCacheId); 16544 newMountPath = PackageHelper.mountSdDir(newCacheId, 16545 getEncryptKey(), Process.SYSTEM_UID); 16546 } else { 16547 newMountPath = PackageHelper.getSdDir(newCacheId); 16548 } 16549 if (newMountPath == null) { 16550 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 16551 return false; 16552 } 16553 Log.i(TAG, "Succesfully renamed " + cid + 16554 " to " + newCacheId + 16555 " at new path: " + newMountPath); 16556 cid = newCacheId; 16557 16558 final File beforeCodeFile = new File(packagePath); 16559 setMountPath(newMountPath); 16560 final File afterCodeFile = new File(packagePath); 16561 16562 // Reflect the rename in scanned details 16563 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 16564 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 16565 afterCodeFile, pkg.baseCodePath)); 16566 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 16567 afterCodeFile, pkg.splitCodePaths)); 16568 16569 // Reflect the rename in app info 16570 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 16571 pkg.setApplicationInfoCodePath(pkg.codePath); 16572 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 16573 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 16574 pkg.setApplicationInfoResourcePath(pkg.codePath); 16575 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 16576 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 16577 16578 return true; 16579 } 16580 16581 private void setMountPath(String mountPath) { 16582 final File mountFile = new File(mountPath); 16583 16584 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 16585 if (monolithicFile.exists()) { 16586 packagePath = monolithicFile.getAbsolutePath(); 16587 if (isFwdLocked()) { 16588 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 16589 } else { 16590 resourcePath = packagePath; 16591 } 16592 } else { 16593 packagePath = mountFile.getAbsolutePath(); 16594 resourcePath = packagePath; 16595 } 16596 } 16597 16598 int doPostInstall(int status, int uid) { 16599 if (status != PackageManager.INSTALL_SUCCEEDED) { 16600 cleanUp(); 16601 } else { 16602 final int groupOwner; 16603 final String protectedFile; 16604 if (isFwdLocked()) { 16605 groupOwner = UserHandle.getSharedAppGid(uid); 16606 protectedFile = RES_FILE_NAME; 16607 } else { 16608 groupOwner = -1; 16609 protectedFile = null; 16610 } 16611 16612 if (uid < Process.FIRST_APPLICATION_UID 16613 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 16614 Slog.e(TAG, "Failed to finalize " + cid); 16615 PackageHelper.destroySdDir(cid); 16616 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 16617 } 16618 16619 boolean mounted = PackageHelper.isContainerMounted(cid); 16620 if (!mounted) { 16621 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 16622 } 16623 } 16624 return status; 16625 } 16626 16627 private void cleanUp() { 16628 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 16629 16630 // Destroy secure container 16631 PackageHelper.destroySdDir(cid); 16632 } 16633 16634 private List<String> getAllCodePaths() { 16635 final File codeFile = new File(getCodePath()); 16636 if (codeFile != null && codeFile.exists()) { 16637 try { 16638 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 16639 return pkg.getAllCodePaths(); 16640 } catch (PackageParserException e) { 16641 // Ignored; we tried our best 16642 } 16643 } 16644 return Collections.EMPTY_LIST; 16645 } 16646 16647 void cleanUpResourcesLI() { 16648 // Enumerate all code paths before deleting 16649 cleanUpResourcesLI(getAllCodePaths()); 16650 } 16651 16652 private void cleanUpResourcesLI(List<String> allCodePaths) { 16653 cleanUp(); 16654 removeDexFiles(allCodePaths, instructionSets); 16655 } 16656 16657 String getPackageName() { 16658 return getAsecPackageName(cid); 16659 } 16660 16661 boolean doPostDeleteLI(boolean delete) { 16662 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 16663 final List<String> allCodePaths = getAllCodePaths(); 16664 boolean mounted = PackageHelper.isContainerMounted(cid); 16665 if (mounted) { 16666 // Unmount first 16667 if (PackageHelper.unMountSdDir(cid)) { 16668 mounted = false; 16669 } 16670 } 16671 if (!mounted && delete) { 16672 cleanUpResourcesLI(allCodePaths); 16673 } 16674 return !mounted; 16675 } 16676 16677 @Override 16678 int doPreCopy() { 16679 if (isFwdLocked()) { 16680 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 16681 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 16682 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 16683 } 16684 } 16685 16686 return PackageManager.INSTALL_SUCCEEDED; 16687 } 16688 16689 @Override 16690 int doPostCopy(int uid) { 16691 if (isFwdLocked()) { 16692 if (uid < Process.FIRST_APPLICATION_UID 16693 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 16694 RES_FILE_NAME)) { 16695 Slog.e(TAG, "Failed to finalize " + cid); 16696 PackageHelper.destroySdDir(cid); 16697 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 16698 } 16699 } 16700 16701 return PackageManager.INSTALL_SUCCEEDED; 16702 } 16703 } 16704 16705 /** 16706 * Logic to handle movement of existing installed applications. 16707 */ 16708 class MoveInstallArgs extends InstallArgs { 16709 private File codeFile; 16710 private File resourceFile; 16711 16712 /** New install */ 16713 MoveInstallArgs(InstallParams params) { 16714 super(params.origin, params.move, params.observer, params.installFlags, 16715 params.installerPackageName, params.volumeUuid, 16716 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 16717 params.grantedRuntimePermissions, 16718 params.traceMethod, params.traceCookie, params.certificates, 16719 params.installReason); 16720 } 16721 16722 int copyApk(IMediaContainerService imcs, boolean temp) { 16723 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 16724 + move.fromUuid + " to " + move.toUuid); 16725 synchronized (mInstaller) { 16726 try { 16727 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 16728 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 16729 } catch (InstallerException e) { 16730 Slog.w(TAG, "Failed to move app", e); 16731 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 16732 } 16733 } 16734 16735 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 16736 resourceFile = codeFile; 16737 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 16738 16739 return PackageManager.INSTALL_SUCCEEDED; 16740 } 16741 16742 int doPreInstall(int status) { 16743 if (status != PackageManager.INSTALL_SUCCEEDED) { 16744 cleanUp(move.toUuid); 16745 } 16746 return status; 16747 } 16748 16749 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 16750 if (status != PackageManager.INSTALL_SUCCEEDED) { 16751 cleanUp(move.toUuid); 16752 return false; 16753 } 16754 16755 // Reflect the move in app info 16756 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 16757 pkg.setApplicationInfoCodePath(pkg.codePath); 16758 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 16759 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 16760 pkg.setApplicationInfoResourcePath(pkg.codePath); 16761 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 16762 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 16763 16764 return true; 16765 } 16766 16767 int doPostInstall(int status, int uid) { 16768 if (status == PackageManager.INSTALL_SUCCEEDED) { 16769 cleanUp(move.fromUuid); 16770 } else { 16771 cleanUp(move.toUuid); 16772 } 16773 return status; 16774 } 16775 16776 @Override 16777 String getCodePath() { 16778 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 16779 } 16780 16781 @Override 16782 String getResourcePath() { 16783 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 16784 } 16785 16786 private boolean cleanUp(String volumeUuid) { 16787 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 16788 move.dataAppName); 16789 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 16790 final int[] userIds = sUserManager.getUserIds(); 16791 synchronized (mInstallLock) { 16792 // Clean up both app data and code 16793 // All package moves are frozen until finished 16794 for (int userId : userIds) { 16795 try { 16796 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 16797 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 16798 } catch (InstallerException e) { 16799 Slog.w(TAG, String.valueOf(e)); 16800 } 16801 } 16802 removeCodePathLI(codeFile); 16803 } 16804 return true; 16805 } 16806 16807 void cleanUpResourcesLI() { 16808 throw new UnsupportedOperationException(); 16809 } 16810 16811 boolean doPostDeleteLI(boolean delete) { 16812 throw new UnsupportedOperationException(); 16813 } 16814 } 16815 16816 static String getAsecPackageName(String packageCid) { 16817 int idx = packageCid.lastIndexOf("-"); 16818 if (idx == -1) { 16819 return packageCid; 16820 } 16821 return packageCid.substring(0, idx); 16822 } 16823 16824 // Utility method used to create code paths based on package name and available index. 16825 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 16826 String idxStr = ""; 16827 int idx = 1; 16828 // Fall back to default value of idx=1 if prefix is not 16829 // part of oldCodePath 16830 if (oldCodePath != null) { 16831 String subStr = oldCodePath; 16832 // Drop the suffix right away 16833 if (suffix != null && subStr.endsWith(suffix)) { 16834 subStr = subStr.substring(0, subStr.length() - suffix.length()); 16835 } 16836 // If oldCodePath already contains prefix find out the 16837 // ending index to either increment or decrement. 16838 int sidx = subStr.lastIndexOf(prefix); 16839 if (sidx != -1) { 16840 subStr = subStr.substring(sidx + prefix.length()); 16841 if (subStr != null) { 16842 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 16843 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 16844 } 16845 try { 16846 idx = Integer.parseInt(subStr); 16847 if (idx <= 1) { 16848 idx++; 16849 } else { 16850 idx--; 16851 } 16852 } catch(NumberFormatException e) { 16853 } 16854 } 16855 } 16856 } 16857 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 16858 return prefix + idxStr; 16859 } 16860 16861 private File getNextCodePath(File targetDir, String packageName) { 16862 File result; 16863 SecureRandom random = new SecureRandom(); 16864 byte[] bytes = new byte[16]; 16865 do { 16866 random.nextBytes(bytes); 16867 String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP); 16868 result = new File(targetDir, packageName + "-" + suffix); 16869 } while (result.exists()); 16870 return result; 16871 } 16872 16873 // Utility method that returns the relative package path with respect 16874 // to the installation directory. Like say for /data/data/com.test-1.apk 16875 // string com.test-1 is returned. 16876 static String deriveCodePathName(String codePath) { 16877 if (codePath == null) { 16878 return null; 16879 } 16880 final File codeFile = new File(codePath); 16881 final String name = codeFile.getName(); 16882 if (codeFile.isDirectory()) { 16883 return name; 16884 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 16885 final int lastDot = name.lastIndexOf('.'); 16886 return name.substring(0, lastDot); 16887 } else { 16888 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 16889 return null; 16890 } 16891 } 16892 16893 static class PackageInstalledInfo { 16894 String name; 16895 int uid; 16896 // The set of users that originally had this package installed. 16897 int[] origUsers; 16898 // The set of users that now have this package installed. 16899 int[] newUsers; 16900 PackageParser.Package pkg; 16901 int returnCode; 16902 String returnMsg; 16903 PackageRemovedInfo removedInfo; 16904 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 16905 16906 public void setError(int code, String msg) { 16907 setReturnCode(code); 16908 setReturnMessage(msg); 16909 Slog.w(TAG, msg); 16910 } 16911 16912 public void setError(String msg, PackageParserException e) { 16913 setReturnCode(e.error); 16914 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 16915 Slog.w(TAG, msg, e); 16916 } 16917 16918 public void setError(String msg, PackageManagerException e) { 16919 returnCode = e.error; 16920 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 16921 Slog.w(TAG, msg, e); 16922 } 16923 16924 public void setReturnCode(int returnCode) { 16925 this.returnCode = returnCode; 16926 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 16927 for (int i = 0; i < childCount; i++) { 16928 addedChildPackages.valueAt(i).returnCode = returnCode; 16929 } 16930 } 16931 16932 private void setReturnMessage(String returnMsg) { 16933 this.returnMsg = returnMsg; 16934 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 16935 for (int i = 0; i < childCount; i++) { 16936 addedChildPackages.valueAt(i).returnMsg = returnMsg; 16937 } 16938 } 16939 16940 // In some error cases we want to convey more info back to the observer 16941 String origPackage; 16942 String origPermission; 16943 } 16944 16945 /* 16946 * Install a non-existing package. 16947 */ 16948 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 16949 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 16950 PackageInstalledInfo res, int installReason) { 16951 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 16952 16953 // Remember this for later, in case we need to rollback this install 16954 String pkgName = pkg.packageName; 16955 16956 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 16957 16958 synchronized(mPackages) { 16959 final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName); 16960 if (renamedPackage != null) { 16961 // A package with the same name is already installed, though 16962 // it has been renamed to an older name. The package we 16963 // are trying to install should be installed as an update to 16964 // the existing one, but that has not been requested, so bail. 16965 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 16966 + " without first uninstalling package running as " 16967 + renamedPackage); 16968 return; 16969 } 16970 if (mPackages.containsKey(pkgName)) { 16971 // Don't allow installation over an existing package with the same name. 16972 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 16973 + " without first uninstalling."); 16974 return; 16975 } 16976 } 16977 16978 try { 16979 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 16980 System.currentTimeMillis(), user); 16981 16982 updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason); 16983 16984 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 16985 prepareAppDataAfterInstallLIF(newPackage); 16986 16987 } else { 16988 // Remove package from internal structures, but keep around any 16989 // data that might have already existed 16990 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 16991 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 16992 } 16993 } catch (PackageManagerException e) { 16994 res.setError("Package couldn't be installed in " + pkg.codePath, e); 16995 } 16996 16997 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16998 } 16999 17000 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 17001 // Can't rotate keys during boot or if sharedUser. 17002 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 17003 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 17004 return false; 17005 } 17006 // app is using upgradeKeySets; make sure all are valid 17007 KeySetManagerService ksms = mSettings.mKeySetManagerService; 17008 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 17009 for (int i = 0; i < upgradeKeySets.length; i++) { 17010 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 17011 Slog.wtf(TAG, "Package " 17012 + (oldPs.name != null ? oldPs.name : "<null>") 17013 + " contains upgrade-key-set reference to unknown key-set: " 17014 + upgradeKeySets[i] 17015 + " reverting to signatures check."); 17016 return false; 17017 } 17018 } 17019 return true; 17020 } 17021 17022 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 17023 // Upgrade keysets are being used. Determine if new package has a superset of the 17024 // required keys. 17025 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 17026 KeySetManagerService ksms = mSettings.mKeySetManagerService; 17027 for (int i = 0; i < upgradeKeySets.length; i++) { 17028 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 17029 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 17030 return true; 17031 } 17032 } 17033 return false; 17034 } 17035 17036 private static void updateDigest(MessageDigest digest, File file) throws IOException { 17037 try (DigestInputStream digestStream = 17038 new DigestInputStream(new FileInputStream(file), digest)) { 17039 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 17040 } 17041 } 17042 17043 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 17044 UserHandle user, String installerPackageName, PackageInstalledInfo res, 17045 int installReason) { 17046 final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 17047 17048 final PackageParser.Package oldPackage; 17049 final PackageSetting ps; 17050 final String pkgName = pkg.packageName; 17051 final int[] allUsers; 17052 final int[] installedUsers; 17053 17054 synchronized(mPackages) { 17055 oldPackage = mPackages.get(pkgName); 17056 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 17057 17058 // don't allow upgrade to target a release SDK from a pre-release SDK 17059 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 17060 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 17061 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 17062 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 17063 if (oldTargetsPreRelease 17064 && !newTargetsPreRelease 17065 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 17066 Slog.w(TAG, "Can't install package targeting released sdk"); 17067 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 17068 return; 17069 } 17070 17071 ps = mSettings.mPackages.get(pkgName); 17072 17073 // verify signatures are valid 17074 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 17075 if (!checkUpgradeKeySetLP(ps, pkg)) { 17076 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 17077 "New package not signed by keys specified by upgrade-keysets: " 17078 + pkgName); 17079 return; 17080 } 17081 } else { 17082 // default to original signature matching 17083 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 17084 != PackageManager.SIGNATURE_MATCH) { 17085 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 17086 "New package has a different signature: " + pkgName); 17087 return; 17088 } 17089 } 17090 17091 // don't allow a system upgrade unless the upgrade hash matches 17092 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 17093 byte[] digestBytes = null; 17094 try { 17095 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 17096 updateDigest(digest, new File(pkg.baseCodePath)); 17097 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 17098 for (String path : pkg.splitCodePaths) { 17099 updateDigest(digest, new File(path)); 17100 } 17101 } 17102 digestBytes = digest.digest(); 17103 } catch (NoSuchAlgorithmException | IOException e) { 17104 res.setError(INSTALL_FAILED_INVALID_APK, 17105 "Could not compute hash: " + pkgName); 17106 return; 17107 } 17108 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 17109 res.setError(INSTALL_FAILED_INVALID_APK, 17110 "New package fails restrict-update check: " + pkgName); 17111 return; 17112 } 17113 // retain upgrade restriction 17114 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 17115 } 17116 17117 // Check for shared user id changes 17118 String invalidPackageName = 17119 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 17120 if (invalidPackageName != null) { 17121 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 17122 "Package " + invalidPackageName + " tried to change user " 17123 + oldPackage.mSharedUserId); 17124 return; 17125 } 17126 17127 // In case of rollback, remember per-user/profile install state 17128 allUsers = sUserManager.getUserIds(); 17129 installedUsers = ps.queryInstalledUsers(allUsers, true); 17130 17131 // don't allow an upgrade from full to ephemeral 17132 if (isInstantApp) { 17133 if (user == null || user.getIdentifier() == UserHandle.USER_ALL) { 17134 for (int currentUser : allUsers) { 17135 if (!ps.getInstantApp(currentUser)) { 17136 // can't downgrade from full to instant 17137 Slog.w(TAG, "Can't replace full app with instant app: " + pkgName 17138 + " for user: " + currentUser); 17139 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 17140 return; 17141 } 17142 } 17143 } else if (!ps.getInstantApp(user.getIdentifier())) { 17144 // can't downgrade from full to instant 17145 Slog.w(TAG, "Can't replace full app with instant app: " + pkgName 17146 + " for user: " + user.getIdentifier()); 17147 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 17148 return; 17149 } 17150 } 17151 } 17152 17153 // Update what is removed 17154 res.removedInfo = new PackageRemovedInfo(this); 17155 res.removedInfo.uid = oldPackage.applicationInfo.uid; 17156 res.removedInfo.removedPackage = oldPackage.packageName; 17157 res.removedInfo.installerPackageName = ps.installerPackageName; 17158 res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null; 17159 res.removedInfo.isUpdate = true; 17160 res.removedInfo.origUsers = installedUsers; 17161 res.removedInfo.installReasons = new SparseArray<>(installedUsers.length); 17162 for (int i = 0; i < installedUsers.length; i++) { 17163 final int userId = installedUsers[i]; 17164 res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId)); 17165 } 17166 17167 final int childCount = (oldPackage.childPackages != null) 17168 ? oldPackage.childPackages.size() : 0; 17169 for (int i = 0; i < childCount; i++) { 17170 boolean childPackageUpdated = false; 17171 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 17172 final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 17173 if (res.addedChildPackages != null) { 17174 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 17175 if (childRes != null) { 17176 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 17177 childRes.removedInfo.removedPackage = childPkg.packageName; 17178 if (childPs != null) { 17179 childRes.removedInfo.installerPackageName = childPs.installerPackageName; 17180 } 17181 childRes.removedInfo.isUpdate = true; 17182 childRes.removedInfo.installReasons = res.removedInfo.installReasons; 17183 childPackageUpdated = true; 17184 } 17185 } 17186 if (!childPackageUpdated) { 17187 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this); 17188 childRemovedRes.removedPackage = childPkg.packageName; 17189 if (childPs != null) { 17190 childRemovedRes.installerPackageName = childPs.installerPackageName; 17191 } 17192 childRemovedRes.isUpdate = false; 17193 childRemovedRes.dataRemoved = true; 17194 synchronized (mPackages) { 17195 if (childPs != null) { 17196 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 17197 } 17198 } 17199 if (res.removedInfo.removedChildPackages == null) { 17200 res.removedInfo.removedChildPackages = new ArrayMap<>(); 17201 } 17202 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 17203 } 17204 } 17205 17206 boolean sysPkg = (isSystemApp(oldPackage)); 17207 if (sysPkg) { 17208 // Set the system/privileged flags as needed 17209 final boolean privileged = 17210 (oldPackage.applicationInfo.privateFlags 17211 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 17212 final int systemPolicyFlags = policyFlags 17213 | PackageParser.PARSE_IS_SYSTEM 17214 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 17215 17216 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 17217 user, allUsers, installerPackageName, res, installReason); 17218 } else { 17219 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 17220 user, allUsers, installerPackageName, res, installReason); 17221 } 17222 } 17223 17224 @Override 17225 public List<String> getPreviousCodePaths(String packageName) { 17226 final int callingUid = Binder.getCallingUid(); 17227 final List<String> result = new ArrayList<>(); 17228 if (getInstantAppPackageName(callingUid) != null) { 17229 return result; 17230 } 17231 final PackageSetting ps = mSettings.mPackages.get(packageName); 17232 if (ps != null 17233 && ps.oldCodePaths != null 17234 && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 17235 result.addAll(ps.oldCodePaths); 17236 } 17237 return result; 17238 } 17239 17240 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 17241 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 17242 int[] allUsers, String installerPackageName, PackageInstalledInfo res, 17243 int installReason) { 17244 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 17245 + deletedPackage); 17246 17247 String pkgName = deletedPackage.packageName; 17248 boolean deletedPkg = true; 17249 boolean addedPkg = false; 17250 boolean updatedSettings = false; 17251 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 17252 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 17253 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 17254 17255 final long origUpdateTime = (pkg.mExtras != null) 17256 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 17257 17258 // First delete the existing package while retaining the data directory 17259 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 17260 res.removedInfo, true, pkg)) { 17261 // If the existing package wasn't successfully deleted 17262 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 17263 deletedPkg = false; 17264 } else { 17265 // Successfully deleted the old package; proceed with replace. 17266 17267 // If deleted package lived in a container, give users a chance to 17268 // relinquish resources before killing. 17269 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 17270 if (DEBUG_INSTALL) { 17271 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 17272 } 17273 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 17274 final ArrayList<String> pkgList = new ArrayList<String>(1); 17275 pkgList.add(deletedPackage.applicationInfo.packageName); 17276 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 17277 } 17278 17279 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 17280 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 17281 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 17282 17283 try { 17284 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 17285 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 17286 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 17287 installReason); 17288 17289 // Update the in-memory copy of the previous code paths. 17290 PackageSetting ps = mSettings.mPackages.get(pkgName); 17291 if (!killApp) { 17292 if (ps.oldCodePaths == null) { 17293 ps.oldCodePaths = new ArraySet<>(); 17294 } 17295 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 17296 if (deletedPackage.splitCodePaths != null) { 17297 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 17298 } 17299 } else { 17300 ps.oldCodePaths = null; 17301 } 17302 if (ps.childPackageNames != null) { 17303 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 17304 final String childPkgName = ps.childPackageNames.get(i); 17305 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 17306 childPs.oldCodePaths = ps.oldCodePaths; 17307 } 17308 } 17309 // set instant app status, but, only if it's explicitly specified 17310 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 17311 final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0; 17312 setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp); 17313 prepareAppDataAfterInstallLIF(newPackage); 17314 addedPkg = true; 17315 mDexManager.notifyPackageUpdated(newPackage.packageName, 17316 newPackage.baseCodePath, newPackage.splitCodePaths); 17317 } catch (PackageManagerException e) { 17318 res.setError("Package couldn't be installed in " + pkg.codePath, e); 17319 } 17320 } 17321 17322 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 17323 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 17324 17325 // Revert all internal state mutations and added folders for the failed install 17326 if (addedPkg) { 17327 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 17328 res.removedInfo, true, null); 17329 } 17330 17331 // Restore the old package 17332 if (deletedPkg) { 17333 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 17334 File restoreFile = new File(deletedPackage.codePath); 17335 // Parse old package 17336 boolean oldExternal = isExternal(deletedPackage); 17337 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 17338 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 17339 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 17340 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 17341 try { 17342 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 17343 null); 17344 } catch (PackageManagerException e) { 17345 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 17346 + e.getMessage()); 17347 return; 17348 } 17349 17350 synchronized (mPackages) { 17351 // Ensure the installer package name up to date 17352 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 17353 17354 // Update permissions for restored package 17355 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 17356 17357 mSettings.writeLPr(); 17358 } 17359 17360 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 17361 } 17362 } else { 17363 synchronized (mPackages) { 17364 PackageSetting ps = mSettings.getPackageLPr(pkg.packageName); 17365 if (ps != null) { 17366 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 17367 if (res.removedInfo.removedChildPackages != null) { 17368 final int childCount = res.removedInfo.removedChildPackages.size(); 17369 // Iterate in reverse as we may modify the collection 17370 for (int i = childCount - 1; i >= 0; i--) { 17371 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 17372 if (res.addedChildPackages.containsKey(childPackageName)) { 17373 res.removedInfo.removedChildPackages.removeAt(i); 17374 } else { 17375 PackageRemovedInfo childInfo = res.removedInfo 17376 .removedChildPackages.valueAt(i); 17377 childInfo.removedForAllUsers = mPackages.get( 17378 childInfo.removedPackage) == null; 17379 } 17380 } 17381 } 17382 } 17383 } 17384 } 17385 } 17386 17387 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 17388 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 17389 int[] allUsers, String installerPackageName, PackageInstalledInfo res, 17390 int installReason) { 17391 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 17392 + ", old=" + deletedPackage); 17393 17394 final boolean disabledSystem; 17395 17396 // Remove existing system package 17397 removePackageLI(deletedPackage, true); 17398 17399 synchronized (mPackages) { 17400 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 17401 } 17402 if (!disabledSystem) { 17403 // We didn't need to disable the .apk as a current system package, 17404 // which means we are replacing another update that is already 17405 // installed. We need to make sure to delete the older one's .apk. 17406 res.removedInfo.args = createInstallArgsForExisting(0, 17407 deletedPackage.applicationInfo.getCodePath(), 17408 deletedPackage.applicationInfo.getResourcePath(), 17409 getAppDexInstructionSets(deletedPackage.applicationInfo)); 17410 } else { 17411 res.removedInfo.args = null; 17412 } 17413 17414 // Successfully disabled the old package. Now proceed with re-installation 17415 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 17416 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 17417 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 17418 17419 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 17420 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 17421 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 17422 17423 PackageParser.Package newPackage = null; 17424 try { 17425 // Add the package to the internal data structures 17426 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 17427 17428 // Set the update and install times 17429 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 17430 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 17431 System.currentTimeMillis()); 17432 17433 // Update the package dynamic state if succeeded 17434 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 17435 // Now that the install succeeded make sure we remove data 17436 // directories for any child package the update removed. 17437 final int deletedChildCount = (deletedPackage.childPackages != null) 17438 ? deletedPackage.childPackages.size() : 0; 17439 final int newChildCount = (newPackage.childPackages != null) 17440 ? newPackage.childPackages.size() : 0; 17441 for (int i = 0; i < deletedChildCount; i++) { 17442 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 17443 boolean childPackageDeleted = true; 17444 for (int j = 0; j < newChildCount; j++) { 17445 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 17446 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 17447 childPackageDeleted = false; 17448 break; 17449 } 17450 } 17451 if (childPackageDeleted) { 17452 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 17453 deletedChildPkg.packageName); 17454 if (ps != null && res.removedInfo.removedChildPackages != null) { 17455 PackageRemovedInfo removedChildRes = res.removedInfo 17456 .removedChildPackages.get(deletedChildPkg.packageName); 17457 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 17458 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 17459 } 17460 } 17461 } 17462 17463 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 17464 installReason); 17465 prepareAppDataAfterInstallLIF(newPackage); 17466 17467 mDexManager.notifyPackageUpdated(newPackage.packageName, 17468 newPackage.baseCodePath, newPackage.splitCodePaths); 17469 } 17470 } catch (PackageManagerException e) { 17471 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 17472 res.setError("Package couldn't be installed in " + pkg.codePath, e); 17473 } 17474 17475 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 17476 // Re installation failed. Restore old information 17477 // Remove new pkg information 17478 if (newPackage != null) { 17479 removeInstalledPackageLI(newPackage, true); 17480 } 17481 // Add back the old system package 17482 try { 17483 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 17484 } catch (PackageManagerException e) { 17485 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 17486 } 17487 17488 synchronized (mPackages) { 17489 if (disabledSystem) { 17490 enableSystemPackageLPw(deletedPackage); 17491 } 17492 17493 // Ensure the installer package name up to date 17494 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 17495 17496 // Update permissions for restored package 17497 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 17498 17499 mSettings.writeLPr(); 17500 } 17501 17502 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 17503 + " after failed upgrade"); 17504 } 17505 } 17506 17507 /** 17508 * Checks whether the parent or any of the child packages have a change shared 17509 * user. For a package to be a valid update the shred users of the parent and 17510 * the children should match. We may later support changing child shared users. 17511 * @param oldPkg The updated package. 17512 * @param newPkg The update package. 17513 * @return The shared user that change between the versions. 17514 */ 17515 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 17516 PackageParser.Package newPkg) { 17517 // Check parent shared user 17518 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 17519 return newPkg.packageName; 17520 } 17521 // Check child shared users 17522 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 17523 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 17524 for (int i = 0; i < newChildCount; i++) { 17525 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 17526 // If this child was present, did it have the same shared user? 17527 for (int j = 0; j < oldChildCount; j++) { 17528 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 17529 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 17530 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 17531 return newChildPkg.packageName; 17532 } 17533 } 17534 } 17535 return null; 17536 } 17537 17538 private void removeNativeBinariesLI(PackageSetting ps) { 17539 // Remove the lib path for the parent package 17540 if (ps != null) { 17541 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 17542 // Remove the lib path for the child packages 17543 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 17544 for (int i = 0; i < childCount; i++) { 17545 PackageSetting childPs = null; 17546 synchronized (mPackages) { 17547 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 17548 } 17549 if (childPs != null) { 17550 NativeLibraryHelper.removeNativeBinariesLI(childPs 17551 .legacyNativeLibraryPathString); 17552 } 17553 } 17554 } 17555 } 17556 17557 private void enableSystemPackageLPw(PackageParser.Package pkg) { 17558 // Enable the parent package 17559 mSettings.enableSystemPackageLPw(pkg.packageName); 17560 // Enable the child packages 17561 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 17562 for (int i = 0; i < childCount; i++) { 17563 PackageParser.Package childPkg = pkg.childPackages.get(i); 17564 mSettings.enableSystemPackageLPw(childPkg.packageName); 17565 } 17566 } 17567 17568 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 17569 PackageParser.Package newPkg) { 17570 // Disable the parent package (parent always replaced) 17571 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 17572 // Disable the child packages 17573 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 17574 for (int i = 0; i < childCount; i++) { 17575 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 17576 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 17577 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 17578 } 17579 return disabled; 17580 } 17581 17582 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 17583 String installerPackageName) { 17584 // Enable the parent package 17585 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 17586 // Enable the child packages 17587 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 17588 for (int i = 0; i < childCount; i++) { 17589 PackageParser.Package childPkg = pkg.childPackages.get(i); 17590 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 17591 } 17592 } 17593 17594 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 17595 // Collect all used permissions in the UID 17596 ArraySet<String> usedPermissions = new ArraySet<>(); 17597 final int packageCount = su.packages.size(); 17598 for (int i = 0; i < packageCount; i++) { 17599 PackageSetting ps = su.packages.valueAt(i); 17600 if (ps.pkg == null) { 17601 continue; 17602 } 17603 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 17604 for (int j = 0; j < requestedPermCount; j++) { 17605 String permission = ps.pkg.requestedPermissions.get(j); 17606 BasePermission bp = mSettings.mPermissions.get(permission); 17607 if (bp != null) { 17608 usedPermissions.add(permission); 17609 } 17610 } 17611 } 17612 17613 PermissionsState permissionsState = su.getPermissionsState(); 17614 // Prune install permissions 17615 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 17616 final int installPermCount = installPermStates.size(); 17617 for (int i = installPermCount - 1; i >= 0; i--) { 17618 PermissionState permissionState = installPermStates.get(i); 17619 if (!usedPermissions.contains(permissionState.getName())) { 17620 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 17621 if (bp != null) { 17622 permissionsState.revokeInstallPermission(bp); 17623 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 17624 PackageManager.MASK_PERMISSION_FLAGS, 0); 17625 } 17626 } 17627 } 17628 17629 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 17630 17631 // Prune runtime permissions 17632 for (int userId : allUserIds) { 17633 List<PermissionState> runtimePermStates = permissionsState 17634 .getRuntimePermissionStates(userId); 17635 final int runtimePermCount = runtimePermStates.size(); 17636 for (int i = runtimePermCount - 1; i >= 0; i--) { 17637 PermissionState permissionState = runtimePermStates.get(i); 17638 if (!usedPermissions.contains(permissionState.getName())) { 17639 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 17640 if (bp != null) { 17641 permissionsState.revokeRuntimePermission(bp, userId); 17642 permissionsState.updatePermissionFlags(bp, userId, 17643 PackageManager.MASK_PERMISSION_FLAGS, 0); 17644 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 17645 runtimePermissionChangedUserIds, userId); 17646 } 17647 } 17648 } 17649 } 17650 17651 return runtimePermissionChangedUserIds; 17652 } 17653 17654 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 17655 int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) { 17656 // Update the parent package setting 17657 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 17658 res, user, installReason); 17659 // Update the child packages setting 17660 final int childCount = (newPackage.childPackages != null) 17661 ? newPackage.childPackages.size() : 0; 17662 for (int i = 0; i < childCount; i++) { 17663 PackageParser.Package childPackage = newPackage.childPackages.get(i); 17664 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 17665 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 17666 childRes.origUsers, childRes, user, installReason); 17667 } 17668 } 17669 17670 private void updateSettingsInternalLI(PackageParser.Package newPackage, 17671 String installerPackageName, int[] allUsers, int[] installedForUsers, 17672 PackageInstalledInfo res, UserHandle user, int installReason) { 17673 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 17674 17675 String pkgName = newPackage.packageName; 17676 synchronized (mPackages) { 17677 //write settings. the installStatus will be incomplete at this stage. 17678 //note that the new package setting would have already been 17679 //added to mPackages. It hasn't been persisted yet. 17680 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 17681 // TODO: Remove this write? It's also written at the end of this method 17682 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 17683 mSettings.writeLPr(); 17684 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 17685 } 17686 17687 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 17688 synchronized (mPackages) { 17689 updatePermissionsLPw(newPackage.packageName, newPackage, 17690 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 17691 ? UPDATE_PERMISSIONS_ALL : 0)); 17692 // For system-bundled packages, we assume that installing an upgraded version 17693 // of the package implies that the user actually wants to run that new code, 17694 // so we enable the package. 17695 PackageSetting ps = mSettings.mPackages.get(pkgName); 17696 final int userId = user.getIdentifier(); 17697 if (ps != null) { 17698 if (isSystemApp(newPackage)) { 17699 if (DEBUG_INSTALL) { 17700 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 17701 } 17702 // Enable system package for requested users 17703 if (res.origUsers != null) { 17704 for (int origUserId : res.origUsers) { 17705 if (userId == UserHandle.USER_ALL || userId == origUserId) { 17706 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 17707 origUserId, installerPackageName); 17708 } 17709 } 17710 } 17711 // Also convey the prior install/uninstall state 17712 if (allUsers != null && installedForUsers != null) { 17713 for (int currentUserId : allUsers) { 17714 final boolean installed = ArrayUtils.contains( 17715 installedForUsers, currentUserId); 17716 if (DEBUG_INSTALL) { 17717 Slog.d(TAG, " user " + currentUserId + " => " + installed); 17718 } 17719 ps.setInstalled(installed, currentUserId); 17720 } 17721 // these install state changes will be persisted in the 17722 // upcoming call to mSettings.writeLPr(). 17723 } 17724 } 17725 // It's implied that when a user requests installation, they want the app to be 17726 // installed and enabled. 17727 if (userId != UserHandle.USER_ALL) { 17728 ps.setInstalled(true, userId); 17729 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 17730 } 17731 17732 // When replacing an existing package, preserve the original install reason for all 17733 // users that had the package installed before. 17734 final Set<Integer> previousUserIds = new ArraySet<>(); 17735 if (res.removedInfo != null && res.removedInfo.installReasons != null) { 17736 final int installReasonCount = res.removedInfo.installReasons.size(); 17737 for (int i = 0; i < installReasonCount; i++) { 17738 final int previousUserId = res.removedInfo.installReasons.keyAt(i); 17739 final int previousInstallReason = res.removedInfo.installReasons.valueAt(i); 17740 ps.setInstallReason(previousInstallReason, previousUserId); 17741 previousUserIds.add(previousUserId); 17742 } 17743 } 17744 17745 // Set install reason for users that are having the package newly installed. 17746 if (userId == UserHandle.USER_ALL) { 17747 for (int currentUserId : sUserManager.getUserIds()) { 17748 if (!previousUserIds.contains(currentUserId)) { 17749 ps.setInstallReason(installReason, currentUserId); 17750 } 17751 } 17752 } else if (!previousUserIds.contains(userId)) { 17753 ps.setInstallReason(installReason, userId); 17754 } 17755 mSettings.writeKernelMappingLPr(ps); 17756 } 17757 res.name = pkgName; 17758 res.uid = newPackage.applicationInfo.uid; 17759 res.pkg = newPackage; 17760 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 17761 mSettings.setInstallerPackageName(pkgName, installerPackageName); 17762 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 17763 //to update install status 17764 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 17765 mSettings.writeLPr(); 17766 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 17767 } 17768 17769 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 17770 } 17771 17772 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 17773 try { 17774 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 17775 installPackageLI(args, res); 17776 } finally { 17777 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 17778 } 17779 } 17780 17781 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 17782 final int installFlags = args.installFlags; 17783 final String installerPackageName = args.installerPackageName; 17784 final String volumeUuid = args.volumeUuid; 17785 final File tmpPackageFile = new File(args.getCodePath()); 17786 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 17787 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 17788 || (args.volumeUuid != null)); 17789 final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0); 17790 final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0); 17791 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 17792 boolean replace = false; 17793 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 17794 if (args.move != null) { 17795 // moving a complete application; perform an initial scan on the new install location 17796 scanFlags |= SCAN_INITIAL; 17797 } 17798 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 17799 scanFlags |= SCAN_DONT_KILL_APP; 17800 } 17801 if (instantApp) { 17802 scanFlags |= SCAN_AS_INSTANT_APP; 17803 } 17804 if (fullApp) { 17805 scanFlags |= SCAN_AS_FULL_APP; 17806 } 17807 17808 // Result object to be returned 17809 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 17810 17811 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 17812 17813 // Sanity check 17814 if (instantApp && (forwardLocked || onExternal)) { 17815 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 17816 + " external=" + onExternal); 17817 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 17818 return; 17819 } 17820 17821 // Retrieve PackageSettings and parse package 17822 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 17823 | PackageParser.PARSE_ENFORCE_CODE 17824 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 17825 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 17826 | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0) 17827 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 17828 PackageParser pp = new PackageParser(); 17829 pp.setSeparateProcesses(mSeparateProcesses); 17830 pp.setDisplayMetrics(mMetrics); 17831 pp.setCallback(mPackageParserCallback); 17832 17833 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 17834 final PackageParser.Package pkg; 17835 try { 17836 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 17837 } catch (PackageParserException e) { 17838 res.setError("Failed parse during installPackageLI", e); 17839 return; 17840 } finally { 17841 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 17842 } 17843 17844 // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2 17845 if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) { 17846 Slog.w(TAG, "Instant app package " + pkg.packageName + " does not target O"); 17847 res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE, 17848 "Instant app package must target O"); 17849 return; 17850 } 17851 if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) { 17852 Slog.w(TAG, "Instant app package " + pkg.packageName 17853 + " does not target targetSandboxVersion 2"); 17854 res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE, 17855 "Instant app package must use targetSanboxVersion 2"); 17856 return; 17857 } 17858 17859 if (pkg.applicationInfo.isStaticSharedLibrary()) { 17860 // Static shared libraries have synthetic package names 17861 renameStaticSharedLibraryPackage(pkg); 17862 17863 // No static shared libs on external storage 17864 if (onExternal) { 17865 Slog.i(TAG, "Static shared libs can only be installed on internal storage."); 17866 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 17867 "Packages declaring static-shared libs cannot be updated"); 17868 return; 17869 } 17870 } 17871 17872 // If we are installing a clustered package add results for the children 17873 if (pkg.childPackages != null) { 17874 synchronized (mPackages) { 17875 final int childCount = pkg.childPackages.size(); 17876 for (int i = 0; i < childCount; i++) { 17877 PackageParser.Package childPkg = pkg.childPackages.get(i); 17878 PackageInstalledInfo childRes = new PackageInstalledInfo(); 17879 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 17880 childRes.pkg = childPkg; 17881 childRes.name = childPkg.packageName; 17882 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 17883 if (childPs != null) { 17884 childRes.origUsers = childPs.queryInstalledUsers( 17885 sUserManager.getUserIds(), true); 17886 } 17887 if ((mPackages.containsKey(childPkg.packageName))) { 17888 childRes.removedInfo = new PackageRemovedInfo(this); 17889 childRes.removedInfo.removedPackage = childPkg.packageName; 17890 childRes.removedInfo.installerPackageName = childPs.installerPackageName; 17891 } 17892 if (res.addedChildPackages == null) { 17893 res.addedChildPackages = new ArrayMap<>(); 17894 } 17895 res.addedChildPackages.put(childPkg.packageName, childRes); 17896 } 17897 } 17898 } 17899 17900 // If package doesn't declare API override, mark that we have an install 17901 // time CPU ABI override. 17902 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 17903 pkg.cpuAbiOverride = args.abiOverride; 17904 } 17905 17906 String pkgName = res.name = pkg.packageName; 17907 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 17908 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 17909 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 17910 return; 17911 } 17912 } 17913 17914 try { 17915 // either use what we've been given or parse directly from the APK 17916 if (args.certificates != null) { 17917 try { 17918 PackageParser.populateCertificates(pkg, args.certificates); 17919 } catch (PackageParserException e) { 17920 // there was something wrong with the certificates we were given; 17921 // try to pull them from the APK 17922 PackageParser.collectCertificates(pkg, parseFlags); 17923 } 17924 } else { 17925 PackageParser.collectCertificates(pkg, parseFlags); 17926 } 17927 } catch (PackageParserException e) { 17928 res.setError("Failed collect during installPackageLI", e); 17929 return; 17930 } 17931 17932 // Get rid of all references to package scan path via parser. 17933 pp = null; 17934 String oldCodePath = null; 17935 boolean systemApp = false; 17936 synchronized (mPackages) { 17937 // Check if installing already existing package 17938 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 17939 String oldName = mSettings.getRenamedPackageLPr(pkgName); 17940 if (pkg.mOriginalPackages != null 17941 && pkg.mOriginalPackages.contains(oldName) 17942 && mPackages.containsKey(oldName)) { 17943 // This package is derived from an original package, 17944 // and this device has been updating from that original 17945 // name. We must continue using the original name, so 17946 // rename the new package here. 17947 pkg.setPackageName(oldName); 17948 pkgName = pkg.packageName; 17949 replace = true; 17950 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 17951 + oldName + " pkgName=" + pkgName); 17952 } else if (mPackages.containsKey(pkgName)) { 17953 // This package, under its official name, already exists 17954 // on the device; we should replace it. 17955 replace = true; 17956 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 17957 } 17958 17959 // Child packages are installed through the parent package 17960 if (pkg.parentPackage != null) { 17961 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 17962 "Package " + pkg.packageName + " is child of package " 17963 + pkg.parentPackage.parentPackage + ". Child packages " 17964 + "can be updated only through the parent package."); 17965 return; 17966 } 17967 17968 if (replace) { 17969 // Prevent apps opting out from runtime permissions 17970 PackageParser.Package oldPackage = mPackages.get(pkgName); 17971 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 17972 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 17973 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 17974 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 17975 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 17976 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 17977 + " doesn't support runtime permissions but the old" 17978 + " target SDK " + oldTargetSdk + " does."); 17979 return; 17980 } 17981 // Prevent apps from downgrading their targetSandbox. 17982 final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion; 17983 final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion; 17984 if (oldTargetSandbox == 2 && newTargetSandbox != 2) { 17985 res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE, 17986 "Package " + pkg.packageName + " new target sandbox " 17987 + newTargetSandbox + " is incompatible with the previous value of" 17988 + oldTargetSandbox + "."); 17989 return; 17990 } 17991 17992 // Prevent installing of child packages 17993 if (oldPackage.parentPackage != null) { 17994 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 17995 "Package " + pkg.packageName + " is child of package " 17996 + oldPackage.parentPackage + ". Child packages " 17997 + "can be updated only through the parent package."); 17998 return; 17999 } 18000 } 18001 } 18002 18003 PackageSetting ps = mSettings.mPackages.get(pkgName); 18004 if (ps != null) { 18005 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 18006 18007 // Static shared libs have same package with different versions where 18008 // we internally use a synthetic package name to allow multiple versions 18009 // of the same package, therefore we need to compare signatures against 18010 // the package setting for the latest library version. 18011 PackageSetting signatureCheckPs = ps; 18012 if (pkg.applicationInfo.isStaticSharedLibrary()) { 18013 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg); 18014 if (libraryEntry != null) { 18015 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk); 18016 } 18017 } 18018 18019 // Quick sanity check that we're signed correctly if updating; 18020 // we'll check this again later when scanning, but we want to 18021 // bail early here before tripping over redefined permissions. 18022 if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) { 18023 if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) { 18024 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 18025 + pkg.packageName + " upgrade keys do not match the " 18026 + "previously installed version"); 18027 return; 18028 } 18029 } else { 18030 try { 18031 verifySignaturesLP(signatureCheckPs, pkg); 18032 } catch (PackageManagerException e) { 18033 res.setError(e.error, e.getMessage()); 18034 return; 18035 } 18036 } 18037 18038 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 18039 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 18040 systemApp = (ps.pkg.applicationInfo.flags & 18041 ApplicationInfo.FLAG_SYSTEM) != 0; 18042 } 18043 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 18044 } 18045 18046 int N = pkg.permissions.size(); 18047 for (int i = N-1; i >= 0; i--) { 18048 PackageParser.Permission perm = pkg.permissions.get(i); 18049 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 18050 18051 // Don't allow anyone but the system to define ephemeral permissions. 18052 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_EPHEMERAL) != 0 18053 && !systemApp) { 18054 Slog.w(TAG, "Non-System package " + pkg.packageName 18055 + " attempting to delcare ephemeral permission " 18056 + perm.info.name + "; Removing ephemeral."); 18057 perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_EPHEMERAL; 18058 } 18059 // Check whether the newly-scanned package wants to define an already-defined perm 18060 if (bp != null) { 18061 // If the defining package is signed with our cert, it's okay. This 18062 // also includes the "updating the same package" case, of course. 18063 // "updating same package" could also involve key-rotation. 18064 final boolean sigsOk; 18065 if (bp.sourcePackage.equals(pkg.packageName) 18066 && (bp.packageSetting instanceof PackageSetting) 18067 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 18068 scanFlags))) { 18069 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 18070 } else { 18071 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 18072 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 18073 } 18074 if (!sigsOk) { 18075 // If the owning package is the system itself, we log but allow 18076 // install to proceed; we fail the install on all other permission 18077 // redefinitions. 18078 if (!bp.sourcePackage.equals("android")) { 18079 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 18080 + pkg.packageName + " attempting to redeclare permission " 18081 + perm.info.name + " already owned by " + bp.sourcePackage); 18082 res.origPermission = perm.info.name; 18083 res.origPackage = bp.sourcePackage; 18084 return; 18085 } else { 18086 Slog.w(TAG, "Package " + pkg.packageName 18087 + " attempting to redeclare system permission " 18088 + perm.info.name + "; ignoring new declaration"); 18089 pkg.permissions.remove(i); 18090 } 18091 } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) { 18092 // Prevent apps to change protection level to dangerous from any other 18093 // type as this would allow a privilege escalation where an app adds a 18094 // normal/signature permission in other app's group and later redefines 18095 // it as dangerous leading to the group auto-grant. 18096 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE) 18097 == PermissionInfo.PROTECTION_DANGEROUS) { 18098 if (bp != null && !bp.isRuntime()) { 18099 Slog.w(TAG, "Package " + pkg.packageName + " trying to change a " 18100 + "non-runtime permission " + perm.info.name 18101 + " to runtime; keeping old protection level"); 18102 perm.info.protectionLevel = bp.protectionLevel; 18103 } 18104 } 18105 } 18106 } 18107 } 18108 } 18109 18110 if (systemApp) { 18111 if (onExternal) { 18112 // Abort update; system app can't be replaced with app on sdcard 18113 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 18114 "Cannot install updates to system apps on sdcard"); 18115 return; 18116 } else if (instantApp) { 18117 // Abort update; system app can't be replaced with an instant app 18118 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID, 18119 "Cannot update a system app with an instant app"); 18120 return; 18121 } 18122 } 18123 18124 if (args.move != null) { 18125 // We did an in-place move, so dex is ready to roll 18126 scanFlags |= SCAN_NO_DEX; 18127 scanFlags |= SCAN_MOVE; 18128 18129 synchronized (mPackages) { 18130 final PackageSetting ps = mSettings.mPackages.get(pkgName); 18131 if (ps == null) { 18132 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 18133 "Missing settings for moved package " + pkgName); 18134 } 18135 18136 // We moved the entire application as-is, so bring over the 18137 // previously derived ABI information. 18138 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 18139 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 18140 } 18141 18142 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 18143 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 18144 scanFlags |= SCAN_NO_DEX; 18145 18146 try { 18147 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 18148 args.abiOverride : pkg.cpuAbiOverride); 18149 final boolean extractNativeLibs = !pkg.isLibrary(); 18150 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 18151 extractNativeLibs, mAppLib32InstallDir); 18152 } catch (PackageManagerException pme) { 18153 Slog.e(TAG, "Error deriving application ABI", pme); 18154 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 18155 return; 18156 } 18157 18158 // Shared libraries for the package need to be updated. 18159 synchronized (mPackages) { 18160 try { 18161 updateSharedLibrariesLPr(pkg, null); 18162 } catch (PackageManagerException e) { 18163 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 18164 } 18165 } 18166 18167 // dexopt can take some time to complete, so, for instant apps, we skip this 18168 // step during installation. Instead, we'll take extra time the first time the 18169 // instant app starts. It's preferred to do it this way to provide continuous 18170 // progress to the user instead of mysteriously blocking somewhere in the 18171 // middle of running an instant app. The default behaviour can be overridden 18172 // via gservices. 18173 if (!instantApp || Global.getInt( 18174 mContext.getContentResolver(), Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0) { 18175 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 18176 // Do not run PackageDexOptimizer through the local performDexOpt 18177 // method because `pkg` may not be in `mPackages` yet. 18178 // 18179 // Also, don't fail application installs if the dexopt step fails. 18180 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 18181 null /* instructionSets */, false /* checkProfiles */, 18182 getCompilerFilterForReason(REASON_INSTALL), 18183 getOrCreateCompilerPackageStats(pkg), 18184 mDexManager.isUsedByOtherApps(pkg.packageName)); 18185 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 18186 } 18187 18188 // Notify BackgroundDexOptService that the package has been changed. 18189 // If this is an update of a package which used to fail to compile, 18190 // BDOS will remove it from its blacklist. 18191 // TODO: Layering violation 18192 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 18193 } 18194 18195 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 18196 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 18197 return; 18198 } 18199 18200 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 18201 18202 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 18203 "installPackageLI")) { 18204 if (replace) { 18205 if (pkg.applicationInfo.isStaticSharedLibrary()) { 18206 // Static libs have a synthetic package name containing the version 18207 // and cannot be updated as an update would get a new package name, 18208 // unless this is the exact same version code which is useful for 18209 // development. 18210 PackageParser.Package existingPkg = mPackages.get(pkg.packageName); 18211 if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) { 18212 res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring " 18213 + "static-shared libs cannot be updated"); 18214 return; 18215 } 18216 } 18217 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 18218 installerPackageName, res, args.installReason); 18219 } else { 18220 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 18221 args.user, installerPackageName, volumeUuid, res, args.installReason); 18222 } 18223 } 18224 18225 synchronized (mPackages) { 18226 final PackageSetting ps = mSettings.mPackages.get(pkgName); 18227 if (ps != null) { 18228 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 18229 ps.setUpdateAvailable(false /*updateAvailable*/); 18230 } 18231 18232 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 18233 for (int i = 0; i < childCount; i++) { 18234 PackageParser.Package childPkg = pkg.childPackages.get(i); 18235 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 18236 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 18237 if (childPs != null) { 18238 childRes.newUsers = childPs.queryInstalledUsers( 18239 sUserManager.getUserIds(), true); 18240 } 18241 } 18242 18243 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 18244 updateSequenceNumberLP(ps, res.newUsers); 18245 updateInstantAppInstallerLocked(pkgName); 18246 } 18247 } 18248 } 18249 18250 private void startIntentFilterVerifications(int userId, boolean replacing, 18251 PackageParser.Package pkg) { 18252 if (mIntentFilterVerifierComponent == null) { 18253 Slog.w(TAG, "No IntentFilter verification will not be done as " 18254 + "there is no IntentFilterVerifier available!"); 18255 return; 18256 } 18257 18258 final int verifierUid = getPackageUid( 18259 mIntentFilterVerifierComponent.getPackageName(), 18260 MATCH_DEBUG_TRIAGED_MISSING, 18261 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 18262 18263 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 18264 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 18265 mHandler.sendMessage(msg); 18266 18267 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 18268 for (int i = 0; i < childCount; i++) { 18269 PackageParser.Package childPkg = pkg.childPackages.get(i); 18270 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 18271 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 18272 mHandler.sendMessage(msg); 18273 } 18274 } 18275 18276 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 18277 PackageParser.Package pkg) { 18278 int size = pkg.activities.size(); 18279 if (size == 0) { 18280 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 18281 "No activity, so no need to verify any IntentFilter!"); 18282 return; 18283 } 18284 18285 final boolean hasDomainURLs = hasDomainURLs(pkg); 18286 if (!hasDomainURLs) { 18287 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 18288 "No domain URLs, so no need to verify any IntentFilter!"); 18289 return; 18290 } 18291 18292 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 18293 + " if any IntentFilter from the " + size 18294 + " Activities needs verification ..."); 18295 18296 int count = 0; 18297 final String packageName = pkg.packageName; 18298 18299 synchronized (mPackages) { 18300 // If this is a new install and we see that we've already run verification for this 18301 // package, we have nothing to do: it means the state was restored from backup. 18302 if (!replacing) { 18303 IntentFilterVerificationInfo ivi = 18304 mSettings.getIntentFilterVerificationLPr(packageName); 18305 if (ivi != null) { 18306 if (DEBUG_DOMAIN_VERIFICATION) { 18307 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 18308 + ivi.getStatusString()); 18309 } 18310 return; 18311 } 18312 } 18313 18314 // If any filters need to be verified, then all need to be. 18315 boolean needToVerify = false; 18316 for (PackageParser.Activity a : pkg.activities) { 18317 for (ActivityIntentInfo filter : a.intents) { 18318 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 18319 if (DEBUG_DOMAIN_VERIFICATION) { 18320 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 18321 } 18322 needToVerify = true; 18323 break; 18324 } 18325 } 18326 } 18327 18328 if (needToVerify) { 18329 final int verificationId = mIntentFilterVerificationToken++; 18330 for (PackageParser.Activity a : pkg.activities) { 18331 for (ActivityIntentInfo filter : a.intents) { 18332 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 18333 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 18334 "Verification needed for IntentFilter:" + filter.toString()); 18335 mIntentFilterVerifier.addOneIntentFilterVerification( 18336 verifierUid, userId, verificationId, filter, packageName); 18337 count++; 18338 } 18339 } 18340 } 18341 } 18342 } 18343 18344 if (count > 0) { 18345 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 18346 + " IntentFilter verification" + (count > 1 ? "s" : "") 18347 + " for userId:" + userId); 18348 mIntentFilterVerifier.startVerifications(userId); 18349 } else { 18350 if (DEBUG_DOMAIN_VERIFICATION) { 18351 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 18352 } 18353 } 18354 } 18355 18356 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 18357 final ComponentName cn = filter.activity.getComponentName(); 18358 final String packageName = cn.getPackageName(); 18359 18360 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 18361 packageName); 18362 if (ivi == null) { 18363 return true; 18364 } 18365 int status = ivi.getStatus(); 18366 switch (status) { 18367 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 18368 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 18369 return true; 18370 18371 default: 18372 // Nothing to do 18373 return false; 18374 } 18375 } 18376 18377 private static boolean isMultiArch(ApplicationInfo info) { 18378 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 18379 } 18380 18381 private static boolean isExternal(PackageParser.Package pkg) { 18382 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 18383 } 18384 18385 private static boolean isExternal(PackageSetting ps) { 18386 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 18387 } 18388 18389 private static boolean isSystemApp(PackageParser.Package pkg) { 18390 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 18391 } 18392 18393 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 18394 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 18395 } 18396 18397 private static boolean hasDomainURLs(PackageParser.Package pkg) { 18398 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 18399 } 18400 18401 private static boolean isSystemApp(PackageSetting ps) { 18402 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 18403 } 18404 18405 private static boolean isUpdatedSystemApp(PackageSetting ps) { 18406 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 18407 } 18408 18409 private int packageFlagsToInstallFlags(PackageSetting ps) { 18410 int installFlags = 0; 18411 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 18412 // This existing package was an external ASEC install when we have 18413 // the external flag without a UUID 18414 installFlags |= PackageManager.INSTALL_EXTERNAL; 18415 } 18416 if (ps.isForwardLocked()) { 18417 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 18418 } 18419 return installFlags; 18420 } 18421 18422 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 18423 if (isExternal(pkg)) { 18424 if (TextUtils.isEmpty(pkg.volumeUuid)) { 18425 return StorageManager.UUID_PRIMARY_PHYSICAL; 18426 } else { 18427 return pkg.volumeUuid; 18428 } 18429 } else { 18430 return StorageManager.UUID_PRIVATE_INTERNAL; 18431 } 18432 } 18433 18434 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 18435 if (isExternal(pkg)) { 18436 if (TextUtils.isEmpty(pkg.volumeUuid)) { 18437 return mSettings.getExternalVersion(); 18438 } else { 18439 return mSettings.findOrCreateVersion(pkg.volumeUuid); 18440 } 18441 } else { 18442 return mSettings.getInternalVersion(); 18443 } 18444 } 18445 18446 private void deleteTempPackageFiles() { 18447 final FilenameFilter filter = new FilenameFilter() { 18448 public boolean accept(File dir, String name) { 18449 return name.startsWith("vmdl") && name.endsWith(".tmp"); 18450 } 18451 }; 18452 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 18453 file.delete(); 18454 } 18455 } 18456 18457 @Override 18458 public void deletePackageAsUser(String packageName, int versionCode, 18459 IPackageDeleteObserver observer, int userId, int flags) { 18460 deletePackageVersioned(new VersionedPackage(packageName, versionCode), 18461 new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags); 18462 } 18463 18464 @Override 18465 public void deletePackageVersioned(VersionedPackage versionedPackage, 18466 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 18467 final int callingUid = Binder.getCallingUid(); 18468 mContext.enforceCallingOrSelfPermission( 18469 android.Manifest.permission.DELETE_PACKAGES, null); 18470 final boolean canViewInstantApps = canViewInstantApps(callingUid, userId); 18471 Preconditions.checkNotNull(versionedPackage); 18472 Preconditions.checkNotNull(observer); 18473 Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(), 18474 PackageManager.VERSION_CODE_HIGHEST, 18475 Integer.MAX_VALUE, "versionCode must be >= -1"); 18476 18477 final String packageName = versionedPackage.getPackageName(); 18478 final int versionCode = versionedPackage.getVersionCode(); 18479 final String internalPackageName; 18480 synchronized (mPackages) { 18481 // Normalize package name to handle renamed packages and static libs 18482 internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(), 18483 versionedPackage.getVersionCode()); 18484 } 18485 18486 final int uid = Binder.getCallingUid(); 18487 if (!isOrphaned(internalPackageName) 18488 && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) { 18489 try { 18490 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 18491 intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null)); 18492 intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder()); 18493 observer.onUserActionRequired(intent); 18494 } catch (RemoteException re) { 18495 } 18496 return; 18497 } 18498 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 18499 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 18500 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 18501 mContext.enforceCallingOrSelfPermission( 18502 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 18503 "deletePackage for user " + userId); 18504 } 18505 18506 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 18507 try { 18508 observer.onPackageDeleted(packageName, 18509 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 18510 } catch (RemoteException re) { 18511 } 18512 return; 18513 } 18514 18515 if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) { 18516 try { 18517 observer.onPackageDeleted(packageName, 18518 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 18519 } catch (RemoteException re) { 18520 } 18521 return; 18522 } 18523 18524 if (DEBUG_REMOVE) { 18525 Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId 18526 + " deleteAllUsers: " + deleteAllUsers + " version=" 18527 + (versionCode == PackageManager.VERSION_CODE_HIGHEST 18528 ? "VERSION_CODE_HIGHEST" : versionCode)); 18529 } 18530 // Queue up an async operation since the package deletion may take a little while. 18531 mHandler.post(new Runnable() { 18532 public void run() { 18533 mHandler.removeCallbacks(this); 18534 int returnCode; 18535 final PackageSetting ps = mSettings.mPackages.get(internalPackageName); 18536 boolean doDeletePackage = true; 18537 if (ps != null) { 18538 final boolean targetIsInstantApp = 18539 ps.getInstantApp(UserHandle.getUserId(callingUid)); 18540 doDeletePackage = !targetIsInstantApp 18541 || canViewInstantApps; 18542 } 18543 if (doDeletePackage) { 18544 if (!deleteAllUsers) { 18545 returnCode = deletePackageX(internalPackageName, versionCode, 18546 userId, deleteFlags); 18547 } else { 18548 int[] blockUninstallUserIds = getBlockUninstallForUsers( 18549 internalPackageName, users); 18550 // If nobody is blocking uninstall, proceed with delete for all users 18551 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 18552 returnCode = deletePackageX(internalPackageName, versionCode, 18553 userId, deleteFlags); 18554 } else { 18555 // Otherwise uninstall individually for users with blockUninstalls=false 18556 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 18557 for (int userId : users) { 18558 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 18559 returnCode = deletePackageX(internalPackageName, versionCode, 18560 userId, userFlags); 18561 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 18562 Slog.w(TAG, "Package delete failed for user " + userId 18563 + ", returnCode " + returnCode); 18564 } 18565 } 18566 } 18567 // The app has only been marked uninstalled for certain users. 18568 // We still need to report that delete was blocked 18569 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 18570 } 18571 } 18572 } else { 18573 returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR; 18574 } 18575 try { 18576 observer.onPackageDeleted(packageName, returnCode, null); 18577 } catch (RemoteException e) { 18578 Log.i(TAG, "Observer no longer exists."); 18579 } //end catch 18580 } //end run 18581 }); 18582 } 18583 18584 private String resolveExternalPackageNameLPr(PackageParser.Package pkg) { 18585 if (pkg.staticSharedLibName != null) { 18586 return pkg.manifestPackageName; 18587 } 18588 return pkg.packageName; 18589 } 18590 18591 private String resolveInternalPackageNameLPr(String packageName, int versionCode) { 18592 // Handle renamed packages 18593 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 18594 packageName = normalizedPackageName != null ? normalizedPackageName : packageName; 18595 18596 // Is this a static library? 18597 SparseArray<SharedLibraryEntry> versionedLib = 18598 mStaticLibsByDeclaringPackage.get(packageName); 18599 if (versionedLib == null || versionedLib.size() <= 0) { 18600 return packageName; 18601 } 18602 18603 // Figure out which lib versions the caller can see 18604 SparseIntArray versionsCallerCanSee = null; 18605 final int callingAppId = UserHandle.getAppId(Binder.getCallingUid()); 18606 if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID 18607 && callingAppId != Process.ROOT_UID) { 18608 versionsCallerCanSee = new SparseIntArray(); 18609 String libName = versionedLib.valueAt(0).info.getName(); 18610 String[] uidPackages = getPackagesForUid(Binder.getCallingUid()); 18611 if (uidPackages != null) { 18612 for (String uidPackage : uidPackages) { 18613 PackageSetting ps = mSettings.getPackageLPr(uidPackage); 18614 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 18615 if (libIdx >= 0) { 18616 final int libVersion = ps.usesStaticLibrariesVersions[libIdx]; 18617 versionsCallerCanSee.append(libVersion, libVersion); 18618 } 18619 } 18620 } 18621 } 18622 18623 // Caller can see nothing - done 18624 if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) { 18625 return packageName; 18626 } 18627 18628 // Find the version the caller can see and the app version code 18629 SharedLibraryEntry highestVersion = null; 18630 final int versionCount = versionedLib.size(); 18631 for (int i = 0; i < versionCount; i++) { 18632 SharedLibraryEntry libEntry = versionedLib.valueAt(i); 18633 if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey( 18634 libEntry.info.getVersion()) < 0) { 18635 continue; 18636 } 18637 final int libVersionCode = libEntry.info.getDeclaringPackage().getVersionCode(); 18638 if (versionCode != PackageManager.VERSION_CODE_HIGHEST) { 18639 if (libVersionCode == versionCode) { 18640 return libEntry.apk; 18641 } 18642 } else if (highestVersion == null) { 18643 highestVersion = libEntry; 18644 } else if (libVersionCode > highestVersion.info 18645 .getDeclaringPackage().getVersionCode()) { 18646 highestVersion = libEntry; 18647 } 18648 } 18649 18650 if (highestVersion != null) { 18651 return highestVersion.apk; 18652 } 18653 18654 return packageName; 18655 } 18656 18657 private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) { 18658 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID 18659 || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 18660 return true; 18661 } 18662 final int callingUserId = UserHandle.getUserId(callingUid); 18663 // If the caller installed the pkgName, then allow it to silently uninstall. 18664 if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) { 18665 return true; 18666 } 18667 18668 // Allow package verifier to silently uninstall. 18669 if (mRequiredVerifierPackage != null && 18670 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) { 18671 return true; 18672 } 18673 18674 // Allow package uninstaller to silently uninstall. 18675 if (mRequiredUninstallerPackage != null && 18676 callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) { 18677 return true; 18678 } 18679 18680 // Allow storage manager to silently uninstall. 18681 if (mStorageManagerPackage != null && 18682 callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) { 18683 return true; 18684 } 18685 return false; 18686 } 18687 18688 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 18689 int[] result = EMPTY_INT_ARRAY; 18690 for (int userId : userIds) { 18691 if (getBlockUninstallForUser(packageName, userId)) { 18692 result = ArrayUtils.appendInt(result, userId); 18693 } 18694 } 18695 return result; 18696 } 18697 18698 @Override 18699 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 18700 final int callingUid = Binder.getCallingUid(); 18701 if (getInstantAppPackageName(callingUid) != null 18702 && !isCallerSameApp(packageName, callingUid)) { 18703 return false; 18704 } 18705 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 18706 } 18707 18708 private boolean isPackageDeviceAdmin(String packageName, int userId) { 18709 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 18710 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 18711 try { 18712 if (dpm != null) { 18713 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 18714 /* callingUserOnly =*/ false); 18715 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 18716 : deviceOwnerComponentName.getPackageName(); 18717 // Does the package contains the device owner? 18718 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 18719 // this check is probably not needed, since DO should be registered as a device 18720 // admin on some user too. (Original bug for this: b/17657954) 18721 if (packageName.equals(deviceOwnerPackageName)) { 18722 return true; 18723 } 18724 // Does it contain a device admin for any user? 18725 int[] users; 18726 if (userId == UserHandle.USER_ALL) { 18727 users = sUserManager.getUserIds(); 18728 } else { 18729 users = new int[]{userId}; 18730 } 18731 for (int i = 0; i < users.length; ++i) { 18732 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 18733 return true; 18734 } 18735 } 18736 } 18737 } catch (RemoteException e) { 18738 } 18739 return false; 18740 } 18741 18742 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 18743 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 18744 } 18745 18746 /** 18747 * This method is an internal method that could be get invoked either 18748 * to delete an installed package or to clean up a failed installation. 18749 * After deleting an installed package, a broadcast is sent to notify any 18750 * listeners that the package has been removed. For cleaning up a failed 18751 * installation, the broadcast is not necessary since the package's 18752 * installation wouldn't have sent the initial broadcast either 18753 * The key steps in deleting a package are 18754 * deleting the package information in internal structures like mPackages, 18755 * deleting the packages base directories through installd 18756 * updating mSettings to reflect current status 18757 * persisting settings for later use 18758 * sending a broadcast if necessary 18759 */ 18760 int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) { 18761 final PackageRemovedInfo info = new PackageRemovedInfo(this); 18762 final boolean res; 18763 18764 final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 18765 ? UserHandle.USER_ALL : userId; 18766 18767 if (isPackageDeviceAdmin(packageName, removeUser)) { 18768 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 18769 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 18770 } 18771 18772 PackageSetting uninstalledPs = null; 18773 PackageParser.Package pkg = null; 18774 18775 // for the uninstall-updates case and restricted profiles, remember the per- 18776 // user handle installed state 18777 int[] allUsers; 18778 synchronized (mPackages) { 18779 uninstalledPs = mSettings.mPackages.get(packageName); 18780 if (uninstalledPs == null) { 18781 Slog.w(TAG, "Not removing non-existent package " + packageName); 18782 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 18783 } 18784 18785 if (versionCode != PackageManager.VERSION_CODE_HIGHEST 18786 && uninstalledPs.versionCode != versionCode) { 18787 Slog.w(TAG, "Not removing package " + packageName + " with versionCode " 18788 + uninstalledPs.versionCode + " != " + versionCode); 18789 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 18790 } 18791 18792 // Static shared libs can be declared by any package, so let us not 18793 // allow removing a package if it provides a lib others depend on. 18794 pkg = mPackages.get(packageName); 18795 18796 allUsers = sUserManager.getUserIds(); 18797 18798 if (pkg != null && pkg.staticSharedLibName != null) { 18799 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName, 18800 pkg.staticSharedLibVersion); 18801 if (libEntry != null) { 18802 for (int currUserId : allUsers) { 18803 if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) { 18804 continue; 18805 } 18806 List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr( 18807 libEntry.info, 0, currUserId); 18808 if (!ArrayUtils.isEmpty(libClientPackages)) { 18809 Slog.w(TAG, "Not removing package " + pkg.manifestPackageName 18810 + " hosting lib " + libEntry.info.getName() + " version " 18811 + libEntry.info.getVersion() + " used by " + libClientPackages 18812 + " for user " + currUserId); 18813 return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY; 18814 } 18815 } 18816 } 18817 } 18818 18819 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 18820 } 18821 18822 final int freezeUser; 18823 if (isUpdatedSystemApp(uninstalledPs) 18824 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) { 18825 // We're downgrading a system app, which will apply to all users, so 18826 // freeze them all during the downgrade 18827 freezeUser = UserHandle.USER_ALL; 18828 } else { 18829 freezeUser = removeUser; 18830 } 18831 18832 synchronized (mInstallLock) { 18833 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 18834 try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser, 18835 deleteFlags, "deletePackageX")) { 18836 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers, 18837 deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null); 18838 } 18839 synchronized (mPackages) { 18840 if (res) { 18841 if (pkg != null) { 18842 mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers); 18843 } 18844 updateSequenceNumberLP(uninstalledPs, info.removedUsers); 18845 updateInstantAppInstallerLocked(packageName); 18846 } 18847 } 18848 } 18849 18850 if (res) { 18851 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 18852 info.sendPackageRemovedBroadcasts(killApp); 18853 info.sendSystemPackageUpdatedBroadcasts(); 18854 info.sendSystemPackageAppearedBroadcasts(); 18855 } 18856 // Force a gc here. 18857 Runtime.getRuntime().gc(); 18858 // Delete the resources here after sending the broadcast to let 18859 // other processes clean up before deleting resources. 18860 if (info.args != null) { 18861 synchronized (mInstallLock) { 18862 info.args.doPostDeleteLI(true); 18863 } 18864 } 18865 18866 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 18867 } 18868 18869 static class PackageRemovedInfo { 18870 final PackageSender packageSender; 18871 String removedPackage; 18872 String installerPackageName; 18873 int uid = -1; 18874 int removedAppId = -1; 18875 int[] origUsers; 18876 int[] removedUsers = null; 18877 int[] broadcastUsers = null; 18878 SparseArray<Integer> installReasons; 18879 boolean isRemovedPackageSystemUpdate = false; 18880 boolean isUpdate; 18881 boolean dataRemoved; 18882 boolean removedForAllUsers; 18883 boolean isStaticSharedLib; 18884 // Clean up resources deleted packages. 18885 InstallArgs args = null; 18886 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 18887 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 18888 18889 PackageRemovedInfo(PackageSender packageSender) { 18890 this.packageSender = packageSender; 18891 } 18892 18893 void sendPackageRemovedBroadcasts(boolean killApp) { 18894 sendPackageRemovedBroadcastInternal(killApp); 18895 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 18896 for (int i = 0; i < childCount; i++) { 18897 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 18898 childInfo.sendPackageRemovedBroadcastInternal(killApp); 18899 } 18900 } 18901 18902 void sendSystemPackageUpdatedBroadcasts() { 18903 if (isRemovedPackageSystemUpdate) { 18904 sendSystemPackageUpdatedBroadcastsInternal(); 18905 final int childCount = (removedChildPackages != null) 18906 ? removedChildPackages.size() : 0; 18907 for (int i = 0; i < childCount; i++) { 18908 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 18909 if (childInfo.isRemovedPackageSystemUpdate) { 18910 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 18911 } 18912 } 18913 } 18914 } 18915 18916 void sendSystemPackageAppearedBroadcasts() { 18917 final int packageCount = (appearedChildPackages != null) 18918 ? appearedChildPackages.size() : 0; 18919 for (int i = 0; i < packageCount; i++) { 18920 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 18921 packageSender.sendPackageAddedForNewUsers(installedInfo.name, 18922 true, UserHandle.getAppId(installedInfo.uid), 18923 installedInfo.newUsers); 18924 } 18925 } 18926 18927 private void sendSystemPackageUpdatedBroadcastsInternal() { 18928 Bundle extras = new Bundle(2); 18929 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 18930 extras.putBoolean(Intent.EXTRA_REPLACING, true); 18931 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 18932 removedPackage, extras, 0, null /*targetPackage*/, null, null); 18933 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 18934 removedPackage, extras, 0, null /*targetPackage*/, null, null); 18935 packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 18936 null, null, 0, removedPackage, null, null); 18937 if (installerPackageName != null) { 18938 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 18939 removedPackage, extras, 0 /*flags*/, 18940 installerPackageName, null, null); 18941 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 18942 removedPackage, extras, 0 /*flags*/, 18943 installerPackageName, null, null); 18944 } 18945 } 18946 18947 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 18948 // Don't send static shared library removal broadcasts as these 18949 // libs are visible only the the apps that depend on them an one 18950 // cannot remove the library if it has a dependency. 18951 if (isStaticSharedLib) { 18952 return; 18953 } 18954 Bundle extras = new Bundle(2); 18955 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 18956 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 18957 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 18958 if (isUpdate || isRemovedPackageSystemUpdate) { 18959 extras.putBoolean(Intent.EXTRA_REPLACING, true); 18960 } 18961 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 18962 if (removedPackage != null) { 18963 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, 18964 removedPackage, extras, 0, null /*targetPackage*/, null, broadcastUsers); 18965 if (installerPackageName != null) { 18966 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, 18967 removedPackage, extras, 0 /*flags*/, 18968 installerPackageName, null, broadcastUsers); 18969 } 18970 if (dataRemoved && !isRemovedPackageSystemUpdate) { 18971 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 18972 removedPackage, extras, 18973 Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, 18974 null, null, broadcastUsers); 18975 } 18976 } 18977 if (removedAppId >= 0) { 18978 packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 18979 Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, null, null, broadcastUsers); 18980 } 18981 } 18982 18983 void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) { 18984 removedUsers = userIds; 18985 if (removedUsers == null) { 18986 broadcastUsers = null; 18987 return; 18988 } 18989 18990 broadcastUsers = EMPTY_INT_ARRAY; 18991 for (int i = userIds.length - 1; i >= 0; --i) { 18992 final int userId = userIds[i]; 18993 if (deletedPackageSetting.getInstantApp(userId)) { 18994 continue; 18995 } 18996 broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId); 18997 } 18998 } 18999 } 19000 19001 /* 19002 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 19003 * flag is not set, the data directory is removed as well. 19004 * make sure this flag is set for partially installed apps. If not its meaningless to 19005 * delete a partially installed application. 19006 */ 19007 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 19008 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 19009 String packageName = ps.name; 19010 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 19011 // Retrieve object to delete permissions for shared user later on 19012 final PackageParser.Package deletedPkg; 19013 final PackageSetting deletedPs; 19014 // reader 19015 synchronized (mPackages) { 19016 deletedPkg = mPackages.get(packageName); 19017 deletedPs = mSettings.mPackages.get(packageName); 19018 if (outInfo != null) { 19019 outInfo.removedPackage = packageName; 19020 outInfo.installerPackageName = ps.installerPackageName; 19021 outInfo.isStaticSharedLib = deletedPkg != null 19022 && deletedPkg.staticSharedLibName != null; 19023 outInfo.populateUsers(deletedPs == null ? null 19024 : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs); 19025 } 19026 } 19027 19028 removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0); 19029 19030 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 19031 final PackageParser.Package resolvedPkg; 19032 if (deletedPkg != null) { 19033 resolvedPkg = deletedPkg; 19034 } else { 19035 // We don't have a parsed package when it lives on an ejected 19036 // adopted storage device, so fake something together 19037 resolvedPkg = new PackageParser.Package(ps.name); 19038 resolvedPkg.setVolumeUuid(ps.volumeUuid); 19039 } 19040 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 19041 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19042 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 19043 if (outInfo != null) { 19044 outInfo.dataRemoved = true; 19045 } 19046 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 19047 } 19048 19049 int removedAppId = -1; 19050 19051 // writer 19052 synchronized (mPackages) { 19053 boolean installedStateChanged = false; 19054 if (deletedPs != null) { 19055 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 19056 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 19057 clearDefaultBrowserIfNeeded(packageName); 19058 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 19059 removedAppId = mSettings.removePackageLPw(packageName); 19060 if (outInfo != null) { 19061 outInfo.removedAppId = removedAppId; 19062 } 19063 updatePermissionsLPw(deletedPs.name, null, 0); 19064 if (deletedPs.sharedUser != null) { 19065 // Remove permissions associated with package. Since runtime 19066 // permissions are per user we have to kill the removed package 19067 // or packages running under the shared user of the removed 19068 // package if revoking the permissions requested only by the removed 19069 // package is successful and this causes a change in gids. 19070 for (int userId : UserManagerService.getInstance().getUserIds()) { 19071 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 19072 userId); 19073 if (userIdToKill == UserHandle.USER_ALL 19074 || userIdToKill >= UserHandle.USER_SYSTEM) { 19075 // If gids changed for this user, kill all affected packages. 19076 mHandler.post(new Runnable() { 19077 @Override 19078 public void run() { 19079 // This has to happen with no lock held. 19080 killApplication(deletedPs.name, deletedPs.appId, 19081 KILL_APP_REASON_GIDS_CHANGED); 19082 } 19083 }); 19084 break; 19085 } 19086 } 19087 } 19088 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 19089 } 19090 // make sure to preserve per-user disabled state if this removal was just 19091 // a downgrade of a system app to the factory package 19092 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 19093 if (DEBUG_REMOVE) { 19094 Slog.d(TAG, "Propagating install state across downgrade"); 19095 } 19096 for (int userId : allUserHandles) { 19097 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 19098 if (DEBUG_REMOVE) { 19099 Slog.d(TAG, " user " + userId + " => " + installed); 19100 } 19101 if (installed != ps.getInstalled(userId)) { 19102 installedStateChanged = true; 19103 } 19104 ps.setInstalled(installed, userId); 19105 } 19106 } 19107 } 19108 // can downgrade to reader 19109 if (writeSettings) { 19110 // Save settings now 19111 mSettings.writeLPr(); 19112 } 19113 if (installedStateChanged) { 19114 mSettings.writeKernelMappingLPr(ps); 19115 } 19116 } 19117 if (removedAppId != -1) { 19118 // A user ID was deleted here. Go through all users and remove it 19119 // from KeyStore. 19120 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId); 19121 } 19122 } 19123 19124 static boolean locationIsPrivileged(File path) { 19125 try { 19126 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 19127 .getCanonicalPath(); 19128 return path.getCanonicalPath().startsWith(privilegedAppDir); 19129 } catch (IOException e) { 19130 Slog.e(TAG, "Unable to access code path " + path); 19131 } 19132 return false; 19133 } 19134 19135 /* 19136 * Tries to delete system package. 19137 */ 19138 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 19139 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 19140 boolean writeSettings) { 19141 if (deletedPs.parentPackageName != null) { 19142 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 19143 return false; 19144 } 19145 19146 final boolean applyUserRestrictions 19147 = (allUserHandles != null) && (outInfo.origUsers != null); 19148 final PackageSetting disabledPs; 19149 // Confirm if the system package has been updated 19150 // An updated system app can be deleted. This will also have to restore 19151 // the system pkg from system partition 19152 // reader 19153 synchronized (mPackages) { 19154 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 19155 } 19156 19157 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 19158 + " disabledPs=" + disabledPs); 19159 19160 if (disabledPs == null) { 19161 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 19162 return false; 19163 } else if (DEBUG_REMOVE) { 19164 Slog.d(TAG, "Deleting system pkg from data partition"); 19165 } 19166 19167 if (DEBUG_REMOVE) { 19168 if (applyUserRestrictions) { 19169 Slog.d(TAG, "Remembering install states:"); 19170 for (int userId : allUserHandles) { 19171 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 19172 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 19173 } 19174 } 19175 } 19176 19177 // Delete the updated package 19178 outInfo.isRemovedPackageSystemUpdate = true; 19179 if (outInfo.removedChildPackages != null) { 19180 final int childCount = (deletedPs.childPackageNames != null) 19181 ? deletedPs.childPackageNames.size() : 0; 19182 for (int i = 0; i < childCount; i++) { 19183 String childPackageName = deletedPs.childPackageNames.get(i); 19184 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 19185 .contains(childPackageName)) { 19186 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 19187 childPackageName); 19188 if (childInfo != null) { 19189 childInfo.isRemovedPackageSystemUpdate = true; 19190 } 19191 } 19192 } 19193 } 19194 19195 if (disabledPs.versionCode < deletedPs.versionCode) { 19196 // Delete data for downgrades 19197 flags &= ~PackageManager.DELETE_KEEP_DATA; 19198 } else { 19199 // Preserve data by setting flag 19200 flags |= PackageManager.DELETE_KEEP_DATA; 19201 } 19202 19203 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 19204 outInfo, writeSettings, disabledPs.pkg); 19205 if (!ret) { 19206 return false; 19207 } 19208 19209 // writer 19210 synchronized (mPackages) { 19211 // Reinstate the old system package 19212 enableSystemPackageLPw(disabledPs.pkg); 19213 // Remove any native libraries from the upgraded package. 19214 removeNativeBinariesLI(deletedPs); 19215 } 19216 19217 // Install the system package 19218 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 19219 int parseFlags = mDefParseFlags 19220 | PackageParser.PARSE_MUST_BE_APK 19221 | PackageParser.PARSE_IS_SYSTEM 19222 | PackageParser.PARSE_IS_SYSTEM_DIR; 19223 if (locationIsPrivileged(disabledPs.codePath)) { 19224 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 19225 } 19226 19227 final PackageParser.Package newPkg; 19228 try { 19229 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */, 19230 0 /* currentTime */, null); 19231 } catch (PackageManagerException e) { 19232 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 19233 + e.getMessage()); 19234 return false; 19235 } 19236 19237 try { 19238 // update shared libraries for the newly re-installed system package 19239 updateSharedLibrariesLPr(newPkg, null); 19240 } catch (PackageManagerException e) { 19241 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 19242 } 19243 19244 prepareAppDataAfterInstallLIF(newPkg); 19245 19246 // writer 19247 synchronized (mPackages) { 19248 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 19249 19250 // Propagate the permissions state as we do not want to drop on the floor 19251 // runtime permissions. The update permissions method below will take 19252 // care of removing obsolete permissions and grant install permissions. 19253 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 19254 updatePermissionsLPw(newPkg.packageName, newPkg, 19255 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 19256 19257 if (applyUserRestrictions) { 19258 boolean installedStateChanged = false; 19259 if (DEBUG_REMOVE) { 19260 Slog.d(TAG, "Propagating install state across reinstall"); 19261 } 19262 for (int userId : allUserHandles) { 19263 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 19264 if (DEBUG_REMOVE) { 19265 Slog.d(TAG, " user " + userId + " => " + installed); 19266 } 19267 if (installed != ps.getInstalled(userId)) { 19268 installedStateChanged = true; 19269 } 19270 ps.setInstalled(installed, userId); 19271 19272 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 19273 } 19274 // Regardless of writeSettings we need to ensure that this restriction 19275 // state propagation is persisted 19276 mSettings.writeAllUsersPackageRestrictionsLPr(); 19277 if (installedStateChanged) { 19278 mSettings.writeKernelMappingLPr(ps); 19279 } 19280 } 19281 // can downgrade to reader here 19282 if (writeSettings) { 19283 mSettings.writeLPr(); 19284 } 19285 } 19286 return true; 19287 } 19288 19289 private boolean deleteInstalledPackageLIF(PackageSetting ps, 19290 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 19291 PackageRemovedInfo outInfo, boolean writeSettings, 19292 PackageParser.Package replacingPackage) { 19293 synchronized (mPackages) { 19294 if (outInfo != null) { 19295 outInfo.uid = ps.appId; 19296 } 19297 19298 if (outInfo != null && outInfo.removedChildPackages != null) { 19299 final int childCount = (ps.childPackageNames != null) 19300 ? ps.childPackageNames.size() : 0; 19301 for (int i = 0; i < childCount; i++) { 19302 String childPackageName = ps.childPackageNames.get(i); 19303 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 19304 if (childPs == null) { 19305 return false; 19306 } 19307 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 19308 childPackageName); 19309 if (childInfo != null) { 19310 childInfo.uid = childPs.appId; 19311 } 19312 } 19313 } 19314 } 19315 19316 // Delete package data from internal structures and also remove data if flag is set 19317 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 19318 19319 // Delete the child packages data 19320 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 19321 for (int i = 0; i < childCount; i++) { 19322 PackageSetting childPs; 19323 synchronized (mPackages) { 19324 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 19325 } 19326 if (childPs != null) { 19327 PackageRemovedInfo childOutInfo = (outInfo != null 19328 && outInfo.removedChildPackages != null) 19329 ? outInfo.removedChildPackages.get(childPs.name) : null; 19330 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 19331 && (replacingPackage != null 19332 && !replacingPackage.hasChildPackage(childPs.name)) 19333 ? flags & ~DELETE_KEEP_DATA : flags; 19334 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 19335 deleteFlags, writeSettings); 19336 } 19337 } 19338 19339 // Delete application code and resources only for parent packages 19340 if (ps.parentPackageName == null) { 19341 if (deleteCodeAndResources && (outInfo != null)) { 19342 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 19343 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 19344 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 19345 } 19346 } 19347 19348 return true; 19349 } 19350 19351 @Override 19352 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 19353 int userId) { 19354 mContext.enforceCallingOrSelfPermission( 19355 android.Manifest.permission.DELETE_PACKAGES, null); 19356 synchronized (mPackages) { 19357 // Cannot block uninstall of static shared libs as they are 19358 // considered a part of the using app (emulating static linking). 19359 // Also static libs are installed always on internal storage. 19360 PackageParser.Package pkg = mPackages.get(packageName); 19361 if (pkg != null && pkg.staticSharedLibName != null) { 19362 Slog.w(TAG, "Cannot block uninstall of package: " + packageName 19363 + " providing static shared library: " + pkg.staticSharedLibName); 19364 return false; 19365 } 19366 mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall); 19367 mSettings.writePackageRestrictionsLPr(userId); 19368 } 19369 return true; 19370 } 19371 19372 @Override 19373 public boolean getBlockUninstallForUser(String packageName, int userId) { 19374 synchronized (mPackages) { 19375 final PackageSetting ps = mSettings.mPackages.get(packageName); 19376 if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) { 19377 return false; 19378 } 19379 return mSettings.getBlockUninstallLPr(userId, packageName); 19380 } 19381 } 19382 19383 @Override 19384 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 19385 enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root"); 19386 synchronized (mPackages) { 19387 PackageSetting ps = mSettings.mPackages.get(packageName); 19388 if (ps == null) { 19389 Log.w(TAG, "Package doesn't exist: " + packageName); 19390 return false; 19391 } 19392 if (systemUserApp) { 19393 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 19394 } else { 19395 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 19396 } 19397 mSettings.writeLPr(); 19398 } 19399 return true; 19400 } 19401 19402 /* 19403 * This method handles package deletion in general 19404 */ 19405 private boolean deletePackageLIF(String packageName, UserHandle user, 19406 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 19407 PackageRemovedInfo outInfo, boolean writeSettings, 19408 PackageParser.Package replacingPackage) { 19409 if (packageName == null) { 19410 Slog.w(TAG, "Attempt to delete null packageName."); 19411 return false; 19412 } 19413 19414 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 19415 19416 PackageSetting ps; 19417 synchronized (mPackages) { 19418 ps = mSettings.mPackages.get(packageName); 19419 if (ps == null) { 19420 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 19421 return false; 19422 } 19423 19424 if (ps.parentPackageName != null && (!isSystemApp(ps) 19425 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 19426 if (DEBUG_REMOVE) { 19427 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 19428 + ((user == null) ? UserHandle.USER_ALL : user)); 19429 } 19430 final int removedUserId = (user != null) ? user.getIdentifier() 19431 : UserHandle.USER_ALL; 19432 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 19433 return false; 19434 } 19435 markPackageUninstalledForUserLPw(ps, user); 19436 scheduleWritePackageRestrictionsLocked(user); 19437 return true; 19438 } 19439 } 19440 19441 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 19442 && user.getIdentifier() != UserHandle.USER_ALL)) { 19443 // The caller is asking that the package only be deleted for a single 19444 // user. To do this, we just mark its uninstalled state and delete 19445 // its data. If this is a system app, we only allow this to happen if 19446 // they have set the special DELETE_SYSTEM_APP which requests different 19447 // semantics than normal for uninstalling system apps. 19448 markPackageUninstalledForUserLPw(ps, user); 19449 19450 if (!isSystemApp(ps)) { 19451 // Do not uninstall the APK if an app should be cached 19452 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 19453 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 19454 // Other user still have this package installed, so all 19455 // we need to do is clear this user's data and save that 19456 // it is uninstalled. 19457 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 19458 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 19459 return false; 19460 } 19461 scheduleWritePackageRestrictionsLocked(user); 19462 return true; 19463 } else { 19464 // We need to set it back to 'installed' so the uninstall 19465 // broadcasts will be sent correctly. 19466 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 19467 ps.setInstalled(true, user.getIdentifier()); 19468 mSettings.writeKernelMappingLPr(ps); 19469 } 19470 } else { 19471 // This is a system app, so we assume that the 19472 // other users still have this package installed, so all 19473 // we need to do is clear this user's data and save that 19474 // it is uninstalled. 19475 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 19476 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 19477 return false; 19478 } 19479 scheduleWritePackageRestrictionsLocked(user); 19480 return true; 19481 } 19482 } 19483 19484 // If we are deleting a composite package for all users, keep track 19485 // of result for each child. 19486 if (ps.childPackageNames != null && outInfo != null) { 19487 synchronized (mPackages) { 19488 final int childCount = ps.childPackageNames.size(); 19489 outInfo.removedChildPackages = new ArrayMap<>(childCount); 19490 for (int i = 0; i < childCount; i++) { 19491 String childPackageName = ps.childPackageNames.get(i); 19492 PackageRemovedInfo childInfo = new PackageRemovedInfo(this); 19493 childInfo.removedPackage = childPackageName; 19494 childInfo.installerPackageName = ps.installerPackageName; 19495 outInfo.removedChildPackages.put(childPackageName, childInfo); 19496 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 19497 if (childPs != null) { 19498 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 19499 } 19500 } 19501 } 19502 } 19503 19504 boolean ret = false; 19505 if (isSystemApp(ps)) { 19506 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 19507 // When an updated system application is deleted we delete the existing resources 19508 // as well and fall back to existing code in system partition 19509 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 19510 } else { 19511 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 19512 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 19513 outInfo, writeSettings, replacingPackage); 19514 } 19515 19516 // Take a note whether we deleted the package for all users 19517 if (outInfo != null) { 19518 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 19519 if (outInfo.removedChildPackages != null) { 19520 synchronized (mPackages) { 19521 final int childCount = outInfo.removedChildPackages.size(); 19522 for (int i = 0; i < childCount; i++) { 19523 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 19524 if (childInfo != null) { 19525 childInfo.removedForAllUsers = mPackages.get( 19526 childInfo.removedPackage) == null; 19527 } 19528 } 19529 } 19530 } 19531 // If we uninstalled an update to a system app there may be some 19532 // child packages that appeared as they are declared in the system 19533 // app but were not declared in the update. 19534 if (isSystemApp(ps)) { 19535 synchronized (mPackages) { 19536 PackageSetting updatedPs = mSettings.getPackageLPr(ps.name); 19537 final int childCount = (updatedPs.childPackageNames != null) 19538 ? updatedPs.childPackageNames.size() : 0; 19539 for (int i = 0; i < childCount; i++) { 19540 String childPackageName = updatedPs.childPackageNames.get(i); 19541 if (outInfo.removedChildPackages == null 19542 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 19543 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 19544 if (childPs == null) { 19545 continue; 19546 } 19547 PackageInstalledInfo installRes = new PackageInstalledInfo(); 19548 installRes.name = childPackageName; 19549 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 19550 installRes.pkg = mPackages.get(childPackageName); 19551 installRes.uid = childPs.pkg.applicationInfo.uid; 19552 if (outInfo.appearedChildPackages == null) { 19553 outInfo.appearedChildPackages = new ArrayMap<>(); 19554 } 19555 outInfo.appearedChildPackages.put(childPackageName, installRes); 19556 } 19557 } 19558 } 19559 } 19560 } 19561 19562 return ret; 19563 } 19564 19565 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 19566 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 19567 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 19568 for (int nextUserId : userIds) { 19569 if (DEBUG_REMOVE) { 19570 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 19571 } 19572 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 19573 false /*installed*/, 19574 true /*stopped*/, 19575 true /*notLaunched*/, 19576 false /*hidden*/, 19577 false /*suspended*/, 19578 false /*instantApp*/, 19579 null /*lastDisableAppCaller*/, 19580 null /*enabledComponents*/, 19581 null /*disabledComponents*/, 19582 ps.readUserState(nextUserId).domainVerificationStatus, 19583 0, PackageManager.INSTALL_REASON_UNKNOWN); 19584 } 19585 mSettings.writeKernelMappingLPr(ps); 19586 } 19587 19588 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 19589 PackageRemovedInfo outInfo) { 19590 final PackageParser.Package pkg; 19591 synchronized (mPackages) { 19592 pkg = mPackages.get(ps.name); 19593 } 19594 19595 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 19596 : new int[] {userId}; 19597 for (int nextUserId : userIds) { 19598 if (DEBUG_REMOVE) { 19599 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 19600 + nextUserId); 19601 } 19602 19603 destroyAppDataLIF(pkg, userId, 19604 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19605 destroyAppProfilesLIF(pkg, userId); 19606 clearDefaultBrowserIfNeededForUser(ps.name, userId); 19607 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 19608 schedulePackageCleaning(ps.name, nextUserId, false); 19609 synchronized (mPackages) { 19610 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 19611 scheduleWritePackageRestrictionsLocked(nextUserId); 19612 } 19613 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 19614 } 19615 } 19616 19617 if (outInfo != null) { 19618 outInfo.removedPackage = ps.name; 19619 outInfo.installerPackageName = ps.installerPackageName; 19620 outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null; 19621 outInfo.removedAppId = ps.appId; 19622 outInfo.removedUsers = userIds; 19623 outInfo.broadcastUsers = userIds; 19624 } 19625 19626 return true; 19627 } 19628 19629 private final class ClearStorageConnection implements ServiceConnection { 19630 IMediaContainerService mContainerService; 19631 19632 @Override 19633 public void onServiceConnected(ComponentName name, IBinder service) { 19634 synchronized (this) { 19635 mContainerService = IMediaContainerService.Stub 19636 .asInterface(Binder.allowBlocking(service)); 19637 notifyAll(); 19638 } 19639 } 19640 19641 @Override 19642 public void onServiceDisconnected(ComponentName name) { 19643 } 19644 } 19645 19646 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 19647 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 19648 19649 final boolean mounted; 19650 if (Environment.isExternalStorageEmulated()) { 19651 mounted = true; 19652 } else { 19653 final String status = Environment.getExternalStorageState(); 19654 19655 mounted = status.equals(Environment.MEDIA_MOUNTED) 19656 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 19657 } 19658 19659 if (!mounted) { 19660 return; 19661 } 19662 19663 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 19664 int[] users; 19665 if (userId == UserHandle.USER_ALL) { 19666 users = sUserManager.getUserIds(); 19667 } else { 19668 users = new int[] { userId }; 19669 } 19670 final ClearStorageConnection conn = new ClearStorageConnection(); 19671 if (mContext.bindServiceAsUser( 19672 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 19673 try { 19674 for (int curUser : users) { 19675 long timeout = SystemClock.uptimeMillis() + 5000; 19676 synchronized (conn) { 19677 long now; 19678 while (conn.mContainerService == null && 19679 (now = SystemClock.uptimeMillis()) < timeout) { 19680 try { 19681 conn.wait(timeout - now); 19682 } catch (InterruptedException e) { 19683 } 19684 } 19685 } 19686 if (conn.mContainerService == null) { 19687 return; 19688 } 19689 19690 final UserEnvironment userEnv = new UserEnvironment(curUser); 19691 clearDirectory(conn.mContainerService, 19692 userEnv.buildExternalStorageAppCacheDirs(packageName)); 19693 if (allData) { 19694 clearDirectory(conn.mContainerService, 19695 userEnv.buildExternalStorageAppDataDirs(packageName)); 19696 clearDirectory(conn.mContainerService, 19697 userEnv.buildExternalStorageAppMediaDirs(packageName)); 19698 } 19699 } 19700 } finally { 19701 mContext.unbindService(conn); 19702 } 19703 } 19704 } 19705 19706 @Override 19707 public void clearApplicationProfileData(String packageName) { 19708 enforceSystemOrRoot("Only the system can clear all profile data"); 19709 19710 final PackageParser.Package pkg; 19711 synchronized (mPackages) { 19712 pkg = mPackages.get(packageName); 19713 } 19714 19715 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 19716 synchronized (mInstallLock) { 19717 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 19718 } 19719 } 19720 } 19721 19722 @Override 19723 public void clearApplicationUserData(final String packageName, 19724 final IPackageDataObserver observer, final int userId) { 19725 mContext.enforceCallingOrSelfPermission( 19726 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 19727 19728 final int callingUid = Binder.getCallingUid(); 19729 enforceCrossUserPermission(callingUid, userId, 19730 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 19731 19732 final PackageSetting ps = mSettings.getPackageLPr(packageName); 19733 if (ps != null && filterAppAccessLPr(ps, callingUid, userId)) { 19734 return; 19735 } 19736 if (mProtectedPackages.isPackageDataProtected(userId, packageName)) { 19737 throw new SecurityException("Cannot clear data for a protected package: " 19738 + packageName); 19739 } 19740 // Queue up an async operation since the package deletion may take a little while. 19741 mHandler.post(new Runnable() { 19742 public void run() { 19743 mHandler.removeCallbacks(this); 19744 final boolean succeeded; 19745 try (PackageFreezer freezer = freezePackage(packageName, 19746 "clearApplicationUserData")) { 19747 synchronized (mInstallLock) { 19748 succeeded = clearApplicationUserDataLIF(packageName, userId); 19749 } 19750 clearExternalStorageDataSync(packageName, userId, true); 19751 synchronized (mPackages) { 19752 mInstantAppRegistry.deleteInstantApplicationMetadataLPw( 19753 packageName, userId); 19754 } 19755 } 19756 if (succeeded) { 19757 // invoke DeviceStorageMonitor's update method to clear any notifications 19758 DeviceStorageMonitorInternal dsm = LocalServices 19759 .getService(DeviceStorageMonitorInternal.class); 19760 if (dsm != null) { 19761 dsm.checkMemory(); 19762 } 19763 } 19764 if(observer != null) { 19765 try { 19766 observer.onRemoveCompleted(packageName, succeeded); 19767 } catch (RemoteException e) { 19768 Log.i(TAG, "Observer no longer exists."); 19769 } 19770 } //end if observer 19771 } //end run 19772 }); 19773 } 19774 19775 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 19776 if (packageName == null) { 19777 Slog.w(TAG, "Attempt to delete null packageName."); 19778 return false; 19779 } 19780 19781 // Try finding details about the requested package 19782 PackageParser.Package pkg; 19783 synchronized (mPackages) { 19784 pkg = mPackages.get(packageName); 19785 if (pkg == null) { 19786 final PackageSetting ps = mSettings.mPackages.get(packageName); 19787 if (ps != null) { 19788 pkg = ps.pkg; 19789 } 19790 } 19791 19792 if (pkg == null) { 19793 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 19794 return false; 19795 } 19796 19797 PackageSetting ps = (PackageSetting) pkg.mExtras; 19798 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 19799 } 19800 19801 clearAppDataLIF(pkg, userId, 19802 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19803 19804 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 19805 removeKeystoreDataIfNeeded(userId, appId); 19806 19807 UserManagerInternal umInternal = getUserManagerInternal(); 19808 final int flags; 19809 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 19810 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19811 } else if (umInternal.isUserRunning(userId)) { 19812 flags = StorageManager.FLAG_STORAGE_DE; 19813 } else { 19814 flags = 0; 19815 } 19816 prepareAppDataContentsLIF(pkg, userId, flags); 19817 19818 return true; 19819 } 19820 19821 /** 19822 * Reverts user permission state changes (permissions and flags) in 19823 * all packages for a given user. 19824 * 19825 * @param userId The device user for which to do a reset. 19826 */ 19827 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 19828 final int packageCount = mPackages.size(); 19829 for (int i = 0; i < packageCount; i++) { 19830 PackageParser.Package pkg = mPackages.valueAt(i); 19831 PackageSetting ps = (PackageSetting) pkg.mExtras; 19832 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 19833 } 19834 } 19835 19836 private void resetNetworkPolicies(int userId) { 19837 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 19838 } 19839 19840 /** 19841 * Reverts user permission state changes (permissions and flags). 19842 * 19843 * @param ps The package for which to reset. 19844 * @param userId The device user for which to do a reset. 19845 */ 19846 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 19847 final PackageSetting ps, final int userId) { 19848 if (ps.pkg == null) { 19849 return; 19850 } 19851 19852 // These are flags that can change base on user actions. 19853 final int userSettableMask = FLAG_PERMISSION_USER_SET 19854 | FLAG_PERMISSION_USER_FIXED 19855 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 19856 | FLAG_PERMISSION_REVIEW_REQUIRED; 19857 19858 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 19859 | FLAG_PERMISSION_POLICY_FIXED; 19860 19861 boolean writeInstallPermissions = false; 19862 boolean writeRuntimePermissions = false; 19863 19864 final int permissionCount = ps.pkg.requestedPermissions.size(); 19865 for (int i = 0; i < permissionCount; i++) { 19866 String permission = ps.pkg.requestedPermissions.get(i); 19867 19868 BasePermission bp = mSettings.mPermissions.get(permission); 19869 if (bp == null) { 19870 continue; 19871 } 19872 19873 // If shared user we just reset the state to which only this app contributed. 19874 if (ps.sharedUser != null) { 19875 boolean used = false; 19876 final int packageCount = ps.sharedUser.packages.size(); 19877 for (int j = 0; j < packageCount; j++) { 19878 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 19879 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 19880 && pkg.pkg.requestedPermissions.contains(permission)) { 19881 used = true; 19882 break; 19883 } 19884 } 19885 if (used) { 19886 continue; 19887 } 19888 } 19889 19890 PermissionsState permissionsState = ps.getPermissionsState(); 19891 19892 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 19893 19894 // Always clear the user settable flags. 19895 final boolean hasInstallState = permissionsState.getInstallPermissionState( 19896 bp.name) != null; 19897 // If permission review is enabled and this is a legacy app, mark the 19898 // permission as requiring a review as this is the initial state. 19899 int flags = 0; 19900 if (mPermissionReviewRequired 19901 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 19902 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 19903 } 19904 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 19905 if (hasInstallState) { 19906 writeInstallPermissions = true; 19907 } else { 19908 writeRuntimePermissions = true; 19909 } 19910 } 19911 19912 // Below is only runtime permission handling. 19913 if (!bp.isRuntime()) { 19914 continue; 19915 } 19916 19917 // Never clobber system or policy. 19918 if ((oldFlags & policyOrSystemFlags) != 0) { 19919 continue; 19920 } 19921 19922 // If this permission was granted by default, make sure it is. 19923 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 19924 if (permissionsState.grantRuntimePermission(bp, userId) 19925 != PERMISSION_OPERATION_FAILURE) { 19926 writeRuntimePermissions = true; 19927 } 19928 // If permission review is enabled the permissions for a legacy apps 19929 // are represented as constantly granted runtime ones, so don't revoke. 19930 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 19931 // Otherwise, reset the permission. 19932 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 19933 switch (revokeResult) { 19934 case PERMISSION_OPERATION_SUCCESS: 19935 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 19936 writeRuntimePermissions = true; 19937 final int appId = ps.appId; 19938 mHandler.post(new Runnable() { 19939 @Override 19940 public void run() { 19941 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 19942 } 19943 }); 19944 } break; 19945 } 19946 } 19947 } 19948 19949 // Synchronously write as we are taking permissions away. 19950 if (writeRuntimePermissions) { 19951 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 19952 } 19953 19954 // Synchronously write as we are taking permissions away. 19955 if (writeInstallPermissions) { 19956 mSettings.writeLPr(); 19957 } 19958 } 19959 19960 /** 19961 * Remove entries from the keystore daemon. Will only remove it if the 19962 * {@code appId} is valid. 19963 */ 19964 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 19965 if (appId < 0) { 19966 return; 19967 } 19968 19969 final KeyStore keyStore = KeyStore.getInstance(); 19970 if (keyStore != null) { 19971 if (userId == UserHandle.USER_ALL) { 19972 for (final int individual : sUserManager.getUserIds()) { 19973 keyStore.clearUid(UserHandle.getUid(individual, appId)); 19974 } 19975 } else { 19976 keyStore.clearUid(UserHandle.getUid(userId, appId)); 19977 } 19978 } else { 19979 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 19980 } 19981 } 19982 19983 @Override 19984 public void deleteApplicationCacheFiles(final String packageName, 19985 final IPackageDataObserver observer) { 19986 final int userId = UserHandle.getCallingUserId(); 19987 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 19988 } 19989 19990 @Override 19991 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 19992 final IPackageDataObserver observer) { 19993 final int callingUid = Binder.getCallingUid(); 19994 mContext.enforceCallingOrSelfPermission( 19995 android.Manifest.permission.DELETE_CACHE_FILES, null); 19996 enforceCrossUserPermission(callingUid, userId, 19997 /* requireFullPermission= */ true, /* checkShell= */ false, 19998 "delete application cache files"); 19999 final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission( 20000 android.Manifest.permission.ACCESS_INSTANT_APPS); 20001 20002 final PackageParser.Package pkg; 20003 synchronized (mPackages) { 20004 pkg = mPackages.get(packageName); 20005 } 20006 20007 // Queue up an async operation since the package deletion may take a little while. 20008 mHandler.post(new Runnable() { 20009 public void run() { 20010 final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras; 20011 boolean doClearData = true; 20012 if (ps != null) { 20013 final boolean targetIsInstantApp = 20014 ps.getInstantApp(UserHandle.getUserId(callingUid)); 20015 doClearData = !targetIsInstantApp 20016 || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED; 20017 } 20018 if (doClearData) { 20019 synchronized (mInstallLock) { 20020 final int flags = StorageManager.FLAG_STORAGE_DE 20021 | StorageManager.FLAG_STORAGE_CE; 20022 // We're only clearing cache files, so we don't care if the 20023 // app is unfrozen and still able to run 20024 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 20025 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 20026 } 20027 clearExternalStorageDataSync(packageName, userId, false); 20028 } 20029 if (observer != null) { 20030 try { 20031 observer.onRemoveCompleted(packageName, true); 20032 } catch (RemoteException e) { 20033 Log.i(TAG, "Observer no longer exists."); 20034 } 20035 } 20036 } 20037 }); 20038 } 20039 20040 @Override 20041 public void getPackageSizeInfo(final String packageName, int userHandle, 20042 final IPackageStatsObserver observer) { 20043 throw new UnsupportedOperationException( 20044 "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!"); 20045 } 20046 20047 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 20048 final PackageSetting ps; 20049 synchronized (mPackages) { 20050 ps = mSettings.mPackages.get(packageName); 20051 if (ps == null) { 20052 Slog.w(TAG, "Failed to find settings for " + packageName); 20053 return false; 20054 } 20055 } 20056 20057 final String[] packageNames = { packageName }; 20058 final long[] ceDataInodes = { ps.getCeDataInode(userId) }; 20059 final String[] codePaths = { ps.codePathString }; 20060 20061 try { 20062 mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0, 20063 ps.appId, ceDataInodes, codePaths, stats); 20064 20065 // For now, ignore code size of packages on system partition 20066 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 20067 stats.codeSize = 0; 20068 } 20069 20070 // External clients expect these to be tracked separately 20071 stats.dataSize -= stats.cacheSize; 20072 20073 } catch (InstallerException e) { 20074 Slog.w(TAG, String.valueOf(e)); 20075 return false; 20076 } 20077 20078 return true; 20079 } 20080 20081 private int getUidTargetSdkVersionLockedLPr(int uid) { 20082 Object obj = mSettings.getUserIdLPr(uid); 20083 if (obj instanceof SharedUserSetting) { 20084 final SharedUserSetting sus = (SharedUserSetting) obj; 20085 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 20086 final Iterator<PackageSetting> it = sus.packages.iterator(); 20087 while (it.hasNext()) { 20088 final PackageSetting ps = it.next(); 20089 if (ps.pkg != null) { 20090 int v = ps.pkg.applicationInfo.targetSdkVersion; 20091 if (v < vers) vers = v; 20092 } 20093 } 20094 return vers; 20095 } else if (obj instanceof PackageSetting) { 20096 final PackageSetting ps = (PackageSetting) obj; 20097 if (ps.pkg != null) { 20098 return ps.pkg.applicationInfo.targetSdkVersion; 20099 } 20100 } 20101 return Build.VERSION_CODES.CUR_DEVELOPMENT; 20102 } 20103 20104 @Override 20105 public void addPreferredActivity(IntentFilter filter, int match, 20106 ComponentName[] set, ComponentName activity, int userId) { 20107 addPreferredActivityInternal(filter, match, set, activity, true, userId, 20108 "Adding preferred"); 20109 } 20110 20111 private void addPreferredActivityInternal(IntentFilter filter, int match, 20112 ComponentName[] set, ComponentName activity, boolean always, int userId, 20113 String opname) { 20114 // writer 20115 int callingUid = Binder.getCallingUid(); 20116 enforceCrossUserPermission(callingUid, userId, 20117 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 20118 if (filter.countActions() == 0) { 20119 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 20120 return; 20121 } 20122 synchronized (mPackages) { 20123 if (mContext.checkCallingOrSelfPermission( 20124 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 20125 != PackageManager.PERMISSION_GRANTED) { 20126 if (getUidTargetSdkVersionLockedLPr(callingUid) 20127 < Build.VERSION_CODES.FROYO) { 20128 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 20129 + callingUid); 20130 return; 20131 } 20132 mContext.enforceCallingOrSelfPermission( 20133 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 20134 } 20135 20136 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 20137 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 20138 + userId + ":"); 20139 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 20140 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 20141 scheduleWritePackageRestrictionsLocked(userId); 20142 postPreferredActivityChangedBroadcast(userId); 20143 } 20144 } 20145 20146 private void postPreferredActivityChangedBroadcast(int userId) { 20147 mHandler.post(() -> { 20148 final IActivityManager am = ActivityManager.getService(); 20149 if (am == null) { 20150 return; 20151 } 20152 20153 final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED); 20154 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 20155 try { 20156 am.broadcastIntent(null, intent, null, null, 20157 0, null, null, null, android.app.AppOpsManager.OP_NONE, 20158 null, false, false, userId); 20159 } catch (RemoteException e) { 20160 } 20161 }); 20162 } 20163 20164 @Override 20165 public void replacePreferredActivity(IntentFilter filter, int match, 20166 ComponentName[] set, ComponentName activity, int userId) { 20167 if (filter.countActions() != 1) { 20168 throw new IllegalArgumentException( 20169 "replacePreferredActivity expects filter to have only 1 action."); 20170 } 20171 if (filter.countDataAuthorities() != 0 20172 || filter.countDataPaths() != 0 20173 || filter.countDataSchemes() > 1 20174 || filter.countDataTypes() != 0) { 20175 throw new IllegalArgumentException( 20176 "replacePreferredActivity expects filter to have no data authorities, " + 20177 "paths, or types; and at most one scheme."); 20178 } 20179 20180 final int callingUid = Binder.getCallingUid(); 20181 enforceCrossUserPermission(callingUid, userId, 20182 true /* requireFullPermission */, false /* checkShell */, 20183 "replace preferred activity"); 20184 synchronized (mPackages) { 20185 if (mContext.checkCallingOrSelfPermission( 20186 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 20187 != PackageManager.PERMISSION_GRANTED) { 20188 if (getUidTargetSdkVersionLockedLPr(callingUid) 20189 < Build.VERSION_CODES.FROYO) { 20190 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 20191 + Binder.getCallingUid()); 20192 return; 20193 } 20194 mContext.enforceCallingOrSelfPermission( 20195 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 20196 } 20197 20198 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 20199 if (pir != null) { 20200 // Get all of the existing entries that exactly match this filter. 20201 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 20202 if (existing != null && existing.size() == 1) { 20203 PreferredActivity cur = existing.get(0); 20204 if (DEBUG_PREFERRED) { 20205 Slog.i(TAG, "Checking replace of preferred:"); 20206 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 20207 if (!cur.mPref.mAlways) { 20208 Slog.i(TAG, " -- CUR; not mAlways!"); 20209 } else { 20210 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 20211 Slog.i(TAG, " -- CUR: mSet=" 20212 + Arrays.toString(cur.mPref.mSetComponents)); 20213 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 20214 Slog.i(TAG, " -- NEW: mMatch=" 20215 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 20216 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 20217 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 20218 } 20219 } 20220 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 20221 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 20222 && cur.mPref.sameSet(set)) { 20223 // Setting the preferred activity to what it happens to be already 20224 if (DEBUG_PREFERRED) { 20225 Slog.i(TAG, "Replacing with same preferred activity " 20226 + cur.mPref.mShortComponent + " for user " 20227 + userId + ":"); 20228 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 20229 } 20230 return; 20231 } 20232 } 20233 20234 if (existing != null) { 20235 if (DEBUG_PREFERRED) { 20236 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 20237 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 20238 } 20239 for (int i = 0; i < existing.size(); i++) { 20240 PreferredActivity pa = existing.get(i); 20241 if (DEBUG_PREFERRED) { 20242 Slog.i(TAG, "Removing existing preferred activity " 20243 + pa.mPref.mComponent + ":"); 20244 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 20245 } 20246 pir.removeFilter(pa); 20247 } 20248 } 20249 } 20250 addPreferredActivityInternal(filter, match, set, activity, true, userId, 20251 "Replacing preferred"); 20252 } 20253 } 20254 20255 @Override 20256 public void clearPackagePreferredActivities(String packageName) { 20257 final int callingUid = Binder.getCallingUid(); 20258 if (getInstantAppPackageName(callingUid) != null) { 20259 return; 20260 } 20261 // writer 20262 synchronized (mPackages) { 20263 PackageParser.Package pkg = mPackages.get(packageName); 20264 if (pkg == null || pkg.applicationInfo.uid != callingUid) { 20265 if (mContext.checkCallingOrSelfPermission( 20266 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 20267 != PackageManager.PERMISSION_GRANTED) { 20268 if (getUidTargetSdkVersionLockedLPr(callingUid) 20269 < Build.VERSION_CODES.FROYO) { 20270 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 20271 + callingUid); 20272 return; 20273 } 20274 mContext.enforceCallingOrSelfPermission( 20275 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 20276 } 20277 } 20278 final PackageSetting ps = mSettings.getPackageLPr(packageName); 20279 if (ps != null 20280 && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 20281 return; 20282 } 20283 int user = UserHandle.getCallingUserId(); 20284 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 20285 scheduleWritePackageRestrictionsLocked(user); 20286 } 20287 } 20288 } 20289 20290 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 20291 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 20292 ArrayList<PreferredActivity> removed = null; 20293 boolean changed = false; 20294 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 20295 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 20296 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 20297 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 20298 continue; 20299 } 20300 Iterator<PreferredActivity> it = pir.filterIterator(); 20301 while (it.hasNext()) { 20302 PreferredActivity pa = it.next(); 20303 // Mark entry for removal only if it matches the package name 20304 // and the entry is of type "always". 20305 if (packageName == null || 20306 (pa.mPref.mComponent.getPackageName().equals(packageName) 20307 && pa.mPref.mAlways)) { 20308 if (removed == null) { 20309 removed = new ArrayList<PreferredActivity>(); 20310 } 20311 removed.add(pa); 20312 } 20313 } 20314 if (removed != null) { 20315 for (int j=0; j<removed.size(); j++) { 20316 PreferredActivity pa = removed.get(j); 20317 pir.removeFilter(pa); 20318 } 20319 changed = true; 20320 } 20321 } 20322 if (changed) { 20323 postPreferredActivityChangedBroadcast(userId); 20324 } 20325 return changed; 20326 } 20327 20328 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 20329 private void clearIntentFilterVerificationsLPw(int userId) { 20330 final int packageCount = mPackages.size(); 20331 for (int i = 0; i < packageCount; i++) { 20332 PackageParser.Package pkg = mPackages.valueAt(i); 20333 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 20334 } 20335 } 20336 20337 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 20338 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 20339 if (userId == UserHandle.USER_ALL) { 20340 if (mSettings.removeIntentFilterVerificationLPw(packageName, 20341 sUserManager.getUserIds())) { 20342 for (int oneUserId : sUserManager.getUserIds()) { 20343 scheduleWritePackageRestrictionsLocked(oneUserId); 20344 } 20345 } 20346 } else { 20347 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 20348 scheduleWritePackageRestrictionsLocked(userId); 20349 } 20350 } 20351 } 20352 20353 /** Clears state for all users, and touches intent filter verification policy */ 20354 void clearDefaultBrowserIfNeeded(String packageName) { 20355 for (int oneUserId : sUserManager.getUserIds()) { 20356 clearDefaultBrowserIfNeededForUser(packageName, oneUserId); 20357 } 20358 } 20359 20360 private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) { 20361 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 20362 if (!TextUtils.isEmpty(defaultBrowserPackageName)) { 20363 if (packageName.equals(defaultBrowserPackageName)) { 20364 setDefaultBrowserPackageName(null, userId); 20365 } 20366 } 20367 } 20368 20369 @Override 20370 public void resetApplicationPreferences(int userId) { 20371 mContext.enforceCallingOrSelfPermission( 20372 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 20373 final long identity = Binder.clearCallingIdentity(); 20374 // writer 20375 try { 20376 synchronized (mPackages) { 20377 clearPackagePreferredActivitiesLPw(null, userId); 20378 mSettings.applyDefaultPreferredAppsLPw(this, userId); 20379 // TODO: We have to reset the default SMS and Phone. This requires 20380 // significant refactoring to keep all default apps in the package 20381 // manager (cleaner but more work) or have the services provide 20382 // callbacks to the package manager to request a default app reset. 20383 applyFactoryDefaultBrowserLPw(userId); 20384 clearIntentFilterVerificationsLPw(userId); 20385 primeDomainVerificationsLPw(userId); 20386 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 20387 scheduleWritePackageRestrictionsLocked(userId); 20388 } 20389 resetNetworkPolicies(userId); 20390 } finally { 20391 Binder.restoreCallingIdentity(identity); 20392 } 20393 } 20394 20395 @Override 20396 public int getPreferredActivities(List<IntentFilter> outFilters, 20397 List<ComponentName> outActivities, String packageName) { 20398 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 20399 return 0; 20400 } 20401 int num = 0; 20402 final int userId = UserHandle.getCallingUserId(); 20403 // reader 20404 synchronized (mPackages) { 20405 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 20406 if (pir != null) { 20407 final Iterator<PreferredActivity> it = pir.filterIterator(); 20408 while (it.hasNext()) { 20409 final PreferredActivity pa = it.next(); 20410 if (packageName == null 20411 || (pa.mPref.mComponent.getPackageName().equals(packageName) 20412 && pa.mPref.mAlways)) { 20413 if (outFilters != null) { 20414 outFilters.add(new IntentFilter(pa)); 20415 } 20416 if (outActivities != null) { 20417 outActivities.add(pa.mPref.mComponent); 20418 } 20419 } 20420 } 20421 } 20422 } 20423 20424 return num; 20425 } 20426 20427 @Override 20428 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 20429 int userId) { 20430 int callingUid = Binder.getCallingUid(); 20431 if (callingUid != Process.SYSTEM_UID) { 20432 throw new SecurityException( 20433 "addPersistentPreferredActivity can only be run by the system"); 20434 } 20435 if (filter.countActions() == 0) { 20436 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 20437 return; 20438 } 20439 synchronized (mPackages) { 20440 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 20441 ":"); 20442 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 20443 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 20444 new PersistentPreferredActivity(filter, activity)); 20445 scheduleWritePackageRestrictionsLocked(userId); 20446 postPreferredActivityChangedBroadcast(userId); 20447 } 20448 } 20449 20450 @Override 20451 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 20452 int callingUid = Binder.getCallingUid(); 20453 if (callingUid != Process.SYSTEM_UID) { 20454 throw new SecurityException( 20455 "clearPackagePersistentPreferredActivities can only be run by the system"); 20456 } 20457 ArrayList<PersistentPreferredActivity> removed = null; 20458 boolean changed = false; 20459 synchronized (mPackages) { 20460 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 20461 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 20462 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 20463 .valueAt(i); 20464 if (userId != thisUserId) { 20465 continue; 20466 } 20467 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 20468 while (it.hasNext()) { 20469 PersistentPreferredActivity ppa = it.next(); 20470 // Mark entry for removal only if it matches the package name. 20471 if (ppa.mComponent.getPackageName().equals(packageName)) { 20472 if (removed == null) { 20473 removed = new ArrayList<PersistentPreferredActivity>(); 20474 } 20475 removed.add(ppa); 20476 } 20477 } 20478 if (removed != null) { 20479 for (int j=0; j<removed.size(); j++) { 20480 PersistentPreferredActivity ppa = removed.get(j); 20481 ppir.removeFilter(ppa); 20482 } 20483 changed = true; 20484 } 20485 } 20486 20487 if (changed) { 20488 scheduleWritePackageRestrictionsLocked(userId); 20489 postPreferredActivityChangedBroadcast(userId); 20490 } 20491 } 20492 } 20493 20494 /** 20495 * Common machinery for picking apart a restored XML blob and passing 20496 * it to a caller-supplied functor to be applied to the running system. 20497 */ 20498 private void restoreFromXml(XmlPullParser parser, int userId, 20499 String expectedStartTag, BlobXmlRestorer functor) 20500 throws IOException, XmlPullParserException { 20501 int type; 20502 while ((type = parser.next()) != XmlPullParser.START_TAG 20503 && type != XmlPullParser.END_DOCUMENT) { 20504 } 20505 if (type != XmlPullParser.START_TAG) { 20506 // oops didn't find a start tag?! 20507 if (DEBUG_BACKUP) { 20508 Slog.e(TAG, "Didn't find start tag during restore"); 20509 } 20510 return; 20511 } 20512Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 20513 // this is supposed to be TAG_PREFERRED_BACKUP 20514 if (!expectedStartTag.equals(parser.getName())) { 20515 if (DEBUG_BACKUP) { 20516 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 20517 } 20518 return; 20519 } 20520 20521 // skip interfering stuff, then we're aligned with the backing implementation 20522 while ((type = parser.next()) == XmlPullParser.TEXT) { } 20523Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 20524 functor.apply(parser, userId); 20525 } 20526 20527 private interface BlobXmlRestorer { 20528 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 20529 } 20530 20531 /** 20532 * Non-Binder method, support for the backup/restore mechanism: write the 20533 * full set of preferred activities in its canonical XML format. Returns the 20534 * XML output as a byte array, or null if there is none. 20535 */ 20536 @Override 20537 public byte[] getPreferredActivityBackup(int userId) { 20538 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 20539 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 20540 } 20541 20542 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 20543 try { 20544 final XmlSerializer serializer = new FastXmlSerializer(); 20545 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 20546 serializer.startDocument(null, true); 20547 serializer.startTag(null, TAG_PREFERRED_BACKUP); 20548 20549 synchronized (mPackages) { 20550 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 20551 } 20552 20553 serializer.endTag(null, TAG_PREFERRED_BACKUP); 20554 serializer.endDocument(); 20555 serializer.flush(); 20556 } catch (Exception e) { 20557 if (DEBUG_BACKUP) { 20558 Slog.e(TAG, "Unable to write preferred activities for backup", e); 20559 } 20560 return null; 20561 } 20562 20563 return dataStream.toByteArray(); 20564 } 20565 20566 @Override 20567 public void restorePreferredActivities(byte[] backup, int userId) { 20568 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 20569 throw new SecurityException("Only the system may call restorePreferredActivities()"); 20570 } 20571 20572 try { 20573 final XmlPullParser parser = Xml.newPullParser(); 20574 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 20575 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 20576 new BlobXmlRestorer() { 20577 @Override 20578 public void apply(XmlPullParser parser, int userId) 20579 throws XmlPullParserException, IOException { 20580 synchronized (mPackages) { 20581 mSettings.readPreferredActivitiesLPw(parser, userId); 20582 } 20583 } 20584 } ); 20585 } catch (Exception e) { 20586 if (DEBUG_BACKUP) { 20587 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 20588 } 20589 } 20590 } 20591 20592 /** 20593 * Non-Binder method, support for the backup/restore mechanism: write the 20594 * default browser (etc) settings in its canonical XML format. Returns the default 20595 * browser XML representation as a byte array, or null if there is none. 20596 */ 20597 @Override 20598 public byte[] getDefaultAppsBackup(int userId) { 20599 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 20600 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 20601 } 20602 20603 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 20604 try { 20605 final XmlSerializer serializer = new FastXmlSerializer(); 20606 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 20607 serializer.startDocument(null, true); 20608 serializer.startTag(null, TAG_DEFAULT_APPS); 20609 20610 synchronized (mPackages) { 20611 mSettings.writeDefaultAppsLPr(serializer, userId); 20612 } 20613 20614 serializer.endTag(null, TAG_DEFAULT_APPS); 20615 serializer.endDocument(); 20616 serializer.flush(); 20617 } catch (Exception e) { 20618 if (DEBUG_BACKUP) { 20619 Slog.e(TAG, "Unable to write default apps for backup", e); 20620 } 20621 return null; 20622 } 20623 20624 return dataStream.toByteArray(); 20625 } 20626 20627 @Override 20628 public void restoreDefaultApps(byte[] backup, int userId) { 20629 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 20630 throw new SecurityException("Only the system may call restoreDefaultApps()"); 20631 } 20632 20633 try { 20634 final XmlPullParser parser = Xml.newPullParser(); 20635 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 20636 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 20637 new BlobXmlRestorer() { 20638 @Override 20639 public void apply(XmlPullParser parser, int userId) 20640 throws XmlPullParserException, IOException { 20641 synchronized (mPackages) { 20642 mSettings.readDefaultAppsLPw(parser, userId); 20643 } 20644 } 20645 } ); 20646 } catch (Exception e) { 20647 if (DEBUG_BACKUP) { 20648 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 20649 } 20650 } 20651 } 20652 20653 @Override 20654 public byte[] getIntentFilterVerificationBackup(int userId) { 20655 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 20656 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 20657 } 20658 20659 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 20660 try { 20661 final XmlSerializer serializer = new FastXmlSerializer(); 20662 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 20663 serializer.startDocument(null, true); 20664 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 20665 20666 synchronized (mPackages) { 20667 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 20668 } 20669 20670 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 20671 serializer.endDocument(); 20672 serializer.flush(); 20673 } catch (Exception e) { 20674 if (DEBUG_BACKUP) { 20675 Slog.e(TAG, "Unable to write default apps for backup", e); 20676 } 20677 return null; 20678 } 20679 20680 return dataStream.toByteArray(); 20681 } 20682 20683 @Override 20684 public void restoreIntentFilterVerification(byte[] backup, int userId) { 20685 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 20686 throw new SecurityException("Only the system may call restorePreferredActivities()"); 20687 } 20688 20689 try { 20690 final XmlPullParser parser = Xml.newPullParser(); 20691 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 20692 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 20693 new BlobXmlRestorer() { 20694 @Override 20695 public void apply(XmlPullParser parser, int userId) 20696 throws XmlPullParserException, IOException { 20697 synchronized (mPackages) { 20698 mSettings.readAllDomainVerificationsLPr(parser, userId); 20699 mSettings.writeLPr(); 20700 } 20701 } 20702 } ); 20703 } catch (Exception e) { 20704 if (DEBUG_BACKUP) { 20705 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 20706 } 20707 } 20708 } 20709 20710 @Override 20711 public byte[] getPermissionGrantBackup(int userId) { 20712 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 20713 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 20714 } 20715 20716 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 20717 try { 20718 final XmlSerializer serializer = new FastXmlSerializer(); 20719 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 20720 serializer.startDocument(null, true); 20721 serializer.startTag(null, TAG_PERMISSION_BACKUP); 20722 20723 synchronized (mPackages) { 20724 serializeRuntimePermissionGrantsLPr(serializer, userId); 20725 } 20726 20727 serializer.endTag(null, TAG_PERMISSION_BACKUP); 20728 serializer.endDocument(); 20729 serializer.flush(); 20730 } catch (Exception e) { 20731 if (DEBUG_BACKUP) { 20732 Slog.e(TAG, "Unable to write default apps for backup", e); 20733 } 20734 return null; 20735 } 20736 20737 return dataStream.toByteArray(); 20738 } 20739 20740 @Override 20741 public void restorePermissionGrants(byte[] backup, int userId) { 20742 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 20743 throw new SecurityException("Only the system may call restorePermissionGrants()"); 20744 } 20745 20746 try { 20747 final XmlPullParser parser = Xml.newPullParser(); 20748 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 20749 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 20750 new BlobXmlRestorer() { 20751 @Override 20752 public void apply(XmlPullParser parser, int userId) 20753 throws XmlPullParserException, IOException { 20754 synchronized (mPackages) { 20755 processRestoredPermissionGrantsLPr(parser, userId); 20756 } 20757 } 20758 } ); 20759 } catch (Exception e) { 20760 if (DEBUG_BACKUP) { 20761 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 20762 } 20763 } 20764 } 20765 20766 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 20767 throws IOException { 20768 serializer.startTag(null, TAG_ALL_GRANTS); 20769 20770 final int N = mSettings.mPackages.size(); 20771 for (int i = 0; i < N; i++) { 20772 final PackageSetting ps = mSettings.mPackages.valueAt(i); 20773 boolean pkgGrantsKnown = false; 20774 20775 PermissionsState packagePerms = ps.getPermissionsState(); 20776 20777 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 20778 final int grantFlags = state.getFlags(); 20779 // only look at grants that are not system/policy fixed 20780 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 20781 final boolean isGranted = state.isGranted(); 20782 // And only back up the user-twiddled state bits 20783 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 20784 final String packageName = mSettings.mPackages.keyAt(i); 20785 if (!pkgGrantsKnown) { 20786 serializer.startTag(null, TAG_GRANT); 20787 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 20788 pkgGrantsKnown = true; 20789 } 20790 20791 final boolean userSet = 20792 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 20793 final boolean userFixed = 20794 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 20795 final boolean revoke = 20796 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 20797 20798 serializer.startTag(null, TAG_PERMISSION); 20799 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 20800 if (isGranted) { 20801 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 20802 } 20803 if (userSet) { 20804 serializer.attribute(null, ATTR_USER_SET, "true"); 20805 } 20806 if (userFixed) { 20807 serializer.attribute(null, ATTR_USER_FIXED, "true"); 20808 } 20809 if (revoke) { 20810 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 20811 } 20812 serializer.endTag(null, TAG_PERMISSION); 20813 } 20814 } 20815 } 20816 20817 if (pkgGrantsKnown) { 20818 serializer.endTag(null, TAG_GRANT); 20819 } 20820 } 20821 20822 serializer.endTag(null, TAG_ALL_GRANTS); 20823 } 20824 20825 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 20826 throws XmlPullParserException, IOException { 20827 String pkgName = null; 20828 int outerDepth = parser.getDepth(); 20829 int type; 20830 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 20831 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 20832 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 20833 continue; 20834 } 20835 20836 final String tagName = parser.getName(); 20837 if (tagName.equals(TAG_GRANT)) { 20838 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 20839 if (DEBUG_BACKUP) { 20840 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 20841 } 20842 } else if (tagName.equals(TAG_PERMISSION)) { 20843 20844 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 20845 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 20846 20847 int newFlagSet = 0; 20848 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 20849 newFlagSet |= FLAG_PERMISSION_USER_SET; 20850 } 20851 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 20852 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 20853 } 20854 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 20855 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 20856 } 20857 if (DEBUG_BACKUP) { 20858 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 20859 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 20860 } 20861 final PackageSetting ps = mSettings.mPackages.get(pkgName); 20862 if (ps != null) { 20863 // Already installed so we apply the grant immediately 20864 if (DEBUG_BACKUP) { 20865 Slog.v(TAG, " + already installed; applying"); 20866 } 20867 PermissionsState perms = ps.getPermissionsState(); 20868 BasePermission bp = mSettings.mPermissions.get(permName); 20869 if (bp != null) { 20870 if (isGranted) { 20871 perms.grantRuntimePermission(bp, userId); 20872 } 20873 if (newFlagSet != 0) { 20874 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 20875 } 20876 } 20877 } else { 20878 // Need to wait for post-restore install to apply the grant 20879 if (DEBUG_BACKUP) { 20880 Slog.v(TAG, " - not yet installed; saving for later"); 20881 } 20882 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 20883 isGranted, newFlagSet, userId); 20884 } 20885 } else { 20886 PackageManagerService.reportSettingsProblem(Log.WARN, 20887 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 20888 XmlUtils.skipCurrentTag(parser); 20889 } 20890 } 20891 20892 scheduleWriteSettingsLocked(); 20893 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 20894 } 20895 20896 @Override 20897 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 20898 int sourceUserId, int targetUserId, int flags) { 20899 mContext.enforceCallingOrSelfPermission( 20900 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 20901 int callingUid = Binder.getCallingUid(); 20902 enforceOwnerRights(ownerPackage, callingUid); 20903 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 20904 if (intentFilter.countActions() == 0) { 20905 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 20906 return; 20907 } 20908 synchronized (mPackages) { 20909 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 20910 ownerPackage, targetUserId, flags); 20911 CrossProfileIntentResolver resolver = 20912 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 20913 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 20914 // We have all those whose filter is equal. Now checking if the rest is equal as well. 20915 if (existing != null) { 20916 int size = existing.size(); 20917 for (int i = 0; i < size; i++) { 20918 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 20919 return; 20920 } 20921 } 20922 } 20923 resolver.addFilter(newFilter); 20924 scheduleWritePackageRestrictionsLocked(sourceUserId); 20925 } 20926 } 20927 20928 @Override 20929 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 20930 mContext.enforceCallingOrSelfPermission( 20931 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 20932 final int callingUid = Binder.getCallingUid(); 20933 enforceOwnerRights(ownerPackage, callingUid); 20934 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 20935 synchronized (mPackages) { 20936 CrossProfileIntentResolver resolver = 20937 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 20938 ArraySet<CrossProfileIntentFilter> set = 20939 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 20940 for (CrossProfileIntentFilter filter : set) { 20941 if (filter.getOwnerPackage().equals(ownerPackage)) { 20942 resolver.removeFilter(filter); 20943 } 20944 } 20945 scheduleWritePackageRestrictionsLocked(sourceUserId); 20946 } 20947 } 20948 20949 // Enforcing that callingUid is owning pkg on userId 20950 private void enforceOwnerRights(String pkg, int callingUid) { 20951 // The system owns everything. 20952 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 20953 return; 20954 } 20955 final int callingUserId = UserHandle.getUserId(callingUid); 20956 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 20957 if (pi == null) { 20958 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 20959 + callingUserId); 20960 } 20961 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 20962 throw new SecurityException("Calling uid " + callingUid 20963 + " does not own package " + pkg); 20964 } 20965 } 20966 20967 @Override 20968 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 20969 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 20970 return null; 20971 } 20972 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 20973 } 20974 20975 public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) { 20976 UserManagerService ums = UserManagerService.getInstance(); 20977 if (ums != null) { 20978 final UserInfo parent = ums.getProfileParent(userId); 20979 final int launcherUid = (parent != null) ? parent.id : userId; 20980 final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid); 20981 if (launcherComponent != null) { 20982 Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED) 20983 .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo) 20984 .putExtra(Intent.EXTRA_USER, UserHandle.of(userId)) 20985 .setPackage(launcherComponent.getPackageName()); 20986 mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid)); 20987 } 20988 } 20989 } 20990 20991 /** 20992 * Report the 'Home' activity which is currently set as "always use this one". If non is set 20993 * then reports the most likely home activity or null if there are more than one. 20994 */ 20995 private ComponentName getDefaultHomeActivity(int userId) { 20996 List<ResolveInfo> allHomeCandidates = new ArrayList<>(); 20997 ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId); 20998 if (cn != null) { 20999 return cn; 21000 } 21001 21002 // Find the launcher with the highest priority and return that component if there are no 21003 // other home activity with the same priority. 21004 int lastPriority = Integer.MIN_VALUE; 21005 ComponentName lastComponent = null; 21006 final int size = allHomeCandidates.size(); 21007 for (int i = 0; i < size; i++) { 21008 final ResolveInfo ri = allHomeCandidates.get(i); 21009 if (ri.priority > lastPriority) { 21010 lastComponent = ri.activityInfo.getComponentName(); 21011 lastPriority = ri.priority; 21012 } else if (ri.priority == lastPriority) { 21013 // Two components found with same priority. 21014 lastComponent = null; 21015 } 21016 } 21017 return lastComponent; 21018 } 21019 21020 private Intent getHomeIntent() { 21021 Intent intent = new Intent(Intent.ACTION_MAIN); 21022 intent.addCategory(Intent.CATEGORY_HOME); 21023 intent.addCategory(Intent.CATEGORY_DEFAULT); 21024 return intent; 21025 } 21026 21027 private IntentFilter getHomeFilter() { 21028 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 21029 filter.addCategory(Intent.CATEGORY_HOME); 21030 filter.addCategory(Intent.CATEGORY_DEFAULT); 21031 return filter; 21032 } 21033 21034 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 21035 int userId) { 21036 Intent intent = getHomeIntent(); 21037 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 21038 PackageManager.GET_META_DATA, userId); 21039 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 21040 true, false, false, userId); 21041 21042 allHomeCandidates.clear(); 21043 if (list != null) { 21044 for (ResolveInfo ri : list) { 21045 allHomeCandidates.add(ri); 21046 } 21047 } 21048 return (preferred == null || preferred.activityInfo == null) 21049 ? null 21050 : new ComponentName(preferred.activityInfo.packageName, 21051 preferred.activityInfo.name); 21052 } 21053 21054 @Override 21055 public void setHomeActivity(ComponentName comp, int userId) { 21056 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 21057 return; 21058 } 21059 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 21060 getHomeActivitiesAsUser(homeActivities, userId); 21061 21062 boolean found = false; 21063 21064 final int size = homeActivities.size(); 21065 final ComponentName[] set = new ComponentName[size]; 21066 for (int i = 0; i < size; i++) { 21067 final ResolveInfo candidate = homeActivities.get(i); 21068 final ActivityInfo info = candidate.activityInfo; 21069 final ComponentName activityName = new ComponentName(info.packageName, info.name); 21070 set[i] = activityName; 21071 if (!found && activityName.equals(comp)) { 21072 found = true; 21073 } 21074 } 21075 if (!found) { 21076 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 21077 + userId); 21078 } 21079 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 21080 set, comp, userId); 21081 } 21082 21083 private @Nullable String getSetupWizardPackageName() { 21084 final Intent intent = new Intent(Intent.ACTION_MAIN); 21085 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 21086 21087 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 21088 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 21089 | MATCH_DISABLED_COMPONENTS, 21090 UserHandle.myUserId()); 21091 if (matches.size() == 1) { 21092 return matches.get(0).getComponentInfo().packageName; 21093 } else { 21094 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 21095 + ": matches=" + matches); 21096 return null; 21097 } 21098 } 21099 21100 private @Nullable String getStorageManagerPackageName() { 21101 final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE); 21102 21103 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 21104 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 21105 | MATCH_DISABLED_COMPONENTS, 21106 UserHandle.myUserId()); 21107 if (matches.size() == 1) { 21108 return matches.get(0).getComponentInfo().packageName; 21109 } else { 21110 Slog.e(TAG, "There should probably be exactly one storage manager; found " 21111 + matches.size() + ": matches=" + matches); 21112 return null; 21113 } 21114 } 21115 21116 @Override 21117 public void setApplicationEnabledSetting(String appPackageName, 21118 int newState, int flags, int userId, String callingPackage) { 21119 if (!sUserManager.exists(userId)) return; 21120 if (callingPackage == null) { 21121 callingPackage = Integer.toString(Binder.getCallingUid()); 21122 } 21123 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 21124 } 21125 21126 @Override 21127 public void setUpdateAvailable(String packageName, boolean updateAvailable) { 21128 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 21129 synchronized (mPackages) { 21130 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 21131 if (pkgSetting != null) { 21132 pkgSetting.setUpdateAvailable(updateAvailable); 21133 } 21134 } 21135 } 21136 21137 @Override 21138 public void setComponentEnabledSetting(ComponentName componentName, 21139 int newState, int flags, int userId) { 21140 if (!sUserManager.exists(userId)) return; 21141 setEnabledSetting(componentName.getPackageName(), 21142 componentName.getClassName(), newState, flags, userId, null); 21143 } 21144 21145 private void setEnabledSetting(final String packageName, String className, int newState, 21146 final int flags, int userId, String callingPackage) { 21147 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 21148 || newState == COMPONENT_ENABLED_STATE_ENABLED 21149 || newState == COMPONENT_ENABLED_STATE_DISABLED 21150 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 21151 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 21152 throw new IllegalArgumentException("Invalid new component state: " 21153 + newState); 21154 } 21155 PackageSetting pkgSetting; 21156 final int callingUid = Binder.getCallingUid(); 21157 final int permission; 21158 if (callingUid == Process.SYSTEM_UID) { 21159 permission = PackageManager.PERMISSION_GRANTED; 21160 } else { 21161 permission = mContext.checkCallingOrSelfPermission( 21162 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 21163 } 21164 enforceCrossUserPermission(callingUid, userId, 21165 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 21166 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 21167 boolean sendNow = false; 21168 boolean isApp = (className == null); 21169 final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null); 21170 String componentName = isApp ? packageName : className; 21171 int packageUid = -1; 21172 ArrayList<String> components; 21173 21174 // reader 21175 synchronized (mPackages) { 21176 pkgSetting = mSettings.mPackages.get(packageName); 21177 if (pkgSetting == null) { 21178 if (!isCallerInstantApp) { 21179 if (className == null) { 21180 throw new IllegalArgumentException("Unknown package: " + packageName); 21181 } 21182 throw new IllegalArgumentException( 21183 "Unknown component: " + packageName + "/" + className); 21184 } else { 21185 // throw SecurityException to prevent leaking package information 21186 throw new SecurityException( 21187 "Attempt to change component state; " 21188 + "pid=" + Binder.getCallingPid() 21189 + ", uid=" + callingUid 21190 + (className == null 21191 ? ", package=" + packageName 21192 : ", component=" + packageName + "/" + className)); 21193 } 21194 } 21195 } 21196 21197 // Limit who can change which apps 21198 if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) { 21199 // Don't allow apps that don't have permission to modify other apps 21200 if (!allowedByPermission 21201 || filterAppAccessLPr(pkgSetting, callingUid, userId)) { 21202 throw new SecurityException( 21203 "Attempt to change component state; " 21204 + "pid=" + Binder.getCallingPid() 21205 + ", uid=" + callingUid 21206 + (className == null 21207 ? ", package=" + packageName 21208 : ", component=" + packageName + "/" + className)); 21209 } 21210 // Don't allow changing protected packages. 21211 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 21212 throw new SecurityException("Cannot disable a protected package: " + packageName); 21213 } 21214 } 21215 21216 synchronized (mPackages) { 21217 if (callingUid == Process.SHELL_UID 21218 && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) { 21219 // Shell can only change whole packages between ENABLED and DISABLED_USER states 21220 // unless it is a test package. 21221 int oldState = pkgSetting.getEnabled(userId); 21222 if (className == null 21223 && 21224 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 21225 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 21226 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 21227 && 21228 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 21229 || newState == COMPONENT_ENABLED_STATE_DEFAULT 21230 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 21231 // ok 21232 } else { 21233 throw new SecurityException( 21234 "Shell cannot change component state for " + packageName + "/" 21235 + className + " to " + newState); 21236 } 21237 } 21238 if (className == null) { 21239 // We're dealing with an application/package level state change 21240 if (pkgSetting.getEnabled(userId) == newState) { 21241 // Nothing to do 21242 return; 21243 } 21244 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 21245 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 21246 // Don't care about who enables an app. 21247 callingPackage = null; 21248 } 21249 pkgSetting.setEnabled(newState, userId, callingPackage); 21250 // pkgSetting.pkg.mSetEnabled = newState; 21251 } else { 21252 // We're dealing with a component level state change 21253 // First, verify that this is a valid class name. 21254 PackageParser.Package pkg = pkgSetting.pkg; 21255 if (pkg == null || !pkg.hasComponentClassName(className)) { 21256 if (pkg != null && 21257 pkg.applicationInfo.targetSdkVersion >= 21258 Build.VERSION_CODES.JELLY_BEAN) { 21259 throw new IllegalArgumentException("Component class " + className 21260 + " does not exist in " + packageName); 21261 } else { 21262 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 21263 + className + " does not exist in " + packageName); 21264 } 21265 } 21266 switch (newState) { 21267 case COMPONENT_ENABLED_STATE_ENABLED: 21268 if (!pkgSetting.enableComponentLPw(className, userId)) { 21269 return; 21270 } 21271 break; 21272 case COMPONENT_ENABLED_STATE_DISABLED: 21273 if (!pkgSetting.disableComponentLPw(className, userId)) { 21274 return; 21275 } 21276 break; 21277 case COMPONENT_ENABLED_STATE_DEFAULT: 21278 if (!pkgSetting.restoreComponentLPw(className, userId)) { 21279 return; 21280 } 21281 break; 21282 default: 21283 Slog.e(TAG, "Invalid new component state: " + newState); 21284 return; 21285 } 21286 } 21287 scheduleWritePackageRestrictionsLocked(userId); 21288 updateSequenceNumberLP(pkgSetting, new int[] { userId }); 21289 final long callingId = Binder.clearCallingIdentity(); 21290 try { 21291 updateInstantAppInstallerLocked(packageName); 21292 } finally { 21293 Binder.restoreCallingIdentity(callingId); 21294 } 21295 components = mPendingBroadcasts.get(userId, packageName); 21296 final boolean newPackage = components == null; 21297 if (newPackage) { 21298 components = new ArrayList<String>(); 21299 } 21300 if (!components.contains(componentName)) { 21301 components.add(componentName); 21302 } 21303 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 21304 sendNow = true; 21305 // Purge entry from pending broadcast list if another one exists already 21306 // since we are sending one right away. 21307 mPendingBroadcasts.remove(userId, packageName); 21308 } else { 21309 if (newPackage) { 21310 mPendingBroadcasts.put(userId, packageName, components); 21311 } 21312 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 21313 // Schedule a message 21314 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 21315 } 21316 } 21317 } 21318 21319 long callingId = Binder.clearCallingIdentity(); 21320 try { 21321 if (sendNow) { 21322 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 21323 sendPackageChangedBroadcast(packageName, 21324 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 21325 } 21326 } finally { 21327 Binder.restoreCallingIdentity(callingId); 21328 } 21329 } 21330 21331 @Override 21332 public void flushPackageRestrictionsAsUser(int userId) { 21333 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 21334 return; 21335 } 21336 if (!sUserManager.exists(userId)) { 21337 return; 21338 } 21339 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 21340 false /* checkShell */, "flushPackageRestrictions"); 21341 synchronized (mPackages) { 21342 mSettings.writePackageRestrictionsLPr(userId); 21343 mDirtyUsers.remove(userId); 21344 if (mDirtyUsers.isEmpty()) { 21345 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 21346 } 21347 } 21348 } 21349 21350 private void sendPackageChangedBroadcast(String packageName, 21351 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 21352 if (DEBUG_INSTALL) 21353 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 21354 + componentNames); 21355 Bundle extras = new Bundle(4); 21356 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 21357 String nameList[] = new String[componentNames.size()]; 21358 componentNames.toArray(nameList); 21359 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 21360 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 21361 extras.putInt(Intent.EXTRA_UID, packageUid); 21362 // If this is not reporting a change of the overall package, then only send it 21363 // to registered receivers. We don't want to launch a swath of apps for every 21364 // little component state change. 21365 final int flags = !componentNames.contains(packageName) 21366 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 21367 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 21368 new int[] {UserHandle.getUserId(packageUid)}); 21369 } 21370 21371 @Override 21372 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 21373 if (!sUserManager.exists(userId)) return; 21374 final int callingUid = Binder.getCallingUid(); 21375 if (getInstantAppPackageName(callingUid) != null) { 21376 return; 21377 } 21378 final int permission = mContext.checkCallingOrSelfPermission( 21379 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 21380 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 21381 enforceCrossUserPermission(callingUid, userId, 21382 true /* requireFullPermission */, true /* checkShell */, "stop package"); 21383 // writer 21384 synchronized (mPackages) { 21385 final PackageSetting ps = mSettings.mPackages.get(packageName); 21386 if (!filterAppAccessLPr(ps, callingUid, userId) 21387 && mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 21388 allowedByPermission, callingUid, userId)) { 21389 scheduleWritePackageRestrictionsLocked(userId); 21390 } 21391 } 21392 } 21393 21394 @Override 21395 public String getInstallerPackageName(String packageName) { 21396 final int callingUid = Binder.getCallingUid(); 21397 if (getInstantAppPackageName(callingUid) != null) { 21398 return null; 21399 } 21400 // reader 21401 synchronized (mPackages) { 21402 final PackageSetting ps = mSettings.mPackages.get(packageName); 21403 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 21404 return null; 21405 } 21406 return mSettings.getInstallerPackageNameLPr(packageName); 21407 } 21408 } 21409 21410 public boolean isOrphaned(String packageName) { 21411 // reader 21412 synchronized (mPackages) { 21413 return mSettings.isOrphaned(packageName); 21414 } 21415 } 21416 21417 @Override 21418 public int getApplicationEnabledSetting(String packageName, int userId) { 21419 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 21420 int callingUid = Binder.getCallingUid(); 21421 enforceCrossUserPermission(callingUid, userId, 21422 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 21423 // reader 21424 synchronized (mPackages) { 21425 if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) { 21426 return COMPONENT_ENABLED_STATE_DISABLED; 21427 } 21428 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 21429 } 21430 } 21431 21432 @Override 21433 public int getComponentEnabledSetting(ComponentName component, int userId) { 21434 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 21435 int callingUid = Binder.getCallingUid(); 21436 enforceCrossUserPermission(callingUid, userId, 21437 false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled"); 21438 synchronized (mPackages) { 21439 if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid, 21440 component, TYPE_UNKNOWN, userId)) { 21441 return COMPONENT_ENABLED_STATE_DISABLED; 21442 } 21443 return mSettings.getComponentEnabledSettingLPr(component, userId); 21444 } 21445 } 21446 21447 @Override 21448 public void enterSafeMode() { 21449 enforceSystemOrRoot("Only the system can request entering safe mode"); 21450 21451 if (!mSystemReady) { 21452 mSafeMode = true; 21453 } 21454 } 21455 21456 @Override 21457 public void systemReady() { 21458 enforceSystemOrRoot("Only the system can claim the system is ready"); 21459 21460 mSystemReady = true; 21461 final ContentResolver resolver = mContext.getContentResolver(); 21462 ContentObserver co = new ContentObserver(mHandler) { 21463 @Override 21464 public void onChange(boolean selfChange) { 21465 mEphemeralAppsDisabled = 21466 (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) || 21467 (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0); 21468 } 21469 }; 21470 mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global 21471 .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE), 21472 false, co, UserHandle.USER_SYSTEM); 21473 mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global 21474 .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM); 21475 co.onChange(true); 21476 21477 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 21478 // disabled after already being started. 21479 CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this, 21480 mContext.getContentResolver(), UserHandle.USER_SYSTEM); 21481 21482 // Read the compatibilty setting when the system is ready. 21483 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 21484 mContext.getContentResolver(), 21485 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 21486 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 21487 if (DEBUG_SETTINGS) { 21488 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 21489 } 21490 21491 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 21492 21493 synchronized (mPackages) { 21494 // Verify that all of the preferred activity components actually 21495 // exist. It is possible for applications to be updated and at 21496 // that point remove a previously declared activity component that 21497 // had been set as a preferred activity. We try to clean this up 21498 // the next time we encounter that preferred activity, but it is 21499 // possible for the user flow to never be able to return to that 21500 // situation so here we do a sanity check to make sure we haven't 21501 // left any junk around. 21502 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 21503 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 21504 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 21505 removed.clear(); 21506 for (PreferredActivity pa : pir.filterSet()) { 21507 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 21508 removed.add(pa); 21509 } 21510 } 21511 if (removed.size() > 0) { 21512 for (int r=0; r<removed.size(); r++) { 21513 PreferredActivity pa = removed.get(r); 21514 Slog.w(TAG, "Removing dangling preferred activity: " 21515 + pa.mPref.mComponent); 21516 pir.removeFilter(pa); 21517 } 21518 mSettings.writePackageRestrictionsLPr( 21519 mSettings.mPreferredActivities.keyAt(i)); 21520 } 21521 } 21522 21523 for (int userId : UserManagerService.getInstance().getUserIds()) { 21524 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 21525 grantPermissionsUserIds = ArrayUtils.appendInt( 21526 grantPermissionsUserIds, userId); 21527 } 21528 } 21529 } 21530 sUserManager.systemReady(); 21531 21532 // If we upgraded grant all default permissions before kicking off. 21533 for (int userId : grantPermissionsUserIds) { 21534 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 21535 } 21536 21537 // If we did not grant default permissions, we preload from this the 21538 // default permission exceptions lazily to ensure we don't hit the 21539 // disk on a new user creation. 21540 if (grantPermissionsUserIds == EMPTY_INT_ARRAY) { 21541 mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions(); 21542 } 21543 21544 // Kick off any messages waiting for system ready 21545 if (mPostSystemReadyMessages != null) { 21546 for (Message msg : mPostSystemReadyMessages) { 21547 msg.sendToTarget(); 21548 } 21549 mPostSystemReadyMessages = null; 21550 } 21551 21552 // Watch for external volumes that come and go over time 21553 final StorageManager storage = mContext.getSystemService(StorageManager.class); 21554 storage.registerListener(mStorageListener); 21555 21556 mInstallerService.systemReady(); 21557 mPackageDexOptimizer.systemReady(); 21558 21559 StorageManagerInternal StorageManagerInternal = LocalServices.getService( 21560 StorageManagerInternal.class); 21561 StorageManagerInternal.addExternalStoragePolicy( 21562 new StorageManagerInternal.ExternalStorageMountPolicy() { 21563 @Override 21564 public int getMountMode(int uid, String packageName) { 21565 if (Process.isIsolated(uid)) { 21566 return Zygote.MOUNT_EXTERNAL_NONE; 21567 } 21568 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 21569 return Zygote.MOUNT_EXTERNAL_DEFAULT; 21570 } 21571 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 21572 return Zygote.MOUNT_EXTERNAL_DEFAULT; 21573 } 21574 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 21575 return Zygote.MOUNT_EXTERNAL_READ; 21576 } 21577 return Zygote.MOUNT_EXTERNAL_WRITE; 21578 } 21579 21580 @Override 21581 public boolean hasExternalStorage(int uid, String packageName) { 21582 return true; 21583 } 21584 }); 21585 21586 // Now that we're mostly running, clean up stale users and apps 21587 sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 21588 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 21589 21590 if (mPrivappPermissionsViolations != null) { 21591 Slog.wtf(TAG,"Signature|privileged permissions not in " 21592 + "privapp-permissions whitelist: " + mPrivappPermissionsViolations); 21593 mPrivappPermissionsViolations = null; 21594 } 21595 } 21596 21597 public void waitForAppDataPrepared() { 21598 if (mPrepareAppDataFuture == null) { 21599 return; 21600 } 21601 ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData"); 21602 mPrepareAppDataFuture = null; 21603 } 21604 21605 @Override 21606 public boolean isSafeMode() { 21607 // allow instant applications 21608 return mSafeMode; 21609 } 21610 21611 @Override 21612 public boolean hasSystemUidErrors() { 21613 // allow instant applications 21614 return mHasSystemUidErrors; 21615 } 21616 21617 static String arrayToString(int[] array) { 21618 StringBuffer buf = new StringBuffer(128); 21619 buf.append('['); 21620 if (array != null) { 21621 for (int i=0; i<array.length; i++) { 21622 if (i > 0) buf.append(", "); 21623 buf.append(array[i]); 21624 } 21625 } 21626 buf.append(']'); 21627 return buf.toString(); 21628 } 21629 21630 static class DumpState { 21631 public static final int DUMP_LIBS = 1 << 0; 21632 public static final int DUMP_FEATURES = 1 << 1; 21633 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 21634 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 21635 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 21636 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 21637 public static final int DUMP_PERMISSIONS = 1 << 6; 21638 public static final int DUMP_PACKAGES = 1 << 7; 21639 public static final int DUMP_SHARED_USERS = 1 << 8; 21640 public static final int DUMP_MESSAGES = 1 << 9; 21641 public static final int DUMP_PROVIDERS = 1 << 10; 21642 public static final int DUMP_VERIFIERS = 1 << 11; 21643 public static final int DUMP_PREFERRED = 1 << 12; 21644 public static final int DUMP_PREFERRED_XML = 1 << 13; 21645 public static final int DUMP_KEYSETS = 1 << 14; 21646 public static final int DUMP_VERSION = 1 << 15; 21647 public static final int DUMP_INSTALLS = 1 << 16; 21648 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 21649 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 21650 public static final int DUMP_FROZEN = 1 << 19; 21651 public static final int DUMP_DEXOPT = 1 << 20; 21652 public static final int DUMP_COMPILER_STATS = 1 << 21; 21653 public static final int DUMP_CHANGES = 1 << 22; 21654 21655 public static final int OPTION_SHOW_FILTERS = 1 << 0; 21656 21657 private int mTypes; 21658 21659 private int mOptions; 21660 21661 private boolean mTitlePrinted; 21662 21663 private SharedUserSetting mSharedUser; 21664 21665 public boolean isDumping(int type) { 21666 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 21667 return true; 21668 } 21669 21670 return (mTypes & type) != 0; 21671 } 21672 21673 public void setDump(int type) { 21674 mTypes |= type; 21675 } 21676 21677 public boolean isOptionEnabled(int option) { 21678 return (mOptions & option) != 0; 21679 } 21680 21681 public void setOptionEnabled(int option) { 21682 mOptions |= option; 21683 } 21684 21685 public boolean onTitlePrinted() { 21686 final boolean printed = mTitlePrinted; 21687 mTitlePrinted = true; 21688 return printed; 21689 } 21690 21691 public boolean getTitlePrinted() { 21692 return mTitlePrinted; 21693 } 21694 21695 public void setTitlePrinted(boolean enabled) { 21696 mTitlePrinted = enabled; 21697 } 21698 21699 public SharedUserSetting getSharedUser() { 21700 return mSharedUser; 21701 } 21702 21703 public void setSharedUser(SharedUserSetting user) { 21704 mSharedUser = user; 21705 } 21706 } 21707 21708 @Override 21709 public void onShellCommand(FileDescriptor in, FileDescriptor out, 21710 FileDescriptor err, String[] args, ShellCallback callback, 21711 ResultReceiver resultReceiver) { 21712 (new PackageManagerShellCommand(this)).exec( 21713 this, in, out, err, args, callback, resultReceiver); 21714 } 21715 21716 @Override 21717 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 21718 if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return; 21719 21720 DumpState dumpState = new DumpState(); 21721 boolean fullPreferred = false; 21722 boolean checkin = false; 21723 21724 String packageName = null; 21725 ArraySet<String> permissionNames = null; 21726 21727 int opti = 0; 21728 while (opti < args.length) { 21729 String opt = args[opti]; 21730 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 21731 break; 21732 } 21733 opti++; 21734 21735 if ("-a".equals(opt)) { 21736 // Right now we only know how to print all. 21737 } else if ("-h".equals(opt)) { 21738 pw.println("Package manager dump options:"); 21739 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 21740 pw.println(" --checkin: dump for a checkin"); 21741 pw.println(" -f: print details of intent filters"); 21742 pw.println(" -h: print this help"); 21743 pw.println(" cmd may be one of:"); 21744 pw.println(" l[ibraries]: list known shared libraries"); 21745 pw.println(" f[eatures]: list device features"); 21746 pw.println(" k[eysets]: print known keysets"); 21747 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 21748 pw.println(" perm[issions]: dump permissions"); 21749 pw.println(" permission [name ...]: dump declaration and use of given permission"); 21750 pw.println(" pref[erred]: print preferred package settings"); 21751 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 21752 pw.println(" prov[iders]: dump content providers"); 21753 pw.println(" p[ackages]: dump installed packages"); 21754 pw.println(" s[hared-users]: dump shared user IDs"); 21755 pw.println(" m[essages]: print collected runtime messages"); 21756 pw.println(" v[erifiers]: print package verifier info"); 21757 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 21758 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 21759 pw.println(" version: print database version info"); 21760 pw.println(" write: write current settings now"); 21761 pw.println(" installs: details about install sessions"); 21762 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 21763 pw.println(" dexopt: dump dexopt state"); 21764 pw.println(" compiler-stats: dump compiler statistics"); 21765 pw.println(" enabled-overlays: dump list of enabled overlay packages"); 21766 pw.println(" <package.name>: info about given package"); 21767 return; 21768 } else if ("--checkin".equals(opt)) { 21769 checkin = true; 21770 } else if ("-f".equals(opt)) { 21771 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 21772 } else if ("--proto".equals(opt)) { 21773 dumpProto(fd); 21774 return; 21775 } else { 21776 pw.println("Unknown argument: " + opt + "; use -h for help"); 21777 } 21778 } 21779 21780 // Is the caller requesting to dump a particular piece of data? 21781 if (opti < args.length) { 21782 String cmd = args[opti]; 21783 opti++; 21784 // Is this a package name? 21785 if ("android".equals(cmd) || cmd.contains(".")) { 21786 packageName = cmd; 21787 // When dumping a single package, we always dump all of its 21788 // filter information since the amount of data will be reasonable. 21789 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 21790 } else if ("check-permission".equals(cmd)) { 21791 if (opti >= args.length) { 21792 pw.println("Error: check-permission missing permission argument"); 21793 return; 21794 } 21795 String perm = args[opti]; 21796 opti++; 21797 if (opti >= args.length) { 21798 pw.println("Error: check-permission missing package argument"); 21799 return; 21800 } 21801 21802 String pkg = args[opti]; 21803 opti++; 21804 int user = UserHandle.getUserId(Binder.getCallingUid()); 21805 if (opti < args.length) { 21806 try { 21807 user = Integer.parseInt(args[opti]); 21808 } catch (NumberFormatException e) { 21809 pw.println("Error: check-permission user argument is not a number: " 21810 + args[opti]); 21811 return; 21812 } 21813 } 21814 21815 // Normalize package name to handle renamed packages and static libs 21816 pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST); 21817 21818 pw.println(checkPermission(perm, pkg, user)); 21819 return; 21820 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 21821 dumpState.setDump(DumpState.DUMP_LIBS); 21822 } else if ("f".equals(cmd) || "features".equals(cmd)) { 21823 dumpState.setDump(DumpState.DUMP_FEATURES); 21824 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 21825 if (opti >= args.length) { 21826 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 21827 | DumpState.DUMP_SERVICE_RESOLVERS 21828 | DumpState.DUMP_RECEIVER_RESOLVERS 21829 | DumpState.DUMP_CONTENT_RESOLVERS); 21830 } else { 21831 while (opti < args.length) { 21832 String name = args[opti]; 21833 if ("a".equals(name) || "activity".equals(name)) { 21834 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 21835 } else if ("s".equals(name) || "service".equals(name)) { 21836 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 21837 } else if ("r".equals(name) || "receiver".equals(name)) { 21838 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 21839 } else if ("c".equals(name) || "content".equals(name)) { 21840 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 21841 } else { 21842 pw.println("Error: unknown resolver table type: " + name); 21843 return; 21844 } 21845 opti++; 21846 } 21847 } 21848 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 21849 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 21850 } else if ("permission".equals(cmd)) { 21851 if (opti >= args.length) { 21852 pw.println("Error: permission requires permission name"); 21853 return; 21854 } 21855 permissionNames = new ArraySet<>(); 21856 while (opti < args.length) { 21857 permissionNames.add(args[opti]); 21858 opti++; 21859 } 21860 dumpState.setDump(DumpState.DUMP_PERMISSIONS 21861 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 21862 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 21863 dumpState.setDump(DumpState.DUMP_PREFERRED); 21864 } else if ("preferred-xml".equals(cmd)) { 21865 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 21866 if (opti < args.length && "--full".equals(args[opti])) { 21867 fullPreferred = true; 21868 opti++; 21869 } 21870 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 21871 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 21872 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 21873 dumpState.setDump(DumpState.DUMP_PACKAGES); 21874 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 21875 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 21876 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 21877 dumpState.setDump(DumpState.DUMP_PROVIDERS); 21878 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 21879 dumpState.setDump(DumpState.DUMP_MESSAGES); 21880 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 21881 dumpState.setDump(DumpState.DUMP_VERIFIERS); 21882 } else if ("i".equals(cmd) || "ifv".equals(cmd) 21883 || "intent-filter-verifiers".equals(cmd)) { 21884 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 21885 } else if ("version".equals(cmd)) { 21886 dumpState.setDump(DumpState.DUMP_VERSION); 21887 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 21888 dumpState.setDump(DumpState.DUMP_KEYSETS); 21889 } else if ("installs".equals(cmd)) { 21890 dumpState.setDump(DumpState.DUMP_INSTALLS); 21891 } else if ("frozen".equals(cmd)) { 21892 dumpState.setDump(DumpState.DUMP_FROZEN); 21893 } else if ("dexopt".equals(cmd)) { 21894 dumpState.setDump(DumpState.DUMP_DEXOPT); 21895 } else if ("compiler-stats".equals(cmd)) { 21896 dumpState.setDump(DumpState.DUMP_COMPILER_STATS); 21897 } else if ("changes".equals(cmd)) { 21898 dumpState.setDump(DumpState.DUMP_CHANGES); 21899 } else if ("write".equals(cmd)) { 21900 synchronized (mPackages) { 21901 mSettings.writeLPr(); 21902 pw.println("Settings written."); 21903 return; 21904 } 21905 } 21906 } 21907 21908 if (checkin) { 21909 pw.println("vers,1"); 21910 } 21911 21912 // reader 21913 synchronized (mPackages) { 21914 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 21915 if (!checkin) { 21916 if (dumpState.onTitlePrinted()) 21917 pw.println(); 21918 pw.println("Database versions:"); 21919 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 21920 } 21921 } 21922 21923 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 21924 if (!checkin) { 21925 if (dumpState.onTitlePrinted()) 21926 pw.println(); 21927 pw.println("Verifiers:"); 21928 pw.print(" Required: "); 21929 pw.print(mRequiredVerifierPackage); 21930 pw.print(" (uid="); 21931 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 21932 UserHandle.USER_SYSTEM)); 21933 pw.println(")"); 21934 } else if (mRequiredVerifierPackage != null) { 21935 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 21936 pw.print(","); 21937 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 21938 UserHandle.USER_SYSTEM)); 21939 } 21940 } 21941 21942 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 21943 packageName == null) { 21944 if (mIntentFilterVerifierComponent != null) { 21945 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 21946 if (!checkin) { 21947 if (dumpState.onTitlePrinted()) 21948 pw.println(); 21949 pw.println("Intent Filter Verifier:"); 21950 pw.print(" Using: "); 21951 pw.print(verifierPackageName); 21952 pw.print(" (uid="); 21953 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 21954 UserHandle.USER_SYSTEM)); 21955 pw.println(")"); 21956 } else if (verifierPackageName != null) { 21957 pw.print("ifv,"); pw.print(verifierPackageName); 21958 pw.print(","); 21959 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 21960 UserHandle.USER_SYSTEM)); 21961 } 21962 } else { 21963 pw.println(); 21964 pw.println("No Intent Filter Verifier available!"); 21965 } 21966 } 21967 21968 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 21969 boolean printedHeader = false; 21970 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 21971 while (it.hasNext()) { 21972 String libName = it.next(); 21973 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName); 21974 if (versionedLib == null) { 21975 continue; 21976 } 21977 final int versionCount = versionedLib.size(); 21978 for (int i = 0; i < versionCount; i++) { 21979 SharedLibraryEntry libEntry = versionedLib.valueAt(i); 21980 if (!checkin) { 21981 if (!printedHeader) { 21982 if (dumpState.onTitlePrinted()) 21983 pw.println(); 21984 pw.println("Libraries:"); 21985 printedHeader = true; 21986 } 21987 pw.print(" "); 21988 } else { 21989 pw.print("lib,"); 21990 } 21991 pw.print(libEntry.info.getName()); 21992 if (libEntry.info.isStatic()) { 21993 pw.print(" version=" + libEntry.info.getVersion()); 21994 } 21995 if (!checkin) { 21996 pw.print(" -> "); 21997 } 21998 if (libEntry.path != null) { 21999 pw.print(" (jar) "); 22000 pw.print(libEntry.path); 22001 } else { 22002 pw.print(" (apk) "); 22003 pw.print(libEntry.apk); 22004 } 22005 pw.println(); 22006 } 22007 } 22008 } 22009 22010 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 22011 if (dumpState.onTitlePrinted()) 22012 pw.println(); 22013 if (!checkin) { 22014 pw.println("Features:"); 22015 } 22016 22017 synchronized (mAvailableFeatures) { 22018 for (FeatureInfo feat : mAvailableFeatures.values()) { 22019 if (checkin) { 22020 pw.print("feat,"); 22021 pw.print(feat.name); 22022 pw.print(","); 22023 pw.println(feat.version); 22024 } else { 22025 pw.print(" "); 22026 pw.print(feat.name); 22027 if (feat.version > 0) { 22028 pw.print(" version="); 22029 pw.print(feat.version); 22030 } 22031 pw.println(); 22032 } 22033 } 22034 } 22035 } 22036 22037 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 22038 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 22039 : "Activity Resolver Table:", " ", packageName, 22040 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 22041 dumpState.setTitlePrinted(true); 22042 } 22043 } 22044 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 22045 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 22046 : "Receiver Resolver Table:", " ", packageName, 22047 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 22048 dumpState.setTitlePrinted(true); 22049 } 22050 } 22051 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 22052 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 22053 : "Service Resolver Table:", " ", packageName, 22054 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 22055 dumpState.setTitlePrinted(true); 22056 } 22057 } 22058 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 22059 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 22060 : "Provider Resolver Table:", " ", packageName, 22061 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 22062 dumpState.setTitlePrinted(true); 22063 } 22064 } 22065 22066 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 22067 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 22068 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 22069 int user = mSettings.mPreferredActivities.keyAt(i); 22070 if (pir.dump(pw, 22071 dumpState.getTitlePrinted() 22072 ? "\nPreferred Activities User " + user + ":" 22073 : "Preferred Activities User " + user + ":", " ", 22074 packageName, true, false)) { 22075 dumpState.setTitlePrinted(true); 22076 } 22077 } 22078 } 22079 22080 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 22081 pw.flush(); 22082 FileOutputStream fout = new FileOutputStream(fd); 22083 BufferedOutputStream str = new BufferedOutputStream(fout); 22084 XmlSerializer serializer = new FastXmlSerializer(); 22085 try { 22086 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 22087 serializer.startDocument(null, true); 22088 serializer.setFeature( 22089 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 22090 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 22091 serializer.endDocument(); 22092 serializer.flush(); 22093 } catch (IllegalArgumentException e) { 22094 pw.println("Failed writing: " + e); 22095 } catch (IllegalStateException e) { 22096 pw.println("Failed writing: " + e); 22097 } catch (IOException e) { 22098 pw.println("Failed writing: " + e); 22099 } 22100 } 22101 22102 if (!checkin 22103 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 22104 && packageName == null) { 22105 pw.println(); 22106 int count = mSettings.mPackages.size(); 22107 if (count == 0) { 22108 pw.println("No applications!"); 22109 pw.println(); 22110 } else { 22111 final String prefix = " "; 22112 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 22113 if (allPackageSettings.size() == 0) { 22114 pw.println("No domain preferred apps!"); 22115 pw.println(); 22116 } else { 22117 pw.println("App verification status:"); 22118 pw.println(); 22119 count = 0; 22120 for (PackageSetting ps : allPackageSettings) { 22121 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 22122 if (ivi == null || ivi.getPackageName() == null) continue; 22123 pw.println(prefix + "Package: " + ivi.getPackageName()); 22124 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 22125 pw.println(prefix + "Status: " + ivi.getStatusString()); 22126 pw.println(); 22127 count++; 22128 } 22129 if (count == 0) { 22130 pw.println(prefix + "No app verification established."); 22131 pw.println(); 22132 } 22133 for (int userId : sUserManager.getUserIds()) { 22134 pw.println("App linkages for user " + userId + ":"); 22135 pw.println(); 22136 count = 0; 22137 for (PackageSetting ps : allPackageSettings) { 22138 final long status = ps.getDomainVerificationStatusForUser(userId); 22139 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 22140 && !DEBUG_DOMAIN_VERIFICATION) { 22141 continue; 22142 } 22143 pw.println(prefix + "Package: " + ps.name); 22144 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 22145 String statusStr = IntentFilterVerificationInfo. 22146 getStatusStringFromValue(status); 22147 pw.println(prefix + "Status: " + statusStr); 22148 pw.println(); 22149 count++; 22150 } 22151 if (count == 0) { 22152 pw.println(prefix + "No configured app linkages."); 22153 pw.println(); 22154 } 22155 } 22156 } 22157 } 22158 } 22159 22160 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 22161 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 22162 if (packageName == null && permissionNames == null) { 22163 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 22164 if (iperm == 0) { 22165 if (dumpState.onTitlePrinted()) 22166 pw.println(); 22167 pw.println("AppOp Permissions:"); 22168 } 22169 pw.print(" AppOp Permission "); 22170 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 22171 pw.println(":"); 22172 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 22173 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 22174 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 22175 } 22176 } 22177 } 22178 } 22179 22180 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 22181 boolean printedSomething = false; 22182 for (PackageParser.Provider p : mProviders.mProviders.values()) { 22183 if (packageName != null && !packageName.equals(p.info.packageName)) { 22184 continue; 22185 } 22186 if (!printedSomething) { 22187 if (dumpState.onTitlePrinted()) 22188 pw.println(); 22189 pw.println("Registered ContentProviders:"); 22190 printedSomething = true; 22191 } 22192 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 22193 pw.print(" "); pw.println(p.toString()); 22194 } 22195 printedSomething = false; 22196 for (Map.Entry<String, PackageParser.Provider> entry : 22197 mProvidersByAuthority.entrySet()) { 22198 PackageParser.Provider p = entry.getValue(); 22199 if (packageName != null && !packageName.equals(p.info.packageName)) { 22200 continue; 22201 } 22202 if (!printedSomething) { 22203 if (dumpState.onTitlePrinted()) 22204 pw.println(); 22205 pw.println("ContentProvider Authorities:"); 22206 printedSomething = true; 22207 } 22208 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 22209 pw.print(" "); pw.println(p.toString()); 22210 if (p.info != null && p.info.applicationInfo != null) { 22211 final String appInfo = p.info.applicationInfo.toString(); 22212 pw.print(" applicationInfo="); pw.println(appInfo); 22213 } 22214 } 22215 } 22216 22217 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 22218 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 22219 } 22220 22221 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 22222 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 22223 } 22224 22225 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 22226 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 22227 } 22228 22229 if (dumpState.isDumping(DumpState.DUMP_CHANGES)) { 22230 if (dumpState.onTitlePrinted()) pw.println(); 22231 pw.println("Package Changes:"); 22232 pw.print(" Sequence number="); pw.println(mChangedPackagesSequenceNumber); 22233 final int K = mChangedPackages.size(); 22234 for (int i = 0; i < K; i++) { 22235 final SparseArray<String> changes = mChangedPackages.valueAt(i); 22236 pw.print(" User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":"); 22237 final int N = changes.size(); 22238 if (N == 0) { 22239 pw.print(" "); pw.println("No packages changed"); 22240 } else { 22241 for (int j = 0; j < N; j++) { 22242 final String pkgName = changes.valueAt(j); 22243 final int sequenceNumber = changes.keyAt(j); 22244 pw.print(" "); 22245 pw.print("seq="); 22246 pw.print(sequenceNumber); 22247 pw.print(", package="); 22248 pw.println(pkgName); 22249 } 22250 } 22251 } 22252 } 22253 22254 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 22255 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 22256 } 22257 22258 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 22259 // XXX should handle packageName != null by dumping only install data that 22260 // the given package is involved with. 22261 if (dumpState.onTitlePrinted()) pw.println(); 22262 22263 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 22264 ipw.println(); 22265 ipw.println("Frozen packages:"); 22266 ipw.increaseIndent(); 22267 if (mFrozenPackages.size() == 0) { 22268 ipw.println("(none)"); 22269 } else { 22270 for (int i = 0; i < mFrozenPackages.size(); i++) { 22271 ipw.println(mFrozenPackages.valueAt(i)); 22272 } 22273 } 22274 ipw.decreaseIndent(); 22275 } 22276 22277 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 22278 if (dumpState.onTitlePrinted()) pw.println(); 22279 dumpDexoptStateLPr(pw, packageName); 22280 } 22281 22282 if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) { 22283 if (dumpState.onTitlePrinted()) pw.println(); 22284 dumpCompilerStatsLPr(pw, packageName); 22285 } 22286 22287 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 22288 if (dumpState.onTitlePrinted()) pw.println(); 22289 mSettings.dumpReadMessagesLPr(pw, dumpState); 22290 22291 pw.println(); 22292 pw.println("Package warning messages:"); 22293 BufferedReader in = null; 22294 String line = null; 22295 try { 22296 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 22297 while ((line = in.readLine()) != null) { 22298 if (line.contains("ignored: updated version")) continue; 22299 pw.println(line); 22300 } 22301 } catch (IOException ignored) { 22302 } finally { 22303 IoUtils.closeQuietly(in); 22304 } 22305 } 22306 22307 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 22308 BufferedReader in = null; 22309 String line = null; 22310 try { 22311 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 22312 while ((line = in.readLine()) != null) { 22313 if (line.contains("ignored: updated version")) continue; 22314 pw.print("msg,"); 22315 pw.println(line); 22316 } 22317 } catch (IOException ignored) { 22318 } finally { 22319 IoUtils.closeQuietly(in); 22320 } 22321 } 22322 } 22323 22324 // PackageInstaller should be called outside of mPackages lock 22325 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 22326 // XXX should handle packageName != null by dumping only install data that 22327 // the given package is involved with. 22328 if (dumpState.onTitlePrinted()) pw.println(); 22329 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 22330 } 22331 } 22332 22333 private void dumpProto(FileDescriptor fd) { 22334 final ProtoOutputStream proto = new ProtoOutputStream(fd); 22335 22336 synchronized (mPackages) { 22337 final long requiredVerifierPackageToken = 22338 proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE); 22339 proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage); 22340 proto.write( 22341 PackageServiceDumpProto.PackageShortProto.UID, 22342 getPackageUid( 22343 mRequiredVerifierPackage, 22344 MATCH_DEBUG_TRIAGED_MISSING, 22345 UserHandle.USER_SYSTEM)); 22346 proto.end(requiredVerifierPackageToken); 22347 22348 if (mIntentFilterVerifierComponent != null) { 22349 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 22350 final long verifierPackageToken = 22351 proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE); 22352 proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName); 22353 proto.write( 22354 PackageServiceDumpProto.PackageShortProto.UID, 22355 getPackageUid( 22356 verifierPackageName, 22357 MATCH_DEBUG_TRIAGED_MISSING, 22358 UserHandle.USER_SYSTEM)); 22359 proto.end(verifierPackageToken); 22360 } 22361 22362 dumpSharedLibrariesProto(proto); 22363 dumpFeaturesProto(proto); 22364 mSettings.dumpPackagesProto(proto); 22365 mSettings.dumpSharedUsersProto(proto); 22366 dumpMessagesProto(proto); 22367 } 22368 proto.flush(); 22369 } 22370 22371 private void dumpMessagesProto(ProtoOutputStream proto) { 22372 BufferedReader in = null; 22373 String line = null; 22374 try { 22375 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 22376 while ((line = in.readLine()) != null) { 22377 if (line.contains("ignored: updated version")) continue; 22378 proto.write(PackageServiceDumpProto.MESSAGES, line); 22379 } 22380 } catch (IOException ignored) { 22381 } finally { 22382 IoUtils.closeQuietly(in); 22383 } 22384 } 22385 22386 private void dumpFeaturesProto(ProtoOutputStream proto) { 22387 synchronized (mAvailableFeatures) { 22388 final int count = mAvailableFeatures.size(); 22389 for (int i = 0; i < count; i++) { 22390 final FeatureInfo feat = mAvailableFeatures.valueAt(i); 22391 final long featureToken = proto.start(PackageServiceDumpProto.FEATURES); 22392 proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name); 22393 proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version); 22394 proto.end(featureToken); 22395 } 22396 } 22397 } 22398 22399 private void dumpSharedLibrariesProto(ProtoOutputStream proto) { 22400 final int count = mSharedLibraries.size(); 22401 for (int i = 0; i < count; i++) { 22402 final String libName = mSharedLibraries.keyAt(i); 22403 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName); 22404 if (versionedLib == null) { 22405 continue; 22406 } 22407 final int versionCount = versionedLib.size(); 22408 for (int j = 0; j < versionCount; j++) { 22409 final SharedLibraryEntry libEntry = versionedLib.valueAt(j); 22410 final long sharedLibraryToken = 22411 proto.start(PackageServiceDumpProto.SHARED_LIBRARIES); 22412 proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName()); 22413 final boolean isJar = (libEntry.path != null); 22414 proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar); 22415 if (isJar) { 22416 proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path); 22417 } else { 22418 proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk); 22419 } 22420 proto.end(sharedLibraryToken); 22421 } 22422 } 22423 } 22424 22425 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 22426 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 22427 ipw.println(); 22428 ipw.println("Dexopt state:"); 22429 ipw.increaseIndent(); 22430 Collection<PackageParser.Package> packages = null; 22431 if (packageName != null) { 22432 PackageParser.Package targetPackage = mPackages.get(packageName); 22433 if (targetPackage != null) { 22434 packages = Collections.singletonList(targetPackage); 22435 } else { 22436 ipw.println("Unable to find package: " + packageName); 22437 return; 22438 } 22439 } else { 22440 packages = mPackages.values(); 22441 } 22442 22443 for (PackageParser.Package pkg : packages) { 22444 ipw.println("[" + pkg.packageName + "]"); 22445 ipw.increaseIndent(); 22446 mPackageDexOptimizer.dumpDexoptState(ipw, pkg); 22447 ipw.decreaseIndent(); 22448 } 22449 } 22450 22451 private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) { 22452 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 22453 ipw.println(); 22454 ipw.println("Compiler stats:"); 22455 ipw.increaseIndent(); 22456 Collection<PackageParser.Package> packages = null; 22457 if (packageName != null) { 22458 PackageParser.Package targetPackage = mPackages.get(packageName); 22459 if (targetPackage != null) { 22460 packages = Collections.singletonList(targetPackage); 22461 } else { 22462 ipw.println("Unable to find package: " + packageName); 22463 return; 22464 } 22465 } else { 22466 packages = mPackages.values(); 22467 } 22468 22469 for (PackageParser.Package pkg : packages) { 22470 ipw.println("[" + pkg.packageName + "]"); 22471 ipw.increaseIndent(); 22472 22473 CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName); 22474 if (stats == null) { 22475 ipw.println("(No recorded stats)"); 22476 } else { 22477 stats.dump(ipw); 22478 } 22479 ipw.decreaseIndent(); 22480 } 22481 } 22482 22483 private String dumpDomainString(String packageName) { 22484 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 22485 .getList(); 22486 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 22487 22488 ArraySet<String> result = new ArraySet<>(); 22489 if (iviList.size() > 0) { 22490 for (IntentFilterVerificationInfo ivi : iviList) { 22491 for (String host : ivi.getDomains()) { 22492 result.add(host); 22493 } 22494 } 22495 } 22496 if (filters != null && filters.size() > 0) { 22497 for (IntentFilter filter : filters) { 22498 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 22499 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 22500 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 22501 result.addAll(filter.getHostsList()); 22502 } 22503 } 22504 } 22505 22506 StringBuilder sb = new StringBuilder(result.size() * 16); 22507 for (String domain : result) { 22508 if (sb.length() > 0) sb.append(" "); 22509 sb.append(domain); 22510 } 22511 return sb.toString(); 22512 } 22513 22514 // ------- apps on sdcard specific code ------- 22515 static final boolean DEBUG_SD_INSTALL = false; 22516 22517 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 22518 22519 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 22520 22521 private boolean mMediaMounted = false; 22522 22523 static String getEncryptKey() { 22524 try { 22525 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 22526 SD_ENCRYPTION_KEYSTORE_NAME); 22527 if (sdEncKey == null) { 22528 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 22529 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 22530 if (sdEncKey == null) { 22531 Slog.e(TAG, "Failed to create encryption keys"); 22532 return null; 22533 } 22534 } 22535 return sdEncKey; 22536 } catch (NoSuchAlgorithmException nsae) { 22537 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 22538 return null; 22539 } catch (IOException ioe) { 22540 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 22541 return null; 22542 } 22543 } 22544 22545 /* 22546 * Update media status on PackageManager. 22547 */ 22548 @Override 22549 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 22550 enforceSystemOrRoot("Media status can only be updated by the system"); 22551 // reader; this apparently protects mMediaMounted, but should probably 22552 // be a different lock in that case. 22553 synchronized (mPackages) { 22554 Log.i(TAG, "Updating external media status from " 22555 + (mMediaMounted ? "mounted" : "unmounted") + " to " 22556 + (mediaStatus ? "mounted" : "unmounted")); 22557 if (DEBUG_SD_INSTALL) 22558 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 22559 + ", mMediaMounted=" + mMediaMounted); 22560 if (mediaStatus == mMediaMounted) { 22561 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 22562 : 0, -1); 22563 mHandler.sendMessage(msg); 22564 return; 22565 } 22566 mMediaMounted = mediaStatus; 22567 } 22568 // Queue up an async operation since the package installation may take a 22569 // little while. 22570 mHandler.post(new Runnable() { 22571 public void run() { 22572 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 22573 } 22574 }); 22575 } 22576 22577 /** 22578 * Called by StorageManagerService when the initial ASECs to scan are available. 22579 * Should block until all the ASEC containers are finished being scanned. 22580 */ 22581 public void scanAvailableAsecs() { 22582 updateExternalMediaStatusInner(true, false, false); 22583 } 22584 22585 /* 22586 * Collect information of applications on external media, map them against 22587 * existing containers and update information based on current mount status. 22588 * Please note that we always have to report status if reportStatus has been 22589 * set to true especially when unloading packages. 22590 */ 22591 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 22592 boolean externalStorage) { 22593 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 22594 int[] uidArr = EmptyArray.INT; 22595 22596 final String[] list = PackageHelper.getSecureContainerList(); 22597 if (ArrayUtils.isEmpty(list)) { 22598 Log.i(TAG, "No secure containers found"); 22599 } else { 22600 // Process list of secure containers and categorize them 22601 // as active or stale based on their package internal state. 22602 22603 // reader 22604 synchronized (mPackages) { 22605 for (String cid : list) { 22606 // Leave stages untouched for now; installer service owns them 22607 if (PackageInstallerService.isStageName(cid)) continue; 22608 22609 if (DEBUG_SD_INSTALL) 22610 Log.i(TAG, "Processing container " + cid); 22611 String pkgName = getAsecPackageName(cid); 22612 if (pkgName == null) { 22613 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 22614 continue; 22615 } 22616 if (DEBUG_SD_INSTALL) 22617 Log.i(TAG, "Looking for pkg : " + pkgName); 22618 22619 final PackageSetting ps = mSettings.mPackages.get(pkgName); 22620 if (ps == null) { 22621 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 22622 continue; 22623 } 22624 22625 /* 22626 * Skip packages that are not external if we're unmounting 22627 * external storage. 22628 */ 22629 if (externalStorage && !isMounted && !isExternal(ps)) { 22630 continue; 22631 } 22632 22633 final AsecInstallArgs args = new AsecInstallArgs(cid, 22634 getAppDexInstructionSets(ps), ps.isForwardLocked()); 22635 // The package status is changed only if the code path 22636 // matches between settings and the container id. 22637 if (ps.codePathString != null 22638 && ps.codePathString.startsWith(args.getCodePath())) { 22639 if (DEBUG_SD_INSTALL) { 22640 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 22641 + " at code path: " + ps.codePathString); 22642 } 22643 22644 // We do have a valid package installed on sdcard 22645 processCids.put(args, ps.codePathString); 22646 final int uid = ps.appId; 22647 if (uid != -1) { 22648 uidArr = ArrayUtils.appendInt(uidArr, uid); 22649 } 22650 } else { 22651 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 22652 + ps.codePathString); 22653 } 22654 } 22655 } 22656 22657 Arrays.sort(uidArr); 22658 } 22659 22660 // Process packages with valid entries. 22661 if (isMounted) { 22662 if (DEBUG_SD_INSTALL) 22663 Log.i(TAG, "Loading packages"); 22664 loadMediaPackages(processCids, uidArr, externalStorage); 22665 startCleaningPackages(); 22666 mInstallerService.onSecureContainersAvailable(); 22667 } else { 22668 if (DEBUG_SD_INSTALL) 22669 Log.i(TAG, "Unloading packages"); 22670 unloadMediaPackages(processCids, uidArr, reportStatus); 22671 } 22672 } 22673 22674 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 22675 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 22676 final int size = infos.size(); 22677 final String[] packageNames = new String[size]; 22678 final int[] packageUids = new int[size]; 22679 for (int i = 0; i < size; i++) { 22680 final ApplicationInfo info = infos.get(i); 22681 packageNames[i] = info.packageName; 22682 packageUids[i] = info.uid; 22683 } 22684 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 22685 finishedReceiver); 22686 } 22687 22688 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 22689 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 22690 sendResourcesChangedBroadcast(mediaStatus, replacing, 22691 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 22692 } 22693 22694 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 22695 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 22696 int size = pkgList.length; 22697 if (size > 0) { 22698 // Send broadcasts here 22699 Bundle extras = new Bundle(); 22700 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 22701 if (uidArr != null) { 22702 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 22703 } 22704 if (replacing) { 22705 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 22706 } 22707 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 22708 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 22709 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 22710 } 22711 } 22712 22713 /* 22714 * Look at potentially valid container ids from processCids If package 22715 * information doesn't match the one on record or package scanning fails, 22716 * the cid is added to list of removeCids. We currently don't delete stale 22717 * containers. 22718 */ 22719 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 22720 boolean externalStorage) { 22721 ArrayList<String> pkgList = new ArrayList<String>(); 22722 Set<AsecInstallArgs> keys = processCids.keySet(); 22723 22724 for (AsecInstallArgs args : keys) { 22725 String codePath = processCids.get(args); 22726 if (DEBUG_SD_INSTALL) 22727 Log.i(TAG, "Loading container : " + args.cid); 22728 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 22729 try { 22730 // Make sure there are no container errors first. 22731 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 22732 Slog.e(TAG, "Failed to mount cid : " + args.cid 22733 + " when installing from sdcard"); 22734 continue; 22735 } 22736 // Check code path here. 22737 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 22738 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 22739 + " does not match one in settings " + codePath); 22740 continue; 22741 } 22742 // Parse package 22743 int parseFlags = mDefParseFlags; 22744 if (args.isExternalAsec()) { 22745 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 22746 } 22747 if (args.isFwdLocked()) { 22748 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 22749 } 22750 22751 synchronized (mInstallLock) { 22752 PackageParser.Package pkg = null; 22753 try { 22754 // Sadly we don't know the package name yet to freeze it 22755 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 22756 SCAN_IGNORE_FROZEN, 0, null); 22757 } catch (PackageManagerException e) { 22758 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 22759 } 22760 // Scan the package 22761 if (pkg != null) { 22762 /* 22763 * TODO why is the lock being held? doPostInstall is 22764 * called in other places without the lock. This needs 22765 * to be straightened out. 22766 */ 22767 // writer 22768 synchronized (mPackages) { 22769 retCode = PackageManager.INSTALL_SUCCEEDED; 22770 pkgList.add(pkg.packageName); 22771 // Post process args 22772 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 22773 pkg.applicationInfo.uid); 22774 } 22775 } else { 22776 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 22777 } 22778 } 22779 22780 } finally { 22781 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 22782 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 22783 } 22784 } 22785 } 22786 // writer 22787 synchronized (mPackages) { 22788 // If the platform SDK has changed since the last time we booted, 22789 // we need to re-grant app permission to catch any new ones that 22790 // appear. This is really a hack, and means that apps can in some 22791 // cases get permissions that the user didn't initially explicitly 22792 // allow... it would be nice to have some better way to handle 22793 // this situation. 22794 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 22795 : mSettings.getInternalVersion(); 22796 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 22797 : StorageManager.UUID_PRIVATE_INTERNAL; 22798 22799 int updateFlags = UPDATE_PERMISSIONS_ALL; 22800 if (ver.sdkVersion != mSdkVersion) { 22801 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 22802 + mSdkVersion + "; regranting permissions for external"); 22803 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 22804 } 22805 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 22806 22807 // Yay, everything is now upgraded 22808 ver.forceCurrent(); 22809 22810 // can downgrade to reader 22811 // Persist settings 22812 mSettings.writeLPr(); 22813 } 22814 // Send a broadcast to let everyone know we are done processing 22815 if (pkgList.size() > 0) { 22816 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 22817 } 22818 } 22819 22820 /* 22821 * Utility method to unload a list of specified containers 22822 */ 22823 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 22824 // Just unmount all valid containers. 22825 for (AsecInstallArgs arg : cidArgs) { 22826 synchronized (mInstallLock) { 22827 arg.doPostDeleteLI(false); 22828 } 22829 } 22830 } 22831 22832 /* 22833 * Unload packages mounted on external media. This involves deleting package 22834 * data from internal structures, sending broadcasts about disabled packages, 22835 * gc'ing to free up references, unmounting all secure containers 22836 * corresponding to packages on external media, and posting a 22837 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 22838 * that we always have to post this message if status has been requested no 22839 * matter what. 22840 */ 22841 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 22842 final boolean reportStatus) { 22843 if (DEBUG_SD_INSTALL) 22844 Log.i(TAG, "unloading media packages"); 22845 ArrayList<String> pkgList = new ArrayList<String>(); 22846 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 22847 final Set<AsecInstallArgs> keys = processCids.keySet(); 22848 for (AsecInstallArgs args : keys) { 22849 String pkgName = args.getPackageName(); 22850 if (DEBUG_SD_INSTALL) 22851 Log.i(TAG, "Trying to unload pkg : " + pkgName); 22852 // Delete package internally 22853 PackageRemovedInfo outInfo = new PackageRemovedInfo(this); 22854 synchronized (mInstallLock) { 22855 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 22856 final boolean res; 22857 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 22858 "unloadMediaPackages")) { 22859 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 22860 null); 22861 } 22862 if (res) { 22863 pkgList.add(pkgName); 22864 } else { 22865 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 22866 failedList.add(args); 22867 } 22868 } 22869 } 22870 22871 // reader 22872 synchronized (mPackages) { 22873 // We didn't update the settings after removing each package; 22874 // write them now for all packages. 22875 mSettings.writeLPr(); 22876 } 22877 22878 // We have to absolutely send UPDATED_MEDIA_STATUS only 22879 // after confirming that all the receivers processed the ordered 22880 // broadcast when packages get disabled, force a gc to clean things up. 22881 // and unload all the containers. 22882 if (pkgList.size() > 0) { 22883 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 22884 new IIntentReceiver.Stub() { 22885 public void performReceive(Intent intent, int resultCode, String data, 22886 Bundle extras, boolean ordered, boolean sticky, 22887 int sendingUser) throws RemoteException { 22888 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 22889 reportStatus ? 1 : 0, 1, keys); 22890 mHandler.sendMessage(msg); 22891 } 22892 }); 22893 } else { 22894 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 22895 keys); 22896 mHandler.sendMessage(msg); 22897 } 22898 } 22899 22900 private void loadPrivatePackages(final VolumeInfo vol) { 22901 mHandler.post(new Runnable() { 22902 @Override 22903 public void run() { 22904 loadPrivatePackagesInner(vol); 22905 } 22906 }); 22907 } 22908 22909 private void loadPrivatePackagesInner(VolumeInfo vol) { 22910 final String volumeUuid = vol.fsUuid; 22911 if (TextUtils.isEmpty(volumeUuid)) { 22912 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 22913 return; 22914 } 22915 22916 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 22917 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 22918 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 22919 22920 final VersionInfo ver; 22921 final List<PackageSetting> packages; 22922 synchronized (mPackages) { 22923 ver = mSettings.findOrCreateVersion(volumeUuid); 22924 packages = mSettings.getVolumePackagesLPr(volumeUuid); 22925 } 22926 22927 for (PackageSetting ps : packages) { 22928 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 22929 synchronized (mInstallLock) { 22930 final PackageParser.Package pkg; 22931 try { 22932 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 22933 loaded.add(pkg.applicationInfo); 22934 22935 } catch (PackageManagerException e) { 22936 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 22937 } 22938 22939 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 22940 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 22941 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 22942 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 22943 } 22944 } 22945 } 22946 22947 // Reconcile app data for all started/unlocked users 22948 final StorageManager sm = mContext.getSystemService(StorageManager.class); 22949 final UserManager um = mContext.getSystemService(UserManager.class); 22950 UserManagerInternal umInternal = getUserManagerInternal(); 22951 for (UserInfo user : um.getUsers()) { 22952 final int flags; 22953 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 22954 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 22955 } else if (umInternal.isUserRunning(user.id)) { 22956 flags = StorageManager.FLAG_STORAGE_DE; 22957 } else { 22958 continue; 22959 } 22960 22961 try { 22962 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 22963 synchronized (mInstallLock) { 22964 reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */); 22965 } 22966 } catch (IllegalStateException e) { 22967 // Device was probably ejected, and we'll process that event momentarily 22968 Slog.w(TAG, "Failed to prepare storage: " + e); 22969 } 22970 } 22971 22972 synchronized (mPackages) { 22973 int updateFlags = UPDATE_PERMISSIONS_ALL; 22974 if (ver.sdkVersion != mSdkVersion) { 22975 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 22976 + mSdkVersion + "; regranting permissions for " + volumeUuid); 22977 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 22978 } 22979 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 22980 22981 // Yay, everything is now upgraded 22982 ver.forceCurrent(); 22983 22984 mSettings.writeLPr(); 22985 } 22986 22987 for (PackageFreezer freezer : freezers) { 22988 freezer.close(); 22989 } 22990 22991 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 22992 sendResourcesChangedBroadcast(true, false, loaded, null); 22993 } 22994 22995 private void unloadPrivatePackages(final VolumeInfo vol) { 22996 mHandler.post(new Runnable() { 22997 @Override 22998 public void run() { 22999 unloadPrivatePackagesInner(vol); 23000 } 23001 }); 23002 } 23003 23004 private void unloadPrivatePackagesInner(VolumeInfo vol) { 23005 final String volumeUuid = vol.fsUuid; 23006 if (TextUtils.isEmpty(volumeUuid)) { 23007 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 23008 return; 23009 } 23010 23011 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 23012 synchronized (mInstallLock) { 23013 synchronized (mPackages) { 23014 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 23015 for (PackageSetting ps : packages) { 23016 if (ps.pkg == null) continue; 23017 23018 final ApplicationInfo info = ps.pkg.applicationInfo; 23019 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 23020 final PackageRemovedInfo outInfo = new PackageRemovedInfo(this); 23021 23022 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 23023 "unloadPrivatePackagesInner")) { 23024 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 23025 false, null)) { 23026 unloaded.add(info); 23027 } else { 23028 Slog.w(TAG, "Failed to unload " + ps.codePath); 23029 } 23030 } 23031 23032 // Try very hard to release any references to this package 23033 // so we don't risk the system server being killed due to 23034 // open FDs 23035 AttributeCache.instance().removePackage(ps.name); 23036 } 23037 23038 mSettings.writeLPr(); 23039 } 23040 } 23041 23042 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 23043 sendResourcesChangedBroadcast(false, false, unloaded, null); 23044 23045 // Try very hard to release any references to this path so we don't risk 23046 // the system server being killed due to open FDs 23047 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 23048 23049 for (int i = 0; i < 3; i++) { 23050 System.gc(); 23051 System.runFinalization(); 23052 } 23053 } 23054 23055 private void assertPackageKnown(String volumeUuid, String packageName) 23056 throws PackageManagerException { 23057 synchronized (mPackages) { 23058 // Normalize package name to handle renamed packages 23059 packageName = normalizePackageNameLPr(packageName); 23060 23061 final PackageSetting ps = mSettings.mPackages.get(packageName); 23062 if (ps == null) { 23063 throw new PackageManagerException("Package " + packageName + " is unknown"); 23064 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 23065 throw new PackageManagerException( 23066 "Package " + packageName + " found on unknown volume " + volumeUuid 23067 + "; expected volume " + ps.volumeUuid); 23068 } 23069 } 23070 } 23071 23072 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 23073 throws PackageManagerException { 23074 synchronized (mPackages) { 23075 // Normalize package name to handle renamed packages 23076 packageName = normalizePackageNameLPr(packageName); 23077 23078 final PackageSetting ps = mSettings.mPackages.get(packageName); 23079 if (ps == null) { 23080 throw new PackageManagerException("Package " + packageName + " is unknown"); 23081 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 23082 throw new PackageManagerException( 23083 "Package " + packageName + " found on unknown volume " + volumeUuid 23084 + "; expected volume " + ps.volumeUuid); 23085 } else if (!ps.getInstalled(userId)) { 23086 throw new PackageManagerException( 23087 "Package " + packageName + " not installed for user " + userId); 23088 } 23089 } 23090 } 23091 23092 private List<String> collectAbsoluteCodePaths() { 23093 synchronized (mPackages) { 23094 List<String> codePaths = new ArrayList<>(); 23095 final int packageCount = mSettings.mPackages.size(); 23096 for (int i = 0; i < packageCount; i++) { 23097 final PackageSetting ps = mSettings.mPackages.valueAt(i); 23098 codePaths.add(ps.codePath.getAbsolutePath()); 23099 } 23100 return codePaths; 23101 } 23102 } 23103 23104 /** 23105 * Examine all apps present on given mounted volume, and destroy apps that 23106 * aren't expected, either due to uninstallation or reinstallation on 23107 * another volume. 23108 */ 23109 private void reconcileApps(String volumeUuid) { 23110 List<String> absoluteCodePaths = collectAbsoluteCodePaths(); 23111 List<File> filesToDelete = null; 23112 23113 final File[] files = FileUtils.listFilesOrEmpty( 23114 Environment.getDataAppDirectory(volumeUuid)); 23115 for (File file : files) { 23116 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 23117 && !PackageInstallerService.isStageName(file.getName()); 23118 if (!isPackage) { 23119 // Ignore entries which are not packages 23120 continue; 23121 } 23122 23123 String absolutePath = file.getAbsolutePath(); 23124 23125 boolean pathValid = false; 23126 final int absoluteCodePathCount = absoluteCodePaths.size(); 23127 for (int i = 0; i < absoluteCodePathCount; i++) { 23128 String absoluteCodePath = absoluteCodePaths.get(i); 23129 if (absolutePath.startsWith(absoluteCodePath)) { 23130 pathValid = true; 23131 break; 23132 } 23133 } 23134 23135 if (!pathValid) { 23136 if (filesToDelete == null) { 23137 filesToDelete = new ArrayList<>(); 23138 } 23139 filesToDelete.add(file); 23140 } 23141 } 23142 23143 if (filesToDelete != null) { 23144 final int fileToDeleteCount = filesToDelete.size(); 23145 for (int i = 0; i < fileToDeleteCount; i++) { 23146 File fileToDelete = filesToDelete.get(i); 23147 logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete); 23148 synchronized (mInstallLock) { 23149 removeCodePathLI(fileToDelete); 23150 } 23151 } 23152 } 23153 } 23154 23155 /** 23156 * Reconcile all app data for the given user. 23157 * <p> 23158 * Verifies that directories exist and that ownership and labeling is 23159 * correct for all installed apps on all mounted volumes. 23160 */ 23161 void reconcileAppsData(int userId, int flags, boolean migrateAppsData) { 23162 final StorageManager storage = mContext.getSystemService(StorageManager.class); 23163 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 23164 final String volumeUuid = vol.getFsUuid(); 23165 synchronized (mInstallLock) { 23166 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData); 23167 } 23168 } 23169 } 23170 23171 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags, 23172 boolean migrateAppData) { 23173 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */); 23174 } 23175 23176 /** 23177 * Reconcile all app data on given mounted volume. 23178 * <p> 23179 * Destroys app data that isn't expected, either due to uninstallation or 23180 * reinstallation on another volume. 23181 * <p> 23182 * Verifies that directories exist and that ownership and labeling is 23183 * correct for all installed apps. 23184 * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true) 23185 */ 23186 private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags, 23187 boolean migrateAppData, boolean onlyCoreApps) { 23188 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 23189 + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData); 23190 List<String> result = onlyCoreApps ? new ArrayList<>() : null; 23191 23192 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 23193 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 23194 23195 // First look for stale data that doesn't belong, and check if things 23196 // have changed since we did our last restorecon 23197 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 23198 if (StorageManager.isFileEncryptedNativeOrEmulated() 23199 && !StorageManager.isUserKeyUnlocked(userId)) { 23200 throw new RuntimeException( 23201 "Yikes, someone asked us to reconcile CE storage while " + userId 23202 + " was still locked; this would have caused massive data loss!"); 23203 } 23204 23205 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 23206 for (File file : files) { 23207 final String packageName = file.getName(); 23208 try { 23209 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 23210 } catch (PackageManagerException e) { 23211 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 23212 try { 23213 mInstaller.destroyAppData(volumeUuid, packageName, userId, 23214 StorageManager.FLAG_STORAGE_CE, 0); 23215 } catch (InstallerException e2) { 23216 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 23217 } 23218 } 23219 } 23220 } 23221 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 23222 final File[] files = FileUtils.listFilesOrEmpty(deDir); 23223 for (File file : files) { 23224 final String packageName = file.getName(); 23225 try { 23226 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 23227 } catch (PackageManagerException e) { 23228 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 23229 try { 23230 mInstaller.destroyAppData(volumeUuid, packageName, userId, 23231 StorageManager.FLAG_STORAGE_DE, 0); 23232 } catch (InstallerException e2) { 23233 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 23234 } 23235 } 23236 } 23237 } 23238 23239 // Ensure that data directories are ready to roll for all packages 23240 // installed for this volume and user 23241 final List<PackageSetting> packages; 23242 synchronized (mPackages) { 23243 packages = mSettings.getVolumePackagesLPr(volumeUuid); 23244 } 23245 int preparedCount = 0; 23246 for (PackageSetting ps : packages) { 23247 final String packageName = ps.name; 23248 if (ps.pkg == null) { 23249 Slog.w(TAG, "Odd, missing scanned package " + packageName); 23250 // TODO: might be due to legacy ASEC apps; we should circle back 23251 // and reconcile again once they're scanned 23252 continue; 23253 } 23254 // Skip non-core apps if requested 23255 if (onlyCoreApps && !ps.pkg.coreApp) { 23256 result.add(packageName); 23257 continue; 23258 } 23259 23260 if (ps.getInstalled(userId)) { 23261 prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData); 23262 preparedCount++; 23263 } 23264 } 23265 23266 Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages"); 23267 return result; 23268 } 23269 23270 /** 23271 * Prepare app data for the given app just after it was installed or 23272 * upgraded. This method carefully only touches users that it's installed 23273 * for, and it forces a restorecon to handle any seinfo changes. 23274 * <p> 23275 * Verifies that directories exist and that ownership and labeling is 23276 * correct for all installed apps. If there is an ownership mismatch, it 23277 * will try recovering system apps by wiping data; third-party app data is 23278 * left intact. 23279 * <p> 23280 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 23281 */ 23282 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 23283 final PackageSetting ps; 23284 synchronized (mPackages) { 23285 ps = mSettings.mPackages.get(pkg.packageName); 23286 mSettings.writeKernelMappingLPr(ps); 23287 } 23288 23289 final UserManager um = mContext.getSystemService(UserManager.class); 23290 UserManagerInternal umInternal = getUserManagerInternal(); 23291 for (UserInfo user : um.getUsers()) { 23292 final int flags; 23293 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 23294 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 23295 } else if (umInternal.isUserRunning(user.id)) { 23296 flags = StorageManager.FLAG_STORAGE_DE; 23297 } else { 23298 continue; 23299 } 23300 23301 if (ps.getInstalled(user.id)) { 23302 // TODO: when user data is locked, mark that we're still dirty 23303 prepareAppDataLIF(pkg, user.id, flags); 23304 } 23305 } 23306 } 23307 23308 /** 23309 * Prepare app data for the given app. 23310 * <p> 23311 * Verifies that directories exist and that ownership and labeling is 23312 * correct for all installed apps. If there is an ownership mismatch, this 23313 * will try recovering system apps by wiping data; third-party app data is 23314 * left intact. 23315 */ 23316 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 23317 if (pkg == null) { 23318 Slog.wtf(TAG, "Package was null!", new Throwable()); 23319 return; 23320 } 23321 prepareAppDataLeafLIF(pkg, userId, flags); 23322 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 23323 for (int i = 0; i < childCount; i++) { 23324 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 23325 } 23326 } 23327 23328 private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags, 23329 boolean maybeMigrateAppData) { 23330 prepareAppDataLIF(pkg, userId, flags); 23331 23332 if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) { 23333 // We may have just shuffled around app data directories, so 23334 // prepare them one more time 23335 prepareAppDataLIF(pkg, userId, flags); 23336 } 23337 } 23338 23339 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 23340 if (DEBUG_APP_DATA) { 23341 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 23342 + Integer.toHexString(flags)); 23343 } 23344 23345 final String volumeUuid = pkg.volumeUuid; 23346 final String packageName = pkg.packageName; 23347 final ApplicationInfo app = pkg.applicationInfo; 23348 final int appId = UserHandle.getAppId(app.uid); 23349 23350 Preconditions.checkNotNull(app.seInfo); 23351 23352 long ceDataInode = -1; 23353 try { 23354 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 23355 appId, app.seInfo, app.targetSdkVersion); 23356 } catch (InstallerException e) { 23357 if (app.isSystemApp()) { 23358 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 23359 + ", but trying to recover: " + e); 23360 destroyAppDataLeafLIF(pkg, userId, flags); 23361 try { 23362 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 23363 appId, app.seInfo, app.targetSdkVersion); 23364 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 23365 } catch (InstallerException e2) { 23366 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 23367 } 23368 } else { 23369 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 23370 } 23371 } 23372 23373 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) { 23374 // TODO: mark this structure as dirty so we persist it! 23375 synchronized (mPackages) { 23376 final PackageSetting ps = mSettings.mPackages.get(packageName); 23377 if (ps != null) { 23378 ps.setCeDataInode(ceDataInode, userId); 23379 } 23380 } 23381 } 23382 23383 prepareAppDataContentsLeafLIF(pkg, userId, flags); 23384 } 23385 23386 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 23387 if (pkg == null) { 23388 Slog.wtf(TAG, "Package was null!", new Throwable()); 23389 return; 23390 } 23391 prepareAppDataContentsLeafLIF(pkg, userId, flags); 23392 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 23393 for (int i = 0; i < childCount; i++) { 23394 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 23395 } 23396 } 23397 23398 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 23399 final String volumeUuid = pkg.volumeUuid; 23400 final String packageName = pkg.packageName; 23401 final ApplicationInfo app = pkg.applicationInfo; 23402 23403 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 23404 // Create a native library symlink only if we have native libraries 23405 // and if the native libraries are 32 bit libraries. We do not provide 23406 // this symlink for 64 bit libraries. 23407 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 23408 final String nativeLibPath = app.nativeLibraryDir; 23409 try { 23410 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 23411 nativeLibPath, userId); 23412 } catch (InstallerException e) { 23413 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 23414 } 23415 } 23416 } 23417 } 23418 23419 /** 23420 * For system apps on non-FBE devices, this method migrates any existing 23421 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 23422 * requested by the app. 23423 */ 23424 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 23425 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 23426 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 23427 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 23428 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 23429 try { 23430 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 23431 storageTarget); 23432 } catch (InstallerException e) { 23433 logCriticalInfo(Log.WARN, 23434 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 23435 } 23436 return true; 23437 } else { 23438 return false; 23439 } 23440 } 23441 23442 public PackageFreezer freezePackage(String packageName, String killReason) { 23443 return freezePackage(packageName, UserHandle.USER_ALL, killReason); 23444 } 23445 23446 public PackageFreezer freezePackage(String packageName, int userId, String killReason) { 23447 return new PackageFreezer(packageName, userId, killReason); 23448 } 23449 23450 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 23451 String killReason) { 23452 return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason); 23453 } 23454 23455 public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags, 23456 String killReason) { 23457 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 23458 return new PackageFreezer(); 23459 } else { 23460 return freezePackage(packageName, userId, killReason); 23461 } 23462 } 23463 23464 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 23465 String killReason) { 23466 return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason); 23467 } 23468 23469 public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags, 23470 String killReason) { 23471 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 23472 return new PackageFreezer(); 23473 } else { 23474 return freezePackage(packageName, userId, killReason); 23475 } 23476 } 23477 23478 /** 23479 * Class that freezes and kills the given package upon creation, and 23480 * unfreezes it upon closing. This is typically used when doing surgery on 23481 * app code/data to prevent the app from running while you're working. 23482 */ 23483 private class PackageFreezer implements AutoCloseable { 23484 private final String mPackageName; 23485 private final PackageFreezer[] mChildren; 23486 23487 private final boolean mWeFroze; 23488 23489 private final AtomicBoolean mClosed = new AtomicBoolean(); 23490 private final CloseGuard mCloseGuard = CloseGuard.get(); 23491 23492 /** 23493 * Create and return a stub freezer that doesn't actually do anything, 23494 * typically used when someone requested 23495 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 23496 * {@link PackageManager#DELETE_DONT_KILL_APP}. 23497 */ 23498 public PackageFreezer() { 23499 mPackageName = null; 23500 mChildren = null; 23501 mWeFroze = false; 23502 mCloseGuard.open("close"); 23503 } 23504 23505 public PackageFreezer(String packageName, int userId, String killReason) { 23506 synchronized (mPackages) { 23507 mPackageName = packageName; 23508 mWeFroze = mFrozenPackages.add(mPackageName); 23509 23510 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 23511 if (ps != null) { 23512 killApplication(ps.name, ps.appId, userId, killReason); 23513 } 23514 23515 final PackageParser.Package p = mPackages.get(packageName); 23516 if (p != null && p.childPackages != null) { 23517 final int N = p.childPackages.size(); 23518 mChildren = new PackageFreezer[N]; 23519 for (int i = 0; i < N; i++) { 23520 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 23521 userId, killReason); 23522 } 23523 } else { 23524 mChildren = null; 23525 } 23526 } 23527 mCloseGuard.open("close"); 23528 } 23529 23530 @Override 23531 protected void finalize() throws Throwable { 23532 try { 23533 mCloseGuard.warnIfOpen(); 23534 close(); 23535 } finally { 23536 super.finalize(); 23537 } 23538 } 23539 23540 @Override 23541 public void close() { 23542 mCloseGuard.close(); 23543 if (mClosed.compareAndSet(false, true)) { 23544 synchronized (mPackages) { 23545 if (mWeFroze) { 23546 mFrozenPackages.remove(mPackageName); 23547 } 23548 23549 if (mChildren != null) { 23550 for (PackageFreezer freezer : mChildren) { 23551 freezer.close(); 23552 } 23553 } 23554 } 23555 } 23556 } 23557 } 23558 23559 /** 23560 * Verify that given package is currently frozen. 23561 */ 23562 private void checkPackageFrozen(String packageName) { 23563 synchronized (mPackages) { 23564 if (!mFrozenPackages.contains(packageName)) { 23565 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 23566 } 23567 } 23568 } 23569 23570 @Override 23571 public int movePackage(final String packageName, final String volumeUuid) { 23572 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 23573 23574 final int callingUid = Binder.getCallingUid(); 23575 final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid)); 23576 final int moveId = mNextMoveId.getAndIncrement(); 23577 mHandler.post(new Runnable() { 23578 @Override 23579 public void run() { 23580 try { 23581 movePackageInternal(packageName, volumeUuid, moveId, callingUid, user); 23582 } catch (PackageManagerException e) { 23583 Slog.w(TAG, "Failed to move " + packageName, e); 23584 mMoveCallbacks.notifyStatusChanged(moveId, 23585 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 23586 } 23587 } 23588 }); 23589 return moveId; 23590 } 23591 23592 private void movePackageInternal(final String packageName, final String volumeUuid, 23593 final int moveId, final int callingUid, UserHandle user) 23594 throws PackageManagerException { 23595 final StorageManager storage = mContext.getSystemService(StorageManager.class); 23596 final PackageManager pm = mContext.getPackageManager(); 23597 23598 final boolean currentAsec; 23599 final String currentVolumeUuid; 23600 final File codeFile; 23601 final String installerPackageName; 23602 final String packageAbiOverride; 23603 final int appId; 23604 final String seinfo; 23605 final String label; 23606 final int targetSdkVersion; 23607 final PackageFreezer freezer; 23608 final int[] installedUserIds; 23609 23610 // reader 23611 synchronized (mPackages) { 23612 final PackageParser.Package pkg = mPackages.get(packageName); 23613 final PackageSetting ps = mSettings.mPackages.get(packageName); 23614 if (pkg == null 23615 || ps == null 23616 || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) { 23617 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 23618 } 23619 if (pkg.applicationInfo.isSystemApp()) { 23620 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 23621 "Cannot move system application"); 23622 } 23623 23624 final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid); 23625 final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean( 23626 com.android.internal.R.bool.config_allow3rdPartyAppOnInternal); 23627 if (isInternalStorage && !allow3rdPartyOnInternal) { 23628 throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL, 23629 "3rd party apps are not allowed on internal storage"); 23630 } 23631 23632 if (pkg.applicationInfo.isExternalAsec()) { 23633 currentAsec = true; 23634 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 23635 } else if (pkg.applicationInfo.isForwardLocked()) { 23636 currentAsec = true; 23637 currentVolumeUuid = "forward_locked"; 23638 } else { 23639 currentAsec = false; 23640 currentVolumeUuid = ps.volumeUuid; 23641 23642 final File probe = new File(pkg.codePath); 23643 final File probeOat = new File(probe, "oat"); 23644 if (!probe.isDirectory() || !probeOat.isDirectory()) { 23645 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 23646 "Move only supported for modern cluster style installs"); 23647 } 23648 } 23649 23650 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 23651 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 23652 "Package already moved to " + volumeUuid); 23653 } 23654 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 23655 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 23656 "Device admin cannot be moved"); 23657 } 23658 23659 if (mFrozenPackages.contains(packageName)) { 23660 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 23661 "Failed to move already frozen package"); 23662 } 23663 23664 codeFile = new File(pkg.codePath); 23665 installerPackageName = ps.installerPackageName; 23666 packageAbiOverride = ps.cpuAbiOverrideString; 23667 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 23668 seinfo = pkg.applicationInfo.seInfo; 23669 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 23670 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 23671 freezer = freezePackage(packageName, "movePackageInternal"); 23672 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 23673 } 23674 23675 final Bundle extras = new Bundle(); 23676 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 23677 extras.putString(Intent.EXTRA_TITLE, label); 23678 mMoveCallbacks.notifyCreated(moveId, extras); 23679 23680 int installFlags; 23681 final boolean moveCompleteApp; 23682 final File measurePath; 23683 23684 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 23685 installFlags = INSTALL_INTERNAL; 23686 moveCompleteApp = !currentAsec; 23687 measurePath = Environment.getDataAppDirectory(volumeUuid); 23688 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 23689 installFlags = INSTALL_EXTERNAL; 23690 moveCompleteApp = false; 23691 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 23692 } else { 23693 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 23694 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 23695 || !volume.isMountedWritable()) { 23696 freezer.close(); 23697 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 23698 "Move location not mounted private volume"); 23699 } 23700 23701 Preconditions.checkState(!currentAsec); 23702 23703 installFlags = INSTALL_INTERNAL; 23704 moveCompleteApp = true; 23705 measurePath = Environment.getDataAppDirectory(volumeUuid); 23706 } 23707 23708 final PackageStats stats = new PackageStats(null, -1); 23709 synchronized (mInstaller) { 23710 for (int userId : installedUserIds) { 23711 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 23712 freezer.close(); 23713 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 23714 "Failed to measure package size"); 23715 } 23716 } 23717 } 23718 23719 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 23720 + stats.dataSize); 23721 23722 final long startFreeBytes = measurePath.getUsableSpace(); 23723 final long sizeBytes; 23724 if (moveCompleteApp) { 23725 sizeBytes = stats.codeSize + stats.dataSize; 23726 } else { 23727 sizeBytes = stats.codeSize; 23728 } 23729 23730 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 23731 freezer.close(); 23732 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 23733 "Not enough free space to move"); 23734 } 23735 23736 mMoveCallbacks.notifyStatusChanged(moveId, 10); 23737 23738 final CountDownLatch installedLatch = new CountDownLatch(1); 23739 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 23740 @Override 23741 public void onUserActionRequired(Intent intent) throws RemoteException { 23742 throw new IllegalStateException(); 23743 } 23744 23745 @Override 23746 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 23747 Bundle extras) throws RemoteException { 23748 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 23749 + PackageManager.installStatusToString(returnCode, msg)); 23750 23751 installedLatch.countDown(); 23752 freezer.close(); 23753 23754 final int status = PackageManager.installStatusToPublicStatus(returnCode); 23755 switch (status) { 23756 case PackageInstaller.STATUS_SUCCESS: 23757 mMoveCallbacks.notifyStatusChanged(moveId, 23758 PackageManager.MOVE_SUCCEEDED); 23759 break; 23760 case PackageInstaller.STATUS_FAILURE_STORAGE: 23761 mMoveCallbacks.notifyStatusChanged(moveId, 23762 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 23763 break; 23764 default: 23765 mMoveCallbacks.notifyStatusChanged(moveId, 23766 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 23767 break; 23768 } 23769 } 23770 }; 23771 23772 final MoveInfo move; 23773 if (moveCompleteApp) { 23774 // Kick off a thread to report progress estimates 23775 new Thread() { 23776 @Override 23777 public void run() { 23778 while (true) { 23779 try { 23780 if (installedLatch.await(1, TimeUnit.SECONDS)) { 23781 break; 23782 } 23783 } catch (InterruptedException ignored) { 23784 } 23785 23786 final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace(); 23787 final int progress = 10 + (int) MathUtils.constrain( 23788 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 23789 mMoveCallbacks.notifyStatusChanged(moveId, progress); 23790 } 23791 } 23792 }.start(); 23793 23794 final String dataAppName = codeFile.getName(); 23795 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 23796 dataAppName, appId, seinfo, targetSdkVersion); 23797 } else { 23798 move = null; 23799 } 23800 23801 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 23802 23803 final Message msg = mHandler.obtainMessage(INIT_COPY); 23804 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 23805 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 23806 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 23807 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/, 23808 PackageManager.INSTALL_REASON_UNKNOWN); 23809 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 23810 msg.obj = params; 23811 23812 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 23813 System.identityHashCode(msg.obj)); 23814 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 23815 System.identityHashCode(msg.obj)); 23816 23817 mHandler.sendMessage(msg); 23818 } 23819 23820 @Override 23821 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 23822 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 23823 23824 final int realMoveId = mNextMoveId.getAndIncrement(); 23825 final Bundle extras = new Bundle(); 23826 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 23827 mMoveCallbacks.notifyCreated(realMoveId, extras); 23828 23829 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 23830 @Override 23831 public void onCreated(int moveId, Bundle extras) { 23832 // Ignored 23833 } 23834 23835 @Override 23836 public void onStatusChanged(int moveId, int status, long estMillis) { 23837 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 23838 } 23839 }; 23840 23841 final StorageManager storage = mContext.getSystemService(StorageManager.class); 23842 storage.setPrimaryStorageUuid(volumeUuid, callback); 23843 return realMoveId; 23844 } 23845 23846 @Override 23847 public int getMoveStatus(int moveId) { 23848 mContext.enforceCallingOrSelfPermission( 23849 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 23850 return mMoveCallbacks.mLastStatus.get(moveId); 23851 } 23852 23853 @Override 23854 public void registerMoveCallback(IPackageMoveObserver callback) { 23855 mContext.enforceCallingOrSelfPermission( 23856 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 23857 mMoveCallbacks.register(callback); 23858 } 23859 23860 @Override 23861 public void unregisterMoveCallback(IPackageMoveObserver callback) { 23862 mContext.enforceCallingOrSelfPermission( 23863 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 23864 mMoveCallbacks.unregister(callback); 23865 } 23866 23867 @Override 23868 public boolean setInstallLocation(int loc) { 23869 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 23870 null); 23871 if (getInstallLocation() == loc) { 23872 return true; 23873 } 23874 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 23875 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 23876 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 23877 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 23878 return true; 23879 } 23880 return false; 23881 } 23882 23883 @Override 23884 public int getInstallLocation() { 23885 // allow instant app access 23886 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 23887 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 23888 PackageHelper.APP_INSTALL_AUTO); 23889 } 23890 23891 /** Called by UserManagerService */ 23892 void cleanUpUser(UserManagerService userManager, int userHandle) { 23893 synchronized (mPackages) { 23894 mDirtyUsers.remove(userHandle); 23895 mUserNeedsBadging.delete(userHandle); 23896 mSettings.removeUserLPw(userHandle); 23897 mPendingBroadcasts.remove(userHandle); 23898 mInstantAppRegistry.onUserRemovedLPw(userHandle); 23899 removeUnusedPackagesLPw(userManager, userHandle); 23900 } 23901 } 23902 23903 /** 23904 * We're removing userHandle and would like to remove any downloaded packages 23905 * that are no longer in use by any other user. 23906 * @param userHandle the user being removed 23907 */ 23908 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 23909 final boolean DEBUG_CLEAN_APKS = false; 23910 int [] users = userManager.getUserIds(); 23911 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 23912 while (psit.hasNext()) { 23913 PackageSetting ps = psit.next(); 23914 if (ps.pkg == null) { 23915 continue; 23916 } 23917 final String packageName = ps.pkg.packageName; 23918 // Skip over if system app 23919 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 23920 continue; 23921 } 23922 if (DEBUG_CLEAN_APKS) { 23923 Slog.i(TAG, "Checking package " + packageName); 23924 } 23925 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 23926 if (keep) { 23927 if (DEBUG_CLEAN_APKS) { 23928 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 23929 } 23930 } else { 23931 for (int i = 0; i < users.length; i++) { 23932 if (users[i] != userHandle && ps.getInstalled(users[i])) { 23933 keep = true; 23934 if (DEBUG_CLEAN_APKS) { 23935 Slog.i(TAG, " Keeping package " + packageName + " for user " 23936 + users[i]); 23937 } 23938 break; 23939 } 23940 } 23941 } 23942 if (!keep) { 23943 if (DEBUG_CLEAN_APKS) { 23944 Slog.i(TAG, " Removing package " + packageName); 23945 } 23946 mHandler.post(new Runnable() { 23947 public void run() { 23948 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 23949 userHandle, 0); 23950 } //end run 23951 }); 23952 } 23953 } 23954 } 23955 23956 /** Called by UserManagerService */ 23957 void createNewUser(int userId, String[] disallowedPackages) { 23958 synchronized (mInstallLock) { 23959 mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages); 23960 } 23961 synchronized (mPackages) { 23962 scheduleWritePackageRestrictionsLocked(userId); 23963 scheduleWritePackageListLocked(userId); 23964 applyFactoryDefaultBrowserLPw(userId); 23965 primeDomainVerificationsLPw(userId); 23966 } 23967 } 23968 23969 void onNewUserCreated(final int userId) { 23970 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 23971 // If permission review for legacy apps is required, we represent 23972 // dagerous permissions for such apps as always granted runtime 23973 // permissions to keep per user flag state whether review is needed. 23974 // Hence, if a new user is added we have to propagate dangerous 23975 // permission grants for these legacy apps. 23976 if (mPermissionReviewRequired) { 23977 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 23978 | UPDATE_PERMISSIONS_REPLACE_ALL); 23979 } 23980 } 23981 23982 @Override 23983 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 23984 mContext.enforceCallingOrSelfPermission( 23985 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 23986 "Only package verification agents can read the verifier device identity"); 23987 23988 synchronized (mPackages) { 23989 return mSettings.getVerifierDeviceIdentityLPw(); 23990 } 23991 } 23992 23993 @Override 23994 public void setPermissionEnforced(String permission, boolean enforced) { 23995 // TODO: Now that we no longer change GID for storage, this should to away. 23996 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 23997 "setPermissionEnforced"); 23998 if (READ_EXTERNAL_STORAGE.equals(permission)) { 23999 synchronized (mPackages) { 24000 if (mSettings.mReadExternalStorageEnforced == null 24001 || mSettings.mReadExternalStorageEnforced != enforced) { 24002 mSettings.mReadExternalStorageEnforced = enforced; 24003 mSettings.writeLPr(); 24004 } 24005 } 24006 // kill any non-foreground processes so we restart them and 24007 // grant/revoke the GID. 24008 final IActivityManager am = ActivityManager.getService(); 24009 if (am != null) { 24010 final long token = Binder.clearCallingIdentity(); 24011 try { 24012 am.killProcessesBelowForeground("setPermissionEnforcement"); 24013 } catch (RemoteException e) { 24014 } finally { 24015 Binder.restoreCallingIdentity(token); 24016 } 24017 } 24018 } else { 24019 throw new IllegalArgumentException("No selective enforcement for " + permission); 24020 } 24021 } 24022 24023 @Override 24024 @Deprecated 24025 public boolean isPermissionEnforced(String permission) { 24026 // allow instant applications 24027 return true; 24028 } 24029 24030 @Override 24031 public boolean isStorageLow() { 24032 // allow instant applications 24033 final long token = Binder.clearCallingIdentity(); 24034 try { 24035 final DeviceStorageMonitorInternal 24036 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 24037 if (dsm != null) { 24038 return dsm.isMemoryLow(); 24039 } else { 24040 return false; 24041 } 24042 } finally { 24043 Binder.restoreCallingIdentity(token); 24044 } 24045 } 24046 24047 @Override 24048 public IPackageInstaller getPackageInstaller() { 24049 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 24050 return null; 24051 } 24052 return mInstallerService; 24053 } 24054 24055 private boolean userNeedsBadging(int userId) { 24056 int index = mUserNeedsBadging.indexOfKey(userId); 24057 if (index < 0) { 24058 final UserInfo userInfo; 24059 final long token = Binder.clearCallingIdentity(); 24060 try { 24061 userInfo = sUserManager.getUserInfo(userId); 24062 } finally { 24063 Binder.restoreCallingIdentity(token); 24064 } 24065 final boolean b; 24066 if (userInfo != null && userInfo.isManagedProfile()) { 24067 b = true; 24068 } else { 24069 b = false; 24070 } 24071 mUserNeedsBadging.put(userId, b); 24072 return b; 24073 } 24074 return mUserNeedsBadging.valueAt(index); 24075 } 24076 24077 @Override 24078 public KeySet getKeySetByAlias(String packageName, String alias) { 24079 if (packageName == null || alias == null) { 24080 return null; 24081 } 24082 synchronized(mPackages) { 24083 final PackageParser.Package pkg = mPackages.get(packageName); 24084 if (pkg == null) { 24085 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 24086 throw new IllegalArgumentException("Unknown package: " + packageName); 24087 } 24088 final PackageSetting ps = (PackageSetting) pkg.mExtras; 24089 if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) { 24090 Slog.w(TAG, "KeySet requested for filtered package: " + packageName); 24091 throw new IllegalArgumentException("Unknown package: " + packageName); 24092 } 24093 KeySetManagerService ksms = mSettings.mKeySetManagerService; 24094 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 24095 } 24096 } 24097 24098 @Override 24099 public KeySet getSigningKeySet(String packageName) { 24100 if (packageName == null) { 24101 return null; 24102 } 24103 synchronized(mPackages) { 24104 final int callingUid = Binder.getCallingUid(); 24105 final int callingUserId = UserHandle.getUserId(callingUid); 24106 final PackageParser.Package pkg = mPackages.get(packageName); 24107 if (pkg == null) { 24108 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 24109 throw new IllegalArgumentException("Unknown package: " + packageName); 24110 } 24111 final PackageSetting ps = (PackageSetting) pkg.mExtras; 24112 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 24113 // filter and pretend the package doesn't exist 24114 Slog.w(TAG, "KeySet requested for filtered package: " + packageName 24115 + ", uid:" + callingUid); 24116 throw new IllegalArgumentException("Unknown package: " + packageName); 24117 } 24118 if (pkg.applicationInfo.uid != callingUid 24119 && Process.SYSTEM_UID != callingUid) { 24120 throw new SecurityException("May not access signing KeySet of other apps."); 24121 } 24122 KeySetManagerService ksms = mSettings.mKeySetManagerService; 24123 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 24124 } 24125 } 24126 24127 @Override 24128 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 24129 final int callingUid = Binder.getCallingUid(); 24130 if (getInstantAppPackageName(callingUid) != null) { 24131 return false; 24132 } 24133 if (packageName == null || ks == null) { 24134 return false; 24135 } 24136 synchronized(mPackages) { 24137 final PackageParser.Package pkg = mPackages.get(packageName); 24138 if (pkg == null 24139 || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid, 24140 UserHandle.getUserId(callingUid))) { 24141 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 24142 throw new IllegalArgumentException("Unknown package: " + packageName); 24143 } 24144 IBinder ksh = ks.getToken(); 24145 if (ksh instanceof KeySetHandle) { 24146 KeySetManagerService ksms = mSettings.mKeySetManagerService; 24147 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 24148 } 24149 return false; 24150 } 24151 } 24152 24153 @Override 24154 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 24155 final int callingUid = Binder.getCallingUid(); 24156 if (getInstantAppPackageName(callingUid) != null) { 24157 return false; 24158 } 24159 if (packageName == null || ks == null) { 24160 return false; 24161 } 24162 synchronized(mPackages) { 24163 final PackageParser.Package pkg = mPackages.get(packageName); 24164 if (pkg == null 24165 || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid, 24166 UserHandle.getUserId(callingUid))) { 24167 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 24168 throw new IllegalArgumentException("Unknown package: " + packageName); 24169 } 24170 IBinder ksh = ks.getToken(); 24171 if (ksh instanceof KeySetHandle) { 24172 KeySetManagerService ksms = mSettings.mKeySetManagerService; 24173 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 24174 } 24175 return false; 24176 } 24177 } 24178 24179 private void deletePackageIfUnusedLPr(final String packageName) { 24180 PackageSetting ps = mSettings.mPackages.get(packageName); 24181 if (ps == null) { 24182 return; 24183 } 24184 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 24185 // TODO Implement atomic delete if package is unused 24186 // It is currently possible that the package will be deleted even if it is installed 24187 // after this method returns. 24188 mHandler.post(new Runnable() { 24189 public void run() { 24190 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 24191 0, PackageManager.DELETE_ALL_USERS); 24192 } 24193 }); 24194 } 24195 } 24196 24197 /** 24198 * Check and throw if the given before/after packages would be considered a 24199 * downgrade. 24200 */ 24201 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 24202 throws PackageManagerException { 24203 if (after.versionCode < before.mVersionCode) { 24204 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 24205 "Update version code " + after.versionCode + " is older than current " 24206 + before.mVersionCode); 24207 } else if (after.versionCode == before.mVersionCode) { 24208 if (after.baseRevisionCode < before.baseRevisionCode) { 24209 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 24210 "Update base revision code " + after.baseRevisionCode 24211 + " is older than current " + before.baseRevisionCode); 24212 } 24213 24214 if (!ArrayUtils.isEmpty(after.splitNames)) { 24215 for (int i = 0; i < after.splitNames.length; i++) { 24216 final String splitName = after.splitNames[i]; 24217 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 24218 if (j != -1) { 24219 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 24220 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 24221 "Update split " + splitName + " revision code " 24222 + after.splitRevisionCodes[i] + " is older than current " 24223 + before.splitRevisionCodes[j]); 24224 } 24225 } 24226 } 24227 } 24228 } 24229 } 24230 24231 private static class MoveCallbacks extends Handler { 24232 private static final int MSG_CREATED = 1; 24233 private static final int MSG_STATUS_CHANGED = 2; 24234 24235 private final RemoteCallbackList<IPackageMoveObserver> 24236 mCallbacks = new RemoteCallbackList<>(); 24237 24238 private final SparseIntArray mLastStatus = new SparseIntArray(); 24239 24240 public MoveCallbacks(Looper looper) { 24241 super(looper); 24242 } 24243 24244 public void register(IPackageMoveObserver callback) { 24245 mCallbacks.register(callback); 24246 } 24247 24248 public void unregister(IPackageMoveObserver callback) { 24249 mCallbacks.unregister(callback); 24250 } 24251 24252 @Override 24253 public void handleMessage(Message msg) { 24254 final SomeArgs args = (SomeArgs) msg.obj; 24255 final int n = mCallbacks.beginBroadcast(); 24256 for (int i = 0; i < n; i++) { 24257 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 24258 try { 24259 invokeCallback(callback, msg.what, args); 24260 } catch (RemoteException ignored) { 24261 } 24262 } 24263 mCallbacks.finishBroadcast(); 24264 args.recycle(); 24265 } 24266 24267 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 24268 throws RemoteException { 24269 switch (what) { 24270 case MSG_CREATED: { 24271 callback.onCreated(args.argi1, (Bundle) args.arg2); 24272 break; 24273 } 24274 case MSG_STATUS_CHANGED: { 24275 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 24276 break; 24277 } 24278 } 24279 } 24280 24281 private void notifyCreated(int moveId, Bundle extras) { 24282 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 24283 24284 final SomeArgs args = SomeArgs.obtain(); 24285 args.argi1 = moveId; 24286 args.arg2 = extras; 24287 obtainMessage(MSG_CREATED, args).sendToTarget(); 24288 } 24289 24290 private void notifyStatusChanged(int moveId, int status) { 24291 notifyStatusChanged(moveId, status, -1); 24292 } 24293 24294 private void notifyStatusChanged(int moveId, int status, long estMillis) { 24295 Slog.v(TAG, "Move " + moveId + " status " + status); 24296 24297 final SomeArgs args = SomeArgs.obtain(); 24298 args.argi1 = moveId; 24299 args.argi2 = status; 24300 args.arg3 = estMillis; 24301 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 24302 24303 synchronized (mLastStatus) { 24304 mLastStatus.put(moveId, status); 24305 } 24306 } 24307 } 24308 24309 private final static class OnPermissionChangeListeners extends Handler { 24310 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 24311 24312 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 24313 new RemoteCallbackList<>(); 24314 24315 public OnPermissionChangeListeners(Looper looper) { 24316 super(looper); 24317 } 24318 24319 @Override 24320 public void handleMessage(Message msg) { 24321 switch (msg.what) { 24322 case MSG_ON_PERMISSIONS_CHANGED: { 24323 final int uid = msg.arg1; 24324 handleOnPermissionsChanged(uid); 24325 } break; 24326 } 24327 } 24328 24329 public void addListenerLocked(IOnPermissionsChangeListener listener) { 24330 mPermissionListeners.register(listener); 24331 24332 } 24333 24334 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 24335 mPermissionListeners.unregister(listener); 24336 } 24337 24338 public void onPermissionsChanged(int uid) { 24339 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 24340 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 24341 } 24342 } 24343 24344 private void handleOnPermissionsChanged(int uid) { 24345 final int count = mPermissionListeners.beginBroadcast(); 24346 try { 24347 for (int i = 0; i < count; i++) { 24348 IOnPermissionsChangeListener callback = mPermissionListeners 24349 .getBroadcastItem(i); 24350 try { 24351 callback.onPermissionsChanged(uid); 24352 } catch (RemoteException e) { 24353 Log.e(TAG, "Permission listener is dead", e); 24354 } 24355 } 24356 } finally { 24357 mPermissionListeners.finishBroadcast(); 24358 } 24359 } 24360 } 24361 24362 private class PackageManagerInternalImpl extends PackageManagerInternal { 24363 @Override 24364 public void setLocationPackagesProvider(PackagesProvider provider) { 24365 synchronized (mPackages) { 24366 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 24367 } 24368 } 24369 24370 @Override 24371 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 24372 synchronized (mPackages) { 24373 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 24374 } 24375 } 24376 24377 @Override 24378 public void setSmsAppPackagesProvider(PackagesProvider provider) { 24379 synchronized (mPackages) { 24380 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 24381 } 24382 } 24383 24384 @Override 24385 public void setDialerAppPackagesProvider(PackagesProvider provider) { 24386 synchronized (mPackages) { 24387 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 24388 } 24389 } 24390 24391 @Override 24392 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 24393 synchronized (mPackages) { 24394 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 24395 } 24396 } 24397 24398 @Override 24399 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 24400 synchronized (mPackages) { 24401 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 24402 } 24403 } 24404 24405 @Override 24406 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 24407 synchronized (mPackages) { 24408 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 24409 packageName, userId); 24410 } 24411 } 24412 24413 @Override 24414 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 24415 synchronized (mPackages) { 24416 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 24417 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 24418 packageName, userId); 24419 } 24420 } 24421 24422 @Override 24423 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 24424 synchronized (mPackages) { 24425 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 24426 packageName, userId); 24427 } 24428 } 24429 24430 @Override 24431 public void setKeepUninstalledPackages(final List<String> packageList) { 24432 Preconditions.checkNotNull(packageList); 24433 List<String> removedFromList = null; 24434 synchronized (mPackages) { 24435 if (mKeepUninstalledPackages != null) { 24436 final int packagesCount = mKeepUninstalledPackages.size(); 24437 for (int i = 0; i < packagesCount; i++) { 24438 String oldPackage = mKeepUninstalledPackages.get(i); 24439 if (packageList != null && packageList.contains(oldPackage)) { 24440 continue; 24441 } 24442 if (removedFromList == null) { 24443 removedFromList = new ArrayList<>(); 24444 } 24445 removedFromList.add(oldPackage); 24446 } 24447 } 24448 mKeepUninstalledPackages = new ArrayList<>(packageList); 24449 if (removedFromList != null) { 24450 final int removedCount = removedFromList.size(); 24451 for (int i = 0; i < removedCount; i++) { 24452 deletePackageIfUnusedLPr(removedFromList.get(i)); 24453 } 24454 } 24455 } 24456 } 24457 24458 @Override 24459 public boolean isPermissionsReviewRequired(String packageName, int userId) { 24460 synchronized (mPackages) { 24461 // If we do not support permission review, done. 24462 if (!mPermissionReviewRequired) { 24463 return false; 24464 } 24465 24466 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 24467 if (packageSetting == null) { 24468 return false; 24469 } 24470 24471 // Permission review applies only to apps not supporting the new permission model. 24472 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 24473 return false; 24474 } 24475 24476 // Legacy apps have the permission and get user consent on launch. 24477 PermissionsState permissionsState = packageSetting.getPermissionsState(); 24478 return permissionsState.isPermissionReviewRequired(userId); 24479 } 24480 } 24481 24482 @Override 24483 public PackageInfo getPackageInfo( 24484 String packageName, int flags, int filterCallingUid, int userId) { 24485 return PackageManagerService.this 24486 .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST, 24487 flags, filterCallingUid, userId); 24488 } 24489 24490 @Override 24491 public ApplicationInfo getApplicationInfo( 24492 String packageName, int flags, int filterCallingUid, int userId) { 24493 return PackageManagerService.this 24494 .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId); 24495 } 24496 24497 @Override 24498 public ActivityInfo getActivityInfo( 24499 ComponentName component, int flags, int filterCallingUid, int userId) { 24500 return PackageManagerService.this 24501 .getActivityInfoInternal(component, flags, filterCallingUid, userId); 24502 } 24503 24504 @Override 24505 public List<ResolveInfo> queryIntentActivities( 24506 Intent intent, int flags, int filterCallingUid, int userId) { 24507 final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver()); 24508 return PackageManagerService.this 24509 .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid, 24510 userId, false /*resolveForStart*/); 24511 } 24512 24513 @Override 24514 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 24515 int userId) { 24516 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 24517 } 24518 24519 @Override 24520 public void setDeviceAndProfileOwnerPackages( 24521 int deviceOwnerUserId, String deviceOwnerPackage, 24522 SparseArray<String> profileOwnerPackages) { 24523 mProtectedPackages.setDeviceAndProfileOwnerPackages( 24524 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages); 24525 } 24526 24527 @Override 24528 public boolean isPackageDataProtected(int userId, String packageName) { 24529 return mProtectedPackages.isPackageDataProtected(userId, packageName); 24530 } 24531 24532 @Override 24533 public boolean isPackageEphemeral(int userId, String packageName) { 24534 synchronized (mPackages) { 24535 final PackageSetting ps = mSettings.mPackages.get(packageName); 24536 return ps != null ? ps.getInstantApp(userId) : false; 24537 } 24538 } 24539 24540 @Override 24541 public boolean wasPackageEverLaunched(String packageName, int userId) { 24542 synchronized (mPackages) { 24543 return mSettings.wasPackageEverLaunchedLPr(packageName, userId); 24544 } 24545 } 24546 24547 @Override 24548 public void grantRuntimePermission(String packageName, String name, int userId, 24549 boolean overridePolicy) { 24550 PackageManagerService.this.grantRuntimePermission(packageName, name, userId, 24551 overridePolicy); 24552 } 24553 24554 @Override 24555 public void revokeRuntimePermission(String packageName, String name, int userId, 24556 boolean overridePolicy) { 24557 PackageManagerService.this.revokeRuntimePermission(packageName, name, userId, 24558 overridePolicy); 24559 } 24560 24561 @Override 24562 public String getNameForUid(int uid) { 24563 return PackageManagerService.this.getNameForUid(uid); 24564 } 24565 24566 @Override 24567 public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj, 24568 Intent origIntent, String resolvedType, String callingPackage, 24569 Bundle verificationBundle, int userId) { 24570 PackageManagerService.this.requestInstantAppResolutionPhaseTwo( 24571 responseObj, origIntent, resolvedType, callingPackage, verificationBundle, 24572 userId); 24573 } 24574 24575 @Override 24576 public void grantEphemeralAccess(int userId, Intent intent, 24577 int targetAppId, int ephemeralAppId) { 24578 synchronized (mPackages) { 24579 mInstantAppRegistry.grantInstantAccessLPw(userId, intent, 24580 targetAppId, ephemeralAppId); 24581 } 24582 } 24583 24584 @Override 24585 public boolean isInstantAppInstallerComponent(ComponentName component) { 24586 synchronized (mPackages) { 24587 return mInstantAppInstallerActivity != null 24588 && mInstantAppInstallerActivity.getComponentName().equals(component); 24589 } 24590 } 24591 24592 @Override 24593 public void pruneInstantApps() { 24594 mInstantAppRegistry.pruneInstantApps(); 24595 } 24596 24597 @Override 24598 public String getSetupWizardPackageName() { 24599 return mSetupWizardPackage; 24600 } 24601 24602 public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) { 24603 if (policy != null) { 24604 mExternalSourcesPolicy = policy; 24605 } 24606 } 24607 24608 @Override 24609 public boolean isPackagePersistent(String packageName) { 24610 synchronized (mPackages) { 24611 PackageParser.Package pkg = mPackages.get(packageName); 24612 return pkg != null 24613 ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM 24614 | ApplicationInfo.FLAG_PERSISTENT)) == 24615 (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT)) 24616 : false; 24617 } 24618 } 24619 24620 @Override 24621 public List<PackageInfo> getOverlayPackages(int userId) { 24622 final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>(); 24623 synchronized (mPackages) { 24624 for (PackageParser.Package p : mPackages.values()) { 24625 if (p.mOverlayTarget != null) { 24626 PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId); 24627 if (pkg != null) { 24628 overlayPackages.add(pkg); 24629 } 24630 } 24631 } 24632 } 24633 return overlayPackages; 24634 } 24635 24636 @Override 24637 public List<String> getTargetPackageNames(int userId) { 24638 List<String> targetPackages = new ArrayList<>(); 24639 synchronized (mPackages) { 24640 for (PackageParser.Package p : mPackages.values()) { 24641 if (p.mOverlayTarget == null) { 24642 targetPackages.add(p.packageName); 24643 } 24644 } 24645 } 24646 return targetPackages; 24647 } 24648 24649 @Override 24650 public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName, 24651 @Nullable List<String> overlayPackageNames) { 24652 synchronized (mPackages) { 24653 if (targetPackageName == null || mPackages.get(targetPackageName) == null) { 24654 Slog.e(TAG, "failed to find package " + targetPackageName); 24655 return false; 24656 } 24657 ArrayList<String> overlayPaths = null; 24658 if (overlayPackageNames != null && overlayPackageNames.size() > 0) { 24659 final int N = overlayPackageNames.size(); 24660 overlayPaths = new ArrayList<>(N); 24661 for (int i = 0; i < N; i++) { 24662 final String packageName = overlayPackageNames.get(i); 24663 final PackageParser.Package pkg = mPackages.get(packageName); 24664 if (pkg == null) { 24665 Slog.e(TAG, "failed to find package " + packageName); 24666 return false; 24667 } 24668 overlayPaths.add(pkg.baseCodePath); 24669 } 24670 } 24671 24672 final PackageSetting ps = mSettings.mPackages.get(targetPackageName); 24673 ps.setOverlayPaths(overlayPaths, userId); 24674 return true; 24675 } 24676 } 24677 24678 @Override 24679 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 24680 int flags, int userId) { 24681 return resolveIntentInternal( 24682 intent, resolvedType, flags, userId, true /*resolveForStart*/); 24683 } 24684 24685 @Override 24686 public ResolveInfo resolveService(Intent intent, String resolvedType, 24687 int flags, int userId, int callingUid) { 24688 return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid); 24689 } 24690 24691 @Override 24692 public void addIsolatedUid(int isolatedUid, int ownerUid) { 24693 synchronized (mPackages) { 24694 mIsolatedOwners.put(isolatedUid, ownerUid); 24695 } 24696 } 24697 24698 @Override 24699 public void removeIsolatedUid(int isolatedUid) { 24700 synchronized (mPackages) { 24701 mIsolatedOwners.delete(isolatedUid); 24702 } 24703 } 24704 24705 @Override 24706 public int getUidTargetSdkVersion(int uid) { 24707 synchronized (mPackages) { 24708 return getUidTargetSdkVersionLockedLPr(uid); 24709 } 24710 } 24711 24712 @Override 24713 public boolean canAccessInstantApps(int callingUid, int userId) { 24714 return PackageManagerService.this.canViewInstantApps(callingUid, userId); 24715 } 24716 } 24717 24718 @Override 24719 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 24720 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 24721 synchronized (mPackages) { 24722 final long identity = Binder.clearCallingIdentity(); 24723 try { 24724 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 24725 packageNames, userId); 24726 } finally { 24727 Binder.restoreCallingIdentity(identity); 24728 } 24729 } 24730 } 24731 24732 @Override 24733 public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) { 24734 enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices"); 24735 synchronized (mPackages) { 24736 final long identity = Binder.clearCallingIdentity(); 24737 try { 24738 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr( 24739 packageNames, userId); 24740 } finally { 24741 Binder.restoreCallingIdentity(identity); 24742 } 24743 } 24744 } 24745 24746 private static void enforceSystemOrPhoneCaller(String tag) { 24747 int callingUid = Binder.getCallingUid(); 24748 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 24749 throw new SecurityException( 24750 "Cannot call " + tag + " from UID " + callingUid); 24751 } 24752 } 24753 24754 boolean isHistoricalPackageUsageAvailable() { 24755 return mPackageUsage.isHistoricalPackageUsageAvailable(); 24756 } 24757 24758 /** 24759 * Return a <b>copy</b> of the collection of packages known to the package manager. 24760 * @return A copy of the values of mPackages. 24761 */ 24762 Collection<PackageParser.Package> getPackages() { 24763 synchronized (mPackages) { 24764 return new ArrayList<>(mPackages.values()); 24765 } 24766 } 24767 24768 /** 24769 * Logs process start information (including base APK hash) to the security log. 24770 * @hide 24771 */ 24772 @Override 24773 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 24774 String apkFile, int pid) { 24775 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 24776 return; 24777 } 24778 if (!SecurityLog.isLoggingEnabled()) { 24779 return; 24780 } 24781 Bundle data = new Bundle(); 24782 data.putLong("startTimestamp", System.currentTimeMillis()); 24783 data.putString("processName", processName); 24784 data.putInt("uid", uid); 24785 data.putString("seinfo", seinfo); 24786 data.putString("apkFile", apkFile); 24787 data.putInt("pid", pid); 24788 Message msg = mProcessLoggingHandler.obtainMessage( 24789 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 24790 msg.setData(data); 24791 mProcessLoggingHandler.sendMessage(msg); 24792 } 24793 24794 public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) { 24795 return mCompilerStats.getPackageStats(pkgName); 24796 } 24797 24798 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) { 24799 return getOrCreateCompilerPackageStats(pkg.packageName); 24800 } 24801 24802 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) { 24803 return mCompilerStats.getOrCreatePackageStats(pkgName); 24804 } 24805 24806 public void deleteCompilerPackageStats(String pkgName) { 24807 mCompilerStats.deletePackageStats(pkgName); 24808 } 24809 24810 @Override 24811 public int getInstallReason(String packageName, int userId) { 24812 final int callingUid = Binder.getCallingUid(); 24813 enforceCrossUserPermission(callingUid, userId, 24814 true /* requireFullPermission */, false /* checkShell */, 24815 "get install reason"); 24816 synchronized (mPackages) { 24817 final PackageSetting ps = mSettings.mPackages.get(packageName); 24818 if (filterAppAccessLPr(ps, callingUid, userId)) { 24819 return PackageManager.INSTALL_REASON_UNKNOWN; 24820 } 24821 if (ps != null) { 24822 return ps.getInstallReason(userId); 24823 } 24824 } 24825 return PackageManager.INSTALL_REASON_UNKNOWN; 24826 } 24827 24828 @Override 24829 public boolean canRequestPackageInstalls(String packageName, int userId) { 24830 return canRequestPackageInstallsInternal(packageName, 0, userId, 24831 true /* throwIfPermNotDeclared*/); 24832 } 24833 24834 private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId, 24835 boolean throwIfPermNotDeclared) { 24836 int callingUid = Binder.getCallingUid(); 24837 int uid = getPackageUid(packageName, 0, userId); 24838 if (callingUid != uid && callingUid != Process.ROOT_UID 24839 && callingUid != Process.SYSTEM_UID) { 24840 throw new SecurityException( 24841 "Caller uid " + callingUid + " does not own package " + packageName); 24842 } 24843 ApplicationInfo info = getApplicationInfo(packageName, flags, userId); 24844 if (info == null) { 24845 return false; 24846 } 24847 if (info.targetSdkVersion < Build.VERSION_CODES.O) { 24848 return false; 24849 } 24850 String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES; 24851 String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission); 24852 if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) { 24853 if (throwIfPermNotDeclared) { 24854 throw new SecurityException("Need to declare " + appOpPermission 24855 + " to call this api"); 24856 } else { 24857 Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api"); 24858 return false; 24859 } 24860 } 24861 if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) { 24862 return false; 24863 } 24864 if (mExternalSourcesPolicy != null) { 24865 int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid); 24866 if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) { 24867 return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED; 24868 } 24869 } 24870 return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED; 24871 } 24872 24873 @Override 24874 public ComponentName getInstantAppResolverSettingsComponent() { 24875 return mInstantAppResolverSettingsComponent; 24876 } 24877 24878 @Override 24879 public ComponentName getInstantAppInstallerComponent() { 24880 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 24881 return null; 24882 } 24883 return mInstantAppInstallerActivity == null 24884 ? null : mInstantAppInstallerActivity.getComponentName(); 24885 } 24886 24887 @Override 24888 public String getInstantAppAndroidId(String packageName, int userId) { 24889 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS, 24890 "getInstantAppAndroidId"); 24891 enforceCrossUserPermission(Binder.getCallingUid(), userId, 24892 true /* requireFullPermission */, false /* checkShell */, 24893 "getInstantAppAndroidId"); 24894 // Make sure the target is an Instant App. 24895 if (!isInstantApp(packageName, userId)) { 24896 return null; 24897 } 24898 synchronized (mPackages) { 24899 return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId); 24900 } 24901 } 24902} 24903 24904interface PackageSender { 24905 void sendPackageBroadcast(final String action, final String pkg, 24906 final Bundle extras, final int flags, final String targetPkg, 24907 final IIntentReceiver finishedReceiver, final int[] userIds); 24908 void sendPackageAddedForNewUsers(String packageName, boolean isSystem, 24909 int appId, int... userIds); 24910} 24911