PackageManagerService.java revision 07b6eabe79261267ecd7114790e96e1f6828672a
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.REQUEST_INSTALL_PACKAGES; 24import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; 25import static android.Manifest.permission.WRITE_MEDIA_STORAGE; 26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 27import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 28import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 29import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 30import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 31import static android.content.pm.PackageManager.DELETE_KEEP_DATA; 32import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 33import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED; 34import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 35import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 36import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 37import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED; 38import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET; 39import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 40import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 41import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 42import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 43import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 44import static android.content.pm.PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID; 45import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 46import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 47import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 48import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 49import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 50import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 51import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 52import static android.content.pm.PackageManager.INSTALL_FAILED_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.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK; 62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 65import static android.content.pm.PackageManager.MATCH_ALL; 66import static android.content.pm.PackageManager.MATCH_ANY_USER; 67import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 68import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE; 69import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE; 70import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS; 71import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY; 72import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES; 73import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY; 74import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES; 75import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL; 76import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN; 77import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 78import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 79import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 80import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 81import static android.content.pm.PackageManager.PERMISSION_DENIED; 82import static android.content.pm.PackageManager.PERMISSION_GRANTED; 83import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED; 84import static android.content.pm.PackageParser.isApkFile; 85import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 86import static android.system.OsConstants.O_CREAT; 87import static android.system.OsConstants.O_RDWR; 88import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 89import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 90import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 91import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 92import static com.android.internal.util.ArrayUtils.appendInt; 93import static com.android.server.pm.Installer.DEXOPT_PUBLIC; 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.getFullCompilerFilter; 101import static com.android.server.pm.PackageManagerServiceCompilerMapping.getNonProfileGuidedCompilerFilter; 102import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 103import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 104import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 105 106import android.Manifest; 107import android.annotation.NonNull; 108import android.annotation.Nullable; 109import android.app.ActivityManager; 110import android.app.AppOpsManager; 111import android.app.IActivityManager; 112import android.app.ResourcesManager; 113import android.app.admin.IDevicePolicyManager; 114import android.app.admin.SecurityLog; 115import android.app.backup.IBackupManager; 116import android.content.BroadcastReceiver; 117import android.content.ComponentName; 118import android.content.ContentResolver; 119import android.content.Context; 120import android.content.IIntentReceiver; 121import android.content.Intent; 122import android.content.IntentFilter; 123import android.content.IntentSender; 124import android.content.IntentSender.SendIntentException; 125import android.content.ServiceConnection; 126import android.content.pm.ActivityInfo; 127import android.content.pm.ApplicationInfo; 128import android.content.pm.AppsQueryHelper; 129import android.content.pm.ChangedPackages; 130import android.content.pm.ComponentInfo; 131import android.content.pm.EphemeralRequest; 132import android.content.pm.EphemeralResolveInfo; 133import android.content.pm.AuxiliaryResolveInfo; 134import android.content.pm.FallbackCategoryProvider; 135import android.content.pm.FeatureInfo; 136import android.content.pm.IOnPermissionsChangeListener; 137import android.content.pm.IPackageDataObserver; 138import android.content.pm.IPackageDeleteObserver; 139import android.content.pm.IPackageDeleteObserver2; 140import android.content.pm.IPackageInstallObserver2; 141import android.content.pm.IPackageInstaller; 142import android.content.pm.IPackageManager; 143import android.content.pm.IPackageMoveObserver; 144import android.content.pm.IPackageStatsObserver; 145import android.content.pm.InstantAppInfo; 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.SELinuxUtil; 168import android.content.pm.ServiceInfo; 169import android.content.pm.SharedLibraryInfo; 170import android.content.pm.Signature; 171import android.content.pm.UserInfo; 172import android.content.pm.VerifierDeviceIdentity; 173import android.content.pm.VerifierInfo; 174import android.content.pm.VersionedPackage; 175import android.content.res.Resources; 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.DisplayMetrics; 225import android.util.EventLog; 226import android.util.ExceptionUtils; 227import android.util.Log; 228import android.util.LogPrinter; 229import android.util.MathUtils; 230import android.util.PackageUtils; 231import android.util.Pair; 232import android.util.PrintStreamPrinter; 233import android.util.Slog; 234import android.util.SparseArray; 235import android.util.SparseBooleanArray; 236import android.util.SparseIntArray; 237import android.util.Xml; 238import android.util.jar.StrictJarFile; 239import android.util.proto.ProtoOutputStream; 240import android.view.Display; 241 242import com.android.internal.R; 243import com.android.internal.annotations.GuardedBy; 244import com.android.internal.app.IMediaContainerService; 245import com.android.internal.app.ResolverActivity; 246import com.android.internal.content.NativeLibraryHelper; 247import com.android.internal.content.PackageHelper; 248import com.android.internal.logging.MetricsLogger; 249import com.android.internal.logging.nano.MetricsProto.MetricsEvent; 250import com.android.internal.os.IParcelFileDescriptorFactory; 251import com.android.internal.os.RoSystemProperties; 252import com.android.internal.os.SomeArgs; 253import com.android.internal.os.Zygote; 254import com.android.internal.telephony.CarrierAppUtils; 255import com.android.internal.util.ArrayUtils; 256import com.android.internal.util.ConcurrentUtils; 257import com.android.internal.util.FastPrintWriter; 258import com.android.internal.util.FastXmlSerializer; 259import com.android.internal.util.IndentingPrintWriter; 260import com.android.internal.util.Preconditions; 261import com.android.internal.util.XmlUtils; 262import com.android.server.AttributeCache; 263import com.android.server.BackgroundDexOptJobService; 264import com.android.server.DeviceIdleController; 265import com.android.server.EventLogTags; 266import com.android.server.FgThread; 267import com.android.server.IntentResolver; 268import com.android.server.LocalServices; 269import com.android.server.ServiceThread; 270import com.android.server.SystemConfig; 271import com.android.server.SystemServerInitThreadPool; 272import com.android.server.Watchdog; 273import com.android.server.net.NetworkPolicyManagerInternal; 274import com.android.server.pm.Installer.InstallerException; 275import com.android.server.pm.PermissionsState.PermissionState; 276import com.android.server.pm.Settings.DatabaseVersion; 277import com.android.server.pm.Settings.VersionInfo; 278import com.android.server.pm.dex.DexManager; 279import com.android.server.storage.DeviceStorageMonitorInternal; 280 281import dalvik.system.CloseGuard; 282import dalvik.system.DexFile; 283import dalvik.system.VMRuntime; 284 285import libcore.io.IoUtils; 286import libcore.util.EmptyArray; 287 288import org.xmlpull.v1.XmlPullParser; 289import org.xmlpull.v1.XmlPullParserException; 290import org.xmlpull.v1.XmlSerializer; 291 292import java.io.BufferedOutputStream; 293import java.io.BufferedReader; 294import java.io.ByteArrayInputStream; 295import java.io.ByteArrayOutputStream; 296import java.io.File; 297import java.io.FileDescriptor; 298import java.io.FileInputStream; 299import java.io.FileNotFoundException; 300import java.io.FileOutputStream; 301import java.io.FileReader; 302import java.io.FilenameFilter; 303import java.io.IOException; 304import java.io.PrintWriter; 305import java.nio.charset.StandardCharsets; 306import java.security.DigestInputStream; 307import java.security.MessageDigest; 308import java.security.NoSuchAlgorithmException; 309import java.security.PublicKey; 310import java.security.SecureRandom; 311import java.security.cert.Certificate; 312import java.security.cert.CertificateEncodingException; 313import java.security.cert.CertificateException; 314import java.text.SimpleDateFormat; 315import java.util.ArrayList; 316import java.util.Arrays; 317import java.util.Collection; 318import java.util.Collections; 319import java.util.Comparator; 320import java.util.Date; 321import java.util.HashMap; 322import java.util.HashSet; 323import java.util.Iterator; 324import java.util.List; 325import java.util.Map; 326import java.util.Objects; 327import java.util.Set; 328import java.util.concurrent.CountDownLatch; 329import java.util.concurrent.Future; 330import java.util.concurrent.TimeUnit; 331import java.util.concurrent.atomic.AtomicBoolean; 332import java.util.concurrent.atomic.AtomicInteger; 333 334/** 335 * Keep track of all those APKs everywhere. 336 * <p> 337 * Internally there are two important locks: 338 * <ul> 339 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 340 * and other related state. It is a fine-grained lock that should only be held 341 * momentarily, as it's one of the most contended locks in the system. 342 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 343 * operations typically involve heavy lifting of application data on disk. Since 344 * {@code installd} is single-threaded, and it's operations can often be slow, 345 * this lock should never be acquired while already holding {@link #mPackages}. 346 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 347 * holding {@link #mInstallLock}. 348 * </ul> 349 * Many internal methods rely on the caller to hold the appropriate locks, and 350 * this contract is expressed through method name suffixes: 351 * <ul> 352 * <li>fooLI(): the caller must hold {@link #mInstallLock} 353 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 354 * being modified must be frozen 355 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 356 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 357 * </ul> 358 * <p> 359 * Because this class is very central to the platform's security; please run all 360 * CTS and unit tests whenever making modifications: 361 * 362 * <pre> 363 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 364 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases 365 * </pre> 366 */ 367public class PackageManagerService extends IPackageManager.Stub { 368 static final String TAG = "PackageManager"; 369 static final boolean DEBUG_SETTINGS = false; 370 static final boolean DEBUG_PREFERRED = false; 371 static final boolean DEBUG_UPGRADE = false; 372 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 373 private static final boolean DEBUG_BACKUP = false; 374 private static final boolean DEBUG_INSTALL = false; 375 private static final boolean DEBUG_REMOVE = false; 376 private static final boolean DEBUG_BROADCASTS = false; 377 private static final boolean DEBUG_SHOW_INFO = false; 378 private static final boolean DEBUG_PACKAGE_INFO = false; 379 private static final boolean DEBUG_INTENT_MATCHING = false; 380 private static final boolean DEBUG_PACKAGE_SCANNING = false; 381 private static final boolean DEBUG_VERIFY = false; 382 private static final boolean DEBUG_FILTERS = false; 383 384 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 385 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 386 // user, but by default initialize to this. 387 public static final boolean DEBUG_DEXOPT = false; 388 389 private static final boolean DEBUG_ABI_SELECTION = false; 390 private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE; 391 private static final boolean DEBUG_TRIAGED_MISSING = false; 392 private static final boolean DEBUG_APP_DATA = false; 393 394 /** REMOVE. According to Svet, this was only used to reset permissions during development. */ 395 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 396 397 private static final boolean DISABLE_EPHEMERAL_APPS = false; 398 private static final boolean HIDE_EPHEMERAL_APIS = false; 399 400 private static final boolean ENABLE_FREE_CACHE_V2 = 401 SystemProperties.getBoolean("fw.free_cache_v2", false); 402 403 private static final int RADIO_UID = Process.PHONE_UID; 404 private static final int LOG_UID = Process.LOG_UID; 405 private static final int NFC_UID = Process.NFC_UID; 406 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 407 private static final int SHELL_UID = Process.SHELL_UID; 408 409 // Cap the size of permission trees that 3rd party apps can define 410 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 411 412 // Suffix used during package installation when copying/moving 413 // package apks to install directory. 414 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 415 416 static final int SCAN_NO_DEX = 1<<1; 417 static final int SCAN_FORCE_DEX = 1<<2; 418 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 419 static final int SCAN_NEW_INSTALL = 1<<4; 420 static final int SCAN_UPDATE_TIME = 1<<5; 421 static final int SCAN_BOOTING = 1<<6; 422 static final int SCAN_TRUSTED_OVERLAY = 1<<7; 423 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8; 424 static final int SCAN_REPLACING = 1<<9; 425 static final int SCAN_REQUIRE_KNOWN = 1<<10; 426 static final int SCAN_MOVE = 1<<11; 427 static final int SCAN_INITIAL = 1<<12; 428 static final int SCAN_CHECK_ONLY = 1<<13; 429 static final int SCAN_DONT_KILL_APP = 1<<14; 430 static final int SCAN_IGNORE_FROZEN = 1<<15; 431 static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16; 432 static final int SCAN_AS_INSTANT_APP = 1<<17; 433 static final int SCAN_AS_FULL_APP = 1<<18; 434 /** Should not be with the scan flags */ 435 static final int FLAGS_REMOVE_CHATTY = 1<<31; 436 437 private static final String STATIC_SHARED_LIB_DELIMITER = "_"; 438 439 private static final int[] EMPTY_INT_ARRAY = new int[0]; 440 441 /** 442 * Timeout (in milliseconds) after which the watchdog should declare that 443 * our handler thread is wedged. The usual default for such things is one 444 * minute but we sometimes do very lengthy I/O operations on this thread, 445 * such as installing multi-gigabyte applications, so ours needs to be longer. 446 */ 447 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 448 449 /** 450 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 451 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 452 * settings entry if available, otherwise we use the hardcoded default. If it's been 453 * more than this long since the last fstrim, we force one during the boot sequence. 454 * 455 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 456 * one gets run at the next available charging+idle time. This final mandatory 457 * no-fstrim check kicks in only of the other scheduling criteria is never met. 458 */ 459 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 460 461 /** 462 * Whether verification is enabled by default. 463 */ 464 private static final boolean DEFAULT_VERIFY_ENABLE = true; 465 466 /** 467 * The default maximum time to wait for the verification agent to return in 468 * milliseconds. 469 */ 470 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 471 472 /** 473 * The default response for package verification timeout. 474 * 475 * This can be either PackageManager.VERIFICATION_ALLOW or 476 * PackageManager.VERIFICATION_REJECT. 477 */ 478 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 479 480 static final String PLATFORM_PACKAGE_NAME = "android"; 481 482 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 483 484 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 485 DEFAULT_CONTAINER_PACKAGE, 486 "com.android.defcontainer.DefaultContainerService"); 487 488 private static final String KILL_APP_REASON_GIDS_CHANGED = 489 "permission grant or revoke changed gids"; 490 491 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 492 "permissions revoked"; 493 494 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 495 496 private static final String PACKAGE_SCHEME = "package"; 497 498 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 499 /** 500 * If VENDOR_OVERLAY_THEME_PROPERTY is set, search for runtime resource overlay APKs also in 501 * VENDOR_OVERLAY_DIR/<value of VENDOR_OVERLAY_THEME_PROPERTY> in addition to 502 * VENDOR_OVERLAY_DIR. 503 */ 504 private static final String VENDOR_OVERLAY_THEME_PROPERTY = "ro.boot.vendor.overlay.theme"; 505 /** 506 * Same as VENDOR_OVERLAY_THEME_PROPERTY, except persistent. If set will override whatever 507 * is in VENDOR_OVERLAY_THEME_PROPERTY. 508 */ 509 private static final String VENDOR_OVERLAY_THEME_PERSIST_PROPERTY 510 = "persist.vendor.overlay.theme"; 511 512 /** Permission grant: not grant the permission. */ 513 private static final int GRANT_DENIED = 1; 514 515 /** Permission grant: grant the permission as an install permission. */ 516 private static final int GRANT_INSTALL = 2; 517 518 /** Permission grant: grant the permission as a runtime one. */ 519 private static final int GRANT_RUNTIME = 3; 520 521 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 522 private static final int GRANT_UPGRADE = 4; 523 524 /** Canonical intent used to identify what counts as a "web browser" app */ 525 private static final Intent sBrowserIntent; 526 static { 527 sBrowserIntent = new Intent(); 528 sBrowserIntent.setAction(Intent.ACTION_VIEW); 529 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 530 sBrowserIntent.setData(Uri.parse("http:")); 531 } 532 533 /** 534 * The set of all protected actions [i.e. those actions for which a high priority 535 * intent filter is disallowed]. 536 */ 537 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 538 static { 539 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 540 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 541 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 542 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 543 } 544 545 // Compilation reasons. 546 public static final int REASON_FIRST_BOOT = 0; 547 public static final int REASON_BOOT = 1; 548 public static final int REASON_INSTALL = 2; 549 public static final int REASON_BACKGROUND_DEXOPT = 3; 550 public static final int REASON_AB_OTA = 4; 551 public static final int REASON_NON_SYSTEM_LIBRARY = 5; 552 public static final int REASON_SHARED_APK = 6; 553 public static final int REASON_FORCED_DEXOPT = 7; 554 public static final int REASON_CORE_APP = 8; 555 556 public static final int REASON_LAST = REASON_CORE_APP; 557 558 /** All dangerous permission names in the same order as the events in MetricsEvent */ 559 private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList( 560 Manifest.permission.READ_CALENDAR, 561 Manifest.permission.WRITE_CALENDAR, 562 Manifest.permission.CAMERA, 563 Manifest.permission.READ_CONTACTS, 564 Manifest.permission.WRITE_CONTACTS, 565 Manifest.permission.GET_ACCOUNTS, 566 Manifest.permission.ACCESS_FINE_LOCATION, 567 Manifest.permission.ACCESS_COARSE_LOCATION, 568 Manifest.permission.RECORD_AUDIO, 569 Manifest.permission.READ_PHONE_STATE, 570 Manifest.permission.CALL_PHONE, 571 Manifest.permission.READ_CALL_LOG, 572 Manifest.permission.WRITE_CALL_LOG, 573 Manifest.permission.ADD_VOICEMAIL, 574 Manifest.permission.USE_SIP, 575 Manifest.permission.PROCESS_OUTGOING_CALLS, 576 Manifest.permission.READ_CELL_BROADCASTS, 577 Manifest.permission.BODY_SENSORS, 578 Manifest.permission.SEND_SMS, 579 Manifest.permission.RECEIVE_SMS, 580 Manifest.permission.READ_SMS, 581 Manifest.permission.RECEIVE_WAP_PUSH, 582 Manifest.permission.RECEIVE_MMS, 583 Manifest.permission.READ_EXTERNAL_STORAGE, 584 Manifest.permission.WRITE_EXTERNAL_STORAGE, 585 Manifest.permission.READ_PHONE_NUMBER, 586 Manifest.permission.ANSWER_PHONE_CALLS); 587 588 589 /** 590 * Version number for the package parser cache. Increment this whenever the format or 591 * extent of cached data changes. See {@code PackageParser#setCacheDir}. 592 */ 593 private static final String PACKAGE_PARSER_CACHE_VERSION = "1"; 594 595 /** 596 * Whether the package parser cache is enabled. 597 */ 598 private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true; 599 600 final ServiceThread mHandlerThread; 601 602 final PackageHandler mHandler; 603 604 private final ProcessLoggingHandler mProcessLoggingHandler; 605 606 /** 607 * Messages for {@link #mHandler} that need to wait for system ready before 608 * being dispatched. 609 */ 610 private ArrayList<Message> mPostSystemReadyMessages; 611 612 final int mSdkVersion = Build.VERSION.SDK_INT; 613 614 final Context mContext; 615 final boolean mFactoryTest; 616 final boolean mOnlyCore; 617 final DisplayMetrics mMetrics; 618 final int mDefParseFlags; 619 final String[] mSeparateProcesses; 620 final boolean mIsUpgrade; 621 final boolean mIsPreNUpgrade; 622 final boolean mIsPreNMR1Upgrade; 623 624 @GuardedBy("mPackages") 625 private boolean mDexOptDialogShown; 626 627 /** The location for ASEC container files on internal storage. */ 628 final String mAsecInternalPath; 629 630 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 631 // LOCK HELD. Can be called with mInstallLock held. 632 @GuardedBy("mInstallLock") 633 final Installer mInstaller; 634 635 /** Directory where installed third-party apps stored */ 636 final File mAppInstallDir; 637 638 /** 639 * Directory to which applications installed internally have their 640 * 32 bit native libraries copied. 641 */ 642 private File mAppLib32InstallDir; 643 644 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 645 // apps. 646 final File mDrmAppPrivateInstallDir; 647 648 // ---------------------------------------------------------------- 649 650 // Lock for state used when installing and doing other long running 651 // operations. Methods that must be called with this lock held have 652 // the suffix "LI". 653 final Object mInstallLock = new Object(); 654 655 // ---------------------------------------------------------------- 656 657 // Keys are String (package name), values are Package. This also serves 658 // as the lock for the global state. Methods that must be called with 659 // this lock held have the prefix "LP". 660 @GuardedBy("mPackages") 661 final ArrayMap<String, PackageParser.Package> mPackages = 662 new ArrayMap<String, PackageParser.Package>(); 663 664 final ArrayMap<String, Set<String>> mKnownCodebase = 665 new ArrayMap<String, Set<String>>(); 666 667 // List of APK paths to load for each user and package. This data is never 668 // persisted by the package manager. Instead, the overlay manager will 669 // ensure the data is up-to-date in runtime. 670 @GuardedBy("mPackages") 671 final SparseArray<ArrayMap<String, ArrayList<String>>> mEnabledOverlayPaths = 672 new SparseArray<ArrayMap<String, ArrayList<String>>>(); 673 674 /** 675 * Tracks new system packages [received in an OTA] that we expect to 676 * find updated user-installed versions. Keys are package name, values 677 * are package location. 678 */ 679 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 680 /** 681 * Tracks high priority intent filters for protected actions. During boot, certain 682 * filter actions are protected and should never be allowed to have a high priority 683 * intent filter for them. However, there is one, and only one exception -- the 684 * setup wizard. It must be able to define a high priority intent filter for these 685 * actions to ensure there are no escapes from the wizard. We need to delay processing 686 * of these during boot as we need to look at all of the system packages in order 687 * to know which component is the setup wizard. 688 */ 689 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 690 /** 691 * Whether or not processing protected filters should be deferred. 692 */ 693 private boolean mDeferProtectedFilters = true; 694 695 /** 696 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 697 */ 698 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 699 /** 700 * Whether or not system app permissions should be promoted from install to runtime. 701 */ 702 boolean mPromoteSystemApps; 703 704 @GuardedBy("mPackages") 705 final Settings mSettings; 706 707 /** 708 * Set of package names that are currently "frozen", which means active 709 * surgery is being done on the code/data for that package. The platform 710 * will refuse to launch frozen packages to avoid race conditions. 711 * 712 * @see PackageFreezer 713 */ 714 @GuardedBy("mPackages") 715 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 716 717 final ProtectedPackages mProtectedPackages; 718 719 boolean mFirstBoot; 720 721 PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy; 722 723 // System configuration read by SystemConfig. 724 final int[] mGlobalGids; 725 final SparseArray<ArraySet<String>> mSystemPermissions; 726 @GuardedBy("mAvailableFeatures") 727 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 728 729 // If mac_permissions.xml was found for seinfo labeling. 730 boolean mFoundPolicyFile; 731 732 private final InstantAppRegistry mInstantAppRegistry; 733 734 @GuardedBy("mPackages") 735 int mChangedPackagesSequenceNumber; 736 /** 737 * List of changed [installed, removed or updated] packages. 738 * mapping from user id -> sequence number -> package name 739 */ 740 @GuardedBy("mPackages") 741 final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>(); 742 /** 743 * The sequence number of the last change to a package. 744 * mapping from user id -> package name -> sequence number 745 */ 746 @GuardedBy("mPackages") 747 final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>(); 748 749 public static final class SharedLibraryEntry { 750 public final String path; 751 public final String apk; 752 public final SharedLibraryInfo info; 753 754 SharedLibraryEntry(String _path, String _apk, String name, int version, int type, 755 String declaringPackageName, int declaringPackageVersionCode) { 756 path = _path; 757 apk = _apk; 758 info = new SharedLibraryInfo(name, version, type, new VersionedPackage( 759 declaringPackageName, declaringPackageVersionCode), null); 760 } 761 } 762 763 // Currently known shared libraries. 764 final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>(); 765 final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage = 766 new ArrayMap<>(); 767 768 // All available activities, for your resolving pleasure. 769 final ActivityIntentResolver mActivities = 770 new ActivityIntentResolver(); 771 772 // All available receivers, for your resolving pleasure. 773 final ActivityIntentResolver mReceivers = 774 new ActivityIntentResolver(); 775 776 // All available services, for your resolving pleasure. 777 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 778 779 // All available providers, for your resolving pleasure. 780 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 781 782 // Mapping from provider base names (first directory in content URI codePath) 783 // to the provider information. 784 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 785 new ArrayMap<String, PackageParser.Provider>(); 786 787 // Mapping from instrumentation class names to info about them. 788 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 789 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 790 791 // Mapping from permission names to info about them. 792 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 793 new ArrayMap<String, PackageParser.PermissionGroup>(); 794 795 // Packages whose data we have transfered into another package, thus 796 // should no longer exist. 797 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 798 799 // Broadcast actions that are only available to the system. 800 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 801 802 /** List of packages waiting for verification. */ 803 final SparseArray<PackageVerificationState> mPendingVerification 804 = new SparseArray<PackageVerificationState>(); 805 806 /** Set of packages associated with each app op permission. */ 807 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 808 809 final PackageInstallerService mInstallerService; 810 811 private final PackageDexOptimizer mPackageDexOptimizer; 812 // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package 813 // is used by other apps). 814 private final DexManager mDexManager; 815 816 private AtomicInteger mNextMoveId = new AtomicInteger(); 817 private final MoveCallbacks mMoveCallbacks; 818 819 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 820 821 // Cache of users who need badging. 822 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 823 824 /** Token for keys in mPendingVerification. */ 825 private int mPendingVerificationToken = 0; 826 827 volatile boolean mSystemReady; 828 volatile boolean mSafeMode; 829 volatile boolean mHasSystemUidErrors; 830 831 ApplicationInfo mAndroidApplication; 832 final ActivityInfo mResolveActivity = new ActivityInfo(); 833 final ResolveInfo mResolveInfo = new ResolveInfo(); 834 ComponentName mResolveComponentName; 835 PackageParser.Package mPlatformPackage; 836 ComponentName mCustomResolverComponentName; 837 838 boolean mResolverReplaced = false; 839 840 private final @Nullable ComponentName mIntentFilterVerifierComponent; 841 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 842 843 private int mIntentFilterVerificationToken = 0; 844 845 /** The service connection to the ephemeral resolver */ 846 final EphemeralResolverConnection mInstantAppResolverConnection; 847 848 /** Component used to install ephemeral applications */ 849 ComponentName mInstantAppInstallerComponent; 850 final ActivityInfo mInstantAppInstallerActivity = new ActivityInfo(); 851 final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo(); 852 853 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 854 = new SparseArray<IntentFilterVerificationState>(); 855 856 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy; 857 858 // List of packages names to keep cached, even if they are uninstalled for all users 859 private List<String> mKeepUninstalledPackages; 860 861 private UserManagerInternal mUserManagerInternal; 862 863 private DeviceIdleController.LocalService mDeviceIdleController; 864 865 private File mCacheDir; 866 867 private ArraySet<String> mPrivappPermissionsViolations; 868 869 private Future<?> mPrepareAppDataFuture; 870 871 private static class IFVerificationParams { 872 PackageParser.Package pkg; 873 boolean replacing; 874 int userId; 875 int verifierUid; 876 877 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 878 int _userId, int _verifierUid) { 879 pkg = _pkg; 880 replacing = _replacing; 881 userId = _userId; 882 replacing = _replacing; 883 verifierUid = _verifierUid; 884 } 885 } 886 887 private interface IntentFilterVerifier<T extends IntentFilter> { 888 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 889 T filter, String packageName); 890 void startVerifications(int userId); 891 void receiveVerificationResponse(int verificationId); 892 } 893 894 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 895 private Context mContext; 896 private ComponentName mIntentFilterVerifierComponent; 897 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 898 899 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 900 mContext = context; 901 mIntentFilterVerifierComponent = verifierComponent; 902 } 903 904 private String getDefaultScheme() { 905 return IntentFilter.SCHEME_HTTPS; 906 } 907 908 @Override 909 public void startVerifications(int userId) { 910 // Launch verifications requests 911 int count = mCurrentIntentFilterVerifications.size(); 912 for (int n=0; n<count; n++) { 913 int verificationId = mCurrentIntentFilterVerifications.get(n); 914 final IntentFilterVerificationState ivs = 915 mIntentFilterVerificationStates.get(verificationId); 916 917 String packageName = ivs.getPackageName(); 918 919 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 920 final int filterCount = filters.size(); 921 ArraySet<String> domainsSet = new ArraySet<>(); 922 for (int m=0; m<filterCount; m++) { 923 PackageParser.ActivityIntentInfo filter = filters.get(m); 924 domainsSet.addAll(filter.getHostsList()); 925 } 926 synchronized (mPackages) { 927 if (mSettings.createIntentFilterVerificationIfNeededLPw( 928 packageName, domainsSet) != null) { 929 scheduleWriteSettingsLocked(); 930 } 931 } 932 sendVerificationRequest(userId, verificationId, ivs); 933 } 934 mCurrentIntentFilterVerifications.clear(); 935 } 936 937 private void sendVerificationRequest(int userId, int verificationId, 938 IntentFilterVerificationState ivs) { 939 940 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 941 verificationIntent.putExtra( 942 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 943 verificationId); 944 verificationIntent.putExtra( 945 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 946 getDefaultScheme()); 947 verificationIntent.putExtra( 948 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 949 ivs.getHostsString()); 950 verificationIntent.putExtra( 951 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 952 ivs.getPackageName()); 953 verificationIntent.setComponent(mIntentFilterVerifierComponent); 954 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 955 956 UserHandle user = new UserHandle(userId); 957 mContext.sendBroadcastAsUser(verificationIntent, user); 958 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 959 "Sending IntentFilter verification broadcast"); 960 } 961 962 public void receiveVerificationResponse(int verificationId) { 963 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 964 965 final boolean verified = ivs.isVerified(); 966 967 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 968 final int count = filters.size(); 969 if (DEBUG_DOMAIN_VERIFICATION) { 970 Slog.i(TAG, "Received verification response " + verificationId 971 + " for " + count + " filters, verified=" + verified); 972 } 973 for (int n=0; n<count; n++) { 974 PackageParser.ActivityIntentInfo filter = filters.get(n); 975 filter.setVerified(verified); 976 977 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 978 + " verified with result:" + verified + " and hosts:" 979 + ivs.getHostsString()); 980 } 981 982 mIntentFilterVerificationStates.remove(verificationId); 983 984 final String packageName = ivs.getPackageName(); 985 IntentFilterVerificationInfo ivi = null; 986 987 synchronized (mPackages) { 988 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 989 } 990 if (ivi == null) { 991 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 992 + verificationId + " packageName:" + packageName); 993 return; 994 } 995 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 996 "Updating IntentFilterVerificationInfo for package " + packageName 997 +" verificationId:" + verificationId); 998 999 synchronized (mPackages) { 1000 if (verified) { 1001 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 1002 } else { 1003 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 1004 } 1005 scheduleWriteSettingsLocked(); 1006 1007 final int userId = ivs.getUserId(); 1008 if (userId != UserHandle.USER_ALL) { 1009 final int userStatus = 1010 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 1011 1012 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 1013 boolean needUpdate = false; 1014 1015 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 1016 // already been set by the User thru the Disambiguation dialog 1017 switch (userStatus) { 1018 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 1019 if (verified) { 1020 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 1021 } else { 1022 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 1023 } 1024 needUpdate = true; 1025 break; 1026 1027 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 1028 if (verified) { 1029 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 1030 needUpdate = true; 1031 } 1032 break; 1033 1034 default: 1035 // Nothing to do 1036 } 1037 1038 if (needUpdate) { 1039 mSettings.updateIntentFilterVerificationStatusLPw( 1040 packageName, updatedStatus, userId); 1041 scheduleWritePackageRestrictionsLocked(userId); 1042 } 1043 } 1044 } 1045 } 1046 1047 @Override 1048 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 1049 ActivityIntentInfo filter, String packageName) { 1050 if (!hasValidDomains(filter)) { 1051 return false; 1052 } 1053 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 1054 if (ivs == null) { 1055 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 1056 packageName); 1057 } 1058 if (DEBUG_DOMAIN_VERIFICATION) { 1059 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 1060 } 1061 ivs.addFilter(filter); 1062 return true; 1063 } 1064 1065 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 1066 int userId, int verificationId, String packageName) { 1067 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 1068 verifierUid, userId, packageName); 1069 ivs.setPendingState(); 1070 synchronized (mPackages) { 1071 mIntentFilterVerificationStates.append(verificationId, ivs); 1072 mCurrentIntentFilterVerifications.add(verificationId); 1073 } 1074 return ivs; 1075 } 1076 } 1077 1078 private static boolean hasValidDomains(ActivityIntentInfo filter) { 1079 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 1080 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 1081 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 1082 } 1083 1084 // Set of pending broadcasts for aggregating enable/disable of components. 1085 static class PendingPackageBroadcasts { 1086 // for each user id, a map of <package name -> components within that package> 1087 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 1088 1089 public PendingPackageBroadcasts() { 1090 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 1091 } 1092 1093 public ArrayList<String> get(int userId, String packageName) { 1094 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1095 return packages.get(packageName); 1096 } 1097 1098 public void put(int userId, String packageName, ArrayList<String> components) { 1099 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1100 packages.put(packageName, components); 1101 } 1102 1103 public void remove(int userId, String packageName) { 1104 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 1105 if (packages != null) { 1106 packages.remove(packageName); 1107 } 1108 } 1109 1110 public void remove(int userId) { 1111 mUidMap.remove(userId); 1112 } 1113 1114 public int userIdCount() { 1115 return mUidMap.size(); 1116 } 1117 1118 public int userIdAt(int n) { 1119 return mUidMap.keyAt(n); 1120 } 1121 1122 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 1123 return mUidMap.get(userId); 1124 } 1125 1126 public int size() { 1127 // total number of pending broadcast entries across all userIds 1128 int num = 0; 1129 for (int i = 0; i< mUidMap.size(); i++) { 1130 num += mUidMap.valueAt(i).size(); 1131 } 1132 return num; 1133 } 1134 1135 public void clear() { 1136 mUidMap.clear(); 1137 } 1138 1139 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1140 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1141 if (map == null) { 1142 map = new ArrayMap<String, ArrayList<String>>(); 1143 mUidMap.put(userId, map); 1144 } 1145 return map; 1146 } 1147 } 1148 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1149 1150 // Service Connection to remote media container service to copy 1151 // package uri's from external media onto secure containers 1152 // or internal storage. 1153 private IMediaContainerService mContainerService = null; 1154 1155 static final int SEND_PENDING_BROADCAST = 1; 1156 static final int MCS_BOUND = 3; 1157 static final int END_COPY = 4; 1158 static final int INIT_COPY = 5; 1159 static final int MCS_UNBIND = 6; 1160 static final int START_CLEANING_PACKAGE = 7; 1161 static final int FIND_INSTALL_LOC = 8; 1162 static final int POST_INSTALL = 9; 1163 static final int MCS_RECONNECT = 10; 1164 static final int MCS_GIVE_UP = 11; 1165 static final int UPDATED_MEDIA_STATUS = 12; 1166 static final int WRITE_SETTINGS = 13; 1167 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1168 static final int PACKAGE_VERIFIED = 15; 1169 static final int CHECK_PENDING_VERIFICATION = 16; 1170 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1171 static final int INTENT_FILTER_VERIFIED = 18; 1172 static final int WRITE_PACKAGE_LIST = 19; 1173 static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20; 1174 1175 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1176 1177 // Delay time in millisecs 1178 static final int BROADCAST_DELAY = 10 * 1000; 1179 1180 static UserManagerService sUserManager; 1181 1182 // Stores a list of users whose package restrictions file needs to be updated 1183 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1184 1185 final private DefaultContainerConnection mDefContainerConn = 1186 new DefaultContainerConnection(); 1187 class DefaultContainerConnection implements ServiceConnection { 1188 public void onServiceConnected(ComponentName name, IBinder service) { 1189 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1190 final IMediaContainerService imcs = IMediaContainerService.Stub 1191 .asInterface(Binder.allowBlocking(service)); 1192 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1193 } 1194 1195 public void onServiceDisconnected(ComponentName name) { 1196 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1197 } 1198 } 1199 1200 // Recordkeeping of restore-after-install operations that are currently in flight 1201 // between the Package Manager and the Backup Manager 1202 static class PostInstallData { 1203 public InstallArgs args; 1204 public PackageInstalledInfo res; 1205 1206 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1207 args = _a; 1208 res = _r; 1209 } 1210 } 1211 1212 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1213 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1214 1215 // XML tags for backup/restore of various bits of state 1216 private static final String TAG_PREFERRED_BACKUP = "pa"; 1217 private static final String TAG_DEFAULT_APPS = "da"; 1218 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1219 1220 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1221 private static final String TAG_ALL_GRANTS = "rt-grants"; 1222 private static final String TAG_GRANT = "grant"; 1223 private static final String ATTR_PACKAGE_NAME = "pkg"; 1224 1225 private static final String TAG_PERMISSION = "perm"; 1226 private static final String ATTR_PERMISSION_NAME = "name"; 1227 private static final String ATTR_IS_GRANTED = "g"; 1228 private static final String ATTR_USER_SET = "set"; 1229 private static final String ATTR_USER_FIXED = "fixed"; 1230 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1231 1232 // System/policy permission grants are not backed up 1233 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1234 FLAG_PERMISSION_POLICY_FIXED 1235 | FLAG_PERMISSION_SYSTEM_FIXED 1236 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1237 1238 // And we back up these user-adjusted states 1239 private static final int USER_RUNTIME_GRANT_MASK = 1240 FLAG_PERMISSION_USER_SET 1241 | FLAG_PERMISSION_USER_FIXED 1242 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1243 1244 final @Nullable String mRequiredVerifierPackage; 1245 final @NonNull String mRequiredInstallerPackage; 1246 final @NonNull String mRequiredUninstallerPackage; 1247 final @Nullable String mSetupWizardPackage; 1248 final @Nullable String mStorageManagerPackage; 1249 final @NonNull String mServicesSystemSharedLibraryPackageName; 1250 final @NonNull String mSharedSystemSharedLibraryPackageName; 1251 1252 final boolean mPermissionReviewRequired; 1253 1254 private final PackageUsage mPackageUsage = new PackageUsage(); 1255 private final CompilerStats mCompilerStats = new CompilerStats(); 1256 1257 class PackageHandler extends Handler { 1258 private boolean mBound = false; 1259 final ArrayList<HandlerParams> mPendingInstalls = 1260 new ArrayList<HandlerParams>(); 1261 1262 private boolean connectToService() { 1263 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1264 " DefaultContainerService"); 1265 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1266 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1267 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1268 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1269 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1270 mBound = true; 1271 return true; 1272 } 1273 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1274 return false; 1275 } 1276 1277 private void disconnectService() { 1278 mContainerService = null; 1279 mBound = false; 1280 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1281 mContext.unbindService(mDefContainerConn); 1282 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1283 } 1284 1285 PackageHandler(Looper looper) { 1286 super(looper); 1287 } 1288 1289 public void handleMessage(Message msg) { 1290 try { 1291 doHandleMessage(msg); 1292 } finally { 1293 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1294 } 1295 } 1296 1297 void doHandleMessage(Message msg) { 1298 switch (msg.what) { 1299 case INIT_COPY: { 1300 HandlerParams params = (HandlerParams) msg.obj; 1301 int idx = mPendingInstalls.size(); 1302 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1303 // If a bind was already initiated we dont really 1304 // need to do anything. The pending install 1305 // will be processed later on. 1306 if (!mBound) { 1307 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1308 System.identityHashCode(mHandler)); 1309 // If this is the only one pending we might 1310 // have to bind to the service again. 1311 if (!connectToService()) { 1312 Slog.e(TAG, "Failed to bind to media container service"); 1313 params.serviceError(); 1314 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1315 System.identityHashCode(mHandler)); 1316 if (params.traceMethod != null) { 1317 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1318 params.traceCookie); 1319 } 1320 return; 1321 } else { 1322 // Once we bind to the service, the first 1323 // pending request will be processed. 1324 mPendingInstalls.add(idx, params); 1325 } 1326 } else { 1327 mPendingInstalls.add(idx, params); 1328 // Already bound to the service. Just make 1329 // sure we trigger off processing the first request. 1330 if (idx == 0) { 1331 mHandler.sendEmptyMessage(MCS_BOUND); 1332 } 1333 } 1334 break; 1335 } 1336 case MCS_BOUND: { 1337 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1338 if (msg.obj != null) { 1339 mContainerService = (IMediaContainerService) msg.obj; 1340 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1341 System.identityHashCode(mHandler)); 1342 } 1343 if (mContainerService == null) { 1344 if (!mBound) { 1345 // Something seriously wrong since we are not bound and we are not 1346 // waiting for connection. Bail out. 1347 Slog.e(TAG, "Cannot bind to media container service"); 1348 for (HandlerParams params : mPendingInstalls) { 1349 // Indicate service bind error 1350 params.serviceError(); 1351 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1352 System.identityHashCode(params)); 1353 if (params.traceMethod != null) { 1354 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1355 params.traceMethod, params.traceCookie); 1356 } 1357 return; 1358 } 1359 mPendingInstalls.clear(); 1360 } else { 1361 Slog.w(TAG, "Waiting to connect to media container service"); 1362 } 1363 } else if (mPendingInstalls.size() > 0) { 1364 HandlerParams params = mPendingInstalls.get(0); 1365 if (params != null) { 1366 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1367 System.identityHashCode(params)); 1368 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1369 if (params.startCopy()) { 1370 // We are done... look for more work or to 1371 // go idle. 1372 if (DEBUG_SD_INSTALL) Log.i(TAG, 1373 "Checking for more work or unbind..."); 1374 // Delete pending install 1375 if (mPendingInstalls.size() > 0) { 1376 mPendingInstalls.remove(0); 1377 } 1378 if (mPendingInstalls.size() == 0) { 1379 if (mBound) { 1380 if (DEBUG_SD_INSTALL) Log.i(TAG, 1381 "Posting delayed MCS_UNBIND"); 1382 removeMessages(MCS_UNBIND); 1383 Message ubmsg = obtainMessage(MCS_UNBIND); 1384 // Unbind after a little delay, to avoid 1385 // continual thrashing. 1386 sendMessageDelayed(ubmsg, 10000); 1387 } 1388 } else { 1389 // There are more pending requests in queue. 1390 // Just post MCS_BOUND message to trigger processing 1391 // of next pending install. 1392 if (DEBUG_SD_INSTALL) Log.i(TAG, 1393 "Posting MCS_BOUND for next work"); 1394 mHandler.sendEmptyMessage(MCS_BOUND); 1395 } 1396 } 1397 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1398 } 1399 } else { 1400 // Should never happen ideally. 1401 Slog.w(TAG, "Empty queue"); 1402 } 1403 break; 1404 } 1405 case MCS_RECONNECT: { 1406 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1407 if (mPendingInstalls.size() > 0) { 1408 if (mBound) { 1409 disconnectService(); 1410 } 1411 if (!connectToService()) { 1412 Slog.e(TAG, "Failed to bind to media container service"); 1413 for (HandlerParams params : mPendingInstalls) { 1414 // Indicate service bind error 1415 params.serviceError(); 1416 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1417 System.identityHashCode(params)); 1418 } 1419 mPendingInstalls.clear(); 1420 } 1421 } 1422 break; 1423 } 1424 case MCS_UNBIND: { 1425 // If there is no actual work left, then time to unbind. 1426 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1427 1428 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1429 if (mBound) { 1430 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1431 1432 disconnectService(); 1433 } 1434 } else if (mPendingInstalls.size() > 0) { 1435 // There are more pending requests in queue. 1436 // Just post MCS_BOUND message to trigger processing 1437 // of next pending install. 1438 mHandler.sendEmptyMessage(MCS_BOUND); 1439 } 1440 1441 break; 1442 } 1443 case MCS_GIVE_UP: { 1444 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1445 HandlerParams params = mPendingInstalls.remove(0); 1446 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1447 System.identityHashCode(params)); 1448 break; 1449 } 1450 case SEND_PENDING_BROADCAST: { 1451 String packages[]; 1452 ArrayList<String> components[]; 1453 int size = 0; 1454 int uids[]; 1455 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1456 synchronized (mPackages) { 1457 if (mPendingBroadcasts == null) { 1458 return; 1459 } 1460 size = mPendingBroadcasts.size(); 1461 if (size <= 0) { 1462 // Nothing to be done. Just return 1463 return; 1464 } 1465 packages = new String[size]; 1466 components = new ArrayList[size]; 1467 uids = new int[size]; 1468 int i = 0; // filling out the above arrays 1469 1470 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1471 int packageUserId = mPendingBroadcasts.userIdAt(n); 1472 Iterator<Map.Entry<String, ArrayList<String>>> it 1473 = mPendingBroadcasts.packagesForUserId(packageUserId) 1474 .entrySet().iterator(); 1475 while (it.hasNext() && i < size) { 1476 Map.Entry<String, ArrayList<String>> ent = it.next(); 1477 packages[i] = ent.getKey(); 1478 components[i] = ent.getValue(); 1479 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1480 uids[i] = (ps != null) 1481 ? UserHandle.getUid(packageUserId, ps.appId) 1482 : -1; 1483 i++; 1484 } 1485 } 1486 size = i; 1487 mPendingBroadcasts.clear(); 1488 } 1489 // Send broadcasts 1490 for (int i = 0; i < size; i++) { 1491 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1492 } 1493 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1494 break; 1495 } 1496 case START_CLEANING_PACKAGE: { 1497 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1498 final String packageName = (String)msg.obj; 1499 final int userId = msg.arg1; 1500 final boolean andCode = msg.arg2 != 0; 1501 synchronized (mPackages) { 1502 if (userId == UserHandle.USER_ALL) { 1503 int[] users = sUserManager.getUserIds(); 1504 for (int user : users) { 1505 mSettings.addPackageToCleanLPw( 1506 new PackageCleanItem(user, packageName, andCode)); 1507 } 1508 } else { 1509 mSettings.addPackageToCleanLPw( 1510 new PackageCleanItem(userId, packageName, andCode)); 1511 } 1512 } 1513 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1514 startCleaningPackages(); 1515 } break; 1516 case POST_INSTALL: { 1517 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1518 1519 PostInstallData data = mRunningInstalls.get(msg.arg1); 1520 final boolean didRestore = (msg.arg2 != 0); 1521 mRunningInstalls.delete(msg.arg1); 1522 1523 if (data != null) { 1524 InstallArgs args = data.args; 1525 PackageInstalledInfo parentRes = data.res; 1526 1527 final boolean grantPermissions = (args.installFlags 1528 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1529 final boolean killApp = (args.installFlags 1530 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1531 final String[] grantedPermissions = args.installGrantPermissions; 1532 1533 // Handle the parent package 1534 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1535 grantedPermissions, didRestore, args.installerPackageName, 1536 args.observer); 1537 1538 // Handle the child packages 1539 final int childCount = (parentRes.addedChildPackages != null) 1540 ? parentRes.addedChildPackages.size() : 0; 1541 for (int i = 0; i < childCount; i++) { 1542 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1543 handlePackagePostInstall(childRes, grantPermissions, killApp, 1544 grantedPermissions, false, args.installerPackageName, 1545 args.observer); 1546 } 1547 1548 // Log tracing if needed 1549 if (args.traceMethod != null) { 1550 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1551 args.traceCookie); 1552 } 1553 } else { 1554 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1555 } 1556 1557 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1558 } break; 1559 case UPDATED_MEDIA_STATUS: { 1560 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1561 boolean reportStatus = msg.arg1 == 1; 1562 boolean doGc = msg.arg2 == 1; 1563 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1564 if (doGc) { 1565 // Force a gc to clear up stale containers. 1566 Runtime.getRuntime().gc(); 1567 } 1568 if (msg.obj != null) { 1569 @SuppressWarnings("unchecked") 1570 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1571 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1572 // Unload containers 1573 unloadAllContainers(args); 1574 } 1575 if (reportStatus) { 1576 try { 1577 if (DEBUG_SD_INSTALL) Log.i(TAG, 1578 "Invoking StorageManagerService call back"); 1579 PackageHelper.getStorageManager().finishMediaUpdate(); 1580 } catch (RemoteException e) { 1581 Log.e(TAG, "StorageManagerService not running?"); 1582 } 1583 } 1584 } break; 1585 case WRITE_SETTINGS: { 1586 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1587 synchronized (mPackages) { 1588 removeMessages(WRITE_SETTINGS); 1589 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1590 mSettings.writeLPr(); 1591 mDirtyUsers.clear(); 1592 } 1593 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1594 } break; 1595 case WRITE_PACKAGE_RESTRICTIONS: { 1596 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1597 synchronized (mPackages) { 1598 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1599 for (int userId : mDirtyUsers) { 1600 mSettings.writePackageRestrictionsLPr(userId); 1601 } 1602 mDirtyUsers.clear(); 1603 } 1604 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1605 } break; 1606 case WRITE_PACKAGE_LIST: { 1607 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1608 synchronized (mPackages) { 1609 removeMessages(WRITE_PACKAGE_LIST); 1610 mSettings.writePackageListLPr(msg.arg1); 1611 } 1612 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1613 } break; 1614 case CHECK_PENDING_VERIFICATION: { 1615 final int verificationId = msg.arg1; 1616 final PackageVerificationState state = mPendingVerification.get(verificationId); 1617 1618 if ((state != null) && !state.timeoutExtended()) { 1619 final InstallArgs args = state.getInstallArgs(); 1620 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1621 1622 Slog.i(TAG, "Verification timed out for " + originUri); 1623 mPendingVerification.remove(verificationId); 1624 1625 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1626 1627 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1628 Slog.i(TAG, "Continuing with installation of " + originUri); 1629 state.setVerifierResponse(Binder.getCallingUid(), 1630 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1631 broadcastPackageVerified(verificationId, originUri, 1632 PackageManager.VERIFICATION_ALLOW, 1633 state.getInstallArgs().getUser()); 1634 try { 1635 ret = args.copyApk(mContainerService, true); 1636 } catch (RemoteException e) { 1637 Slog.e(TAG, "Could not contact the ContainerService"); 1638 } 1639 } else { 1640 broadcastPackageVerified(verificationId, originUri, 1641 PackageManager.VERIFICATION_REJECT, 1642 state.getInstallArgs().getUser()); 1643 } 1644 1645 Trace.asyncTraceEnd( 1646 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1647 1648 processPendingInstall(args, ret); 1649 mHandler.sendEmptyMessage(MCS_UNBIND); 1650 } 1651 break; 1652 } 1653 case PACKAGE_VERIFIED: { 1654 final int verificationId = msg.arg1; 1655 1656 final PackageVerificationState state = mPendingVerification.get(verificationId); 1657 if (state == null) { 1658 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1659 break; 1660 } 1661 1662 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1663 1664 state.setVerifierResponse(response.callerUid, response.code); 1665 1666 if (state.isVerificationComplete()) { 1667 mPendingVerification.remove(verificationId); 1668 1669 final InstallArgs args = state.getInstallArgs(); 1670 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1671 1672 int ret; 1673 if (state.isInstallAllowed()) { 1674 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1675 broadcastPackageVerified(verificationId, originUri, 1676 response.code, state.getInstallArgs().getUser()); 1677 try { 1678 ret = args.copyApk(mContainerService, true); 1679 } catch (RemoteException e) { 1680 Slog.e(TAG, "Could not contact the ContainerService"); 1681 } 1682 } else { 1683 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1684 } 1685 1686 Trace.asyncTraceEnd( 1687 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1688 1689 processPendingInstall(args, ret); 1690 mHandler.sendEmptyMessage(MCS_UNBIND); 1691 } 1692 1693 break; 1694 } 1695 case START_INTENT_FILTER_VERIFICATIONS: { 1696 IFVerificationParams params = (IFVerificationParams) msg.obj; 1697 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1698 params.replacing, params.pkg); 1699 break; 1700 } 1701 case INTENT_FILTER_VERIFIED: { 1702 final int verificationId = msg.arg1; 1703 1704 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1705 verificationId); 1706 if (state == null) { 1707 Slog.w(TAG, "Invalid IntentFilter verification token " 1708 + verificationId + " received"); 1709 break; 1710 } 1711 1712 final int userId = state.getUserId(); 1713 1714 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1715 "Processing IntentFilter verification with token:" 1716 + verificationId + " and userId:" + userId); 1717 1718 final IntentFilterVerificationResponse response = 1719 (IntentFilterVerificationResponse) msg.obj; 1720 1721 state.setVerifierResponse(response.callerUid, response.code); 1722 1723 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1724 "IntentFilter verification with token:" + verificationId 1725 + " and userId:" + userId 1726 + " is settings verifier response with response code:" 1727 + response.code); 1728 1729 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1730 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1731 + response.getFailedDomainsString()); 1732 } 1733 1734 if (state.isVerificationComplete()) { 1735 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1736 } else { 1737 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1738 "IntentFilter verification with token:" + verificationId 1739 + " was not said to be complete"); 1740 } 1741 1742 break; 1743 } 1744 case INSTANT_APP_RESOLUTION_PHASE_TWO: { 1745 EphemeralResolver.doEphemeralResolutionPhaseTwo(mContext, 1746 mInstantAppResolverConnection, 1747 (EphemeralRequest) msg.obj, 1748 mInstantAppInstallerActivity, 1749 mHandler); 1750 } 1751 } 1752 } 1753 } 1754 1755 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1756 boolean killApp, String[] grantedPermissions, 1757 boolean launchedForRestore, String installerPackage, 1758 IPackageInstallObserver2 installObserver) { 1759 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1760 // Send the removed broadcasts 1761 if (res.removedInfo != null) { 1762 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1763 } 1764 1765 // Now that we successfully installed the package, grant runtime 1766 // permissions if requested before broadcasting the install. Also 1767 // for legacy apps in permission review mode we clear the permission 1768 // review flag which is used to emulate runtime permissions for 1769 // legacy apps. 1770 if (grantPermissions) { 1771 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1772 } 1773 1774 final boolean update = res.removedInfo != null 1775 && res.removedInfo.removedPackage != null; 1776 1777 // If this is the first time we have child packages for a disabled privileged 1778 // app that had no children, we grant requested runtime permissions to the new 1779 // children if the parent on the system image had them already granted. 1780 if (res.pkg.parentPackage != null) { 1781 synchronized (mPackages) { 1782 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1783 } 1784 } 1785 1786 synchronized (mPackages) { 1787 mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers); 1788 } 1789 1790 final String packageName = res.pkg.applicationInfo.packageName; 1791 1792 // Determine the set of users who are adding this package for 1793 // the first time vs. those who are seeing an update. 1794 int[] firstUsers = EMPTY_INT_ARRAY; 1795 int[] updateUsers = EMPTY_INT_ARRAY; 1796 final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0; 1797 final PackageSetting ps = (PackageSetting) res.pkg.mExtras; 1798 for (int newUser : res.newUsers) { 1799 if (ps.getInstantApp(newUser)) { 1800 continue; 1801 } 1802 if (allNewUsers) { 1803 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1804 continue; 1805 } 1806 boolean isNew = true; 1807 for (int origUser : res.origUsers) { 1808 if (origUser == newUser) { 1809 isNew = false; 1810 break; 1811 } 1812 } 1813 if (isNew) { 1814 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1815 } else { 1816 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1817 } 1818 } 1819 1820 // Send installed broadcasts if the package is not a static shared lib. 1821 if (res.pkg.staticSharedLibName == null) { 1822 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1823 1824 // Send added for users that see the package for the first time 1825 // sendPackageAddedForNewUsers also deals with system apps 1826 int appId = UserHandle.getAppId(res.uid); 1827 boolean isSystem = res.pkg.applicationInfo.isSystemApp(); 1828 sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers); 1829 1830 // Send added for users that don't see the package for the first time 1831 Bundle extras = new Bundle(1); 1832 extras.putInt(Intent.EXTRA_UID, res.uid); 1833 if (update) { 1834 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1835 } 1836 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1837 extras, 0 /*flags*/, null /*targetPackage*/, 1838 null /*finishedReceiver*/, updateUsers); 1839 1840 // Send replaced for users that don't see the package for the first time 1841 if (update) { 1842 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1843 packageName, extras, 0 /*flags*/, 1844 null /*targetPackage*/, null /*finishedReceiver*/, 1845 updateUsers); 1846 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1847 null /*package*/, null /*extras*/, 0 /*flags*/, 1848 packageName /*targetPackage*/, 1849 null /*finishedReceiver*/, updateUsers); 1850 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 1851 // First-install and we did a restore, so we're responsible for the 1852 // first-launch broadcast. 1853 if (DEBUG_BACKUP) { 1854 Slog.i(TAG, "Post-restore of " + packageName 1855 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers)); 1856 } 1857 sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers); 1858 } 1859 1860 // Send broadcast package appeared if forward locked/external for all users 1861 // treat asec-hosted packages like removable media on upgrade 1862 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1863 if (DEBUG_INSTALL) { 1864 Slog.i(TAG, "upgrading pkg " + res.pkg 1865 + " is ASEC-hosted -> AVAILABLE"); 1866 } 1867 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1868 ArrayList<String> pkgList = new ArrayList<>(1); 1869 pkgList.add(packageName); 1870 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1871 } 1872 } 1873 1874 // Work that needs to happen on first install within each user 1875 if (firstUsers != null && firstUsers.length > 0) { 1876 synchronized (mPackages) { 1877 for (int userId : firstUsers) { 1878 // If this app is a browser and it's newly-installed for some 1879 // users, clear any default-browser state in those users. The 1880 // app's nature doesn't depend on the user, so we can just check 1881 // its browser nature in any user and generalize. 1882 if (packageIsBrowser(packageName, userId)) { 1883 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1884 } 1885 1886 // We may also need to apply pending (restored) runtime 1887 // permission grants within these users. 1888 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1889 } 1890 } 1891 } 1892 1893 // Log current value of "unknown sources" setting 1894 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1895 getUnknownSourcesSettings()); 1896 1897 // Force a gc to clear up things 1898 Runtime.getRuntime().gc(); 1899 1900 // Remove the replaced package's older resources safely now 1901 // We delete after a gc for applications on sdcard. 1902 if (res.removedInfo != null && res.removedInfo.args != null) { 1903 synchronized (mInstallLock) { 1904 res.removedInfo.args.doPostDeleteLI(true); 1905 } 1906 } 1907 1908 // Notify DexManager that the package was installed for new users. 1909 // The updated users should already be indexed and the package code paths 1910 // should not change. 1911 // Don't notify the manager for ephemeral apps as they are not expected to 1912 // survive long enough to benefit of background optimizations. 1913 for (int userId : firstUsers) { 1914 PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId); 1915 mDexManager.notifyPackageInstalled(info, userId); 1916 } 1917 } 1918 1919 // If someone is watching installs - notify them 1920 if (installObserver != null) { 1921 try { 1922 Bundle extras = extrasForInstallResult(res); 1923 installObserver.onPackageInstalled(res.name, res.returnCode, 1924 res.returnMsg, extras); 1925 } catch (RemoteException e) { 1926 Slog.i(TAG, "Observer no longer exists."); 1927 } 1928 } 1929 } 1930 1931 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1932 PackageParser.Package pkg) { 1933 if (pkg.parentPackage == null) { 1934 return; 1935 } 1936 if (pkg.requestedPermissions == null) { 1937 return; 1938 } 1939 final PackageSetting disabledSysParentPs = mSettings 1940 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1941 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1942 || !disabledSysParentPs.isPrivileged() 1943 || (disabledSysParentPs.childPackageNames != null 1944 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1945 return; 1946 } 1947 final int[] allUserIds = sUserManager.getUserIds(); 1948 final int permCount = pkg.requestedPermissions.size(); 1949 for (int i = 0; i < permCount; i++) { 1950 String permission = pkg.requestedPermissions.get(i); 1951 BasePermission bp = mSettings.mPermissions.get(permission); 1952 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1953 continue; 1954 } 1955 for (int userId : allUserIds) { 1956 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1957 permission, userId)) { 1958 grantRuntimePermission(pkg.packageName, permission, userId); 1959 } 1960 } 1961 } 1962 } 1963 1964 private StorageEventListener mStorageListener = new StorageEventListener() { 1965 @Override 1966 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1967 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1968 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1969 final String volumeUuid = vol.getFsUuid(); 1970 1971 // Clean up any users or apps that were removed or recreated 1972 // while this volume was missing 1973 sUserManager.reconcileUsers(volumeUuid); 1974 reconcileApps(volumeUuid); 1975 1976 // Clean up any install sessions that expired or were 1977 // cancelled while this volume was missing 1978 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1979 1980 loadPrivatePackages(vol); 1981 1982 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1983 unloadPrivatePackages(vol); 1984 } 1985 } 1986 1987 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1988 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1989 updateExternalMediaStatus(true, false); 1990 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1991 updateExternalMediaStatus(false, false); 1992 } 1993 } 1994 } 1995 1996 @Override 1997 public void onVolumeForgotten(String fsUuid) { 1998 if (TextUtils.isEmpty(fsUuid)) { 1999 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 2000 return; 2001 } 2002 2003 // Remove any apps installed on the forgotten volume 2004 synchronized (mPackages) { 2005 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 2006 for (PackageSetting ps : packages) { 2007 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 2008 deletePackageVersioned(new VersionedPackage(ps.name, 2009 PackageManager.VERSION_CODE_HIGHEST), 2010 new LegacyPackageDeleteObserver(null).getBinder(), 2011 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 2012 // Try very hard to release any references to this package 2013 // so we don't risk the system server being killed due to 2014 // open FDs 2015 AttributeCache.instance().removePackage(ps.name); 2016 } 2017 2018 mSettings.onVolumeForgotten(fsUuid); 2019 mSettings.writeLPr(); 2020 } 2021 } 2022 }; 2023 2024 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 2025 String[] grantedPermissions) { 2026 for (int userId : userIds) { 2027 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 2028 } 2029 } 2030 2031 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 2032 String[] grantedPermissions) { 2033 SettingBase sb = (SettingBase) pkg.mExtras; 2034 if (sb == null) { 2035 return; 2036 } 2037 2038 PermissionsState permissionsState = sb.getPermissionsState(); 2039 2040 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 2041 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 2042 2043 final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 2044 >= Build.VERSION_CODES.M; 2045 2046 for (String permission : pkg.requestedPermissions) { 2047 final BasePermission bp; 2048 synchronized (mPackages) { 2049 bp = mSettings.mPermissions.get(permission); 2050 } 2051 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 2052 && (grantedPermissions == null 2053 || ArrayUtils.contains(grantedPermissions, permission))) { 2054 final int flags = permissionsState.getPermissionFlags(permission, userId); 2055 if (supportsRuntimePermissions) { 2056 // Installer cannot change immutable permissions. 2057 if ((flags & immutableFlags) == 0) { 2058 grantRuntimePermission(pkg.packageName, permission, userId); 2059 } 2060 } else if (mPermissionReviewRequired) { 2061 // In permission review mode we clear the review flag when we 2062 // are asked to install the app with all permissions granted. 2063 if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 2064 updatePermissionFlags(permission, pkg.packageName, 2065 PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId); 2066 } 2067 } 2068 } 2069 } 2070 } 2071 2072 Bundle extrasForInstallResult(PackageInstalledInfo res) { 2073 Bundle extras = null; 2074 switch (res.returnCode) { 2075 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 2076 extras = new Bundle(); 2077 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 2078 res.origPermission); 2079 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 2080 res.origPackage); 2081 break; 2082 } 2083 case PackageManager.INSTALL_SUCCEEDED: { 2084 extras = new Bundle(); 2085 extras.putBoolean(Intent.EXTRA_REPLACING, 2086 res.removedInfo != null && res.removedInfo.removedPackage != null); 2087 break; 2088 } 2089 } 2090 return extras; 2091 } 2092 2093 void scheduleWriteSettingsLocked() { 2094 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2095 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2096 } 2097 } 2098 2099 void scheduleWritePackageListLocked(int userId) { 2100 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) { 2101 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST); 2102 msg.arg1 = userId; 2103 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY); 2104 } 2105 } 2106 2107 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2108 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2109 scheduleWritePackageRestrictionsLocked(userId); 2110 } 2111 2112 void scheduleWritePackageRestrictionsLocked(int userId) { 2113 final int[] userIds = (userId == UserHandle.USER_ALL) 2114 ? sUserManager.getUserIds() : new int[]{userId}; 2115 for (int nextUserId : userIds) { 2116 if (!sUserManager.exists(nextUserId)) return; 2117 mDirtyUsers.add(nextUserId); 2118 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2119 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2120 } 2121 } 2122 } 2123 2124 public static PackageManagerService main(Context context, Installer installer, 2125 boolean factoryTest, boolean onlyCore) { 2126 // Self-check for initial settings. 2127 PackageManagerServiceCompilerMapping.checkProperties(); 2128 2129 PackageManagerService m = new PackageManagerService(context, installer, 2130 factoryTest, onlyCore); 2131 m.enableSystemUserPackages(); 2132 ServiceManager.addService("package", m); 2133 return m; 2134 } 2135 2136 private void enableSystemUserPackages() { 2137 if (!UserManager.isSplitSystemUser()) { 2138 return; 2139 } 2140 // For system user, enable apps based on the following conditions: 2141 // - app is whitelisted or belong to one of these groups: 2142 // -- system app which has no launcher icons 2143 // -- system app which has INTERACT_ACROSS_USERS permission 2144 // -- system IME app 2145 // - app is not in the blacklist 2146 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2147 Set<String> enableApps = new ArraySet<>(); 2148 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2149 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2150 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2151 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2152 enableApps.addAll(wlApps); 2153 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2154 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2155 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2156 enableApps.removeAll(blApps); 2157 Log.i(TAG, "Applications installed for system user: " + enableApps); 2158 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2159 UserHandle.SYSTEM); 2160 final int allAppsSize = allAps.size(); 2161 synchronized (mPackages) { 2162 for (int i = 0; i < allAppsSize; i++) { 2163 String pName = allAps.get(i); 2164 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2165 // Should not happen, but we shouldn't be failing if it does 2166 if (pkgSetting == null) { 2167 continue; 2168 } 2169 boolean install = enableApps.contains(pName); 2170 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2171 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2172 + " for system user"); 2173 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2174 } 2175 } 2176 scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM); 2177 } 2178 } 2179 2180 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2181 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2182 Context.DISPLAY_SERVICE); 2183 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2184 } 2185 2186 /** 2187 * Requests that files preopted on a secondary system partition be copied to the data partition 2188 * if possible. Note that the actual copying of the files is accomplished by init for security 2189 * reasons. This simply requests that the copy takes place and awaits confirmation of its 2190 * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy. 2191 */ 2192 private static void requestCopyPreoptedFiles() { 2193 final int WAIT_TIME_MS = 100; 2194 final String CP_PREOPT_PROPERTY = "sys.cppreopt"; 2195 if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) { 2196 SystemProperties.set(CP_PREOPT_PROPERTY, "requested"); 2197 // We will wait for up to 100 seconds. 2198 final long timeStart = SystemClock.uptimeMillis(); 2199 final long timeEnd = timeStart + 100 * 1000; 2200 long timeNow = timeStart; 2201 while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) { 2202 try { 2203 Thread.sleep(WAIT_TIME_MS); 2204 } catch (InterruptedException e) { 2205 // Do nothing 2206 } 2207 timeNow = SystemClock.uptimeMillis(); 2208 if (timeNow > timeEnd) { 2209 SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out"); 2210 Slog.wtf(TAG, "cppreopt did not finish!"); 2211 break; 2212 } 2213 } 2214 2215 Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms"); 2216 } 2217 } 2218 2219 public PackageManagerService(Context context, Installer installer, 2220 boolean factoryTest, boolean onlyCore) { 2221 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager"); 2222 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2223 SystemClock.uptimeMillis()); 2224 2225 if (mSdkVersion <= 0) { 2226 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2227 } 2228 2229 mContext = context; 2230 2231 mPermissionReviewRequired = context.getResources().getBoolean( 2232 R.bool.config_permissionReviewRequired); 2233 2234 mFactoryTest = factoryTest; 2235 mOnlyCore = onlyCore; 2236 mMetrics = new DisplayMetrics(); 2237 mSettings = new Settings(mPackages); 2238 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2239 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2240 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2241 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2242 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2243 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2244 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2245 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2246 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2247 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2248 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2249 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2250 2251 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2252 if (separateProcesses != null && separateProcesses.length() > 0) { 2253 if ("*".equals(separateProcesses)) { 2254 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2255 mSeparateProcesses = null; 2256 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2257 } else { 2258 mDefParseFlags = 0; 2259 mSeparateProcesses = separateProcesses.split(","); 2260 Slog.w(TAG, "Running with debug.separate_processes: " 2261 + separateProcesses); 2262 } 2263 } else { 2264 mDefParseFlags = 0; 2265 mSeparateProcesses = null; 2266 } 2267 2268 mInstaller = installer; 2269 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2270 "*dexopt*"); 2271 mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock); 2272 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2273 2274 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2275 FgThread.get().getLooper()); 2276 2277 getDefaultDisplayMetrics(context, mMetrics); 2278 2279 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config"); 2280 SystemConfig systemConfig = SystemConfig.getInstance(); 2281 mGlobalGids = systemConfig.getGlobalGids(); 2282 mSystemPermissions = systemConfig.getSystemPermissions(); 2283 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2284 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2285 2286 mProtectedPackages = new ProtectedPackages(mContext); 2287 2288 synchronized (mInstallLock) { 2289 // writer 2290 synchronized (mPackages) { 2291 mHandlerThread = new ServiceThread(TAG, 2292 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2293 mHandlerThread.start(); 2294 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2295 mProcessLoggingHandler = new ProcessLoggingHandler(); 2296 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2297 2298 mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this); 2299 mInstantAppRegistry = new InstantAppRegistry(this); 2300 2301 File dataDir = Environment.getDataDirectory(); 2302 mAppInstallDir = new File(dataDir, "app"); 2303 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2304 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2305 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2306 sUserManager = new UserManagerService(context, this, 2307 new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages); 2308 2309 // Propagate permission configuration in to package manager. 2310 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2311 = systemConfig.getPermissions(); 2312 for (int i=0; i<permConfig.size(); i++) { 2313 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2314 BasePermission bp = mSettings.mPermissions.get(perm.name); 2315 if (bp == null) { 2316 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2317 mSettings.mPermissions.put(perm.name, bp); 2318 } 2319 if (perm.gids != null) { 2320 bp.setGids(perm.gids, perm.perUser); 2321 } 2322 } 2323 2324 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2325 final int builtInLibCount = libConfig.size(); 2326 for (int i = 0; i < builtInLibCount; i++) { 2327 String name = libConfig.keyAt(i); 2328 String path = libConfig.valueAt(i); 2329 addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED, 2330 SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0); 2331 } 2332 2333 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2334 2335 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings"); 2336 mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false)); 2337 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2338 2339 // Clean up orphaned packages for which the code path doesn't exist 2340 // and they are an update to a system app - caused by bug/32321269 2341 final int packageSettingCount = mSettings.mPackages.size(); 2342 for (int i = packageSettingCount - 1; i >= 0; i--) { 2343 PackageSetting ps = mSettings.mPackages.valueAt(i); 2344 if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists()) 2345 && mSettings.getDisabledSystemPkgLPr(ps.name) != null) { 2346 mSettings.mPackages.removeAt(i); 2347 mSettings.enableSystemPackageLPw(ps.name); 2348 } 2349 } 2350 2351 if (mFirstBoot) { 2352 requestCopyPreoptedFiles(); 2353 } 2354 2355 String customResolverActivity = Resources.getSystem().getString( 2356 R.string.config_customResolverActivity); 2357 if (TextUtils.isEmpty(customResolverActivity)) { 2358 customResolverActivity = null; 2359 } else { 2360 mCustomResolverComponentName = ComponentName.unflattenFromString( 2361 customResolverActivity); 2362 } 2363 2364 long startTime = SystemClock.uptimeMillis(); 2365 2366 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2367 startTime); 2368 2369 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2370 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2371 2372 if (bootClassPath == null) { 2373 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2374 } 2375 2376 if (systemServerClassPath == null) { 2377 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2378 } 2379 2380 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2381 final String[] dexCodeInstructionSets = 2382 getDexCodeInstructionSets( 2383 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2384 2385 /** 2386 * Ensure all external libraries have had dexopt run on them. 2387 */ 2388 if (mSharedLibraries.size() > 0) { 2389 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 2390 // NOTE: For now, we're compiling these system "shared libraries" 2391 // (and framework jars) into all available architectures. It's possible 2392 // to compile them only when we come across an app that uses them (there's 2393 // already logic for that in scanPackageLI) but that adds some complexity. 2394 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2395 final int libCount = mSharedLibraries.size(); 2396 for (int i = 0; i < libCount; i++) { 2397 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 2398 final int versionCount = versionedLib.size(); 2399 for (int j = 0; j < versionCount; j++) { 2400 SharedLibraryEntry libEntry = versionedLib.valueAt(j); 2401 final String libPath = libEntry.path != null 2402 ? libEntry.path : libEntry.apk; 2403 if (libPath == null) { 2404 continue; 2405 } 2406 try { 2407 // Shared libraries do not have profiles so we perform a full 2408 // AOT compilation (if needed). 2409 int dexoptNeeded = DexFile.getDexOptNeeded( 2410 libPath, dexCodeInstructionSet, 2411 getCompilerFilterForReason(REASON_SHARED_APK), 2412 false /* newProfile */); 2413 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2414 mInstaller.dexopt(libPath, Process.SYSTEM_UID, "*", 2415 dexCodeInstructionSet, dexoptNeeded, null, 2416 DEXOPT_PUBLIC, 2417 getCompilerFilterForReason(REASON_SHARED_APK), 2418 StorageManager.UUID_PRIVATE_INTERNAL, 2419 PackageDexOptimizer.SKIP_SHARED_LIBRARY_CHECK); 2420 } 2421 } catch (FileNotFoundException e) { 2422 Slog.w(TAG, "Library not found: " + libPath); 2423 } catch (IOException | InstallerException e) { 2424 Slog.w(TAG, "Cannot dexopt " + libPath + "; is it an APK or JAR? " 2425 + e.getMessage()); 2426 } 2427 } 2428 } 2429 } 2430 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2431 } 2432 2433 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2434 2435 final VersionInfo ver = mSettings.getInternalVersion(); 2436 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2437 2438 // when upgrading from pre-M, promote system app permissions from install to runtime 2439 mPromoteSystemApps = 2440 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2441 2442 // When upgrading from pre-N, we need to handle package extraction like first boot, 2443 // as there is no profiling data available. 2444 mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N; 2445 2446 mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1; 2447 2448 // save off the names of pre-existing system packages prior to scanning; we don't 2449 // want to automatically grant runtime permissions for new system apps 2450 if (mPromoteSystemApps) { 2451 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2452 while (pkgSettingIter.hasNext()) { 2453 PackageSetting ps = pkgSettingIter.next(); 2454 if (isSystemApp(ps)) { 2455 mExistingSystemPackages.add(ps.name); 2456 } 2457 } 2458 } 2459 2460 mCacheDir = preparePackageParserCache(mIsUpgrade); 2461 2462 // Set flag to monitor and not change apk file paths when 2463 // scanning install directories. 2464 int scanFlags = SCAN_BOOTING | SCAN_INITIAL; 2465 2466 if (mIsUpgrade || mFirstBoot) { 2467 scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE; 2468 } 2469 2470 // Collect vendor overlay packages. (Do this before scanning any apps.) 2471 // For security and version matching reason, only consider 2472 // overlay packages if they reside in the right directory. 2473 String overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PERSIST_PROPERTY); 2474 if (overlayThemeDir.isEmpty()) { 2475 overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PROPERTY); 2476 } 2477 if (!overlayThemeDir.isEmpty()) { 2478 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR, overlayThemeDir), mDefParseFlags 2479 | PackageParser.PARSE_IS_SYSTEM 2480 | PackageParser.PARSE_IS_SYSTEM_DIR 2481 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2482 } 2483 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags 2484 | PackageParser.PARSE_IS_SYSTEM 2485 | PackageParser.PARSE_IS_SYSTEM_DIR 2486 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2487 2488 // Find base frameworks (resource packages without code). 2489 scanDirTracedLI(frameworkDir, mDefParseFlags 2490 | PackageParser.PARSE_IS_SYSTEM 2491 | PackageParser.PARSE_IS_SYSTEM_DIR 2492 | PackageParser.PARSE_IS_PRIVILEGED, 2493 scanFlags | SCAN_NO_DEX, 0); 2494 2495 // Collected privileged system packages. 2496 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2497 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2498 | PackageParser.PARSE_IS_SYSTEM 2499 | PackageParser.PARSE_IS_SYSTEM_DIR 2500 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2501 2502 // Collect ordinary system packages. 2503 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2504 scanDirTracedLI(systemAppDir, mDefParseFlags 2505 | PackageParser.PARSE_IS_SYSTEM 2506 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2507 2508 // Collect all vendor packages. 2509 File vendorAppDir = new File("/vendor/app"); 2510 try { 2511 vendorAppDir = vendorAppDir.getCanonicalFile(); 2512 } catch (IOException e) { 2513 // failed to look up canonical path, continue with original one 2514 } 2515 scanDirTracedLI(vendorAppDir, mDefParseFlags 2516 | PackageParser.PARSE_IS_SYSTEM 2517 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2518 2519 // Collect all OEM packages. 2520 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2521 scanDirTracedLI(oemAppDir, mDefParseFlags 2522 | PackageParser.PARSE_IS_SYSTEM 2523 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2524 2525 // Prune any system packages that no longer exist. 2526 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2527 if (!mOnlyCore) { 2528 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2529 while (psit.hasNext()) { 2530 PackageSetting ps = psit.next(); 2531 2532 /* 2533 * If this is not a system app, it can't be a 2534 * disable system app. 2535 */ 2536 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2537 continue; 2538 } 2539 2540 /* 2541 * If the package is scanned, it's not erased. 2542 */ 2543 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2544 if (scannedPkg != null) { 2545 /* 2546 * If the system app is both scanned and in the 2547 * disabled packages list, then it must have been 2548 * added via OTA. Remove it from the currently 2549 * scanned package so the previously user-installed 2550 * application can be scanned. 2551 */ 2552 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2553 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2554 + ps.name + "; removing system app. Last known codePath=" 2555 + ps.codePathString + ", installStatus=" + ps.installStatus 2556 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2557 + scannedPkg.mVersionCode); 2558 removePackageLI(scannedPkg, true); 2559 mExpectingBetter.put(ps.name, ps.codePath); 2560 } 2561 2562 continue; 2563 } 2564 2565 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2566 psit.remove(); 2567 logCriticalInfo(Log.WARN, "System package " + ps.name 2568 + " no longer exists; it's data will be wiped"); 2569 // Actual deletion of code and data will be handled by later 2570 // reconciliation step 2571 } else { 2572 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2573 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2574 possiblyDeletedUpdatedSystemApps.add(ps.name); 2575 } 2576 } 2577 } 2578 } 2579 2580 //look for any incomplete package installations 2581 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2582 for (int i = 0; i < deletePkgsList.size(); i++) { 2583 // Actual deletion of code and data will be handled by later 2584 // reconciliation step 2585 final String packageName = deletePkgsList.get(i).name; 2586 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2587 synchronized (mPackages) { 2588 mSettings.removePackageLPw(packageName); 2589 } 2590 } 2591 2592 //delete tmp files 2593 deleteTempPackageFiles(); 2594 2595 // Remove any shared userIDs that have no associated packages 2596 mSettings.pruneSharedUsersLPw(); 2597 2598 if (!mOnlyCore) { 2599 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2600 SystemClock.uptimeMillis()); 2601 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2602 2603 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2604 | PackageParser.PARSE_FORWARD_LOCK, 2605 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2606 2607 /** 2608 * Remove disable package settings for any updated system 2609 * apps that were removed via an OTA. If they're not a 2610 * previously-updated app, remove them completely. 2611 * Otherwise, just revoke their system-level permissions. 2612 */ 2613 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2614 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2615 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2616 2617 String msg; 2618 if (deletedPkg == null) { 2619 msg = "Updated system package " + deletedAppName 2620 + " no longer exists; it's data will be wiped"; 2621 // Actual deletion of code and data will be handled by later 2622 // reconciliation step 2623 } else { 2624 msg = "Updated system app + " + deletedAppName 2625 + " no longer present; removing system privileges for " 2626 + deletedAppName; 2627 2628 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2629 2630 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2631 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2632 } 2633 logCriticalInfo(Log.WARN, msg); 2634 } 2635 2636 /** 2637 * Make sure all system apps that we expected to appear on 2638 * the userdata partition actually showed up. If they never 2639 * appeared, crawl back and revive the system version. 2640 */ 2641 for (int i = 0; i < mExpectingBetter.size(); i++) { 2642 final String packageName = mExpectingBetter.keyAt(i); 2643 if (!mPackages.containsKey(packageName)) { 2644 final File scanFile = mExpectingBetter.valueAt(i); 2645 2646 logCriticalInfo(Log.WARN, "Expected better " + packageName 2647 + " but never showed up; reverting to system"); 2648 2649 int reparseFlags = mDefParseFlags; 2650 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2651 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2652 | PackageParser.PARSE_IS_SYSTEM_DIR 2653 | PackageParser.PARSE_IS_PRIVILEGED; 2654 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2655 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2656 | PackageParser.PARSE_IS_SYSTEM_DIR; 2657 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2658 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2659 | PackageParser.PARSE_IS_SYSTEM_DIR; 2660 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2661 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2662 | PackageParser.PARSE_IS_SYSTEM_DIR; 2663 } else { 2664 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2665 continue; 2666 } 2667 2668 mSettings.enableSystemPackageLPw(packageName); 2669 2670 try { 2671 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2672 } catch (PackageManagerException e) { 2673 Slog.e(TAG, "Failed to parse original system package: " 2674 + e.getMessage()); 2675 } 2676 } 2677 } 2678 } 2679 mExpectingBetter.clear(); 2680 2681 // Resolve the storage manager. 2682 mStorageManagerPackage = getStorageManagerPackageName(); 2683 2684 // Resolve protected action filters. Only the setup wizard is allowed to 2685 // have a high priority filter for these actions. 2686 mSetupWizardPackage = getSetupWizardPackageName(); 2687 if (mProtectedFilters.size() > 0) { 2688 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2689 Slog.i(TAG, "No setup wizard;" 2690 + " All protected intents capped to priority 0"); 2691 } 2692 for (ActivityIntentInfo filter : mProtectedFilters) { 2693 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2694 if (DEBUG_FILTERS) { 2695 Slog.i(TAG, "Found setup wizard;" 2696 + " allow priority " + filter.getPriority() + ";" 2697 + " package: " + filter.activity.info.packageName 2698 + " activity: " + filter.activity.className 2699 + " priority: " + filter.getPriority()); 2700 } 2701 // skip setup wizard; allow it to keep the high priority filter 2702 continue; 2703 } 2704 Slog.w(TAG, "Protected action; cap priority to 0;" 2705 + " package: " + filter.activity.info.packageName 2706 + " activity: " + filter.activity.className 2707 + " origPrio: " + filter.getPriority()); 2708 filter.setPriority(0); 2709 } 2710 } 2711 mDeferProtectedFilters = false; 2712 mProtectedFilters.clear(); 2713 2714 // Now that we know all of the shared libraries, update all clients to have 2715 // the correct library paths. 2716 updateAllSharedLibrariesLPw(null); 2717 2718 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2719 // NOTE: We ignore potential failures here during a system scan (like 2720 // the rest of the commands above) because there's precious little we 2721 // can do about it. A settings error is reported, though. 2722 adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/); 2723 } 2724 2725 // Now that we know all the packages we are keeping, 2726 // read and update their last usage times. 2727 mPackageUsage.read(mPackages); 2728 mCompilerStats.read(); 2729 2730 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2731 SystemClock.uptimeMillis()); 2732 Slog.i(TAG, "Time to scan packages: " 2733 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2734 + " seconds"); 2735 2736 // If the platform SDK has changed since the last time we booted, 2737 // we need to re-grant app permission to catch any new ones that 2738 // appear. This is really a hack, and means that apps can in some 2739 // cases get permissions that the user didn't initially explicitly 2740 // allow... it would be nice to have some better way to handle 2741 // this situation. 2742 int updateFlags = UPDATE_PERMISSIONS_ALL; 2743 if (ver.sdkVersion != mSdkVersion) { 2744 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2745 + mSdkVersion + "; regranting permissions for internal storage"); 2746 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2747 } 2748 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2749 ver.sdkVersion = mSdkVersion; 2750 2751 // If this is the first boot or an update from pre-M, and it is a normal 2752 // boot, then we need to initialize the default preferred apps across 2753 // all defined users. 2754 if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) { 2755 for (UserInfo user : sUserManager.getUsers(true)) { 2756 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2757 applyFactoryDefaultBrowserLPw(user.id); 2758 primeDomainVerificationsLPw(user.id); 2759 } 2760 } 2761 2762 // Prepare storage for system user really early during boot, 2763 // since core system apps like SettingsProvider and SystemUI 2764 // can't wait for user to start 2765 final int storageFlags; 2766 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2767 storageFlags = StorageManager.FLAG_STORAGE_DE; 2768 } else { 2769 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2770 } 2771 List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, 2772 UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */, 2773 true /* onlyCoreApps */); 2774 mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> { 2775 if (deferPackages == null || deferPackages.isEmpty()) { 2776 return; 2777 } 2778 int count = 0; 2779 for (String pkgName : deferPackages) { 2780 PackageParser.Package pkg = null; 2781 synchronized (mPackages) { 2782 PackageSetting ps = mSettings.getPackageLPr(pkgName); 2783 if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) { 2784 pkg = ps.pkg; 2785 } 2786 } 2787 if (pkg != null) { 2788 synchronized (mInstallLock) { 2789 prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags, 2790 true /* maybeMigrateAppData */); 2791 } 2792 count++; 2793 } 2794 } 2795 Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages"); 2796 }, "prepareAppData"); 2797 2798 // If this is first boot after an OTA, and a normal boot, then 2799 // we need to clear code cache directories. 2800 // Note that we do *not* clear the application profiles. These remain valid 2801 // across OTAs and are used to drive profile verification (post OTA) and 2802 // profile compilation (without waiting to collect a fresh set of profiles). 2803 if (mIsUpgrade && !onlyCore) { 2804 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2805 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2806 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2807 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2808 // No apps are running this early, so no need to freeze 2809 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2810 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2811 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2812 } 2813 } 2814 ver.fingerprint = Build.FINGERPRINT; 2815 } 2816 2817 checkDefaultBrowser(); 2818 2819 // clear only after permissions and other defaults have been updated 2820 mExistingSystemPackages.clear(); 2821 mPromoteSystemApps = false; 2822 2823 // All the changes are done during package scanning. 2824 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2825 2826 // can downgrade to reader 2827 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings"); 2828 mSettings.writeLPr(); 2829 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2830 2831 // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty 2832 // early on (before the package manager declares itself as early) because other 2833 // components in the system server might ask for package contexts for these apps. 2834 // 2835 // Note that "onlyCore" in this context means the system is encrypted or encrypting 2836 // (i.e, that the data partition is unavailable). 2837 if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) { 2838 long start = System.nanoTime(); 2839 List<PackageParser.Package> coreApps = new ArrayList<>(); 2840 for (PackageParser.Package pkg : mPackages.values()) { 2841 if (pkg.coreApp) { 2842 coreApps.add(pkg); 2843 } 2844 } 2845 2846 int[] stats = performDexOptUpgrade(coreApps, false, 2847 getCompilerFilterForReason(REASON_CORE_APP)); 2848 2849 final int elapsedTimeSeconds = 2850 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start); 2851 MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds); 2852 2853 if (DEBUG_DEXOPT) { 2854 Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" + 2855 stats[0] + ", " + stats[1] + ", " + stats[2] + ")"); 2856 } 2857 2858 2859 // TODO: Should we log these stats to tron too ? 2860 // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]); 2861 // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]); 2862 // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]); 2863 // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size()); 2864 } 2865 2866 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2867 SystemClock.uptimeMillis()); 2868 2869 if (!mOnlyCore) { 2870 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2871 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2872 mRequiredUninstallerPackage = getRequiredUninstallerLPr(); 2873 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2874 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2875 mIntentFilterVerifierComponent); 2876 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2877 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES, 2878 SharedLibraryInfo.VERSION_UNDEFINED); 2879 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2880 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED, 2881 SharedLibraryInfo.VERSION_UNDEFINED); 2882 } else { 2883 mRequiredVerifierPackage = null; 2884 mRequiredInstallerPackage = null; 2885 mRequiredUninstallerPackage = null; 2886 mIntentFilterVerifierComponent = null; 2887 mIntentFilterVerifier = null; 2888 mServicesSystemSharedLibraryPackageName = null; 2889 mSharedSystemSharedLibraryPackageName = null; 2890 } 2891 2892 mInstallerService = new PackageInstallerService(context, this); 2893 2894 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2895 if (ephemeralResolverComponent != null) { 2896 if (DEBUG_EPHEMERAL) { 2897 Slog.i(TAG, "Ephemeral resolver: " + ephemeralResolverComponent); 2898 } 2899 mInstantAppResolverConnection = 2900 new EphemeralResolverConnection(mContext, ephemeralResolverComponent); 2901 } else { 2902 mInstantAppResolverConnection = null; 2903 } 2904 mInstantAppInstallerComponent = getEphemeralInstallerLPr(); 2905 if (mInstantAppInstallerComponent != null) { 2906 if (DEBUG_EPHEMERAL) { 2907 Slog.i(TAG, "Ephemeral installer: " + mInstantAppInstallerComponent); 2908 } 2909 setUpInstantAppInstallerActivityLP(mInstantAppInstallerComponent); 2910 } 2911 2912 // Read and update the usage of dex files. 2913 // Do this at the end of PM init so that all the packages have their 2914 // data directory reconciled. 2915 // At this point we know the code paths of the packages, so we can validate 2916 // the disk file and build the internal cache. 2917 // The usage file is expected to be small so loading and verifying it 2918 // should take a fairly small time compare to the other activities (e.g. package 2919 // scanning). 2920 final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>(); 2921 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 2922 for (int userId : currentUserIds) { 2923 userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList()); 2924 } 2925 mDexManager.load(userPackages); 2926 } // synchronized (mPackages) 2927 } // synchronized (mInstallLock) 2928 2929 // Now after opening every single application zip, make sure they 2930 // are all flushed. Not really needed, but keeps things nice and 2931 // tidy. 2932 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC"); 2933 Runtime.getRuntime().gc(); 2934 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2935 2936 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks"); 2937 FallbackCategoryProvider.loadFallbacks(); 2938 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2939 2940 // The initial scanning above does many calls into installd while 2941 // holding the mPackages lock, but we're mostly interested in yelling 2942 // once we have a booted system. 2943 mInstaller.setWarnIfHeld(mPackages); 2944 2945 // Expose private service for system components to use. 2946 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2947 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2948 } 2949 2950 private static File preparePackageParserCache(boolean isUpgrade) { 2951 if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) { 2952 return null; 2953 } 2954 2955 // Disable package parsing on eng builds to allow for faster incremental development. 2956 if ("eng".equals(Build.TYPE)) { 2957 return null; 2958 } 2959 2960 if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) { 2961 Slog.i(TAG, "Disabling package parser cache due to system property."); 2962 return null; 2963 } 2964 2965 // The base directory for the package parser cache lives under /data/system/. 2966 final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(), 2967 "package_cache"); 2968 if (cacheBaseDir == null) { 2969 return null; 2970 } 2971 2972 // If this is a system upgrade scenario, delete the contents of the package cache dir. 2973 // This also serves to "GC" unused entries when the package cache version changes (which 2974 // can only happen during upgrades). 2975 if (isUpgrade) { 2976 FileUtils.deleteContents(cacheBaseDir); 2977 } 2978 2979 2980 // Return the versioned package cache directory. This is something like 2981 // "/data/system/package_cache/1" 2982 File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION); 2983 2984 // The following is a workaround to aid development on non-numbered userdebug 2985 // builds or cases where "adb sync" is used on userdebug builds. If we detect that 2986 // the system partition is newer. 2987 // 2988 // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build 2989 // that starts with "eng." to signify that this is an engineering build and not 2990 // destined for release. 2991 if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) { 2992 Slog.w(TAG, "Wiping cache directory because the system partition changed."); 2993 2994 // Heuristic: If the /system directory has been modified recently due to an "adb sync" 2995 // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable 2996 // in general and should not be used for production changes. In this specific case, 2997 // we know that they will work. 2998 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2999 if (cacheDir.lastModified() < frameworkDir.lastModified()) { 3000 FileUtils.deleteContents(cacheBaseDir); 3001 cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION); 3002 } 3003 } 3004 3005 return cacheDir; 3006 } 3007 3008 @Override 3009 public boolean isFirstBoot() { 3010 return mFirstBoot; 3011 } 3012 3013 @Override 3014 public boolean isOnlyCoreApps() { 3015 return mOnlyCore; 3016 } 3017 3018 @Override 3019 public boolean isUpgrade() { 3020 return mIsUpgrade; 3021 } 3022 3023 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 3024 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 3025 3026 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 3027 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3028 UserHandle.USER_SYSTEM); 3029 if (matches.size() == 1) { 3030 return matches.get(0).getComponentInfo().packageName; 3031 } else if (matches.size() == 0) { 3032 Log.e(TAG, "There should probably be a verifier, but, none were found"); 3033 return null; 3034 } 3035 throw new RuntimeException("There must be exactly one verifier; found " + matches); 3036 } 3037 3038 private @NonNull String getRequiredSharedLibraryLPr(String name, int version) { 3039 synchronized (mPackages) { 3040 SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version); 3041 if (libraryEntry == null) { 3042 throw new IllegalStateException("Missing required shared library:" + name); 3043 } 3044 return libraryEntry.apk; 3045 } 3046 } 3047 3048 private @NonNull String getRequiredInstallerLPr() { 3049 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 3050 intent.addCategory(Intent.CATEGORY_DEFAULT); 3051 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 3052 3053 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3054 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3055 UserHandle.USER_SYSTEM); 3056 if (matches.size() == 1) { 3057 ResolveInfo resolveInfo = matches.get(0); 3058 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 3059 throw new RuntimeException("The installer must be a privileged app"); 3060 } 3061 return matches.get(0).getComponentInfo().packageName; 3062 } else { 3063 throw new RuntimeException("There must be exactly one installer; found " + matches); 3064 } 3065 } 3066 3067 private @NonNull String getRequiredUninstallerLPr() { 3068 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 3069 intent.addCategory(Intent.CATEGORY_DEFAULT); 3070 intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null)); 3071 3072 final ResolveInfo resolveInfo = resolveIntent(intent, null, 3073 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3074 UserHandle.USER_SYSTEM); 3075 if (resolveInfo == null || 3076 mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) { 3077 throw new RuntimeException("There must be exactly one uninstaller; found " 3078 + resolveInfo); 3079 } 3080 return resolveInfo.getComponentInfo().packageName; 3081 } 3082 3083 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 3084 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 3085 3086 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 3087 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3088 UserHandle.USER_SYSTEM); 3089 ResolveInfo best = null; 3090 final int N = matches.size(); 3091 for (int i = 0; i < N; i++) { 3092 final ResolveInfo cur = matches.get(i); 3093 final String packageName = cur.getComponentInfo().packageName; 3094 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 3095 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 3096 continue; 3097 } 3098 3099 if (best == null || cur.priority > best.priority) { 3100 best = cur; 3101 } 3102 } 3103 3104 if (best != null) { 3105 return best.getComponentInfo().getComponentName(); 3106 } else { 3107 throw new RuntimeException("There must be at least one intent filter verifier"); 3108 } 3109 } 3110 3111 private @Nullable ComponentName getEphemeralResolverLPr() { 3112 final String[] packageArray = 3113 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 3114 if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) { 3115 if (DEBUG_EPHEMERAL) { 3116 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 3117 } 3118 return null; 3119 } 3120 3121 final int resolveFlags = 3122 MATCH_DIRECT_BOOT_AWARE 3123 | MATCH_DIRECT_BOOT_UNAWARE 3124 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3125 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 3126 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 3127 resolveFlags, UserHandle.USER_SYSTEM); 3128 3129 final int N = resolvers.size(); 3130 if (N == 0) { 3131 if (DEBUG_EPHEMERAL) { 3132 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 3133 } 3134 return null; 3135 } 3136 3137 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 3138 for (int i = 0; i < N; i++) { 3139 final ResolveInfo info = resolvers.get(i); 3140 3141 if (info.serviceInfo == null) { 3142 continue; 3143 } 3144 3145 final String packageName = info.serviceInfo.packageName; 3146 if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) { 3147 if (DEBUG_EPHEMERAL) { 3148 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 3149 + " pkg: " + packageName + ", info:" + info); 3150 } 3151 continue; 3152 } 3153 3154 if (DEBUG_EPHEMERAL) { 3155 Slog.v(TAG, "Ephemeral resolver found;" 3156 + " pkg: " + packageName + ", info:" + info); 3157 } 3158 return new ComponentName(packageName, info.serviceInfo.name); 3159 } 3160 if (DEBUG_EPHEMERAL) { 3161 Slog.v(TAG, "Ephemeral resolver NOT found"); 3162 } 3163 return null; 3164 } 3165 3166 private @Nullable ComponentName getEphemeralInstallerLPr() { 3167 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 3168 intent.addCategory(Intent.CATEGORY_DEFAULT); 3169 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 3170 3171 final int resolveFlags = 3172 MATCH_DIRECT_BOOT_AWARE 3173 | MATCH_DIRECT_BOOT_UNAWARE 3174 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3175 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3176 resolveFlags, UserHandle.USER_SYSTEM); 3177 Iterator<ResolveInfo> iter = matches.iterator(); 3178 while (iter.hasNext()) { 3179 final ResolveInfo rInfo = iter.next(); 3180 final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName); 3181 if (ps != null) { 3182 final PermissionsState permissionsState = ps.getPermissionsState(); 3183 if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) { 3184 continue; 3185 } 3186 } 3187 iter.remove(); 3188 } 3189 if (matches.size() == 0) { 3190 return null; 3191 } else if (matches.size() == 1) { 3192 return matches.get(0).getComponentInfo().getComponentName(); 3193 } else { 3194 throw new RuntimeException( 3195 "There must be at most one ephemeral installer; found " + matches); 3196 } 3197 } 3198 3199 private void primeDomainVerificationsLPw(int userId) { 3200 if (DEBUG_DOMAIN_VERIFICATION) { 3201 Slog.d(TAG, "Priming domain verifications in user " + userId); 3202 } 3203 3204 SystemConfig systemConfig = SystemConfig.getInstance(); 3205 ArraySet<String> packages = systemConfig.getLinkedApps(); 3206 3207 for (String packageName : packages) { 3208 PackageParser.Package pkg = mPackages.get(packageName); 3209 if (pkg != null) { 3210 if (!pkg.isSystemApp()) { 3211 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 3212 continue; 3213 } 3214 3215 ArraySet<String> domains = null; 3216 for (PackageParser.Activity a : pkg.activities) { 3217 for (ActivityIntentInfo filter : a.intents) { 3218 if (hasValidDomains(filter)) { 3219 if (domains == null) { 3220 domains = new ArraySet<String>(); 3221 } 3222 domains.addAll(filter.getHostsList()); 3223 } 3224 } 3225 } 3226 3227 if (domains != null && domains.size() > 0) { 3228 if (DEBUG_DOMAIN_VERIFICATION) { 3229 Slog.v(TAG, " + " + packageName); 3230 } 3231 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 3232 // state w.r.t. the formal app-linkage "no verification attempted" state; 3233 // and then 'always' in the per-user state actually used for intent resolution. 3234 final IntentFilterVerificationInfo ivi; 3235 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains); 3236 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 3237 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 3238 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 3239 } else { 3240 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 3241 + "' does not handle web links"); 3242 } 3243 } else { 3244 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 3245 } 3246 } 3247 3248 scheduleWritePackageRestrictionsLocked(userId); 3249 scheduleWriteSettingsLocked(); 3250 } 3251 3252 private void applyFactoryDefaultBrowserLPw(int userId) { 3253 // The default browser app's package name is stored in a string resource, 3254 // with a product-specific overlay used for vendor customization. 3255 String browserPkg = mContext.getResources().getString( 3256 com.android.internal.R.string.default_browser); 3257 if (!TextUtils.isEmpty(browserPkg)) { 3258 // non-empty string => required to be a known package 3259 PackageSetting ps = mSettings.mPackages.get(browserPkg); 3260 if (ps == null) { 3261 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 3262 browserPkg = null; 3263 } else { 3264 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3265 } 3266 } 3267 3268 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3269 // default. If there's more than one, just leave everything alone. 3270 if (browserPkg == null) { 3271 calculateDefaultBrowserLPw(userId); 3272 } 3273 } 3274 3275 private void calculateDefaultBrowserLPw(int userId) { 3276 List<String> allBrowsers = resolveAllBrowserApps(userId); 3277 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3278 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3279 } 3280 3281 private List<String> resolveAllBrowserApps(int userId) { 3282 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3283 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3284 PackageManager.MATCH_ALL, userId); 3285 3286 final int count = list.size(); 3287 List<String> result = new ArrayList<String>(count); 3288 for (int i=0; i<count; i++) { 3289 ResolveInfo info = list.get(i); 3290 if (info.activityInfo == null 3291 || !info.handleAllWebDataURI 3292 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3293 || result.contains(info.activityInfo.packageName)) { 3294 continue; 3295 } 3296 result.add(info.activityInfo.packageName); 3297 } 3298 3299 return result; 3300 } 3301 3302 private boolean packageIsBrowser(String packageName, int userId) { 3303 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3304 PackageManager.MATCH_ALL, userId); 3305 final int N = list.size(); 3306 for (int i = 0; i < N; i++) { 3307 ResolveInfo info = list.get(i); 3308 if (packageName.equals(info.activityInfo.packageName)) { 3309 return true; 3310 } 3311 } 3312 return false; 3313 } 3314 3315 private void checkDefaultBrowser() { 3316 final int myUserId = UserHandle.myUserId(); 3317 final String packageName = getDefaultBrowserPackageName(myUserId); 3318 if (packageName != null) { 3319 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3320 if (info == null) { 3321 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3322 synchronized (mPackages) { 3323 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3324 } 3325 } 3326 } 3327 } 3328 3329 @Override 3330 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3331 throws RemoteException { 3332 try { 3333 return super.onTransact(code, data, reply, flags); 3334 } catch (RuntimeException e) { 3335 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3336 Slog.wtf(TAG, "Package Manager Crash", e); 3337 } 3338 throw e; 3339 } 3340 } 3341 3342 static int[] appendInts(int[] cur, int[] add) { 3343 if (add == null) return cur; 3344 if (cur == null) return add; 3345 final int N = add.length; 3346 for (int i=0; i<N; i++) { 3347 cur = appendInt(cur, add[i]); 3348 } 3349 return cur; 3350 } 3351 3352 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3353 if (!sUserManager.exists(userId)) return null; 3354 if (ps == null) { 3355 return null; 3356 } 3357 final PackageParser.Package p = ps.pkg; 3358 if (p == null) { 3359 return null; 3360 } 3361 // Filter out ephemeral app metadata: 3362 // * The system/shell/root can see metadata for any app 3363 // * An installed app can see metadata for 1) other installed apps 3364 // and 2) ephemeral apps that have explicitly interacted with it 3365 // * Ephemeral apps can only see their own metadata 3366 // * Holding a signature permission allows seeing instant apps 3367 final int callingAppId = UserHandle.getAppId(Binder.getCallingUid()); 3368 if (callingAppId != Process.SYSTEM_UID 3369 && callingAppId != Process.SHELL_UID 3370 && callingAppId != Process.ROOT_UID 3371 && checkUidPermission(Manifest.permission.ACCESS_INSTANT_APPS, 3372 Binder.getCallingUid()) != PackageManager.PERMISSION_GRANTED) { 3373 final String instantAppPackageName = getInstantAppPackageName(Binder.getCallingUid()); 3374 if (instantAppPackageName != null) { 3375 // ephemeral apps can only get information on themselves 3376 if (!instantAppPackageName.equals(p.packageName)) { 3377 return null; 3378 } 3379 } else { 3380 if (ps.getInstantApp(userId)) { 3381 // only get access to the ephemeral app if we've been granted access 3382 if (!mInstantAppRegistry.isInstantAccessGranted( 3383 userId, callingAppId, ps.appId)) { 3384 return null; 3385 } 3386 } 3387 } 3388 } 3389 3390 final PermissionsState permissionsState = ps.getPermissionsState(); 3391 3392 // Compute GIDs only if requested 3393 final int[] gids = (flags & PackageManager.GET_GIDS) == 0 3394 ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId); 3395 // Compute granted permissions only if package has requested permissions 3396 final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions) 3397 ? Collections.<String>emptySet() : permissionsState.getPermissions(userId); 3398 final PackageUserState state = ps.readUserState(userId); 3399 3400 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0 3401 && ps.isSystem()) { 3402 flags |= MATCH_ANY_USER; 3403 } 3404 3405 PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags, 3406 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3407 3408 if (packageInfo == null) { 3409 return null; 3410 } 3411 3412 packageInfo.packageName = packageInfo.applicationInfo.packageName = 3413 resolveExternalPackageNameLPr(p); 3414 3415 return packageInfo; 3416 } 3417 3418 @Override 3419 public void checkPackageStartable(String packageName, int userId) { 3420 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3421 3422 synchronized (mPackages) { 3423 final PackageSetting ps = mSettings.mPackages.get(packageName); 3424 if (ps == null) { 3425 throw new SecurityException("Package " + packageName + " was not found!"); 3426 } 3427 3428 if (!ps.getInstalled(userId)) { 3429 throw new SecurityException( 3430 "Package " + packageName + " was not installed for user " + userId + "!"); 3431 } 3432 3433 if (mSafeMode && !ps.isSystem()) { 3434 throw new SecurityException("Package " + packageName + " not a system app!"); 3435 } 3436 3437 if (mFrozenPackages.contains(packageName)) { 3438 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3439 } 3440 3441 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3442 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3443 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3444 } 3445 } 3446 } 3447 3448 @Override 3449 public boolean isPackageAvailable(String packageName, int userId) { 3450 if (!sUserManager.exists(userId)) return false; 3451 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3452 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3453 synchronized (mPackages) { 3454 PackageParser.Package p = mPackages.get(packageName); 3455 if (p != null) { 3456 final PackageSetting ps = (PackageSetting) p.mExtras; 3457 if (ps != null) { 3458 final PackageUserState state = ps.readUserState(userId); 3459 if (state != null) { 3460 return PackageParser.isAvailable(state); 3461 } 3462 } 3463 } 3464 } 3465 return false; 3466 } 3467 3468 @Override 3469 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3470 return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST, 3471 flags, userId); 3472 } 3473 3474 @Override 3475 public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage, 3476 int flags, int userId) { 3477 return getPackageInfoInternal(versionedPackage.getPackageName(), 3478 // TODO: We will change version code to long, so in the new API it is long 3479 (int) versionedPackage.getVersionCode(), flags, userId); 3480 } 3481 3482 private PackageInfo getPackageInfoInternal(String packageName, int versionCode, 3483 int flags, int userId) { 3484 if (!sUserManager.exists(userId)) return null; 3485 flags = updateFlagsForPackage(flags, userId, packageName); 3486 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3487 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3488 3489 // reader 3490 synchronized (mPackages) { 3491 // Normalize package name to handle renamed packages and static libs 3492 packageName = resolveInternalPackageNameLPr(packageName, versionCode); 3493 3494 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3495 if (matchFactoryOnly) { 3496 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3497 if (ps != null) { 3498 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 3499 return null; 3500 } 3501 return generatePackageInfo(ps, flags, userId); 3502 } 3503 } 3504 3505 PackageParser.Package p = mPackages.get(packageName); 3506 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3507 return null; 3508 } 3509 if (DEBUG_PACKAGE_INFO) 3510 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3511 if (p != null) { 3512 if (filterSharedLibPackageLPr((PackageSetting) p.mExtras, 3513 Binder.getCallingUid(), userId)) { 3514 return null; 3515 } 3516 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3517 } 3518 if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) { 3519 final PackageSetting ps = mSettings.mPackages.get(packageName); 3520 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 3521 return null; 3522 } 3523 return generatePackageInfo(ps, flags, userId); 3524 } 3525 } 3526 return null; 3527 } 3528 3529 3530 private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId) { 3531 // System/shell/root get to see all static libs 3532 final int appId = UserHandle.getAppId(uid); 3533 if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID 3534 || appId == Process.ROOT_UID) { 3535 return false; 3536 } 3537 3538 // No package means no static lib as it is always on internal storage 3539 if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) { 3540 return false; 3541 } 3542 3543 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName, 3544 ps.pkg.staticSharedLibVersion); 3545 if (libEntry == null) { 3546 return false; 3547 } 3548 3549 final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid)); 3550 final String[] uidPackageNames = getPackagesForUid(resolvedUid); 3551 if (uidPackageNames == null) { 3552 return true; 3553 } 3554 3555 for (String uidPackageName : uidPackageNames) { 3556 if (ps.name.equals(uidPackageName)) { 3557 return false; 3558 } 3559 PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName); 3560 if (uidPs != null) { 3561 final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries, 3562 libEntry.info.getName()); 3563 if (index < 0) { 3564 continue; 3565 } 3566 if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) { 3567 return false; 3568 } 3569 } 3570 } 3571 return true; 3572 } 3573 3574 @Override 3575 public String[] currentToCanonicalPackageNames(String[] names) { 3576 String[] out = new String[names.length]; 3577 // reader 3578 synchronized (mPackages) { 3579 for (int i=names.length-1; i>=0; i--) { 3580 PackageSetting ps = mSettings.mPackages.get(names[i]); 3581 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3582 } 3583 } 3584 return out; 3585 } 3586 3587 @Override 3588 public String[] canonicalToCurrentPackageNames(String[] names) { 3589 String[] out = new String[names.length]; 3590 // reader 3591 synchronized (mPackages) { 3592 for (int i=names.length-1; i>=0; i--) { 3593 String cur = mSettings.getRenamedPackageLPr(names[i]); 3594 out[i] = cur != null ? cur : names[i]; 3595 } 3596 } 3597 return out; 3598 } 3599 3600 @Override 3601 public int getPackageUid(String packageName, int flags, int userId) { 3602 if (!sUserManager.exists(userId)) return -1; 3603 flags = updateFlagsForPackage(flags, userId, packageName); 3604 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3605 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3606 3607 // reader 3608 synchronized (mPackages) { 3609 final PackageParser.Package p = mPackages.get(packageName); 3610 if (p != null && p.isMatch(flags)) { 3611 return UserHandle.getUid(userId, p.applicationInfo.uid); 3612 } 3613 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3614 final PackageSetting ps = mSettings.mPackages.get(packageName); 3615 if (ps != null && ps.isMatch(flags)) { 3616 return UserHandle.getUid(userId, ps.appId); 3617 } 3618 } 3619 } 3620 3621 return -1; 3622 } 3623 3624 @Override 3625 public int[] getPackageGids(String packageName, int flags, int userId) { 3626 if (!sUserManager.exists(userId)) return null; 3627 flags = updateFlagsForPackage(flags, userId, packageName); 3628 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3629 false /* requireFullPermission */, false /* checkShell */, 3630 "getPackageGids"); 3631 3632 // reader 3633 synchronized (mPackages) { 3634 final PackageParser.Package p = mPackages.get(packageName); 3635 if (p != null && p.isMatch(flags)) { 3636 PackageSetting ps = (PackageSetting) p.mExtras; 3637 // TODO: Shouldn't this be checking for package installed state for userId and 3638 // return null? 3639 return ps.getPermissionsState().computeGids(userId); 3640 } 3641 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3642 final PackageSetting ps = mSettings.mPackages.get(packageName); 3643 if (ps != null && ps.isMatch(flags)) { 3644 return ps.getPermissionsState().computeGids(userId); 3645 } 3646 } 3647 } 3648 3649 return null; 3650 } 3651 3652 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3653 if (bp.perm != null) { 3654 return PackageParser.generatePermissionInfo(bp.perm, flags); 3655 } 3656 PermissionInfo pi = new PermissionInfo(); 3657 pi.name = bp.name; 3658 pi.packageName = bp.sourcePackage; 3659 pi.nonLocalizedLabel = bp.name; 3660 pi.protectionLevel = bp.protectionLevel; 3661 return pi; 3662 } 3663 3664 @Override 3665 public PermissionInfo getPermissionInfo(String name, int flags) { 3666 // reader 3667 synchronized (mPackages) { 3668 final BasePermission p = mSettings.mPermissions.get(name); 3669 if (p != null) { 3670 return generatePermissionInfo(p, flags); 3671 } 3672 return null; 3673 } 3674 } 3675 3676 @Override 3677 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3678 int flags) { 3679 // reader 3680 synchronized (mPackages) { 3681 if (group != null && !mPermissionGroups.containsKey(group)) { 3682 // This is thrown as NameNotFoundException 3683 return null; 3684 } 3685 3686 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3687 for (BasePermission p : mSettings.mPermissions.values()) { 3688 if (group == null) { 3689 if (p.perm == null || p.perm.info.group == null) { 3690 out.add(generatePermissionInfo(p, flags)); 3691 } 3692 } else { 3693 if (p.perm != null && group.equals(p.perm.info.group)) { 3694 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3695 } 3696 } 3697 } 3698 return new ParceledListSlice<>(out); 3699 } 3700 } 3701 3702 @Override 3703 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3704 // reader 3705 synchronized (mPackages) { 3706 return PackageParser.generatePermissionGroupInfo( 3707 mPermissionGroups.get(name), flags); 3708 } 3709 } 3710 3711 @Override 3712 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3713 // reader 3714 synchronized (mPackages) { 3715 final int N = mPermissionGroups.size(); 3716 ArrayList<PermissionGroupInfo> out 3717 = new ArrayList<PermissionGroupInfo>(N); 3718 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3719 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3720 } 3721 return new ParceledListSlice<>(out); 3722 } 3723 } 3724 3725 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3726 int uid, int userId) { 3727 if (!sUserManager.exists(userId)) return null; 3728 PackageSetting ps = mSettings.mPackages.get(packageName); 3729 if (ps != null) { 3730 if (filterSharedLibPackageLPr(ps, uid, userId)) { 3731 return null; 3732 } 3733 if (ps.pkg == null) { 3734 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3735 if (pInfo != null) { 3736 return pInfo.applicationInfo; 3737 } 3738 return null; 3739 } 3740 ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 3741 ps.readUserState(userId), userId); 3742 if (ai != null) { 3743 rebaseEnabledOverlays(ai, userId); 3744 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 3745 } 3746 return ai; 3747 } 3748 return null; 3749 } 3750 3751 @Override 3752 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3753 if (!sUserManager.exists(userId)) return null; 3754 flags = updateFlagsForApplication(flags, userId, packageName); 3755 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3756 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3757 3758 // writer 3759 synchronized (mPackages) { 3760 // Normalize package name to handle renamed packages and static libs 3761 packageName = resolveInternalPackageNameLPr(packageName, 3762 PackageManager.VERSION_CODE_HIGHEST); 3763 3764 PackageParser.Package p = mPackages.get(packageName); 3765 if (DEBUG_PACKAGE_INFO) Log.v( 3766 TAG, "getApplicationInfo " + packageName 3767 + ": " + p); 3768 if (p != null) { 3769 PackageSetting ps = mSettings.mPackages.get(packageName); 3770 if (ps == null) return null; 3771 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 3772 return null; 3773 } 3774 // Note: isEnabledLP() does not apply here - always return info 3775 ApplicationInfo ai = PackageParser.generateApplicationInfo( 3776 p, flags, ps.readUserState(userId), userId); 3777 if (ai != null) { 3778 rebaseEnabledOverlays(ai, userId); 3779 ai.packageName = resolveExternalPackageNameLPr(p); 3780 } 3781 return ai; 3782 } 3783 if ("android".equals(packageName)||"system".equals(packageName)) { 3784 return mAndroidApplication; 3785 } 3786 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3787 // Already generates the external package name 3788 return generateApplicationInfoFromSettingsLPw(packageName, 3789 Binder.getCallingUid(), flags, userId); 3790 } 3791 } 3792 return null; 3793 } 3794 3795 private void rebaseEnabledOverlays(@NonNull ApplicationInfo ai, int userId) { 3796 List<String> paths = new ArrayList<>(); 3797 ArrayMap<String, ArrayList<String>> userSpecificOverlays = 3798 mEnabledOverlayPaths.get(userId); 3799 if (userSpecificOverlays != null) { 3800 if (!"android".equals(ai.packageName)) { 3801 ArrayList<String> frameworkOverlays = userSpecificOverlays.get("android"); 3802 if (frameworkOverlays != null) { 3803 paths.addAll(frameworkOverlays); 3804 } 3805 } 3806 3807 ArrayList<String> appOverlays = userSpecificOverlays.get(ai.packageName); 3808 if (appOverlays != null) { 3809 paths.addAll(appOverlays); 3810 } 3811 } 3812 ai.resourceDirs = paths.size() > 0 ? paths.toArray(new String[paths.size()]) : null; 3813 } 3814 3815 private String normalizePackageNameLPr(String packageName) { 3816 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 3817 return normalizedPackageName != null ? normalizedPackageName : packageName; 3818 } 3819 3820 @Override 3821 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3822 final IPackageDataObserver observer) { 3823 mContext.enforceCallingOrSelfPermission( 3824 android.Manifest.permission.CLEAR_APP_CACHE, null); 3825 mHandler.post(() -> { 3826 boolean success = false; 3827 try { 3828 freeStorage(volumeUuid, freeStorageSize, 0); 3829 success = true; 3830 } catch (IOException e) { 3831 Slog.w(TAG, e); 3832 } 3833 if (observer != null) { 3834 try { 3835 observer.onRemoveCompleted(null, success); 3836 } catch (RemoteException e) { 3837 Slog.w(TAG, e); 3838 } 3839 } 3840 }); 3841 } 3842 3843 @Override 3844 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3845 final IntentSender pi) { 3846 mContext.enforceCallingOrSelfPermission( 3847 android.Manifest.permission.CLEAR_APP_CACHE, TAG); 3848 mHandler.post(() -> { 3849 boolean success = false; 3850 try { 3851 freeStorage(volumeUuid, freeStorageSize, 0); 3852 success = true; 3853 } catch (IOException e) { 3854 Slog.w(TAG, e); 3855 } 3856 if (pi != null) { 3857 try { 3858 pi.sendIntent(null, success ? 1 : 0, null, null, null); 3859 } catch (SendIntentException e) { 3860 Slog.w(TAG, e); 3861 } 3862 } 3863 }); 3864 } 3865 3866 /** 3867 * Blocking call to clear various types of cached data across the system 3868 * until the requested bytes are available. 3869 */ 3870 public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException { 3871 final StorageManager storage = mContext.getSystemService(StorageManager.class); 3872 final File file = storage.findPathForUuid(volumeUuid); 3873 3874 if (ENABLE_FREE_CACHE_V2) { 3875 final boolean aggressive = (storageFlags 3876 & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0; 3877 3878 // 1. Pre-flight to determine if we have any chance to succeed 3879 // 2. Consider preloaded data (after 1w honeymoon, unless aggressive) 3880 3881 // 3. Consider parsed APK data (aggressive only) 3882 if (aggressive) { 3883 FileUtils.deleteContents(mCacheDir); 3884 } 3885 if (file.getUsableSpace() >= bytes) return; 3886 3887 // 4. Consider cached app data (above quotas) 3888 try { 3889 mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2); 3890 } catch (InstallerException ignored) { 3891 } 3892 if (file.getUsableSpace() >= bytes) return; 3893 3894 // 5. Consider shared libraries with refcount=0 and age>2h 3895 // 6. Consider dexopt output (aggressive only) 3896 // 7. Consider ephemeral apps not used in last week 3897 3898 // 8. Consider cached app data (below quotas) 3899 try { 3900 mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2 3901 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA); 3902 } catch (InstallerException ignored) { 3903 } 3904 if (file.getUsableSpace() >= bytes) return; 3905 3906 // 9. Consider DropBox entries 3907 // 10. Consider ephemeral cookies 3908 3909 } else { 3910 try { 3911 mInstaller.freeCache(volumeUuid, bytes, 0); 3912 } catch (InstallerException ignored) { 3913 } 3914 if (file.getUsableSpace() >= bytes) return; 3915 } 3916 3917 throw new IOException("Failed to free " + bytes + " on storage device at " + file); 3918 } 3919 3920 /** 3921 * Update given flags based on encryption status of current user. 3922 */ 3923 private int updateFlags(int flags, int userId) { 3924 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3925 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3926 // Caller expressed an explicit opinion about what encryption 3927 // aware/unaware components they want to see, so fall through and 3928 // give them what they want 3929 } else { 3930 // Caller expressed no opinion, so match based on user state 3931 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 3932 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3933 } else { 3934 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3935 } 3936 } 3937 return flags; 3938 } 3939 3940 private UserManagerInternal getUserManagerInternal() { 3941 if (mUserManagerInternal == null) { 3942 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 3943 } 3944 return mUserManagerInternal; 3945 } 3946 3947 private DeviceIdleController.LocalService getDeviceIdleController() { 3948 if (mDeviceIdleController == null) { 3949 mDeviceIdleController = 3950 LocalServices.getService(DeviceIdleController.LocalService.class); 3951 } 3952 return mDeviceIdleController; 3953 } 3954 3955 /** 3956 * Update given flags when being used to request {@link PackageInfo}. 3957 */ 3958 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3959 final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM; 3960 boolean triaged = true; 3961 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3962 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3963 // Caller is asking for component details, so they'd better be 3964 // asking for specific encryption matching behavior, or be triaged 3965 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3966 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3967 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3968 triaged = false; 3969 } 3970 } 3971 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3972 | PackageManager.MATCH_SYSTEM_ONLY 3973 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3974 triaged = false; 3975 } 3976 if ((flags & PackageManager.MATCH_ANY_USER) != 0) { 3977 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 3978 "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at " 3979 + Debug.getCallers(5)); 3980 } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser 3981 && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) { 3982 // If the caller wants all packages and has a restricted profile associated with it, 3983 // then match all users. This is to make sure that launchers that need to access work 3984 // profile apps don't start breaking. TODO: Remove this hack when launchers stop using 3985 // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380 3986 flags |= PackageManager.MATCH_ANY_USER; 3987 } 3988 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3989 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3990 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3991 } 3992 return updateFlags(flags, userId); 3993 } 3994 3995 /** 3996 * Update given flags when being used to request {@link ApplicationInfo}. 3997 */ 3998 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3999 return updateFlagsForPackage(flags, userId, cookie); 4000 } 4001 4002 /** 4003 * Update given flags when being used to request {@link ComponentInfo}. 4004 */ 4005 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 4006 if (cookie instanceof Intent) { 4007 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 4008 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 4009 } 4010 } 4011 4012 boolean triaged = true; 4013 // Caller is asking for component details, so they'd better be 4014 // asking for specific encryption matching behavior, or be triaged 4015 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 4016 | PackageManager.MATCH_DIRECT_BOOT_AWARE 4017 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 4018 triaged = false; 4019 } 4020 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 4021 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 4022 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 4023 } 4024 4025 return updateFlags(flags, userId); 4026 } 4027 4028 /** 4029 * Update given intent when being used to request {@link ResolveInfo}. 4030 */ 4031 private Intent updateIntentForResolve(Intent intent) { 4032 if (intent.getSelector() != null) { 4033 intent = intent.getSelector(); 4034 } 4035 if (DEBUG_PREFERRED) { 4036 intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4037 } 4038 return intent; 4039 } 4040 4041 /** 4042 * Update given flags when being used to request {@link ResolveInfo}. 4043 * <p>Instant apps are resolved specially, depending upon context. Minimally, 4044 * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT} 4045 * flag set. However, this flag is only honoured in three circumstances: 4046 * <ul> 4047 * <li>when called from a system process</li> 4048 * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li> 4049 * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW} 4050 * action and a {@code android.intent.category.BROWSABLE} category</li> 4051 * </ul> 4052 */ 4053 int updateFlagsForResolve(int flags, int userId, Intent intent, boolean includeInstantApp) { 4054 // Safe mode means we shouldn't match any third-party components 4055 if (mSafeMode) { 4056 flags |= PackageManager.MATCH_SYSTEM_ONLY; 4057 } 4058 final int callingUid = Binder.getCallingUid(); 4059 if (getInstantAppPackageName(callingUid) != null) { 4060 // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components 4061 flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY; 4062 flags |= PackageManager.MATCH_INSTANT; 4063 } else { 4064 // Otherwise, prevent leaking ephemeral components 4065 final boolean isSpecialProcess = 4066 callingUid == Process.SYSTEM_UID 4067 || callingUid == Process.SHELL_UID 4068 || callingUid == 0; 4069 final boolean allowMatchInstant = 4070 (includeInstantApp 4071 && Intent.ACTION_VIEW.equals(intent.getAction()) 4072 && intent.hasCategory(Intent.CATEGORY_BROWSABLE) 4073 && hasWebURI(intent)) 4074 || isSpecialProcess 4075 || mContext.checkCallingOrSelfPermission( 4076 android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED; 4077 flags &= ~PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY; 4078 if (!allowMatchInstant) { 4079 flags &= ~PackageManager.MATCH_INSTANT; 4080 } 4081 } 4082 return updateFlagsForComponent(flags, userId, intent /*cookie*/); 4083 } 4084 4085 @Override 4086 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 4087 if (!sUserManager.exists(userId)) return null; 4088 flags = updateFlagsForComponent(flags, userId, component); 4089 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4090 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 4091 synchronized (mPackages) { 4092 PackageParser.Activity a = mActivities.mActivities.get(component); 4093 4094 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 4095 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 4096 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4097 if (ps == null) return null; 4098 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 4099 userId); 4100 } 4101 if (mResolveComponentName.equals(component)) { 4102 return PackageParser.generateActivityInfo(mResolveActivity, flags, 4103 new PackageUserState(), userId); 4104 } 4105 } 4106 return null; 4107 } 4108 4109 @Override 4110 public boolean activitySupportsIntent(ComponentName component, Intent intent, 4111 String resolvedType) { 4112 synchronized (mPackages) { 4113 if (component.equals(mResolveComponentName)) { 4114 // The resolver supports EVERYTHING! 4115 return true; 4116 } 4117 PackageParser.Activity a = mActivities.mActivities.get(component); 4118 if (a == null) { 4119 return false; 4120 } 4121 for (int i=0; i<a.intents.size(); i++) { 4122 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 4123 intent.getData(), intent.getCategories(), TAG) >= 0) { 4124 return true; 4125 } 4126 } 4127 return false; 4128 } 4129 } 4130 4131 @Override 4132 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 4133 if (!sUserManager.exists(userId)) return null; 4134 flags = updateFlagsForComponent(flags, userId, component); 4135 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4136 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 4137 synchronized (mPackages) { 4138 PackageParser.Activity a = mReceivers.mActivities.get(component); 4139 if (DEBUG_PACKAGE_INFO) Log.v( 4140 TAG, "getReceiverInfo " + component + ": " + a); 4141 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 4142 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4143 if (ps == null) return null; 4144 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 4145 userId); 4146 } 4147 } 4148 return null; 4149 } 4150 4151 @Override 4152 public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(int flags, int userId) { 4153 if (!sUserManager.exists(userId)) return null; 4154 Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0"); 4155 4156 flags = updateFlagsForPackage(flags, userId, null); 4157 4158 final boolean canSeeStaticLibraries = 4159 mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES) 4160 == PERMISSION_GRANTED 4161 || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES) 4162 == PERMISSION_GRANTED 4163 || mContext.checkCallingOrSelfPermission(REQUEST_INSTALL_PACKAGES) 4164 == PERMISSION_GRANTED 4165 || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES) 4166 == PERMISSION_GRANTED; 4167 4168 synchronized (mPackages) { 4169 List<SharedLibraryInfo> result = null; 4170 4171 final int libCount = mSharedLibraries.size(); 4172 for (int i = 0; i < libCount; i++) { 4173 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 4174 if (versionedLib == null) { 4175 continue; 4176 } 4177 4178 final int versionCount = versionedLib.size(); 4179 for (int j = 0; j < versionCount; j++) { 4180 SharedLibraryInfo libInfo = versionedLib.valueAt(j).info; 4181 if (!canSeeStaticLibraries && libInfo.isStatic()) { 4182 break; 4183 } 4184 final long identity = Binder.clearCallingIdentity(); 4185 try { 4186 // TODO: We will change version code to long, so in the new API it is long 4187 PackageInfo packageInfo = getPackageInfoVersioned( 4188 libInfo.getDeclaringPackage(), flags, userId); 4189 if (packageInfo == null) { 4190 continue; 4191 } 4192 } finally { 4193 Binder.restoreCallingIdentity(identity); 4194 } 4195 4196 SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(), 4197 libInfo.getVersion(), libInfo.getType(), libInfo.getDeclaringPackage(), 4198 getPackagesUsingSharedLibraryLPr(libInfo, flags, userId)); 4199 4200 if (result == null) { 4201 result = new ArrayList<>(); 4202 } 4203 result.add(resLibInfo); 4204 } 4205 } 4206 4207 return result != null ? new ParceledListSlice<>(result) : null; 4208 } 4209 } 4210 4211 private List<VersionedPackage> getPackagesUsingSharedLibraryLPr( 4212 SharedLibraryInfo libInfo, int flags, int userId) { 4213 List<VersionedPackage> versionedPackages = null; 4214 final int packageCount = mSettings.mPackages.size(); 4215 for (int i = 0; i < packageCount; i++) { 4216 PackageSetting ps = mSettings.mPackages.valueAt(i); 4217 4218 if (ps == null) { 4219 continue; 4220 } 4221 4222 if (!ps.getUserState().get(userId).isAvailable(flags)) { 4223 continue; 4224 } 4225 4226 final String libName = libInfo.getName(); 4227 if (libInfo.isStatic()) { 4228 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 4229 if (libIdx < 0) { 4230 continue; 4231 } 4232 if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) { 4233 continue; 4234 } 4235 if (versionedPackages == null) { 4236 versionedPackages = new ArrayList<>(); 4237 } 4238 // If the dependent is a static shared lib, use the public package name 4239 String dependentPackageName = ps.name; 4240 if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) { 4241 dependentPackageName = ps.pkg.manifestPackageName; 4242 } 4243 versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode)); 4244 } else if (ps.pkg != null) { 4245 if (ArrayUtils.contains(ps.pkg.usesLibraries, libName) 4246 || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) { 4247 if (versionedPackages == null) { 4248 versionedPackages = new ArrayList<>(); 4249 } 4250 versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode)); 4251 } 4252 } 4253 } 4254 4255 return versionedPackages; 4256 } 4257 4258 @Override 4259 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 4260 if (!sUserManager.exists(userId)) return null; 4261 flags = updateFlagsForComponent(flags, userId, component); 4262 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4263 false /* requireFullPermission */, false /* checkShell */, "get service info"); 4264 synchronized (mPackages) { 4265 PackageParser.Service s = mServices.mServices.get(component); 4266 if (DEBUG_PACKAGE_INFO) Log.v( 4267 TAG, "getServiceInfo " + component + ": " + s); 4268 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 4269 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4270 if (ps == null) return null; 4271 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 4272 userId); 4273 } 4274 } 4275 return null; 4276 } 4277 4278 @Override 4279 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 4280 if (!sUserManager.exists(userId)) return null; 4281 flags = updateFlagsForComponent(flags, userId, component); 4282 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4283 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 4284 synchronized (mPackages) { 4285 PackageParser.Provider p = mProviders.mProviders.get(component); 4286 if (DEBUG_PACKAGE_INFO) Log.v( 4287 TAG, "getProviderInfo " + component + ": " + p); 4288 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 4289 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4290 if (ps == null) return null; 4291 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 4292 userId); 4293 } 4294 } 4295 return null; 4296 } 4297 4298 @Override 4299 public String[] getSystemSharedLibraryNames() { 4300 synchronized (mPackages) { 4301 Set<String> libs = null; 4302 final int libCount = mSharedLibraries.size(); 4303 for (int i = 0; i < libCount; i++) { 4304 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 4305 if (versionedLib == null) { 4306 continue; 4307 } 4308 final int versionCount = versionedLib.size(); 4309 for (int j = 0; j < versionCount; j++) { 4310 SharedLibraryEntry libEntry = versionedLib.valueAt(j); 4311 if (!libEntry.info.isStatic()) { 4312 if (libs == null) { 4313 libs = new ArraySet<>(); 4314 } 4315 libs.add(libEntry.info.getName()); 4316 break; 4317 } 4318 PackageSetting ps = mSettings.getPackageLPr(libEntry.apk); 4319 if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(), 4320 UserHandle.getUserId(Binder.getCallingUid()))) { 4321 if (libs == null) { 4322 libs = new ArraySet<>(); 4323 } 4324 libs.add(libEntry.info.getName()); 4325 break; 4326 } 4327 } 4328 } 4329 4330 if (libs != null) { 4331 String[] libsArray = new String[libs.size()]; 4332 libs.toArray(libsArray); 4333 return libsArray; 4334 } 4335 4336 return null; 4337 } 4338 } 4339 4340 @Override 4341 public @NonNull String getServicesSystemSharedLibraryPackageName() { 4342 synchronized (mPackages) { 4343 return mServicesSystemSharedLibraryPackageName; 4344 } 4345 } 4346 4347 @Override 4348 public @NonNull String getSharedSystemSharedLibraryPackageName() { 4349 synchronized (mPackages) { 4350 return mSharedSystemSharedLibraryPackageName; 4351 } 4352 } 4353 4354 private void updateSequenceNumberLP(String packageName, int[] userList) { 4355 for (int i = userList.length - 1; i >= 0; --i) { 4356 final int userId = userList[i]; 4357 SparseArray<String> changedPackages = mChangedPackages.get(userId); 4358 if (changedPackages == null) { 4359 changedPackages = new SparseArray<>(); 4360 mChangedPackages.put(userId, changedPackages); 4361 } 4362 Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId); 4363 if (sequenceNumbers == null) { 4364 sequenceNumbers = new HashMap<>(); 4365 mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers); 4366 } 4367 final Integer sequenceNumber = sequenceNumbers.get(packageName); 4368 if (sequenceNumber != null) { 4369 changedPackages.remove(sequenceNumber); 4370 } 4371 changedPackages.put(mChangedPackagesSequenceNumber, packageName); 4372 sequenceNumbers.put(packageName, mChangedPackagesSequenceNumber); 4373 } 4374 mChangedPackagesSequenceNumber++; 4375 } 4376 4377 @Override 4378 public ChangedPackages getChangedPackages(int sequenceNumber, int userId) { 4379 synchronized (mPackages) { 4380 if (sequenceNumber >= mChangedPackagesSequenceNumber) { 4381 return null; 4382 } 4383 final SparseArray<String> changedPackages = mChangedPackages.get(userId); 4384 if (changedPackages == null) { 4385 return null; 4386 } 4387 final List<String> packageNames = 4388 new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber); 4389 for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) { 4390 final String packageName = changedPackages.get(i); 4391 if (packageName != null) { 4392 packageNames.add(packageName); 4393 } 4394 } 4395 return packageNames.isEmpty() 4396 ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames); 4397 } 4398 } 4399 4400 @Override 4401 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 4402 ArrayList<FeatureInfo> res; 4403 synchronized (mAvailableFeatures) { 4404 res = new ArrayList<>(mAvailableFeatures.size() + 1); 4405 res.addAll(mAvailableFeatures.values()); 4406 } 4407 final FeatureInfo fi = new FeatureInfo(); 4408 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 4409 FeatureInfo.GL_ES_VERSION_UNDEFINED); 4410 res.add(fi); 4411 4412 return new ParceledListSlice<>(res); 4413 } 4414 4415 @Override 4416 public boolean hasSystemFeature(String name, int version) { 4417 synchronized (mAvailableFeatures) { 4418 final FeatureInfo feat = mAvailableFeatures.get(name); 4419 if (feat == null) { 4420 return false; 4421 } else { 4422 return feat.version >= version; 4423 } 4424 } 4425 } 4426 4427 @Override 4428 public int checkPermission(String permName, String pkgName, int userId) { 4429 if (!sUserManager.exists(userId)) { 4430 return PackageManager.PERMISSION_DENIED; 4431 } 4432 4433 synchronized (mPackages) { 4434 final PackageParser.Package p = mPackages.get(pkgName); 4435 if (p != null && p.mExtras != null) { 4436 final PackageSetting ps = (PackageSetting) p.mExtras; 4437 final PermissionsState permissionsState = ps.getPermissionsState(); 4438 if (permissionsState.hasPermission(permName, userId)) { 4439 return PackageManager.PERMISSION_GRANTED; 4440 } 4441 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 4442 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 4443 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 4444 return PackageManager.PERMISSION_GRANTED; 4445 } 4446 } 4447 } 4448 4449 return PackageManager.PERMISSION_DENIED; 4450 } 4451 4452 @Override 4453 public int checkUidPermission(String permName, int uid) { 4454 final int userId = UserHandle.getUserId(uid); 4455 4456 if (!sUserManager.exists(userId)) { 4457 return PackageManager.PERMISSION_DENIED; 4458 } 4459 4460 synchronized (mPackages) { 4461 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4462 if (obj != null) { 4463 final SettingBase ps = (SettingBase) obj; 4464 final PermissionsState permissionsState = ps.getPermissionsState(); 4465 if (permissionsState.hasPermission(permName, userId)) { 4466 return PackageManager.PERMISSION_GRANTED; 4467 } 4468 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 4469 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 4470 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 4471 return PackageManager.PERMISSION_GRANTED; 4472 } 4473 } else { 4474 ArraySet<String> perms = mSystemPermissions.get(uid); 4475 if (perms != null) { 4476 if (perms.contains(permName)) { 4477 return PackageManager.PERMISSION_GRANTED; 4478 } 4479 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 4480 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 4481 return PackageManager.PERMISSION_GRANTED; 4482 } 4483 } 4484 } 4485 } 4486 4487 return PackageManager.PERMISSION_DENIED; 4488 } 4489 4490 @Override 4491 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 4492 if (UserHandle.getCallingUserId() != userId) { 4493 mContext.enforceCallingPermission( 4494 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4495 "isPermissionRevokedByPolicy for user " + userId); 4496 } 4497 4498 if (checkPermission(permission, packageName, userId) 4499 == PackageManager.PERMISSION_GRANTED) { 4500 return false; 4501 } 4502 4503 final long identity = Binder.clearCallingIdentity(); 4504 try { 4505 final int flags = getPermissionFlags(permission, packageName, userId); 4506 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 4507 } finally { 4508 Binder.restoreCallingIdentity(identity); 4509 } 4510 } 4511 4512 @Override 4513 public String getPermissionControllerPackageName() { 4514 synchronized (mPackages) { 4515 return mRequiredInstallerPackage; 4516 } 4517 } 4518 4519 /** 4520 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 4521 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 4522 * @param checkShell whether to prevent shell from access if there's a debugging restriction 4523 * @param message the message to log on security exception 4524 */ 4525 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 4526 boolean checkShell, String message) { 4527 if (userId < 0) { 4528 throw new IllegalArgumentException("Invalid userId " + userId); 4529 } 4530 if (checkShell) { 4531 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 4532 } 4533 if (userId == UserHandle.getUserId(callingUid)) return; 4534 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4535 if (requireFullPermission) { 4536 mContext.enforceCallingOrSelfPermission( 4537 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 4538 } else { 4539 try { 4540 mContext.enforceCallingOrSelfPermission( 4541 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 4542 } catch (SecurityException se) { 4543 mContext.enforceCallingOrSelfPermission( 4544 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 4545 } 4546 } 4547 } 4548 } 4549 4550 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 4551 if (callingUid == Process.SHELL_UID) { 4552 if (userHandle >= 0 4553 && sUserManager.hasUserRestriction(restriction, userHandle)) { 4554 throw new SecurityException("Shell does not have permission to access user " 4555 + userHandle); 4556 } else if (userHandle < 0) { 4557 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 4558 + Debug.getCallers(3)); 4559 } 4560 } 4561 } 4562 4563 private BasePermission findPermissionTreeLP(String permName) { 4564 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 4565 if (permName.startsWith(bp.name) && 4566 permName.length() > bp.name.length() && 4567 permName.charAt(bp.name.length()) == '.') { 4568 return bp; 4569 } 4570 } 4571 return null; 4572 } 4573 4574 private BasePermission checkPermissionTreeLP(String permName) { 4575 if (permName != null) { 4576 BasePermission bp = findPermissionTreeLP(permName); 4577 if (bp != null) { 4578 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 4579 return bp; 4580 } 4581 throw new SecurityException("Calling uid " 4582 + Binder.getCallingUid() 4583 + " is not allowed to add to permission tree " 4584 + bp.name + " owned by uid " + bp.uid); 4585 } 4586 } 4587 throw new SecurityException("No permission tree found for " + permName); 4588 } 4589 4590 static boolean compareStrings(CharSequence s1, CharSequence s2) { 4591 if (s1 == null) { 4592 return s2 == null; 4593 } 4594 if (s2 == null) { 4595 return false; 4596 } 4597 if (s1.getClass() != s2.getClass()) { 4598 return false; 4599 } 4600 return s1.equals(s2); 4601 } 4602 4603 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 4604 if (pi1.icon != pi2.icon) return false; 4605 if (pi1.logo != pi2.logo) return false; 4606 if (pi1.protectionLevel != pi2.protectionLevel) return false; 4607 if (!compareStrings(pi1.name, pi2.name)) return false; 4608 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 4609 // We'll take care of setting this one. 4610 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 4611 // These are not currently stored in settings. 4612 //if (!compareStrings(pi1.group, pi2.group)) return false; 4613 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 4614 //if (pi1.labelRes != pi2.labelRes) return false; 4615 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 4616 return true; 4617 } 4618 4619 int permissionInfoFootprint(PermissionInfo info) { 4620 int size = info.name.length(); 4621 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 4622 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 4623 return size; 4624 } 4625 4626 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 4627 int size = 0; 4628 for (BasePermission perm : mSettings.mPermissions.values()) { 4629 if (perm.uid == tree.uid) { 4630 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 4631 } 4632 } 4633 return size; 4634 } 4635 4636 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 4637 // We calculate the max size of permissions defined by this uid and throw 4638 // if that plus the size of 'info' would exceed our stated maximum. 4639 if (tree.uid != Process.SYSTEM_UID) { 4640 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 4641 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 4642 throw new SecurityException("Permission tree size cap exceeded"); 4643 } 4644 } 4645 } 4646 4647 boolean addPermissionLocked(PermissionInfo info, boolean async) { 4648 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 4649 throw new SecurityException("Label must be specified in permission"); 4650 } 4651 BasePermission tree = checkPermissionTreeLP(info.name); 4652 BasePermission bp = mSettings.mPermissions.get(info.name); 4653 boolean added = bp == null; 4654 boolean changed = true; 4655 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 4656 if (added) { 4657 enforcePermissionCapLocked(info, tree); 4658 bp = new BasePermission(info.name, tree.sourcePackage, 4659 BasePermission.TYPE_DYNAMIC); 4660 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 4661 throw new SecurityException( 4662 "Not allowed to modify non-dynamic permission " 4663 + info.name); 4664 } else { 4665 if (bp.protectionLevel == fixedLevel 4666 && bp.perm.owner.equals(tree.perm.owner) 4667 && bp.uid == tree.uid 4668 && comparePermissionInfos(bp.perm.info, info)) { 4669 changed = false; 4670 } 4671 } 4672 bp.protectionLevel = fixedLevel; 4673 info = new PermissionInfo(info); 4674 info.protectionLevel = fixedLevel; 4675 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 4676 bp.perm.info.packageName = tree.perm.info.packageName; 4677 bp.uid = tree.uid; 4678 if (added) { 4679 mSettings.mPermissions.put(info.name, bp); 4680 } 4681 if (changed) { 4682 if (!async) { 4683 mSettings.writeLPr(); 4684 } else { 4685 scheduleWriteSettingsLocked(); 4686 } 4687 } 4688 return added; 4689 } 4690 4691 @Override 4692 public boolean addPermission(PermissionInfo info) { 4693 synchronized (mPackages) { 4694 return addPermissionLocked(info, false); 4695 } 4696 } 4697 4698 @Override 4699 public boolean addPermissionAsync(PermissionInfo info) { 4700 synchronized (mPackages) { 4701 return addPermissionLocked(info, true); 4702 } 4703 } 4704 4705 @Override 4706 public void removePermission(String name) { 4707 synchronized (mPackages) { 4708 checkPermissionTreeLP(name); 4709 BasePermission bp = mSettings.mPermissions.get(name); 4710 if (bp != null) { 4711 if (bp.type != BasePermission.TYPE_DYNAMIC) { 4712 throw new SecurityException( 4713 "Not allowed to modify non-dynamic permission " 4714 + name); 4715 } 4716 mSettings.mPermissions.remove(name); 4717 mSettings.writeLPr(); 4718 } 4719 } 4720 } 4721 4722 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 4723 BasePermission bp) { 4724 int index = pkg.requestedPermissions.indexOf(bp.name); 4725 if (index == -1) { 4726 throw new SecurityException("Package " + pkg.packageName 4727 + " has not requested permission " + bp.name); 4728 } 4729 if (!bp.isRuntime() && !bp.isDevelopment()) { 4730 throw new SecurityException("Permission " + bp.name 4731 + " is not a changeable permission type"); 4732 } 4733 } 4734 4735 @Override 4736 public void grantRuntimePermission(String packageName, String name, final int userId) { 4737 grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */); 4738 } 4739 4740 private void grantRuntimePermission(String packageName, String name, final int userId, 4741 boolean overridePolicy) { 4742 if (!sUserManager.exists(userId)) { 4743 Log.e(TAG, "No such user:" + userId); 4744 return; 4745 } 4746 4747 mContext.enforceCallingOrSelfPermission( 4748 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 4749 "grantRuntimePermission"); 4750 4751 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4752 true /* requireFullPermission */, true /* checkShell */, 4753 "grantRuntimePermission"); 4754 4755 final int uid; 4756 final SettingBase sb; 4757 4758 synchronized (mPackages) { 4759 final PackageParser.Package pkg = mPackages.get(packageName); 4760 if (pkg == null) { 4761 throw new IllegalArgumentException("Unknown package: " + packageName); 4762 } 4763 4764 final BasePermission bp = mSettings.mPermissions.get(name); 4765 if (bp == null) { 4766 throw new IllegalArgumentException("Unknown permission: " + name); 4767 } 4768 4769 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4770 4771 // If a permission review is required for legacy apps we represent 4772 // their permissions as always granted runtime ones since we need 4773 // to keep the review required permission flag per user while an 4774 // install permission's state is shared across all users. 4775 if (mPermissionReviewRequired 4776 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4777 && bp.isRuntime()) { 4778 return; 4779 } 4780 4781 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 4782 sb = (SettingBase) pkg.mExtras; 4783 if (sb == null) { 4784 throw new IllegalArgumentException("Unknown package: " + packageName); 4785 } 4786 4787 final PermissionsState permissionsState = sb.getPermissionsState(); 4788 4789 final int flags = permissionsState.getPermissionFlags(name, userId); 4790 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4791 throw new SecurityException("Cannot grant system fixed permission " 4792 + name + " for package " + packageName); 4793 } 4794 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) { 4795 throw new SecurityException("Cannot grant policy fixed permission " 4796 + name + " for package " + packageName); 4797 } 4798 4799 if (bp.isDevelopment()) { 4800 // Development permissions must be handled specially, since they are not 4801 // normal runtime permissions. For now they apply to all users. 4802 if (permissionsState.grantInstallPermission(bp) != 4803 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4804 scheduleWriteSettingsLocked(); 4805 } 4806 return; 4807 } 4808 4809 final PackageSetting ps = mSettings.mPackages.get(packageName); 4810 if (ps.getInstantApp(userId) && !bp.isInstant()) { 4811 throw new SecurityException("Cannot grant non-ephemeral permission" 4812 + name + " for package " + packageName); 4813 } 4814 4815 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4816 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4817 return; 4818 } 4819 4820 final int result = permissionsState.grantRuntimePermission(bp, userId); 4821 switch (result) { 4822 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4823 return; 4824 } 4825 4826 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4827 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4828 mHandler.post(new Runnable() { 4829 @Override 4830 public void run() { 4831 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4832 } 4833 }); 4834 } 4835 break; 4836 } 4837 4838 if (bp.isRuntime()) { 4839 logPermissionGranted(mContext, name, packageName); 4840 } 4841 4842 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4843 4844 // Not critical if that is lost - app has to request again. 4845 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4846 } 4847 4848 // Only need to do this if user is initialized. Otherwise it's a new user 4849 // and there are no processes running as the user yet and there's no need 4850 // to make an expensive call to remount processes for the changed permissions. 4851 if (READ_EXTERNAL_STORAGE.equals(name) 4852 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4853 final long token = Binder.clearCallingIdentity(); 4854 try { 4855 if (sUserManager.isInitialized(userId)) { 4856 StorageManagerInternal storageManagerInternal = LocalServices.getService( 4857 StorageManagerInternal.class); 4858 storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName); 4859 } 4860 } finally { 4861 Binder.restoreCallingIdentity(token); 4862 } 4863 } 4864 } 4865 4866 @Override 4867 public void revokeRuntimePermission(String packageName, String name, int userId) { 4868 revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */); 4869 } 4870 4871 private void revokeRuntimePermission(String packageName, String name, int userId, 4872 boolean overridePolicy) { 4873 if (!sUserManager.exists(userId)) { 4874 Log.e(TAG, "No such user:" + userId); 4875 return; 4876 } 4877 4878 mContext.enforceCallingOrSelfPermission( 4879 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4880 "revokeRuntimePermission"); 4881 4882 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4883 true /* requireFullPermission */, true /* checkShell */, 4884 "revokeRuntimePermission"); 4885 4886 final int appId; 4887 4888 synchronized (mPackages) { 4889 final PackageParser.Package pkg = mPackages.get(packageName); 4890 if (pkg == null) { 4891 throw new IllegalArgumentException("Unknown package: " + packageName); 4892 } 4893 4894 final BasePermission bp = mSettings.mPermissions.get(name); 4895 if (bp == null) { 4896 throw new IllegalArgumentException("Unknown permission: " + name); 4897 } 4898 4899 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4900 4901 // If a permission review is required for legacy apps we represent 4902 // their permissions as always granted runtime ones since we need 4903 // to keep the review required permission flag per user while an 4904 // install permission's state is shared across all users. 4905 if (mPermissionReviewRequired 4906 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4907 && bp.isRuntime()) { 4908 return; 4909 } 4910 4911 SettingBase sb = (SettingBase) pkg.mExtras; 4912 if (sb == null) { 4913 throw new IllegalArgumentException("Unknown package: " + packageName); 4914 } 4915 4916 final PermissionsState permissionsState = sb.getPermissionsState(); 4917 4918 final int flags = permissionsState.getPermissionFlags(name, userId); 4919 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4920 throw new SecurityException("Cannot revoke system fixed permission " 4921 + name + " for package " + packageName); 4922 } 4923 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) { 4924 throw new SecurityException("Cannot revoke policy fixed permission " 4925 + name + " for package " + packageName); 4926 } 4927 4928 if (bp.isDevelopment()) { 4929 // Development permissions must be handled specially, since they are not 4930 // normal runtime permissions. For now they apply to all users. 4931 if (permissionsState.revokeInstallPermission(bp) != 4932 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4933 scheduleWriteSettingsLocked(); 4934 } 4935 return; 4936 } 4937 4938 if (permissionsState.revokeRuntimePermission(bp, userId) == 4939 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4940 return; 4941 } 4942 4943 if (bp.isRuntime()) { 4944 logPermissionRevoked(mContext, name, packageName); 4945 } 4946 4947 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4948 4949 // Critical, after this call app should never have the permission. 4950 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4951 4952 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4953 } 4954 4955 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4956 } 4957 4958 /** 4959 * Get the first event id for the permission. 4960 * 4961 * <p>There are four events for each permission: <ul> 4962 * <li>Request permission: first id + 0</li> 4963 * <li>Grant permission: first id + 1</li> 4964 * <li>Request for permission denied: first id + 2</li> 4965 * <li>Revoke permission: first id + 3</li> 4966 * </ul></p> 4967 * 4968 * @param name name of the permission 4969 * 4970 * @return The first event id for the permission 4971 */ 4972 private static int getBaseEventId(@NonNull String name) { 4973 int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name); 4974 4975 if (eventIdIndex == -1) { 4976 if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE 4977 || "user".equals(Build.TYPE)) { 4978 Log.i(TAG, "Unknown permission " + name); 4979 4980 return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN; 4981 } else { 4982 // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated. 4983 // 4984 // Also update 4985 // - EventLogger#ALL_DANGEROUS_PERMISSIONS 4986 // - metrics_constants.proto 4987 throw new IllegalStateException("Unknown permission " + name); 4988 } 4989 } 4990 4991 return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4; 4992 } 4993 4994 /** 4995 * Log that a permission was revoked. 4996 * 4997 * @param context Context of the caller 4998 * @param name name of the permission 4999 * @param packageName package permission if for 5000 */ 5001 private static void logPermissionRevoked(@NonNull Context context, @NonNull String name, 5002 @NonNull String packageName) { 5003 MetricsLogger.action(context, getBaseEventId(name) + 3, packageName); 5004 } 5005 5006 /** 5007 * Log that a permission request was granted. 5008 * 5009 * @param context Context of the caller 5010 * @param name name of the permission 5011 * @param packageName package permission if for 5012 */ 5013 private static void logPermissionGranted(@NonNull Context context, @NonNull String name, 5014 @NonNull String packageName) { 5015 MetricsLogger.action(context, getBaseEventId(name) + 1, packageName); 5016 } 5017 5018 @Override 5019 public void resetRuntimePermissions() { 5020 mContext.enforceCallingOrSelfPermission( 5021 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 5022 "revokeRuntimePermission"); 5023 5024 int callingUid = Binder.getCallingUid(); 5025 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 5026 mContext.enforceCallingOrSelfPermission( 5027 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5028 "resetRuntimePermissions"); 5029 } 5030 5031 synchronized (mPackages) { 5032 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 5033 for (int userId : UserManagerService.getInstance().getUserIds()) { 5034 final int packageCount = mPackages.size(); 5035 for (int i = 0; i < packageCount; i++) { 5036 PackageParser.Package pkg = mPackages.valueAt(i); 5037 if (!(pkg.mExtras instanceof PackageSetting)) { 5038 continue; 5039 } 5040 PackageSetting ps = (PackageSetting) pkg.mExtras; 5041 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 5042 } 5043 } 5044 } 5045 } 5046 5047 @Override 5048 public int getPermissionFlags(String name, String packageName, int userId) { 5049 if (!sUserManager.exists(userId)) { 5050 return 0; 5051 } 5052 5053 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 5054 5055 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5056 true /* requireFullPermission */, false /* checkShell */, 5057 "getPermissionFlags"); 5058 5059 synchronized (mPackages) { 5060 final PackageParser.Package pkg = mPackages.get(packageName); 5061 if (pkg == null) { 5062 return 0; 5063 } 5064 5065 final BasePermission bp = mSettings.mPermissions.get(name); 5066 if (bp == null) { 5067 return 0; 5068 } 5069 5070 SettingBase sb = (SettingBase) pkg.mExtras; 5071 if (sb == null) { 5072 return 0; 5073 } 5074 5075 PermissionsState permissionsState = sb.getPermissionsState(); 5076 return permissionsState.getPermissionFlags(name, userId); 5077 } 5078 } 5079 5080 @Override 5081 public void updatePermissionFlags(String name, String packageName, int flagMask, 5082 int flagValues, int userId) { 5083 if (!sUserManager.exists(userId)) { 5084 return; 5085 } 5086 5087 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 5088 5089 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5090 true /* requireFullPermission */, true /* checkShell */, 5091 "updatePermissionFlags"); 5092 5093 // Only the system can change these flags and nothing else. 5094 if (getCallingUid() != Process.SYSTEM_UID) { 5095 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5096 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5097 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 5098 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 5099 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 5100 } 5101 5102 synchronized (mPackages) { 5103 final PackageParser.Package pkg = mPackages.get(packageName); 5104 if (pkg == null) { 5105 throw new IllegalArgumentException("Unknown package: " + packageName); 5106 } 5107 5108 final BasePermission bp = mSettings.mPermissions.get(name); 5109 if (bp == null) { 5110 throw new IllegalArgumentException("Unknown permission: " + name); 5111 } 5112 5113 SettingBase sb = (SettingBase) pkg.mExtras; 5114 if (sb == null) { 5115 throw new IllegalArgumentException("Unknown package: " + packageName); 5116 } 5117 5118 PermissionsState permissionsState = sb.getPermissionsState(); 5119 5120 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 5121 5122 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 5123 // Install and runtime permissions are stored in different places, 5124 // so figure out what permission changed and persist the change. 5125 if (permissionsState.getInstallPermissionState(name) != null) { 5126 scheduleWriteSettingsLocked(); 5127 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 5128 || hadState) { 5129 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 5130 } 5131 } 5132 } 5133 } 5134 5135 /** 5136 * Update the permission flags for all packages and runtime permissions of a user in order 5137 * to allow device or profile owner to remove POLICY_FIXED. 5138 */ 5139 @Override 5140 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 5141 if (!sUserManager.exists(userId)) { 5142 return; 5143 } 5144 5145 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 5146 5147 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5148 true /* requireFullPermission */, true /* checkShell */, 5149 "updatePermissionFlagsForAllApps"); 5150 5151 // Only the system can change system fixed flags. 5152 if (getCallingUid() != Process.SYSTEM_UID) { 5153 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5154 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5155 } 5156 5157 synchronized (mPackages) { 5158 boolean changed = false; 5159 final int packageCount = mPackages.size(); 5160 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 5161 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 5162 SettingBase sb = (SettingBase) pkg.mExtras; 5163 if (sb == null) { 5164 continue; 5165 } 5166 PermissionsState permissionsState = sb.getPermissionsState(); 5167 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 5168 userId, flagMask, flagValues); 5169 } 5170 if (changed) { 5171 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 5172 } 5173 } 5174 } 5175 5176 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 5177 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 5178 != PackageManager.PERMISSION_GRANTED 5179 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 5180 != PackageManager.PERMISSION_GRANTED) { 5181 throw new SecurityException(message + " requires " 5182 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 5183 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 5184 } 5185 } 5186 5187 @Override 5188 public boolean shouldShowRequestPermissionRationale(String permissionName, 5189 String packageName, int userId) { 5190 if (UserHandle.getCallingUserId() != userId) { 5191 mContext.enforceCallingPermission( 5192 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5193 "canShowRequestPermissionRationale for user " + userId); 5194 } 5195 5196 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 5197 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 5198 return false; 5199 } 5200 5201 if (checkPermission(permissionName, packageName, userId) 5202 == PackageManager.PERMISSION_GRANTED) { 5203 return false; 5204 } 5205 5206 final int flags; 5207 5208 final long identity = Binder.clearCallingIdentity(); 5209 try { 5210 flags = getPermissionFlags(permissionName, 5211 packageName, userId); 5212 } finally { 5213 Binder.restoreCallingIdentity(identity); 5214 } 5215 5216 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 5217 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 5218 | PackageManager.FLAG_PERMISSION_USER_FIXED; 5219 5220 if ((flags & fixedFlags) != 0) { 5221 return false; 5222 } 5223 5224 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 5225 } 5226 5227 @Override 5228 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 5229 mContext.enforceCallingOrSelfPermission( 5230 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 5231 "addOnPermissionsChangeListener"); 5232 5233 synchronized (mPackages) { 5234 mOnPermissionChangeListeners.addListenerLocked(listener); 5235 } 5236 } 5237 5238 @Override 5239 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 5240 synchronized (mPackages) { 5241 mOnPermissionChangeListeners.removeListenerLocked(listener); 5242 } 5243 } 5244 5245 @Override 5246 public boolean isProtectedBroadcast(String actionName) { 5247 synchronized (mPackages) { 5248 if (mProtectedBroadcasts.contains(actionName)) { 5249 return true; 5250 } else if (actionName != null) { 5251 // TODO: remove these terrible hacks 5252 if (actionName.startsWith("android.net.netmon.lingerExpired") 5253 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 5254 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 5255 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 5256 return true; 5257 } 5258 } 5259 } 5260 return false; 5261 } 5262 5263 @Override 5264 public int checkSignatures(String pkg1, String pkg2) { 5265 synchronized (mPackages) { 5266 final PackageParser.Package p1 = mPackages.get(pkg1); 5267 final PackageParser.Package p2 = mPackages.get(pkg2); 5268 if (p1 == null || p1.mExtras == null 5269 || p2 == null || p2.mExtras == null) { 5270 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5271 } 5272 return compareSignatures(p1.mSignatures, p2.mSignatures); 5273 } 5274 } 5275 5276 @Override 5277 public int checkUidSignatures(int uid1, int uid2) { 5278 // Map to base uids. 5279 uid1 = UserHandle.getAppId(uid1); 5280 uid2 = UserHandle.getAppId(uid2); 5281 // reader 5282 synchronized (mPackages) { 5283 Signature[] s1; 5284 Signature[] s2; 5285 Object obj = mSettings.getUserIdLPr(uid1); 5286 if (obj != null) { 5287 if (obj instanceof SharedUserSetting) { 5288 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 5289 } else if (obj instanceof PackageSetting) { 5290 s1 = ((PackageSetting)obj).signatures.mSignatures; 5291 } else { 5292 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5293 } 5294 } else { 5295 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5296 } 5297 obj = mSettings.getUserIdLPr(uid2); 5298 if (obj != null) { 5299 if (obj instanceof SharedUserSetting) { 5300 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 5301 } else if (obj instanceof PackageSetting) { 5302 s2 = ((PackageSetting)obj).signatures.mSignatures; 5303 } else { 5304 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5305 } 5306 } else { 5307 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5308 } 5309 return compareSignatures(s1, s2); 5310 } 5311 } 5312 5313 /** 5314 * This method should typically only be used when granting or revoking 5315 * permissions, since the app may immediately restart after this call. 5316 * <p> 5317 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 5318 * guard your work against the app being relaunched. 5319 */ 5320 private void killUid(int appId, int userId, String reason) { 5321 final long identity = Binder.clearCallingIdentity(); 5322 try { 5323 IActivityManager am = ActivityManager.getService(); 5324 if (am != null) { 5325 try { 5326 am.killUid(appId, userId, reason); 5327 } catch (RemoteException e) { 5328 /* ignore - same process */ 5329 } 5330 } 5331 } finally { 5332 Binder.restoreCallingIdentity(identity); 5333 } 5334 } 5335 5336 /** 5337 * Compares two sets of signatures. Returns: 5338 * <br /> 5339 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 5340 * <br /> 5341 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 5342 * <br /> 5343 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 5344 * <br /> 5345 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 5346 * <br /> 5347 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 5348 */ 5349 static int compareSignatures(Signature[] s1, Signature[] s2) { 5350 if (s1 == null) { 5351 return s2 == null 5352 ? PackageManager.SIGNATURE_NEITHER_SIGNED 5353 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 5354 } 5355 5356 if (s2 == null) { 5357 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 5358 } 5359 5360 if (s1.length != s2.length) { 5361 return PackageManager.SIGNATURE_NO_MATCH; 5362 } 5363 5364 // Since both signature sets are of size 1, we can compare without HashSets. 5365 if (s1.length == 1) { 5366 return s1[0].equals(s2[0]) ? 5367 PackageManager.SIGNATURE_MATCH : 5368 PackageManager.SIGNATURE_NO_MATCH; 5369 } 5370 5371 ArraySet<Signature> set1 = new ArraySet<Signature>(); 5372 for (Signature sig : s1) { 5373 set1.add(sig); 5374 } 5375 ArraySet<Signature> set2 = new ArraySet<Signature>(); 5376 for (Signature sig : s2) { 5377 set2.add(sig); 5378 } 5379 // Make sure s2 contains all signatures in s1. 5380 if (set1.equals(set2)) { 5381 return PackageManager.SIGNATURE_MATCH; 5382 } 5383 return PackageManager.SIGNATURE_NO_MATCH; 5384 } 5385 5386 /** 5387 * If the database version for this type of package (internal storage or 5388 * external storage) is less than the version where package signatures 5389 * were updated, return true. 5390 */ 5391 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 5392 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 5393 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 5394 } 5395 5396 /** 5397 * Used for backward compatibility to make sure any packages with 5398 * certificate chains get upgraded to the new style. {@code existingSigs} 5399 * will be in the old format (since they were stored on disk from before the 5400 * system upgrade) and {@code scannedSigs} will be in the newer format. 5401 */ 5402 private int compareSignaturesCompat(PackageSignatures existingSigs, 5403 PackageParser.Package scannedPkg) { 5404 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 5405 return PackageManager.SIGNATURE_NO_MATCH; 5406 } 5407 5408 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 5409 for (Signature sig : existingSigs.mSignatures) { 5410 existingSet.add(sig); 5411 } 5412 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 5413 for (Signature sig : scannedPkg.mSignatures) { 5414 try { 5415 Signature[] chainSignatures = sig.getChainSignatures(); 5416 for (Signature chainSig : chainSignatures) { 5417 scannedCompatSet.add(chainSig); 5418 } 5419 } catch (CertificateEncodingException e) { 5420 scannedCompatSet.add(sig); 5421 } 5422 } 5423 /* 5424 * Make sure the expanded scanned set contains all signatures in the 5425 * existing one. 5426 */ 5427 if (scannedCompatSet.equals(existingSet)) { 5428 // Migrate the old signatures to the new scheme. 5429 existingSigs.assignSignatures(scannedPkg.mSignatures); 5430 // The new KeySets will be re-added later in the scanning process. 5431 synchronized (mPackages) { 5432 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 5433 } 5434 return PackageManager.SIGNATURE_MATCH; 5435 } 5436 return PackageManager.SIGNATURE_NO_MATCH; 5437 } 5438 5439 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 5440 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 5441 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 5442 } 5443 5444 private int compareSignaturesRecover(PackageSignatures existingSigs, 5445 PackageParser.Package scannedPkg) { 5446 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 5447 return PackageManager.SIGNATURE_NO_MATCH; 5448 } 5449 5450 String msg = null; 5451 try { 5452 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 5453 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 5454 + scannedPkg.packageName); 5455 return PackageManager.SIGNATURE_MATCH; 5456 } 5457 } catch (CertificateException e) { 5458 msg = e.getMessage(); 5459 } 5460 5461 logCriticalInfo(Log.INFO, 5462 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 5463 return PackageManager.SIGNATURE_NO_MATCH; 5464 } 5465 5466 @Override 5467 public List<String> getAllPackages() { 5468 synchronized (mPackages) { 5469 return new ArrayList<String>(mPackages.keySet()); 5470 } 5471 } 5472 5473 @Override 5474 public String[] getPackagesForUid(int uid) { 5475 final int userId = UserHandle.getUserId(uid); 5476 uid = UserHandle.getAppId(uid); 5477 // reader 5478 synchronized (mPackages) { 5479 Object obj = mSettings.getUserIdLPr(uid); 5480 if (obj instanceof SharedUserSetting) { 5481 final SharedUserSetting sus = (SharedUserSetting) obj; 5482 final int N = sus.packages.size(); 5483 String[] res = new String[N]; 5484 final Iterator<PackageSetting> it = sus.packages.iterator(); 5485 int i = 0; 5486 while (it.hasNext()) { 5487 PackageSetting ps = it.next(); 5488 if (ps.getInstalled(userId)) { 5489 res[i++] = ps.name; 5490 } else { 5491 res = ArrayUtils.removeElement(String.class, res, res[i]); 5492 } 5493 } 5494 return res; 5495 } else if (obj instanceof PackageSetting) { 5496 final PackageSetting ps = (PackageSetting) obj; 5497 if (ps.getInstalled(userId)) { 5498 return new String[]{ps.name}; 5499 } 5500 } 5501 } 5502 return null; 5503 } 5504 5505 @Override 5506 public String getNameForUid(int uid) { 5507 // reader 5508 synchronized (mPackages) { 5509 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5510 if (obj instanceof SharedUserSetting) { 5511 final SharedUserSetting sus = (SharedUserSetting) obj; 5512 return sus.name + ":" + sus.userId; 5513 } else if (obj instanceof PackageSetting) { 5514 final PackageSetting ps = (PackageSetting) obj; 5515 return ps.name; 5516 } 5517 } 5518 return null; 5519 } 5520 5521 @Override 5522 public int getUidForSharedUser(String sharedUserName) { 5523 if(sharedUserName == null) { 5524 return -1; 5525 } 5526 // reader 5527 synchronized (mPackages) { 5528 SharedUserSetting suid; 5529 try { 5530 suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 5531 if (suid != null) { 5532 return suid.userId; 5533 } 5534 } catch (PackageManagerException ignore) { 5535 // can't happen, but, still need to catch it 5536 } 5537 return -1; 5538 } 5539 } 5540 5541 @Override 5542 public int getFlagsForUid(int uid) { 5543 synchronized (mPackages) { 5544 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5545 if (obj instanceof SharedUserSetting) { 5546 final SharedUserSetting sus = (SharedUserSetting) obj; 5547 return sus.pkgFlags; 5548 } else if (obj instanceof PackageSetting) { 5549 final PackageSetting ps = (PackageSetting) obj; 5550 return ps.pkgFlags; 5551 } 5552 } 5553 return 0; 5554 } 5555 5556 @Override 5557 public int getPrivateFlagsForUid(int uid) { 5558 synchronized (mPackages) { 5559 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5560 if (obj instanceof SharedUserSetting) { 5561 final SharedUserSetting sus = (SharedUserSetting) obj; 5562 return sus.pkgPrivateFlags; 5563 } else if (obj instanceof PackageSetting) { 5564 final PackageSetting ps = (PackageSetting) obj; 5565 return ps.pkgPrivateFlags; 5566 } 5567 } 5568 return 0; 5569 } 5570 5571 @Override 5572 public boolean isUidPrivileged(int uid) { 5573 uid = UserHandle.getAppId(uid); 5574 // reader 5575 synchronized (mPackages) { 5576 Object obj = mSettings.getUserIdLPr(uid); 5577 if (obj instanceof SharedUserSetting) { 5578 final SharedUserSetting sus = (SharedUserSetting) obj; 5579 final Iterator<PackageSetting> it = sus.packages.iterator(); 5580 while (it.hasNext()) { 5581 if (it.next().isPrivileged()) { 5582 return true; 5583 } 5584 } 5585 } else if (obj instanceof PackageSetting) { 5586 final PackageSetting ps = (PackageSetting) obj; 5587 return ps.isPrivileged(); 5588 } 5589 } 5590 return false; 5591 } 5592 5593 @Override 5594 public String[] getAppOpPermissionPackages(String permissionName) { 5595 synchronized (mPackages) { 5596 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 5597 if (pkgs == null) { 5598 return null; 5599 } 5600 return pkgs.toArray(new String[pkgs.size()]); 5601 } 5602 } 5603 5604 @Override 5605 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 5606 int flags, int userId) { 5607 return resolveIntentInternal( 5608 intent, resolvedType, flags, userId, false /*includeInstantApp*/); 5609 } 5610 5611 private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType, 5612 int flags, int userId, boolean includeInstantApp) { 5613 try { 5614 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 5615 5616 if (!sUserManager.exists(userId)) return null; 5617 flags = updateFlagsForResolve(flags, userId, intent, includeInstantApp); 5618 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5619 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 5620 5621 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5622 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 5623 flags, userId, includeInstantApp); 5624 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5625 5626 final ResolveInfo bestChoice = 5627 chooseBestActivity(intent, resolvedType, flags, query, userId); 5628 return bestChoice; 5629 } finally { 5630 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5631 } 5632 } 5633 5634 @Override 5635 public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) { 5636 if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) { 5637 throw new SecurityException( 5638 "findPersistentPreferredActivity can only be run by the system"); 5639 } 5640 if (!sUserManager.exists(userId)) { 5641 return null; 5642 } 5643 intent = updateIntentForResolve(intent); 5644 final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver()); 5645 final int flags = updateFlagsForResolve(0, userId, intent, false); 5646 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5647 userId); 5648 synchronized (mPackages) { 5649 return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false, 5650 userId); 5651 } 5652 } 5653 5654 @Override 5655 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 5656 IntentFilter filter, int match, ComponentName activity) { 5657 final int userId = UserHandle.getCallingUserId(); 5658 if (DEBUG_PREFERRED) { 5659 Log.v(TAG, "setLastChosenActivity intent=" + intent 5660 + " resolvedType=" + resolvedType 5661 + " flags=" + flags 5662 + " filter=" + filter 5663 + " match=" + match 5664 + " activity=" + activity); 5665 filter.dump(new PrintStreamPrinter(System.out), " "); 5666 } 5667 intent.setComponent(null); 5668 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5669 userId); 5670 // Find any earlier preferred or last chosen entries and nuke them 5671 findPreferredActivity(intent, resolvedType, 5672 flags, query, 0, false, true, false, userId); 5673 // Add the new activity as the last chosen for this filter 5674 addPreferredActivityInternal(filter, match, null, activity, false, userId, 5675 "Setting last chosen"); 5676 } 5677 5678 @Override 5679 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 5680 final int userId = UserHandle.getCallingUserId(); 5681 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 5682 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5683 userId); 5684 return findPreferredActivity(intent, resolvedType, flags, query, 0, 5685 false, false, false, userId); 5686 } 5687 5688 /** 5689 * Returns whether or not instant apps have been disabled remotely. 5690 * <p><em>IMPORTANT</em> This should not be called with the package manager lock 5691 * held. Otherwise we run the risk of deadlock. 5692 */ 5693 private boolean isEphemeralDisabled() { 5694 // ephemeral apps have been disabled across the board 5695 if (DISABLE_EPHEMERAL_APPS) { 5696 return true; 5697 } 5698 // system isn't up yet; can't read settings, so, assume no ephemeral apps 5699 if (!mSystemReady) { 5700 return true; 5701 } 5702 // we can't get a content resolver until the system is ready; these checks must happen last 5703 final ContentResolver resolver = mContext.getContentResolver(); 5704 if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) { 5705 return true; 5706 } 5707 return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0; 5708 } 5709 5710 private boolean isEphemeralAllowed( 5711 Intent intent, List<ResolveInfo> resolvedActivities, int userId, 5712 boolean skipPackageCheck) { 5713 final int callingUser = UserHandle.getCallingUserId(); 5714 if (callingUser != UserHandle.USER_SYSTEM) { 5715 return false; 5716 } 5717 if (mInstantAppResolverConnection == null) { 5718 return false; 5719 } 5720 if (mInstantAppInstallerComponent == null) { 5721 return false; 5722 } 5723 if (intent.getComponent() != null) { 5724 return false; 5725 } 5726 if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) { 5727 return false; 5728 } 5729 if (!skipPackageCheck && intent.getPackage() != null) { 5730 return false; 5731 } 5732 final boolean isWebUri = hasWebURI(intent); 5733 if (!isWebUri || intent.getData().getHost() == null) { 5734 return false; 5735 } 5736 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 5737 // Or if there's already an ephemeral app installed that handles the action 5738 synchronized (mPackages) { 5739 final int count = (resolvedActivities == null ? 0 : resolvedActivities.size()); 5740 for (int n = 0; n < count; n++) { 5741 ResolveInfo info = resolvedActivities.get(n); 5742 String packageName = info.activityInfo.packageName; 5743 PackageSetting ps = mSettings.mPackages.get(packageName); 5744 if (ps != null) { 5745 // Try to get the status from User settings first 5746 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5747 int status = (int) (packedStatus >> 32); 5748 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 5749 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5750 if (DEBUG_EPHEMERAL) { 5751 Slog.v(TAG, "DENY ephemeral apps;" 5752 + " pkg: " + packageName + ", status: " + status); 5753 } 5754 return false; 5755 } 5756 if (ps.getInstantApp(userId)) { 5757 return false; 5758 } 5759 } 5760 } 5761 } 5762 // We've exhausted all ways to deny ephemeral application; let the system look for them. 5763 return true; 5764 } 5765 5766 private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj, 5767 Intent origIntent, String resolvedType, String callingPackage, 5768 int userId) { 5769 final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO, 5770 new EphemeralRequest(responseObj, origIntent, resolvedType, 5771 callingPackage, userId)); 5772 mHandler.sendMessage(msg); 5773 } 5774 5775 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 5776 int flags, List<ResolveInfo> query, int userId) { 5777 if (query != null) { 5778 final int N = query.size(); 5779 if (N == 1) { 5780 return query.get(0); 5781 } else if (N > 1) { 5782 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 5783 // If there is more than one activity with the same priority, 5784 // then let the user decide between them. 5785 ResolveInfo r0 = query.get(0); 5786 ResolveInfo r1 = query.get(1); 5787 if (DEBUG_INTENT_MATCHING || debug) { 5788 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 5789 + r1.activityInfo.name + "=" + r1.priority); 5790 } 5791 // If the first activity has a higher priority, or a different 5792 // default, then it is always desirable to pick it. 5793 if (r0.priority != r1.priority 5794 || r0.preferredOrder != r1.preferredOrder 5795 || r0.isDefault != r1.isDefault) { 5796 return query.get(0); 5797 } 5798 // If we have saved a preference for a preferred activity for 5799 // this Intent, use that. 5800 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 5801 flags, query, r0.priority, true, false, debug, userId); 5802 if (ri != null) { 5803 return ri; 5804 } 5805 // If we have an ephemeral app, use it 5806 for (int i = 0; i < N; i++) { 5807 ri = query.get(i); 5808 if (ri.activityInfo.applicationInfo.isInstantApp()) { 5809 return ri; 5810 } 5811 } 5812 ri = new ResolveInfo(mResolveInfo); 5813 ri.activityInfo = new ActivityInfo(ri.activityInfo); 5814 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 5815 // If all of the options come from the same package, show the application's 5816 // label and icon instead of the generic resolver's. 5817 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 5818 // and then throw away the ResolveInfo itself, meaning that the caller loses 5819 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 5820 // a fallback for this case; we only set the target package's resources on 5821 // the ResolveInfo, not the ActivityInfo. 5822 final String intentPackage = intent.getPackage(); 5823 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 5824 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 5825 ri.resolvePackageName = intentPackage; 5826 if (userNeedsBadging(userId)) { 5827 ri.noResourceId = true; 5828 } else { 5829 ri.icon = appi.icon; 5830 } 5831 ri.iconResourceId = appi.icon; 5832 ri.labelRes = appi.labelRes; 5833 } 5834 ri.activityInfo.applicationInfo = new ApplicationInfo( 5835 ri.activityInfo.applicationInfo); 5836 if (userId != 0) { 5837 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 5838 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 5839 } 5840 // Make sure that the resolver is displayable in car mode 5841 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 5842 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 5843 return ri; 5844 } 5845 } 5846 return null; 5847 } 5848 5849 /** 5850 * Return true if the given list is not empty and all of its contents have 5851 * an activityInfo with the given package name. 5852 */ 5853 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 5854 if (ArrayUtils.isEmpty(list)) { 5855 return false; 5856 } 5857 for (int i = 0, N = list.size(); i < N; i++) { 5858 final ResolveInfo ri = list.get(i); 5859 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 5860 if (ai == null || !packageName.equals(ai.packageName)) { 5861 return false; 5862 } 5863 } 5864 return true; 5865 } 5866 5867 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 5868 int flags, List<ResolveInfo> query, boolean debug, int userId) { 5869 final int N = query.size(); 5870 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 5871 .get(userId); 5872 // Get the list of persistent preferred activities that handle the intent 5873 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 5874 List<PersistentPreferredActivity> pprefs = ppir != null 5875 ? ppir.queryIntent(intent, resolvedType, 5876 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 5877 userId) 5878 : null; 5879 if (pprefs != null && pprefs.size() > 0) { 5880 final int M = pprefs.size(); 5881 for (int i=0; i<M; i++) { 5882 final PersistentPreferredActivity ppa = pprefs.get(i); 5883 if (DEBUG_PREFERRED || debug) { 5884 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 5885 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 5886 + "\n component=" + ppa.mComponent); 5887 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5888 } 5889 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 5890 flags | MATCH_DISABLED_COMPONENTS, userId); 5891 if (DEBUG_PREFERRED || debug) { 5892 Slog.v(TAG, "Found persistent preferred activity:"); 5893 if (ai != null) { 5894 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5895 } else { 5896 Slog.v(TAG, " null"); 5897 } 5898 } 5899 if (ai == null) { 5900 // This previously registered persistent preferred activity 5901 // component is no longer known. Ignore it and do NOT remove it. 5902 continue; 5903 } 5904 for (int j=0; j<N; j++) { 5905 final ResolveInfo ri = query.get(j); 5906 if (!ri.activityInfo.applicationInfo.packageName 5907 .equals(ai.applicationInfo.packageName)) { 5908 continue; 5909 } 5910 if (!ri.activityInfo.name.equals(ai.name)) { 5911 continue; 5912 } 5913 // Found a persistent preference that can handle the intent. 5914 if (DEBUG_PREFERRED || debug) { 5915 Slog.v(TAG, "Returning persistent preferred activity: " + 5916 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5917 } 5918 return ri; 5919 } 5920 } 5921 } 5922 return null; 5923 } 5924 5925 // TODO: handle preferred activities missing while user has amnesia 5926 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5927 List<ResolveInfo> query, int priority, boolean always, 5928 boolean removeMatches, boolean debug, int userId) { 5929 if (!sUserManager.exists(userId)) return null; 5930 flags = updateFlagsForResolve(flags, userId, intent, false); 5931 intent = updateIntentForResolve(intent); 5932 // writer 5933 synchronized (mPackages) { 5934 // Try to find a matching persistent preferred activity. 5935 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5936 debug, userId); 5937 5938 // If a persistent preferred activity matched, use it. 5939 if (pri != null) { 5940 return pri; 5941 } 5942 5943 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5944 // Get the list of preferred activities that handle the intent 5945 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5946 List<PreferredActivity> prefs = pir != null 5947 ? pir.queryIntent(intent, resolvedType, 5948 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 5949 userId) 5950 : null; 5951 if (prefs != null && prefs.size() > 0) { 5952 boolean changed = false; 5953 try { 5954 // First figure out how good the original match set is. 5955 // We will only allow preferred activities that came 5956 // from the same match quality. 5957 int match = 0; 5958 5959 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5960 5961 final int N = query.size(); 5962 for (int j=0; j<N; j++) { 5963 final ResolveInfo ri = query.get(j); 5964 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5965 + ": 0x" + Integer.toHexString(match)); 5966 if (ri.match > match) { 5967 match = ri.match; 5968 } 5969 } 5970 5971 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5972 + Integer.toHexString(match)); 5973 5974 match &= IntentFilter.MATCH_CATEGORY_MASK; 5975 final int M = prefs.size(); 5976 for (int i=0; i<M; i++) { 5977 final PreferredActivity pa = prefs.get(i); 5978 if (DEBUG_PREFERRED || debug) { 5979 Slog.v(TAG, "Checking PreferredActivity ds=" 5980 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5981 + "\n component=" + pa.mPref.mComponent); 5982 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5983 } 5984 if (pa.mPref.mMatch != match) { 5985 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5986 + Integer.toHexString(pa.mPref.mMatch)); 5987 continue; 5988 } 5989 // If it's not an "always" type preferred activity and that's what we're 5990 // looking for, skip it. 5991 if (always && !pa.mPref.mAlways) { 5992 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5993 continue; 5994 } 5995 final ActivityInfo ai = getActivityInfo( 5996 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5997 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5998 userId); 5999 if (DEBUG_PREFERRED || debug) { 6000 Slog.v(TAG, "Found preferred activity:"); 6001 if (ai != null) { 6002 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6003 } else { 6004 Slog.v(TAG, " null"); 6005 } 6006 } 6007 if (ai == null) { 6008 // This previously registered preferred activity 6009 // component is no longer known. Most likely an update 6010 // to the app was installed and in the new version this 6011 // component no longer exists. Clean it up by removing 6012 // it from the preferred activities list, and skip it. 6013 Slog.w(TAG, "Removing dangling preferred activity: " 6014 + pa.mPref.mComponent); 6015 pir.removeFilter(pa); 6016 changed = true; 6017 continue; 6018 } 6019 for (int j=0; j<N; j++) { 6020 final ResolveInfo ri = query.get(j); 6021 if (!ri.activityInfo.applicationInfo.packageName 6022 .equals(ai.applicationInfo.packageName)) { 6023 continue; 6024 } 6025 if (!ri.activityInfo.name.equals(ai.name)) { 6026 continue; 6027 } 6028 6029 if (removeMatches) { 6030 pir.removeFilter(pa); 6031 changed = true; 6032 if (DEBUG_PREFERRED) { 6033 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 6034 } 6035 break; 6036 } 6037 6038 // Okay we found a previously set preferred or last chosen app. 6039 // If the result set is different from when this 6040 // was created, we need to clear it and re-ask the 6041 // user their preference, if we're looking for an "always" type entry. 6042 if (always && !pa.mPref.sameSet(query)) { 6043 Slog.i(TAG, "Result set changed, dropping preferred activity for " 6044 + intent + " type " + resolvedType); 6045 if (DEBUG_PREFERRED) { 6046 Slog.v(TAG, "Removing preferred activity since set changed " 6047 + pa.mPref.mComponent); 6048 } 6049 pir.removeFilter(pa); 6050 // Re-add the filter as a "last chosen" entry (!always) 6051 PreferredActivity lastChosen = new PreferredActivity( 6052 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 6053 pir.addFilter(lastChosen); 6054 changed = true; 6055 return null; 6056 } 6057 6058 // Yay! Either the set matched or we're looking for the last chosen 6059 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 6060 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 6061 return ri; 6062 } 6063 } 6064 } finally { 6065 if (changed) { 6066 if (DEBUG_PREFERRED) { 6067 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 6068 } 6069 scheduleWritePackageRestrictionsLocked(userId); 6070 } 6071 } 6072 } 6073 } 6074 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 6075 return null; 6076 } 6077 6078 /* 6079 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 6080 */ 6081 @Override 6082 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 6083 int targetUserId) { 6084 mContext.enforceCallingOrSelfPermission( 6085 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 6086 List<CrossProfileIntentFilter> matches = 6087 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 6088 if (matches != null) { 6089 int size = matches.size(); 6090 for (int i = 0; i < size; i++) { 6091 if (matches.get(i).getTargetUserId() == targetUserId) return true; 6092 } 6093 } 6094 if (hasWebURI(intent)) { 6095 // cross-profile app linking works only towards the parent. 6096 final UserInfo parent = getProfileParent(sourceUserId); 6097 synchronized(mPackages) { 6098 int flags = updateFlagsForResolve(0, parent.id, intent, false); 6099 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 6100 intent, resolvedType, flags, sourceUserId, parent.id); 6101 return xpDomainInfo != null; 6102 } 6103 } 6104 return false; 6105 } 6106 6107 private UserInfo getProfileParent(int userId) { 6108 final long identity = Binder.clearCallingIdentity(); 6109 try { 6110 return sUserManager.getProfileParent(userId); 6111 } finally { 6112 Binder.restoreCallingIdentity(identity); 6113 } 6114 } 6115 6116 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 6117 String resolvedType, int userId) { 6118 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 6119 if (resolver != null) { 6120 return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId); 6121 } 6122 return null; 6123 } 6124 6125 @Override 6126 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 6127 String resolvedType, int flags, int userId) { 6128 try { 6129 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 6130 6131 return new ParceledListSlice<>( 6132 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 6133 } finally { 6134 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6135 } 6136 } 6137 6138 /** 6139 * Returns the package name of the calling Uid if it's an instant app. If it isn't 6140 * instant, returns {@code null}. 6141 */ 6142 private String getInstantAppPackageName(int callingUid) { 6143 final int appId = UserHandle.getAppId(callingUid); 6144 synchronized (mPackages) { 6145 final Object obj = mSettings.getUserIdLPr(appId); 6146 if (obj instanceof PackageSetting) { 6147 final PackageSetting ps = (PackageSetting) obj; 6148 final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid)); 6149 return isInstantApp ? ps.pkg.packageName : null; 6150 } 6151 } 6152 return null; 6153 } 6154 6155 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 6156 String resolvedType, int flags, int userId) { 6157 return queryIntentActivitiesInternal(intent, resolvedType, flags, userId, false); 6158 } 6159 6160 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 6161 String resolvedType, int flags, int userId, boolean includeInstantApp) { 6162 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6163 final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid()); 6164 flags = updateFlagsForResolve(flags, userId, intent, includeInstantApp); 6165 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6166 false /* requireFullPermission */, false /* checkShell */, 6167 "query intent activities"); 6168 ComponentName comp = intent.getComponent(); 6169 if (comp == null) { 6170 if (intent.getSelector() != null) { 6171 intent = intent.getSelector(); 6172 comp = intent.getComponent(); 6173 } 6174 } 6175 6176 if (comp != null) { 6177 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6178 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 6179 if (ai != null) { 6180 // When specifying an explicit component, we prevent the activity from being 6181 // used when either 1) the calling package is normal and the activity is within 6182 // an ephemeral application or 2) the calling package is ephemeral and the 6183 // activity is not visible to ephemeral applications. 6184 final boolean matchInstantApp = 6185 (flags & PackageManager.MATCH_INSTANT) != 0; 6186 final boolean matchVisibleToInstantAppOnly = 6187 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 6188 final boolean isCallerInstantApp = 6189 instantAppPkgName != null; 6190 final boolean isTargetSameInstantApp = 6191 comp.getPackageName().equals(instantAppPkgName); 6192 final boolean isTargetInstantApp = 6193 (ai.applicationInfo.privateFlags 6194 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 6195 final boolean isTargetHiddenFromInstantApp = 6196 (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0; 6197 final boolean blockResolution = 6198 !isTargetSameInstantApp 6199 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 6200 || (matchVisibleToInstantAppOnly && isCallerInstantApp 6201 && isTargetHiddenFromInstantApp)); 6202 if (!blockResolution) { 6203 final ResolveInfo ri = new ResolveInfo(); 6204 ri.activityInfo = ai; 6205 list.add(ri); 6206 } 6207 } 6208 return applyPostResolutionFilter(list, instantAppPkgName); 6209 } 6210 6211 // reader 6212 boolean sortResult = false; 6213 boolean addEphemeral = false; 6214 List<ResolveInfo> result; 6215 final String pkgName = intent.getPackage(); 6216 final boolean ephemeralDisabled = isEphemeralDisabled(); 6217 synchronized (mPackages) { 6218 if (pkgName == null) { 6219 List<CrossProfileIntentFilter> matchingFilters = 6220 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 6221 // Check for results that need to skip the current profile. 6222 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 6223 resolvedType, flags, userId); 6224 if (xpResolveInfo != null) { 6225 List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1); 6226 xpResult.add(xpResolveInfo); 6227 return applyPostResolutionFilter( 6228 filterIfNotSystemUser(xpResult, userId), instantAppPkgName); 6229 } 6230 6231 // Check for results in the current profile. 6232 result = filterIfNotSystemUser(mActivities.queryIntent( 6233 intent, resolvedType, flags, userId), userId); 6234 addEphemeral = !ephemeralDisabled 6235 && isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/); 6236 6237 // Check for cross profile results. 6238 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 6239 xpResolveInfo = queryCrossProfileIntents( 6240 matchingFilters, intent, resolvedType, flags, userId, 6241 hasNonNegativePriorityResult); 6242 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 6243 boolean isVisibleToUser = filterIfNotSystemUser( 6244 Collections.singletonList(xpResolveInfo), userId).size() > 0; 6245 if (isVisibleToUser) { 6246 result.add(xpResolveInfo); 6247 sortResult = true; 6248 } 6249 } 6250 if (hasWebURI(intent)) { 6251 CrossProfileDomainInfo xpDomainInfo = null; 6252 final UserInfo parent = getProfileParent(userId); 6253 if (parent != null) { 6254 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 6255 flags, userId, parent.id); 6256 } 6257 if (xpDomainInfo != null) { 6258 if (xpResolveInfo != null) { 6259 // If we didn't remove it, the cross-profile ResolveInfo would be twice 6260 // in the result. 6261 result.remove(xpResolveInfo); 6262 } 6263 if (result.size() == 0 && !addEphemeral) { 6264 // No result in current profile, but found candidate in parent user. 6265 // And we are not going to add emphemeral app, so we can return the 6266 // result straight away. 6267 result.add(xpDomainInfo.resolveInfo); 6268 return applyPostResolutionFilter(result, instantAppPkgName); 6269 } 6270 } else if (result.size() <= 1 && !addEphemeral) { 6271 // No result in parent user and <= 1 result in current profile, and we 6272 // are not going to add emphemeral app, so we can return the result without 6273 // further processing. 6274 return applyPostResolutionFilter(result, instantAppPkgName); 6275 } 6276 // We have more than one candidate (combining results from current and parent 6277 // profile), so we need filtering and sorting. 6278 result = filterCandidatesWithDomainPreferredActivitiesLPr( 6279 intent, flags, result, xpDomainInfo, userId); 6280 sortResult = true; 6281 } 6282 } else { 6283 final PackageParser.Package pkg = mPackages.get(pkgName); 6284 if (pkg != null) { 6285 result = applyPostResolutionFilter(filterIfNotSystemUser( 6286 mActivities.queryIntentForPackage( 6287 intent, resolvedType, flags, pkg.activities, userId), 6288 userId), instantAppPkgName); 6289 } else { 6290 // the caller wants to resolve for a particular package; however, there 6291 // were no installed results, so, try to find an ephemeral result 6292 addEphemeral = !ephemeralDisabled 6293 && isEphemeralAllowed( 6294 intent, null /*result*/, userId, true /*skipPackageCheck*/); 6295 result = new ArrayList<ResolveInfo>(); 6296 } 6297 } 6298 } 6299 if (addEphemeral) { 6300 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 6301 final EphemeralRequest requestObject = new EphemeralRequest( 6302 null /*responseObj*/, intent /*origIntent*/, resolvedType, 6303 null /*callingPackage*/, userId); 6304 final AuxiliaryResolveInfo auxiliaryResponse = 6305 EphemeralResolver.doEphemeralResolutionPhaseOne( 6306 mContext, mInstantAppResolverConnection, requestObject); 6307 if (auxiliaryResponse != null) { 6308 if (DEBUG_EPHEMERAL) { 6309 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 6310 } 6311 final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo); 6312 ephemeralInstaller.auxiliaryInfo = auxiliaryResponse; 6313 // make sure this resolver is the default 6314 ephemeralInstaller.isDefault = true; 6315 ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 6316 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 6317 // add a non-generic filter 6318 ephemeralInstaller.filter = new IntentFilter(intent.getAction()); 6319 ephemeralInstaller.filter.addDataPath( 6320 intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL); 6321 ephemeralInstaller.instantAppAvailable = true; 6322 result.add(ephemeralInstaller); 6323 } 6324 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6325 } 6326 if (sortResult) { 6327 Collections.sort(result, mResolvePrioritySorter); 6328 } 6329 return applyPostResolutionFilter(result, instantAppPkgName); 6330 } 6331 6332 private static class CrossProfileDomainInfo { 6333 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 6334 ResolveInfo resolveInfo; 6335 /* Best domain verification status of the activities found in the other profile */ 6336 int bestDomainVerificationStatus; 6337 } 6338 6339 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 6340 String resolvedType, int flags, int sourceUserId, int parentUserId) { 6341 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 6342 sourceUserId)) { 6343 return null; 6344 } 6345 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 6346 resolvedType, flags, parentUserId); 6347 6348 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 6349 return null; 6350 } 6351 CrossProfileDomainInfo result = null; 6352 int size = resultTargetUser.size(); 6353 for (int i = 0; i < size; i++) { 6354 ResolveInfo riTargetUser = resultTargetUser.get(i); 6355 // Intent filter verification is only for filters that specify a host. So don't return 6356 // those that handle all web uris. 6357 if (riTargetUser.handleAllWebDataURI) { 6358 continue; 6359 } 6360 String packageName = riTargetUser.activityInfo.packageName; 6361 PackageSetting ps = mSettings.mPackages.get(packageName); 6362 if (ps == null) { 6363 continue; 6364 } 6365 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 6366 int status = (int)(verificationState >> 32); 6367 if (result == null) { 6368 result = new CrossProfileDomainInfo(); 6369 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 6370 sourceUserId, parentUserId); 6371 result.bestDomainVerificationStatus = status; 6372 } else { 6373 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 6374 result.bestDomainVerificationStatus); 6375 } 6376 } 6377 // Don't consider matches with status NEVER across profiles. 6378 if (result != null && result.bestDomainVerificationStatus 6379 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6380 return null; 6381 } 6382 return result; 6383 } 6384 6385 /** 6386 * Verification statuses are ordered from the worse to the best, except for 6387 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 6388 */ 6389 private int bestDomainVerificationStatus(int status1, int status2) { 6390 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6391 return status2; 6392 } 6393 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6394 return status1; 6395 } 6396 return (int) MathUtils.max(status1, status2); 6397 } 6398 6399 private boolean isUserEnabled(int userId) { 6400 long callingId = Binder.clearCallingIdentity(); 6401 try { 6402 UserInfo userInfo = sUserManager.getUserInfo(userId); 6403 return userInfo != null && userInfo.isEnabled(); 6404 } finally { 6405 Binder.restoreCallingIdentity(callingId); 6406 } 6407 } 6408 6409 /** 6410 * Filter out activities with systemUserOnly flag set, when current user is not System. 6411 * 6412 * @return filtered list 6413 */ 6414 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 6415 if (userId == UserHandle.USER_SYSTEM) { 6416 return resolveInfos; 6417 } 6418 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 6419 ResolveInfo info = resolveInfos.get(i); 6420 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 6421 resolveInfos.remove(i); 6422 } 6423 } 6424 return resolveInfos; 6425 } 6426 6427 /** 6428 * Filters out ephemeral activities. 6429 * <p>When resolving for an ephemeral app, only activities that 1) are defined in the 6430 * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned. 6431 * 6432 * @param resolveInfos The pre-filtered list of resolved activities 6433 * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering 6434 * is performed. 6435 * @return A filtered list of resolved activities. 6436 */ 6437 private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos, 6438 String ephemeralPkgName) { 6439 // TODO: When adding on-demand split support for non-instant apps, remove this check 6440 // and always apply post filtering 6441 if (ephemeralPkgName == null) { 6442 return resolveInfos; 6443 } 6444 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 6445 final ResolveInfo info = resolveInfos.get(i); 6446 final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp(); 6447 // allow activities that are defined in the provided package 6448 if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) { 6449 if (info.activityInfo.splitName != null 6450 && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames, 6451 info.activityInfo.splitName)) { 6452 // requested activity is defined in a split that hasn't been installed yet. 6453 // add the installer to the resolve list 6454 if (DEBUG_EPHEMERAL) { 6455 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 6456 } 6457 final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo); 6458 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 6459 info.activityInfo.packageName, info.activityInfo.splitName, 6460 info.activityInfo.applicationInfo.versionCode); 6461 // make sure this resolver is the default 6462 installerInfo.isDefault = true; 6463 installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 6464 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 6465 // add a non-generic filter 6466 installerInfo.filter = new IntentFilter(); 6467 // load resources from the correct package 6468 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 6469 resolveInfos.set(i, installerInfo); 6470 } 6471 continue; 6472 } 6473 // allow activities that have been explicitly exposed to ephemeral apps 6474 if (!isEphemeralApp 6475 && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) { 6476 continue; 6477 } 6478 resolveInfos.remove(i); 6479 } 6480 return resolveInfos; 6481 } 6482 6483 /** 6484 * @param resolveInfos list of resolve infos in descending priority order 6485 * @return if the list contains a resolve info with non-negative priority 6486 */ 6487 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 6488 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 6489 } 6490 6491 private static boolean hasWebURI(Intent intent) { 6492 if (intent.getData() == null) { 6493 return false; 6494 } 6495 final String scheme = intent.getScheme(); 6496 if (TextUtils.isEmpty(scheme)) { 6497 return false; 6498 } 6499 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 6500 } 6501 6502 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 6503 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 6504 int userId) { 6505 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 6506 6507 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 6508 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 6509 candidates.size()); 6510 } 6511 6512 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 6513 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 6514 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 6515 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 6516 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 6517 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 6518 6519 synchronized (mPackages) { 6520 final int count = candidates.size(); 6521 // First, try to use linked apps. Partition the candidates into four lists: 6522 // one for the final results, one for the "do not use ever", one for "undefined status" 6523 // and finally one for "browser app type". 6524 for (int n=0; n<count; n++) { 6525 ResolveInfo info = candidates.get(n); 6526 String packageName = info.activityInfo.packageName; 6527 PackageSetting ps = mSettings.mPackages.get(packageName); 6528 if (ps != null) { 6529 // Add to the special match all list (Browser use case) 6530 if (info.handleAllWebDataURI) { 6531 matchAllList.add(info); 6532 continue; 6533 } 6534 // Try to get the status from User settings first 6535 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 6536 int status = (int)(packedStatus >> 32); 6537 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 6538 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 6539 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6540 Slog.i(TAG, " + always: " + info.activityInfo.packageName 6541 + " : linkgen=" + linkGeneration); 6542 } 6543 // Use link-enabled generation as preferredOrder, i.e. 6544 // prefer newly-enabled over earlier-enabled. 6545 info.preferredOrder = linkGeneration; 6546 alwaysList.add(info); 6547 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6548 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6549 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 6550 } 6551 neverList.add(info); 6552 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 6553 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6554 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 6555 } 6556 alwaysAskList.add(info); 6557 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 6558 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 6559 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6560 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 6561 } 6562 undefinedList.add(info); 6563 } 6564 } 6565 } 6566 6567 // We'll want to include browser possibilities in a few cases 6568 boolean includeBrowser = false; 6569 6570 // First try to add the "always" resolution(s) for the current user, if any 6571 if (alwaysList.size() > 0) { 6572 result.addAll(alwaysList); 6573 } else { 6574 // Add all undefined apps as we want them to appear in the disambiguation dialog. 6575 result.addAll(undefinedList); 6576 // Maybe add one for the other profile. 6577 if (xpDomainInfo != null && ( 6578 xpDomainInfo.bestDomainVerificationStatus 6579 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 6580 result.add(xpDomainInfo.resolveInfo); 6581 } 6582 includeBrowser = true; 6583 } 6584 6585 // The presence of any 'always ask' alternatives means we'll also offer browsers. 6586 // If there were 'always' entries their preferred order has been set, so we also 6587 // back that off to make the alternatives equivalent 6588 if (alwaysAskList.size() > 0) { 6589 for (ResolveInfo i : result) { 6590 i.preferredOrder = 0; 6591 } 6592 result.addAll(alwaysAskList); 6593 includeBrowser = true; 6594 } 6595 6596 if (includeBrowser) { 6597 // Also add browsers (all of them or only the default one) 6598 if (DEBUG_DOMAIN_VERIFICATION) { 6599 Slog.v(TAG, " ...including browsers in candidate set"); 6600 } 6601 if ((matchFlags & MATCH_ALL) != 0) { 6602 result.addAll(matchAllList); 6603 } else { 6604 // Browser/generic handling case. If there's a default browser, go straight 6605 // to that (but only if there is no other higher-priority match). 6606 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 6607 int maxMatchPrio = 0; 6608 ResolveInfo defaultBrowserMatch = null; 6609 final int numCandidates = matchAllList.size(); 6610 for (int n = 0; n < numCandidates; n++) { 6611 ResolveInfo info = matchAllList.get(n); 6612 // track the highest overall match priority... 6613 if (info.priority > maxMatchPrio) { 6614 maxMatchPrio = info.priority; 6615 } 6616 // ...and the highest-priority default browser match 6617 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 6618 if (defaultBrowserMatch == null 6619 || (defaultBrowserMatch.priority < info.priority)) { 6620 if (debug) { 6621 Slog.v(TAG, "Considering default browser match " + info); 6622 } 6623 defaultBrowserMatch = info; 6624 } 6625 } 6626 } 6627 if (defaultBrowserMatch != null 6628 && defaultBrowserMatch.priority >= maxMatchPrio 6629 && !TextUtils.isEmpty(defaultBrowserPackageName)) 6630 { 6631 if (debug) { 6632 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 6633 } 6634 result.add(defaultBrowserMatch); 6635 } else { 6636 result.addAll(matchAllList); 6637 } 6638 } 6639 6640 // If there is nothing selected, add all candidates and remove the ones that the user 6641 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 6642 if (result.size() == 0) { 6643 result.addAll(candidates); 6644 result.removeAll(neverList); 6645 } 6646 } 6647 } 6648 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 6649 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 6650 result.size()); 6651 for (ResolveInfo info : result) { 6652 Slog.v(TAG, " + " + info.activityInfo); 6653 } 6654 } 6655 return result; 6656 } 6657 6658 // Returns a packed value as a long: 6659 // 6660 // high 'int'-sized word: link status: undefined/ask/never/always. 6661 // low 'int'-sized word: relative priority among 'always' results. 6662 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 6663 long result = ps.getDomainVerificationStatusForUser(userId); 6664 // if none available, get the master status 6665 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 6666 if (ps.getIntentFilterVerificationInfo() != null) { 6667 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 6668 } 6669 } 6670 return result; 6671 } 6672 6673 private ResolveInfo querySkipCurrentProfileIntents( 6674 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 6675 int flags, int sourceUserId) { 6676 if (matchingFilters != null) { 6677 int size = matchingFilters.size(); 6678 for (int i = 0; i < size; i ++) { 6679 CrossProfileIntentFilter filter = matchingFilters.get(i); 6680 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 6681 // Checking if there are activities in the target user that can handle the 6682 // intent. 6683 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 6684 resolvedType, flags, sourceUserId); 6685 if (resolveInfo != null) { 6686 return resolveInfo; 6687 } 6688 } 6689 } 6690 } 6691 return null; 6692 } 6693 6694 // Return matching ResolveInfo in target user if any. 6695 private ResolveInfo queryCrossProfileIntents( 6696 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 6697 int flags, int sourceUserId, boolean matchInCurrentProfile) { 6698 if (matchingFilters != null) { 6699 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 6700 // match the same intent. For performance reasons, it is better not to 6701 // run queryIntent twice for the same userId 6702 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 6703 int size = matchingFilters.size(); 6704 for (int i = 0; i < size; i++) { 6705 CrossProfileIntentFilter filter = matchingFilters.get(i); 6706 int targetUserId = filter.getTargetUserId(); 6707 boolean skipCurrentProfile = 6708 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 6709 boolean skipCurrentProfileIfNoMatchFound = 6710 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 6711 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 6712 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 6713 // Checking if there are activities in the target user that can handle the 6714 // intent. 6715 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 6716 resolvedType, flags, sourceUserId); 6717 if (resolveInfo != null) return resolveInfo; 6718 alreadyTriedUserIds.put(targetUserId, true); 6719 } 6720 } 6721 } 6722 return null; 6723 } 6724 6725 /** 6726 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 6727 * will forward the intent to the filter's target user. 6728 * Otherwise, returns null. 6729 */ 6730 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 6731 String resolvedType, int flags, int sourceUserId) { 6732 int targetUserId = filter.getTargetUserId(); 6733 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 6734 resolvedType, flags, targetUserId); 6735 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 6736 // If all the matches in the target profile are suspended, return null. 6737 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 6738 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 6739 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 6740 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 6741 targetUserId); 6742 } 6743 } 6744 } 6745 return null; 6746 } 6747 6748 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 6749 int sourceUserId, int targetUserId) { 6750 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 6751 long ident = Binder.clearCallingIdentity(); 6752 boolean targetIsProfile; 6753 try { 6754 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 6755 } finally { 6756 Binder.restoreCallingIdentity(ident); 6757 } 6758 String className; 6759 if (targetIsProfile) { 6760 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 6761 } else { 6762 className = FORWARD_INTENT_TO_PARENT; 6763 } 6764 ComponentName forwardingActivityComponentName = new ComponentName( 6765 mAndroidApplication.packageName, className); 6766 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 6767 sourceUserId); 6768 if (!targetIsProfile) { 6769 forwardingActivityInfo.showUserIcon = targetUserId; 6770 forwardingResolveInfo.noResourceId = true; 6771 } 6772 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 6773 forwardingResolveInfo.priority = 0; 6774 forwardingResolveInfo.preferredOrder = 0; 6775 forwardingResolveInfo.match = 0; 6776 forwardingResolveInfo.isDefault = true; 6777 forwardingResolveInfo.filter = filter; 6778 forwardingResolveInfo.targetUserId = targetUserId; 6779 return forwardingResolveInfo; 6780 } 6781 6782 @Override 6783 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 6784 Intent[] specifics, String[] specificTypes, Intent intent, 6785 String resolvedType, int flags, int userId) { 6786 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 6787 specificTypes, intent, resolvedType, flags, userId)); 6788 } 6789 6790 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 6791 Intent[] specifics, String[] specificTypes, Intent intent, 6792 String resolvedType, int flags, int userId) { 6793 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6794 flags = updateFlagsForResolve(flags, userId, intent, false); 6795 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6796 false /* requireFullPermission */, false /* checkShell */, 6797 "query intent activity options"); 6798 final String resultsAction = intent.getAction(); 6799 6800 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 6801 | PackageManager.GET_RESOLVED_FILTER, userId); 6802 6803 if (DEBUG_INTENT_MATCHING) { 6804 Log.v(TAG, "Query " + intent + ": " + results); 6805 } 6806 6807 int specificsPos = 0; 6808 int N; 6809 6810 // todo: note that the algorithm used here is O(N^2). This 6811 // isn't a problem in our current environment, but if we start running 6812 // into situations where we have more than 5 or 10 matches then this 6813 // should probably be changed to something smarter... 6814 6815 // First we go through and resolve each of the specific items 6816 // that were supplied, taking care of removing any corresponding 6817 // duplicate items in the generic resolve list. 6818 if (specifics != null) { 6819 for (int i=0; i<specifics.length; i++) { 6820 final Intent sintent = specifics[i]; 6821 if (sintent == null) { 6822 continue; 6823 } 6824 6825 if (DEBUG_INTENT_MATCHING) { 6826 Log.v(TAG, "Specific #" + i + ": " + sintent); 6827 } 6828 6829 String action = sintent.getAction(); 6830 if (resultsAction != null && resultsAction.equals(action)) { 6831 // If this action was explicitly requested, then don't 6832 // remove things that have it. 6833 action = null; 6834 } 6835 6836 ResolveInfo ri = null; 6837 ActivityInfo ai = null; 6838 6839 ComponentName comp = sintent.getComponent(); 6840 if (comp == null) { 6841 ri = resolveIntent( 6842 sintent, 6843 specificTypes != null ? specificTypes[i] : null, 6844 flags, userId); 6845 if (ri == null) { 6846 continue; 6847 } 6848 if (ri == mResolveInfo) { 6849 // ACK! Must do something better with this. 6850 } 6851 ai = ri.activityInfo; 6852 comp = new ComponentName(ai.applicationInfo.packageName, 6853 ai.name); 6854 } else { 6855 ai = getActivityInfo(comp, flags, userId); 6856 if (ai == null) { 6857 continue; 6858 } 6859 } 6860 6861 // Look for any generic query activities that are duplicates 6862 // of this specific one, and remove them from the results. 6863 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 6864 N = results.size(); 6865 int j; 6866 for (j=specificsPos; j<N; j++) { 6867 ResolveInfo sri = results.get(j); 6868 if ((sri.activityInfo.name.equals(comp.getClassName()) 6869 && sri.activityInfo.applicationInfo.packageName.equals( 6870 comp.getPackageName())) 6871 || (action != null && sri.filter.matchAction(action))) { 6872 results.remove(j); 6873 if (DEBUG_INTENT_MATCHING) Log.v( 6874 TAG, "Removing duplicate item from " + j 6875 + " due to specific " + specificsPos); 6876 if (ri == null) { 6877 ri = sri; 6878 } 6879 j--; 6880 N--; 6881 } 6882 } 6883 6884 // Add this specific item to its proper place. 6885 if (ri == null) { 6886 ri = new ResolveInfo(); 6887 ri.activityInfo = ai; 6888 } 6889 results.add(specificsPos, ri); 6890 ri.specificIndex = i; 6891 specificsPos++; 6892 } 6893 } 6894 6895 // Now we go through the remaining generic results and remove any 6896 // duplicate actions that are found here. 6897 N = results.size(); 6898 for (int i=specificsPos; i<N-1; i++) { 6899 final ResolveInfo rii = results.get(i); 6900 if (rii.filter == null) { 6901 continue; 6902 } 6903 6904 // Iterate over all of the actions of this result's intent 6905 // filter... typically this should be just one. 6906 final Iterator<String> it = rii.filter.actionsIterator(); 6907 if (it == null) { 6908 continue; 6909 } 6910 while (it.hasNext()) { 6911 final String action = it.next(); 6912 if (resultsAction != null && resultsAction.equals(action)) { 6913 // If this action was explicitly requested, then don't 6914 // remove things that have it. 6915 continue; 6916 } 6917 for (int j=i+1; j<N; j++) { 6918 final ResolveInfo rij = results.get(j); 6919 if (rij.filter != null && rij.filter.hasAction(action)) { 6920 results.remove(j); 6921 if (DEBUG_INTENT_MATCHING) Log.v( 6922 TAG, "Removing duplicate item from " + j 6923 + " due to action " + action + " at " + i); 6924 j--; 6925 N--; 6926 } 6927 } 6928 } 6929 6930 // If the caller didn't request filter information, drop it now 6931 // so we don't have to marshall/unmarshall it. 6932 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6933 rii.filter = null; 6934 } 6935 } 6936 6937 // Filter out the caller activity if so requested. 6938 if (caller != null) { 6939 N = results.size(); 6940 for (int i=0; i<N; i++) { 6941 ActivityInfo ainfo = results.get(i).activityInfo; 6942 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 6943 && caller.getClassName().equals(ainfo.name)) { 6944 results.remove(i); 6945 break; 6946 } 6947 } 6948 } 6949 6950 // If the caller didn't request filter information, 6951 // drop them now so we don't have to 6952 // marshall/unmarshall it. 6953 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6954 N = results.size(); 6955 for (int i=0; i<N; i++) { 6956 results.get(i).filter = null; 6957 } 6958 } 6959 6960 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 6961 return results; 6962 } 6963 6964 @Override 6965 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 6966 String resolvedType, int flags, int userId) { 6967 return new ParceledListSlice<>( 6968 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 6969 } 6970 6971 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 6972 String resolvedType, int flags, int userId) { 6973 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6974 flags = updateFlagsForResolve(flags, userId, intent, false); 6975 ComponentName comp = intent.getComponent(); 6976 if (comp == null) { 6977 if (intent.getSelector() != null) { 6978 intent = intent.getSelector(); 6979 comp = intent.getComponent(); 6980 } 6981 } 6982 if (comp != null) { 6983 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6984 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 6985 if (ai != null) { 6986 ResolveInfo ri = new ResolveInfo(); 6987 ri.activityInfo = ai; 6988 list.add(ri); 6989 } 6990 return list; 6991 } 6992 6993 // reader 6994 synchronized (mPackages) { 6995 String pkgName = intent.getPackage(); 6996 if (pkgName == null) { 6997 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 6998 } 6999 final PackageParser.Package pkg = mPackages.get(pkgName); 7000 if (pkg != null) { 7001 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 7002 userId); 7003 } 7004 return Collections.emptyList(); 7005 } 7006 } 7007 7008 @Override 7009 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 7010 if (!sUserManager.exists(userId)) return null; 7011 flags = updateFlagsForResolve(flags, userId, intent, false); 7012 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 7013 if (query != null) { 7014 if (query.size() >= 1) { 7015 // If there is more than one service with the same priority, 7016 // just arbitrarily pick the first one. 7017 return query.get(0); 7018 } 7019 } 7020 return null; 7021 } 7022 7023 @Override 7024 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 7025 String resolvedType, int flags, int userId) { 7026 return new ParceledListSlice<>( 7027 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 7028 } 7029 7030 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 7031 String resolvedType, int flags, int userId) { 7032 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7033 flags = updateFlagsForResolve(flags, userId, intent, false); 7034 ComponentName comp = intent.getComponent(); 7035 if (comp == null) { 7036 if (intent.getSelector() != null) { 7037 intent = intent.getSelector(); 7038 comp = intent.getComponent(); 7039 } 7040 } 7041 if (comp != null) { 7042 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7043 final ServiceInfo si = getServiceInfo(comp, flags, userId); 7044 if (si != null) { 7045 final ResolveInfo ri = new ResolveInfo(); 7046 ri.serviceInfo = si; 7047 list.add(ri); 7048 } 7049 return list; 7050 } 7051 7052 // reader 7053 synchronized (mPackages) { 7054 String pkgName = intent.getPackage(); 7055 if (pkgName == null) { 7056 return mServices.queryIntent(intent, resolvedType, flags, userId); 7057 } 7058 final PackageParser.Package pkg = mPackages.get(pkgName); 7059 if (pkg != null) { 7060 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 7061 userId); 7062 } 7063 return Collections.emptyList(); 7064 } 7065 } 7066 7067 @Override 7068 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 7069 String resolvedType, int flags, int userId) { 7070 return new ParceledListSlice<>( 7071 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 7072 } 7073 7074 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 7075 Intent intent, String resolvedType, int flags, int userId) { 7076 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7077 flags = updateFlagsForResolve(flags, userId, intent, false); 7078 ComponentName comp = intent.getComponent(); 7079 if (comp == null) { 7080 if (intent.getSelector() != null) { 7081 intent = intent.getSelector(); 7082 comp = intent.getComponent(); 7083 } 7084 } 7085 if (comp != null) { 7086 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7087 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 7088 if (pi != null) { 7089 final ResolveInfo ri = new ResolveInfo(); 7090 ri.providerInfo = pi; 7091 list.add(ri); 7092 } 7093 return list; 7094 } 7095 7096 // reader 7097 synchronized (mPackages) { 7098 String pkgName = intent.getPackage(); 7099 if (pkgName == null) { 7100 return mProviders.queryIntent(intent, resolvedType, flags, userId); 7101 } 7102 final PackageParser.Package pkg = mPackages.get(pkgName); 7103 if (pkg != null) { 7104 return mProviders.queryIntentForPackage( 7105 intent, resolvedType, flags, pkg.providers, userId); 7106 } 7107 return Collections.emptyList(); 7108 } 7109 } 7110 7111 @Override 7112 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 7113 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7114 flags = updateFlagsForPackage(flags, userId, null); 7115 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7116 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7117 true /* requireFullPermission */, false /* checkShell */, 7118 "get installed packages"); 7119 7120 // writer 7121 synchronized (mPackages) { 7122 ArrayList<PackageInfo> list; 7123 if (listUninstalled) { 7124 list = new ArrayList<>(mSettings.mPackages.size()); 7125 for (PackageSetting ps : mSettings.mPackages.values()) { 7126 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 7127 continue; 7128 } 7129 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 7130 if (pi != null) { 7131 list.add(pi); 7132 } 7133 } 7134 } else { 7135 list = new ArrayList<>(mPackages.size()); 7136 for (PackageParser.Package p : mPackages.values()) { 7137 if (filterSharedLibPackageLPr((PackageSetting) p.mExtras, 7138 Binder.getCallingUid(), userId)) { 7139 continue; 7140 } 7141 final PackageInfo pi = generatePackageInfo((PackageSetting) 7142 p.mExtras, flags, userId); 7143 if (pi != null) { 7144 list.add(pi); 7145 } 7146 } 7147 } 7148 7149 return new ParceledListSlice<>(list); 7150 } 7151 } 7152 7153 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 7154 String[] permissions, boolean[] tmp, int flags, int userId) { 7155 int numMatch = 0; 7156 final PermissionsState permissionsState = ps.getPermissionsState(); 7157 for (int i=0; i<permissions.length; i++) { 7158 final String permission = permissions[i]; 7159 if (permissionsState.hasPermission(permission, userId)) { 7160 tmp[i] = true; 7161 numMatch++; 7162 } else { 7163 tmp[i] = false; 7164 } 7165 } 7166 if (numMatch == 0) { 7167 return; 7168 } 7169 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 7170 7171 // The above might return null in cases of uninstalled apps or install-state 7172 // skew across users/profiles. 7173 if (pi != null) { 7174 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 7175 if (numMatch == permissions.length) { 7176 pi.requestedPermissions = permissions; 7177 } else { 7178 pi.requestedPermissions = new String[numMatch]; 7179 numMatch = 0; 7180 for (int i=0; i<permissions.length; i++) { 7181 if (tmp[i]) { 7182 pi.requestedPermissions[numMatch] = permissions[i]; 7183 numMatch++; 7184 } 7185 } 7186 } 7187 } 7188 list.add(pi); 7189 } 7190 } 7191 7192 @Override 7193 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 7194 String[] permissions, int flags, int userId) { 7195 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7196 flags = updateFlagsForPackage(flags, userId, permissions); 7197 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7198 true /* requireFullPermission */, false /* checkShell */, 7199 "get packages holding permissions"); 7200 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7201 7202 // writer 7203 synchronized (mPackages) { 7204 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 7205 boolean[] tmpBools = new boolean[permissions.length]; 7206 if (listUninstalled) { 7207 for (PackageSetting ps : mSettings.mPackages.values()) { 7208 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 7209 userId); 7210 } 7211 } else { 7212 for (PackageParser.Package pkg : mPackages.values()) { 7213 PackageSetting ps = (PackageSetting)pkg.mExtras; 7214 if (ps != null) { 7215 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 7216 userId); 7217 } 7218 } 7219 } 7220 7221 return new ParceledListSlice<PackageInfo>(list); 7222 } 7223 } 7224 7225 @Override 7226 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 7227 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7228 flags = updateFlagsForApplication(flags, userId, null); 7229 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7230 7231 // writer 7232 synchronized (mPackages) { 7233 ArrayList<ApplicationInfo> list; 7234 if (listUninstalled) { 7235 list = new ArrayList<>(mSettings.mPackages.size()); 7236 for (PackageSetting ps : mSettings.mPackages.values()) { 7237 ApplicationInfo ai; 7238 int effectiveFlags = flags; 7239 if (ps.isSystem()) { 7240 effectiveFlags |= PackageManager.MATCH_ANY_USER; 7241 } 7242 if (ps.pkg != null) { 7243 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 7244 continue; 7245 } 7246 ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags, 7247 ps.readUserState(userId), userId); 7248 if (ai != null) { 7249 rebaseEnabledOverlays(ai, userId); 7250 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 7251 } 7252 } else { 7253 // Shared lib filtering done in generateApplicationInfoFromSettingsLPw 7254 // and already converts to externally visible package name 7255 ai = generateApplicationInfoFromSettingsLPw(ps.name, 7256 Binder.getCallingUid(), effectiveFlags, userId); 7257 } 7258 if (ai != null) { 7259 list.add(ai); 7260 } 7261 } 7262 } else { 7263 list = new ArrayList<>(mPackages.size()); 7264 for (PackageParser.Package p : mPackages.values()) { 7265 if (p.mExtras != null) { 7266 PackageSetting ps = (PackageSetting) p.mExtras; 7267 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 7268 continue; 7269 } 7270 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 7271 ps.readUserState(userId), userId); 7272 if (ai != null) { 7273 rebaseEnabledOverlays(ai, userId); 7274 ai.packageName = resolveExternalPackageNameLPr(p); 7275 list.add(ai); 7276 } 7277 } 7278 } 7279 } 7280 7281 return new ParceledListSlice<>(list); 7282 } 7283 } 7284 7285 @Override 7286 public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) { 7287 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7288 return null; 7289 } 7290 7291 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS, 7292 "getEphemeralApplications"); 7293 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7294 true /* requireFullPermission */, false /* checkShell */, 7295 "getEphemeralApplications"); 7296 synchronized (mPackages) { 7297 List<InstantAppInfo> instantApps = mInstantAppRegistry 7298 .getInstantAppsLPr(userId); 7299 if (instantApps != null) { 7300 return new ParceledListSlice<>(instantApps); 7301 } 7302 } 7303 return null; 7304 } 7305 7306 @Override 7307 public boolean isInstantApp(String packageName, int userId) { 7308 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7309 true /* requireFullPermission */, false /* checkShell */, 7310 "isInstantApp"); 7311 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7312 return false; 7313 } 7314 7315 synchronized (mPackages) { 7316 final PackageSetting ps = mSettings.mPackages.get(packageName); 7317 final boolean returnAllowed = 7318 ps != null 7319 && (isCallerSameApp(packageName) 7320 || mContext.checkCallingOrSelfPermission( 7321 android.Manifest.permission.ACCESS_INSTANT_APPS) 7322 == PERMISSION_GRANTED 7323 || mInstantAppRegistry.isInstantAccessGranted( 7324 userId, UserHandle.getAppId(Binder.getCallingUid()), ps.appId)); 7325 if (returnAllowed) { 7326 return ps.getInstantApp(userId); 7327 } 7328 } 7329 return false; 7330 } 7331 7332 @Override 7333 public byte[] getInstantAppCookie(String packageName, int userId) { 7334 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7335 return null; 7336 } 7337 7338 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7339 true /* requireFullPermission */, false /* checkShell */, 7340 "getInstantAppCookie"); 7341 if (!isCallerSameApp(packageName)) { 7342 return null; 7343 } 7344 synchronized (mPackages) { 7345 return mInstantAppRegistry.getInstantAppCookieLPw( 7346 packageName, userId); 7347 } 7348 } 7349 7350 @Override 7351 public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) { 7352 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7353 return true; 7354 } 7355 7356 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7357 true /* requireFullPermission */, true /* checkShell */, 7358 "setInstantAppCookie"); 7359 if (!isCallerSameApp(packageName)) { 7360 return false; 7361 } 7362 synchronized (mPackages) { 7363 return mInstantAppRegistry.setInstantAppCookieLPw( 7364 packageName, cookie, userId); 7365 } 7366 } 7367 7368 @Override 7369 public Bitmap getInstantAppIcon(String packageName, int userId) { 7370 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7371 return null; 7372 } 7373 7374 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS, 7375 "getInstantAppIcon"); 7376 7377 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7378 true /* requireFullPermission */, false /* checkShell */, 7379 "getInstantAppIcon"); 7380 7381 synchronized (mPackages) { 7382 return mInstantAppRegistry.getInstantAppIconLPw( 7383 packageName, userId); 7384 } 7385 } 7386 7387 private boolean isCallerSameApp(String packageName) { 7388 PackageParser.Package pkg = mPackages.get(packageName); 7389 return pkg != null 7390 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 7391 } 7392 7393 @Override 7394 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 7395 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 7396 } 7397 7398 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 7399 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 7400 7401 // reader 7402 synchronized (mPackages) { 7403 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 7404 final int userId = UserHandle.getCallingUserId(); 7405 while (i.hasNext()) { 7406 final PackageParser.Package p = i.next(); 7407 if (p.applicationInfo == null) continue; 7408 7409 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 7410 && !p.applicationInfo.isDirectBootAware(); 7411 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 7412 && p.applicationInfo.isDirectBootAware(); 7413 7414 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 7415 && (!mSafeMode || isSystemApp(p)) 7416 && (matchesUnaware || matchesAware)) { 7417 PackageSetting ps = mSettings.mPackages.get(p.packageName); 7418 if (ps != null) { 7419 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 7420 ps.readUserState(userId), userId); 7421 if (ai != null) { 7422 rebaseEnabledOverlays(ai, userId); 7423 finalList.add(ai); 7424 } 7425 } 7426 } 7427 } 7428 } 7429 7430 return finalList; 7431 } 7432 7433 @Override 7434 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 7435 if (!sUserManager.exists(userId)) return null; 7436 flags = updateFlagsForComponent(flags, userId, name); 7437 // reader 7438 synchronized (mPackages) { 7439 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 7440 PackageSetting ps = provider != null 7441 ? mSettings.mPackages.get(provider.owner.packageName) 7442 : null; 7443 return ps != null 7444 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 7445 ? PackageParser.generateProviderInfo(provider, flags, 7446 ps.readUserState(userId), userId) 7447 : null; 7448 } 7449 } 7450 7451 /** 7452 * @deprecated 7453 */ 7454 @Deprecated 7455 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 7456 // reader 7457 synchronized (mPackages) { 7458 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 7459 .entrySet().iterator(); 7460 final int userId = UserHandle.getCallingUserId(); 7461 while (i.hasNext()) { 7462 Map.Entry<String, PackageParser.Provider> entry = i.next(); 7463 PackageParser.Provider p = entry.getValue(); 7464 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 7465 7466 if (ps != null && p.syncable 7467 && (!mSafeMode || (p.info.applicationInfo.flags 7468 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 7469 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 7470 ps.readUserState(userId), userId); 7471 if (info != null) { 7472 outNames.add(entry.getKey()); 7473 outInfo.add(info); 7474 } 7475 } 7476 } 7477 } 7478 } 7479 7480 @Override 7481 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 7482 int uid, int flags, String metaDataKey) { 7483 final int userId = processName != null ? UserHandle.getUserId(uid) 7484 : UserHandle.getCallingUserId(); 7485 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7486 flags = updateFlagsForComponent(flags, userId, processName); 7487 7488 ArrayList<ProviderInfo> finalList = null; 7489 // reader 7490 synchronized (mPackages) { 7491 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 7492 while (i.hasNext()) { 7493 final PackageParser.Provider p = i.next(); 7494 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 7495 if (ps != null && p.info.authority != null 7496 && (processName == null 7497 || (p.info.processName.equals(processName) 7498 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 7499 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 7500 7501 // See PM.queryContentProviders()'s javadoc for why we have the metaData 7502 // parameter. 7503 if (metaDataKey != null 7504 && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) { 7505 continue; 7506 } 7507 7508 if (finalList == null) { 7509 finalList = new ArrayList<ProviderInfo>(3); 7510 } 7511 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 7512 ps.readUserState(userId), userId); 7513 if (info != null) { 7514 finalList.add(info); 7515 } 7516 } 7517 } 7518 } 7519 7520 if (finalList != null) { 7521 Collections.sort(finalList, mProviderInitOrderSorter); 7522 return new ParceledListSlice<ProviderInfo>(finalList); 7523 } 7524 7525 return ParceledListSlice.emptyList(); 7526 } 7527 7528 @Override 7529 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 7530 // reader 7531 synchronized (mPackages) { 7532 final PackageParser.Instrumentation i = mInstrumentation.get(name); 7533 return PackageParser.generateInstrumentationInfo(i, flags); 7534 } 7535 } 7536 7537 @Override 7538 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 7539 String targetPackage, int flags) { 7540 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 7541 } 7542 7543 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 7544 int flags) { 7545 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 7546 7547 // reader 7548 synchronized (mPackages) { 7549 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 7550 while (i.hasNext()) { 7551 final PackageParser.Instrumentation p = i.next(); 7552 if (targetPackage == null 7553 || targetPackage.equals(p.info.targetPackage)) { 7554 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 7555 flags); 7556 if (ii != null) { 7557 finalList.add(ii); 7558 } 7559 } 7560 } 7561 } 7562 7563 return finalList; 7564 } 7565 7566 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 7567 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]"); 7568 try { 7569 scanDirLI(dir, parseFlags, scanFlags, currentTime); 7570 } finally { 7571 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7572 } 7573 } 7574 7575 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 7576 final File[] files = dir.listFiles(); 7577 if (ArrayUtils.isEmpty(files)) { 7578 Log.d(TAG, "No files in app dir " + dir); 7579 return; 7580 } 7581 7582 if (DEBUG_PACKAGE_SCANNING) { 7583 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 7584 + " flags=0x" + Integer.toHexString(parseFlags)); 7585 } 7586 ParallelPackageParser parallelPackageParser = new ParallelPackageParser( 7587 mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir); 7588 7589 // Submit files for parsing in parallel 7590 int fileCount = 0; 7591 for (File file : files) { 7592 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 7593 && !PackageInstallerService.isStageName(file.getName()); 7594 if (!isPackage) { 7595 // Ignore entries which are not packages 7596 continue; 7597 } 7598 parallelPackageParser.submit(file, parseFlags); 7599 fileCount++; 7600 } 7601 7602 // Process results one by one 7603 for (; fileCount > 0; fileCount--) { 7604 ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take(); 7605 Throwable throwable = parseResult.throwable; 7606 int errorCode = PackageManager.INSTALL_SUCCEEDED; 7607 7608 if (throwable == null) { 7609 // Static shared libraries have synthetic package names 7610 if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) { 7611 renameStaticSharedLibraryPackage(parseResult.pkg); 7612 } 7613 try { 7614 if (errorCode == PackageManager.INSTALL_SUCCEEDED) { 7615 scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags, 7616 currentTime, null); 7617 } 7618 } catch (PackageManagerException e) { 7619 errorCode = e.error; 7620 Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage()); 7621 } 7622 } else if (throwable instanceof PackageParser.PackageParserException) { 7623 PackageParser.PackageParserException e = (PackageParser.PackageParserException) 7624 throwable; 7625 errorCode = e.error; 7626 Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage()); 7627 } else { 7628 throw new IllegalStateException("Unexpected exception occurred while parsing " 7629 + parseResult.scanFile, throwable); 7630 } 7631 7632 // Delete invalid userdata apps 7633 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 7634 errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) { 7635 logCriticalInfo(Log.WARN, 7636 "Deleting invalid package at " + parseResult.scanFile); 7637 removeCodePathLI(parseResult.scanFile); 7638 } 7639 } 7640 parallelPackageParser.close(); 7641 } 7642 7643 private static File getSettingsProblemFile() { 7644 File dataDir = Environment.getDataDirectory(); 7645 File systemDir = new File(dataDir, "system"); 7646 File fname = new File(systemDir, "uiderrors.txt"); 7647 return fname; 7648 } 7649 7650 static void reportSettingsProblem(int priority, String msg) { 7651 logCriticalInfo(priority, msg); 7652 } 7653 7654 static void logCriticalInfo(int priority, String msg) { 7655 Slog.println(priority, TAG, msg); 7656 EventLogTags.writePmCriticalInfo(msg); 7657 try { 7658 File fname = getSettingsProblemFile(); 7659 FileOutputStream out = new FileOutputStream(fname, true); 7660 PrintWriter pw = new FastPrintWriter(out); 7661 SimpleDateFormat formatter = new SimpleDateFormat(); 7662 String dateString = formatter.format(new Date(System.currentTimeMillis())); 7663 pw.println(dateString + ": " + msg); 7664 pw.close(); 7665 FileUtils.setPermissions( 7666 fname.toString(), 7667 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 7668 -1, -1); 7669 } catch (java.io.IOException e) { 7670 } 7671 } 7672 7673 private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) { 7674 if (srcFile.isDirectory()) { 7675 final File baseFile = new File(pkg.baseCodePath); 7676 long maxModifiedTime = baseFile.lastModified(); 7677 if (pkg.splitCodePaths != null) { 7678 for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) { 7679 final File splitFile = new File(pkg.splitCodePaths[i]); 7680 maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified()); 7681 } 7682 } 7683 return maxModifiedTime; 7684 } 7685 return srcFile.lastModified(); 7686 } 7687 7688 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 7689 final int policyFlags) throws PackageManagerException { 7690 // When upgrading from pre-N MR1, verify the package time stamp using the package 7691 // directory and not the APK file. 7692 final long lastModifiedTime = mIsPreNMR1Upgrade 7693 ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile); 7694 if (ps != null 7695 && ps.codePath.equals(srcFile) 7696 && ps.timeStamp == lastModifiedTime 7697 && !isCompatSignatureUpdateNeeded(pkg) 7698 && !isRecoverSignatureUpdateNeeded(pkg)) { 7699 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 7700 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7701 ArraySet<PublicKey> signingKs; 7702 synchronized (mPackages) { 7703 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 7704 } 7705 if (ps.signatures.mSignatures != null 7706 && ps.signatures.mSignatures.length != 0 7707 && signingKs != null) { 7708 // Optimization: reuse the existing cached certificates 7709 // if the package appears to be unchanged. 7710 pkg.mSignatures = ps.signatures.mSignatures; 7711 pkg.mSigningKeys = signingKs; 7712 return; 7713 } 7714 7715 Slog.w(TAG, "PackageSetting for " + ps.name 7716 + " is missing signatures. Collecting certs again to recover them."); 7717 } else { 7718 Slog.i(TAG, srcFile.toString() + " changed; collecting certs"); 7719 } 7720 7721 try { 7722 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 7723 PackageParser.collectCertificates(pkg, policyFlags); 7724 } catch (PackageParserException e) { 7725 throw PackageManagerException.from(e); 7726 } finally { 7727 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7728 } 7729 } 7730 7731 /** 7732 * Traces a package scan. 7733 * @see #scanPackageLI(File, int, int, long, UserHandle) 7734 */ 7735 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 7736 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7737 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]"); 7738 try { 7739 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 7740 } finally { 7741 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7742 } 7743 } 7744 7745 /** 7746 * Scans a package and returns the newly parsed package. 7747 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 7748 */ 7749 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 7750 long currentTime, UserHandle user) throws PackageManagerException { 7751 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 7752 PackageParser pp = new PackageParser(); 7753 pp.setSeparateProcesses(mSeparateProcesses); 7754 pp.setOnlyCoreApps(mOnlyCore); 7755 pp.setDisplayMetrics(mMetrics); 7756 7757 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 7758 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 7759 } 7760 7761 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 7762 final PackageParser.Package pkg; 7763 try { 7764 pkg = pp.parsePackage(scanFile, parseFlags); 7765 } catch (PackageParserException e) { 7766 throw PackageManagerException.from(e); 7767 } finally { 7768 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7769 } 7770 7771 // Static shared libraries have synthetic package names 7772 if (pkg.applicationInfo.isStaticSharedLibrary()) { 7773 renameStaticSharedLibraryPackage(pkg); 7774 } 7775 7776 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 7777 } 7778 7779 /** 7780 * Scans a package and returns the newly parsed package. 7781 * @throws PackageManagerException on a parse error. 7782 */ 7783 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 7784 final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user) 7785 throws PackageManagerException { 7786 // If the package has children and this is the first dive in the function 7787 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 7788 // packages (parent and children) would be successfully scanned before the 7789 // actual scan since scanning mutates internal state and we want to atomically 7790 // install the package and its children. 7791 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7792 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7793 scanFlags |= SCAN_CHECK_ONLY; 7794 } 7795 } else { 7796 scanFlags &= ~SCAN_CHECK_ONLY; 7797 } 7798 7799 // Scan the parent 7800 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 7801 scanFlags, currentTime, user); 7802 7803 // Scan the children 7804 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7805 for (int i = 0; i < childCount; i++) { 7806 PackageParser.Package childPackage = pkg.childPackages.get(i); 7807 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 7808 currentTime, user); 7809 } 7810 7811 7812 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7813 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 7814 } 7815 7816 return scannedPkg; 7817 } 7818 7819 /** 7820 * Scans a package and returns the newly parsed package. 7821 * @throws PackageManagerException on a parse error. 7822 */ 7823 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 7824 int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user) 7825 throws PackageManagerException { 7826 PackageSetting ps = null; 7827 PackageSetting updatedPkg; 7828 // reader 7829 synchronized (mPackages) { 7830 // Look to see if we already know about this package. 7831 String oldName = mSettings.getRenamedPackageLPr(pkg.packageName); 7832 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 7833 // This package has been renamed to its original name. Let's 7834 // use that. 7835 ps = mSettings.getPackageLPr(oldName); 7836 } 7837 // If there was no original package, see one for the real package name. 7838 if (ps == null) { 7839 ps = mSettings.getPackageLPr(pkg.packageName); 7840 } 7841 // Check to see if this package could be hiding/updating a system 7842 // package. Must look for it either under the original or real 7843 // package name depending on our state. 7844 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 7845 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 7846 7847 // If this is a package we don't know about on the system partition, we 7848 // may need to remove disabled child packages on the system partition 7849 // or may need to not add child packages if the parent apk is updated 7850 // on the data partition and no longer defines this child package. 7851 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 7852 // If this is a parent package for an updated system app and this system 7853 // app got an OTA update which no longer defines some of the child packages 7854 // we have to prune them from the disabled system packages. 7855 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 7856 if (disabledPs != null) { 7857 final int scannedChildCount = (pkg.childPackages != null) 7858 ? pkg.childPackages.size() : 0; 7859 final int disabledChildCount = disabledPs.childPackageNames != null 7860 ? disabledPs.childPackageNames.size() : 0; 7861 for (int i = 0; i < disabledChildCount; i++) { 7862 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 7863 boolean disabledPackageAvailable = false; 7864 for (int j = 0; j < scannedChildCount; j++) { 7865 PackageParser.Package childPkg = pkg.childPackages.get(j); 7866 if (childPkg.packageName.equals(disabledChildPackageName)) { 7867 disabledPackageAvailable = true; 7868 break; 7869 } 7870 } 7871 if (!disabledPackageAvailable) { 7872 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 7873 } 7874 } 7875 } 7876 } 7877 } 7878 7879 boolean updatedPkgBetter = false; 7880 // First check if this is a system package that may involve an update 7881 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 7882 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 7883 // it needs to drop FLAG_PRIVILEGED. 7884 if (locationIsPrivileged(scanFile)) { 7885 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7886 } else { 7887 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7888 } 7889 7890 if (ps != null && !ps.codePath.equals(scanFile)) { 7891 // The path has changed from what was last scanned... check the 7892 // version of the new path against what we have stored to determine 7893 // what to do. 7894 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 7895 if (pkg.mVersionCode <= ps.versionCode) { 7896 // The system package has been updated and the code path does not match 7897 // Ignore entry. Skip it. 7898 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 7899 + " ignored: updated version " + ps.versionCode 7900 + " better than this " + pkg.mVersionCode); 7901 if (!updatedPkg.codePath.equals(scanFile)) { 7902 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 7903 + ps.name + " changing from " + updatedPkg.codePathString 7904 + " to " + scanFile); 7905 updatedPkg.codePath = scanFile; 7906 updatedPkg.codePathString = scanFile.toString(); 7907 updatedPkg.resourcePath = scanFile; 7908 updatedPkg.resourcePathString = scanFile.toString(); 7909 } 7910 updatedPkg.pkg = pkg; 7911 updatedPkg.versionCode = pkg.mVersionCode; 7912 7913 // Update the disabled system child packages to point to the package too. 7914 final int childCount = updatedPkg.childPackageNames != null 7915 ? updatedPkg.childPackageNames.size() : 0; 7916 for (int i = 0; i < childCount; i++) { 7917 String childPackageName = updatedPkg.childPackageNames.get(i); 7918 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 7919 childPackageName); 7920 if (updatedChildPkg != null) { 7921 updatedChildPkg.pkg = pkg; 7922 updatedChildPkg.versionCode = pkg.mVersionCode; 7923 } 7924 } 7925 7926 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 7927 + scanFile + " ignored: updated version " + ps.versionCode 7928 + " better than this " + pkg.mVersionCode); 7929 } else { 7930 // The current app on the system partition is better than 7931 // what we have updated to on the data partition; switch 7932 // back to the system partition version. 7933 // At this point, its safely assumed that package installation for 7934 // apps in system partition will go through. If not there won't be a working 7935 // version of the app 7936 // writer 7937 synchronized (mPackages) { 7938 // Just remove the loaded entries from package lists. 7939 mPackages.remove(ps.name); 7940 } 7941 7942 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7943 + " reverting from " + ps.codePathString 7944 + ": new version " + pkg.mVersionCode 7945 + " better than installed " + ps.versionCode); 7946 7947 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7948 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7949 synchronized (mInstallLock) { 7950 args.cleanUpResourcesLI(); 7951 } 7952 synchronized (mPackages) { 7953 mSettings.enableSystemPackageLPw(ps.name); 7954 } 7955 updatedPkgBetter = true; 7956 } 7957 } 7958 } 7959 7960 if (updatedPkg != null) { 7961 // An updated system app will not have the PARSE_IS_SYSTEM flag set 7962 // initially 7963 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 7964 7965 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 7966 // flag set initially 7967 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 7968 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 7969 } 7970 } 7971 7972 // Verify certificates against what was last scanned 7973 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 7974 7975 /* 7976 * A new system app appeared, but we already had a non-system one of the 7977 * same name installed earlier. 7978 */ 7979 boolean shouldHideSystemApp = false; 7980 if (updatedPkg == null && ps != null 7981 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 7982 /* 7983 * Check to make sure the signatures match first. If they don't, 7984 * wipe the installed application and its data. 7985 */ 7986 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 7987 != PackageManager.SIGNATURE_MATCH) { 7988 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 7989 + " signatures don't match existing userdata copy; removing"); 7990 try (PackageFreezer freezer = freezePackage(pkg.packageName, 7991 "scanPackageInternalLI")) { 7992 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 7993 } 7994 ps = null; 7995 } else { 7996 /* 7997 * If the newly-added system app is an older version than the 7998 * already installed version, hide it. It will be scanned later 7999 * and re-added like an update. 8000 */ 8001 if (pkg.mVersionCode <= ps.versionCode) { 8002 shouldHideSystemApp = true; 8003 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 8004 + " but new version " + pkg.mVersionCode + " better than installed " 8005 + ps.versionCode + "; hiding system"); 8006 } else { 8007 /* 8008 * The newly found system app is a newer version that the 8009 * one previously installed. Simply remove the 8010 * already-installed application and replace it with our own 8011 * while keeping the application data. 8012 */ 8013 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 8014 + " reverting from " + ps.codePathString + ": new version " 8015 + pkg.mVersionCode + " better than installed " + ps.versionCode); 8016 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 8017 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 8018 synchronized (mInstallLock) { 8019 args.cleanUpResourcesLI(); 8020 } 8021 } 8022 } 8023 } 8024 8025 // The apk is forward locked (not public) if its code and resources 8026 // are kept in different files. (except for app in either system or 8027 // vendor path). 8028 // TODO grab this value from PackageSettings 8029 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8030 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 8031 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 8032 } 8033 } 8034 8035 // TODO: extend to support forward-locked splits 8036 String resourcePath = null; 8037 String baseResourcePath = null; 8038 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 8039 if (ps != null && ps.resourcePathString != null) { 8040 resourcePath = ps.resourcePathString; 8041 baseResourcePath = ps.resourcePathString; 8042 } else { 8043 // Should not happen at all. Just log an error. 8044 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 8045 } 8046 } else { 8047 resourcePath = pkg.codePath; 8048 baseResourcePath = pkg.baseCodePath; 8049 } 8050 8051 // Set application objects path explicitly. 8052 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 8053 pkg.setApplicationInfoCodePath(pkg.codePath); 8054 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 8055 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 8056 pkg.setApplicationInfoResourcePath(resourcePath); 8057 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 8058 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 8059 8060 final int userId = ((user == null) ? 0 : user.getIdentifier()); 8061 if (ps != null && ps.getInstantApp(userId)) { 8062 scanFlags |= SCAN_AS_INSTANT_APP; 8063 } 8064 8065 // Note that we invoke the following method only if we are about to unpack an application 8066 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 8067 | SCAN_UPDATE_SIGNATURE, currentTime, user); 8068 8069 /* 8070 * If the system app should be overridden by a previously installed 8071 * data, hide the system app now and let the /data/app scan pick it up 8072 * again. 8073 */ 8074 if (shouldHideSystemApp) { 8075 synchronized (mPackages) { 8076 mSettings.disableSystemPackageLPw(pkg.packageName, true); 8077 } 8078 } 8079 8080 return scannedPkg; 8081 } 8082 8083 private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) { 8084 // Derive the new package synthetic package name 8085 pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER 8086 + pkg.staticSharedLibVersion); 8087 } 8088 8089 private static String fixProcessName(String defProcessName, 8090 String processName) { 8091 if (processName == null) { 8092 return defProcessName; 8093 } 8094 return processName; 8095 } 8096 8097 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 8098 throws PackageManagerException { 8099 if (pkgSetting.signatures.mSignatures != null) { 8100 // Already existing package. Make sure signatures match 8101 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 8102 == PackageManager.SIGNATURE_MATCH; 8103 if (!match) { 8104 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 8105 == PackageManager.SIGNATURE_MATCH; 8106 } 8107 if (!match) { 8108 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 8109 == PackageManager.SIGNATURE_MATCH; 8110 } 8111 if (!match) { 8112 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 8113 + pkg.packageName + " signatures do not match the " 8114 + "previously installed version; ignoring!"); 8115 } 8116 } 8117 8118 // Check for shared user signatures 8119 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 8120 // Already existing package. Make sure signatures match 8121 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8122 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 8123 if (!match) { 8124 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 8125 == PackageManager.SIGNATURE_MATCH; 8126 } 8127 if (!match) { 8128 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 8129 == PackageManager.SIGNATURE_MATCH; 8130 } 8131 if (!match) { 8132 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 8133 "Package " + pkg.packageName 8134 + " has no signatures that match those in shared user " 8135 + pkgSetting.sharedUser.name + "; ignoring!"); 8136 } 8137 } 8138 } 8139 8140 /** 8141 * Enforces that only the system UID or root's UID can call a method exposed 8142 * via Binder. 8143 * 8144 * @param message used as message if SecurityException is thrown 8145 * @throws SecurityException if the caller is not system or root 8146 */ 8147 private static final void enforceSystemOrRoot(String message) { 8148 final int uid = Binder.getCallingUid(); 8149 if (uid != Process.SYSTEM_UID && uid != 0) { 8150 throw new SecurityException(message); 8151 } 8152 } 8153 8154 @Override 8155 public void performFstrimIfNeeded() { 8156 enforceSystemOrRoot("Only the system can request fstrim"); 8157 8158 // Before everything else, see whether we need to fstrim. 8159 try { 8160 IStorageManager sm = PackageHelper.getStorageManager(); 8161 if (sm != null) { 8162 boolean doTrim = false; 8163 final long interval = android.provider.Settings.Global.getLong( 8164 mContext.getContentResolver(), 8165 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 8166 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 8167 if (interval > 0) { 8168 final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance(); 8169 if (timeSinceLast > interval) { 8170 doTrim = true; 8171 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 8172 + "; running immediately"); 8173 } 8174 } 8175 if (doTrim) { 8176 final boolean dexOptDialogShown; 8177 synchronized (mPackages) { 8178 dexOptDialogShown = mDexOptDialogShown; 8179 } 8180 if (!isFirstBoot() && dexOptDialogShown) { 8181 try { 8182 ActivityManager.getService().showBootMessage( 8183 mContext.getResources().getString( 8184 R.string.android_upgrading_fstrim), true); 8185 } catch (RemoteException e) { 8186 } 8187 } 8188 sm.runMaintenance(); 8189 } 8190 } else { 8191 Slog.e(TAG, "storageManager service unavailable!"); 8192 } 8193 } catch (RemoteException e) { 8194 // Can't happen; StorageManagerService is local 8195 } 8196 } 8197 8198 @Override 8199 public void updatePackagesIfNeeded() { 8200 enforceSystemOrRoot("Only the system can request package update"); 8201 8202 // We need to re-extract after an OTA. 8203 boolean causeUpgrade = isUpgrade(); 8204 8205 // First boot or factory reset. 8206 // Note: we also handle devices that are upgrading to N right now as if it is their 8207 // first boot, as they do not have profile data. 8208 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 8209 8210 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 8211 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 8212 8213 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 8214 return; 8215 } 8216 8217 List<PackageParser.Package> pkgs; 8218 synchronized (mPackages) { 8219 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 8220 } 8221 8222 final long startTime = System.nanoTime(); 8223 final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */, 8224 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT)); 8225 8226 final int elapsedTimeSeconds = 8227 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 8228 8229 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]); 8230 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]); 8231 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]); 8232 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 8233 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 8234 } 8235 8236 /** 8237 * Performs dexopt on the set of packages in {@code packages} and returns an int array 8238 * containing statistics about the invocation. The array consists of three elements, 8239 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped} 8240 * and {@code numberOfPackagesFailed}. 8241 */ 8242 private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog, 8243 String compilerFilter) { 8244 8245 int numberOfPackagesVisited = 0; 8246 int numberOfPackagesOptimized = 0; 8247 int numberOfPackagesSkipped = 0; 8248 int numberOfPackagesFailed = 0; 8249 final int numberOfPackagesToDexopt = pkgs.size(); 8250 8251 for (PackageParser.Package pkg : pkgs) { 8252 numberOfPackagesVisited++; 8253 8254 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 8255 if (DEBUG_DEXOPT) { 8256 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 8257 } 8258 numberOfPackagesSkipped++; 8259 continue; 8260 } 8261 8262 if (DEBUG_DEXOPT) { 8263 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 8264 numberOfPackagesToDexopt + ": " + pkg.packageName); 8265 } 8266 8267 if (showDialog) { 8268 try { 8269 ActivityManager.getService().showBootMessage( 8270 mContext.getResources().getString(R.string.android_upgrading_apk, 8271 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 8272 } catch (RemoteException e) { 8273 } 8274 synchronized (mPackages) { 8275 mDexOptDialogShown = true; 8276 } 8277 } 8278 8279 // If the OTA updates a system app which was previously preopted to a non-preopted state 8280 // the app might end up being verified at runtime. That's because by default the apps 8281 // are verify-profile but for preopted apps there's no profile. 8282 // Do a hacky check to ensure that if we have no profiles (a reasonable indication 8283 // that before the OTA the app was preopted) the app gets compiled with a non-profile 8284 // filter (by default interpret-only). 8285 // Note that at this stage unused apps are already filtered. 8286 if (isSystemApp(pkg) && 8287 DexFile.isProfileGuidedCompilerFilter(compilerFilter) && 8288 !Environment.getReferenceProfile(pkg.packageName).exists()) { 8289 compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter); 8290 } 8291 8292 // checkProfiles is false to avoid merging profiles during boot which 8293 // might interfere with background compilation (b/28612421). 8294 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 8295 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 8296 // trade-off worth doing to save boot time work. 8297 int dexOptStatus = performDexOptTraced(pkg.packageName, 8298 false /* checkProfiles */, 8299 compilerFilter, 8300 false /* force */); 8301 switch (dexOptStatus) { 8302 case PackageDexOptimizer.DEX_OPT_PERFORMED: 8303 numberOfPackagesOptimized++; 8304 break; 8305 case PackageDexOptimizer.DEX_OPT_SKIPPED: 8306 numberOfPackagesSkipped++; 8307 break; 8308 case PackageDexOptimizer.DEX_OPT_FAILED: 8309 numberOfPackagesFailed++; 8310 break; 8311 default: 8312 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus); 8313 break; 8314 } 8315 } 8316 8317 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped, 8318 numberOfPackagesFailed }; 8319 } 8320 8321 @Override 8322 public void notifyPackageUse(String packageName, int reason) { 8323 synchronized (mPackages) { 8324 PackageParser.Package p = mPackages.get(packageName); 8325 if (p == null) { 8326 return; 8327 } 8328 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 8329 } 8330 } 8331 8332 @Override 8333 public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) { 8334 int userId = UserHandle.getCallingUserId(); 8335 ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId); 8336 if (ai == null) { 8337 Slog.w(TAG, "Loading a package that does not exist for the calling user. package=" 8338 + loadingPackageName + ", user=" + userId); 8339 return; 8340 } 8341 mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId); 8342 } 8343 8344 // TODO: this is not used nor needed. Delete it. 8345 @Override 8346 public boolean performDexOptIfNeeded(String packageName) { 8347 int dexOptStatus = performDexOptTraced(packageName, 8348 false /* checkProfiles */, getFullCompilerFilter(), false /* force */); 8349 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 8350 } 8351 8352 @Override 8353 public boolean performDexOpt(String packageName, 8354 boolean checkProfiles, int compileReason, boolean force) { 8355 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 8356 getCompilerFilterForReason(compileReason), force); 8357 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 8358 } 8359 8360 @Override 8361 public boolean performDexOptMode(String packageName, 8362 boolean checkProfiles, String targetCompilerFilter, boolean force) { 8363 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 8364 targetCompilerFilter, force); 8365 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 8366 } 8367 8368 private int performDexOptTraced(String packageName, 8369 boolean checkProfiles, String targetCompilerFilter, boolean force) { 8370 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 8371 try { 8372 return performDexOptInternal(packageName, checkProfiles, 8373 targetCompilerFilter, force); 8374 } finally { 8375 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8376 } 8377 } 8378 8379 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 8380 // if the package can now be considered up to date for the given filter. 8381 private int performDexOptInternal(String packageName, 8382 boolean checkProfiles, String targetCompilerFilter, boolean force) { 8383 PackageParser.Package p; 8384 synchronized (mPackages) { 8385 p = mPackages.get(packageName); 8386 if (p == null) { 8387 // Package could not be found. Report failure. 8388 return PackageDexOptimizer.DEX_OPT_FAILED; 8389 } 8390 mPackageUsage.maybeWriteAsync(mPackages); 8391 mCompilerStats.maybeWriteAsync(); 8392 } 8393 long callingId = Binder.clearCallingIdentity(); 8394 try { 8395 synchronized (mInstallLock) { 8396 return performDexOptInternalWithDependenciesLI(p, checkProfiles, 8397 targetCompilerFilter, force); 8398 } 8399 } finally { 8400 Binder.restoreCallingIdentity(callingId); 8401 } 8402 } 8403 8404 public ArraySet<String> getOptimizablePackages() { 8405 ArraySet<String> pkgs = new ArraySet<String>(); 8406 synchronized (mPackages) { 8407 for (PackageParser.Package p : mPackages.values()) { 8408 if (PackageDexOptimizer.canOptimizePackage(p)) { 8409 pkgs.add(p.packageName); 8410 } 8411 } 8412 } 8413 return pkgs; 8414 } 8415 8416 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 8417 boolean checkProfiles, String targetCompilerFilter, 8418 boolean force) { 8419 // Select the dex optimizer based on the force parameter. 8420 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 8421 // allocate an object here. 8422 PackageDexOptimizer pdo = force 8423 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 8424 : mPackageDexOptimizer; 8425 8426 // Optimize all dependencies first. Note: we ignore the return value and march on 8427 // on errors. 8428 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 8429 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 8430 if (!deps.isEmpty()) { 8431 for (PackageParser.Package depPackage : deps) { 8432 // TODO: Analyze and investigate if we (should) profile libraries. 8433 // Currently this will do a full compilation of the library by default. 8434 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 8435 false /* checkProfiles */, 8436 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY), 8437 getOrCreateCompilerPackageStats(depPackage), 8438 mDexManager.isUsedByOtherApps(p.packageName)); 8439 } 8440 } 8441 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 8442 targetCompilerFilter, getOrCreateCompilerPackageStats(p), 8443 mDexManager.isUsedByOtherApps(p.packageName)); 8444 } 8445 8446 // Performs dexopt on the used secondary dex files belonging to the given package. 8447 // Returns true if all dex files were process successfully (which could mean either dexopt or 8448 // skip). Returns false if any of the files caused errors. 8449 @Override 8450 public boolean performDexOptSecondary(String packageName, String compilerFilter, 8451 boolean force) { 8452 return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force); 8453 } 8454 8455 /** 8456 * Reconcile the information we have about the secondary dex files belonging to 8457 * {@code packagName} and the actual dex files. For all dex files that were 8458 * deleted, update the internal records and delete the generated oat files. 8459 */ 8460 @Override 8461 public void reconcileSecondaryDexFiles(String packageName) { 8462 mDexManager.reconcileSecondaryDexFiles(packageName); 8463 } 8464 8465 // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject 8466 // a reference there. 8467 /*package*/ DexManager getDexManager() { 8468 return mDexManager; 8469 } 8470 8471 /** 8472 * Execute the background dexopt job immediately. 8473 */ 8474 @Override 8475 public boolean runBackgroundDexoptJob() { 8476 return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext); 8477 } 8478 8479 List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 8480 if (p.usesLibraries != null || p.usesOptionalLibraries != null 8481 || p.usesStaticLibraries != null) { 8482 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 8483 Set<String> collectedNames = new HashSet<>(); 8484 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 8485 8486 retValue.remove(p); 8487 8488 return retValue; 8489 } else { 8490 return Collections.emptyList(); 8491 } 8492 } 8493 8494 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 8495 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) { 8496 if (!collectedNames.contains(p.packageName)) { 8497 collectedNames.add(p.packageName); 8498 collected.add(p); 8499 8500 if (p.usesLibraries != null) { 8501 findSharedNonSystemLibrariesRecursive(p.usesLibraries, 8502 null, collected, collectedNames); 8503 } 8504 if (p.usesOptionalLibraries != null) { 8505 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, 8506 null, collected, collectedNames); 8507 } 8508 if (p.usesStaticLibraries != null) { 8509 findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries, 8510 p.usesStaticLibrariesVersions, collected, collectedNames); 8511 } 8512 } 8513 } 8514 8515 private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions, 8516 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) { 8517 final int libNameCount = libs.size(); 8518 for (int i = 0; i < libNameCount; i++) { 8519 String libName = libs.get(i); 8520 int version = (versions != null && versions.length == libNameCount) 8521 ? versions[i] : PackageManager.VERSION_CODE_HIGHEST; 8522 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version); 8523 if (libPkg != null) { 8524 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 8525 } 8526 } 8527 } 8528 8529 private PackageParser.Package findSharedNonSystemLibrary(String name, int version) { 8530 synchronized (mPackages) { 8531 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version); 8532 if (libEntry != null) { 8533 return mPackages.get(libEntry.apk); 8534 } 8535 return null; 8536 } 8537 } 8538 8539 private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) { 8540 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 8541 if (versionedLib == null) { 8542 return null; 8543 } 8544 return versionedLib.get(version); 8545 } 8546 8547 private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) { 8548 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get( 8549 pkg.staticSharedLibName); 8550 if (versionedLib == null) { 8551 return null; 8552 } 8553 int previousLibVersion = -1; 8554 final int versionCount = versionedLib.size(); 8555 for (int i = 0; i < versionCount; i++) { 8556 final int libVersion = versionedLib.keyAt(i); 8557 if (libVersion < pkg.staticSharedLibVersion) { 8558 previousLibVersion = Math.max(previousLibVersion, libVersion); 8559 } 8560 } 8561 if (previousLibVersion >= 0) { 8562 return versionedLib.get(previousLibVersion); 8563 } 8564 return null; 8565 } 8566 8567 public void shutdown() { 8568 mPackageUsage.writeNow(mPackages); 8569 mCompilerStats.writeNow(); 8570 } 8571 8572 @Override 8573 public void dumpProfiles(String packageName) { 8574 PackageParser.Package pkg; 8575 synchronized (mPackages) { 8576 pkg = mPackages.get(packageName); 8577 if (pkg == null) { 8578 throw new IllegalArgumentException("Unknown package: " + packageName); 8579 } 8580 } 8581 /* Only the shell, root, or the app user should be able to dump profiles. */ 8582 int callingUid = Binder.getCallingUid(); 8583 if (callingUid != Process.SHELL_UID && 8584 callingUid != Process.ROOT_UID && 8585 callingUid != pkg.applicationInfo.uid) { 8586 throw new SecurityException("dumpProfiles"); 8587 } 8588 8589 synchronized (mInstallLock) { 8590 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles"); 8591 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 8592 try { 8593 List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly(); 8594 String codePaths = TextUtils.join(";", allCodePaths); 8595 mInstaller.dumpProfiles(sharedGid, packageName, codePaths); 8596 } catch (InstallerException e) { 8597 Slog.w(TAG, "Failed to dump profiles", e); 8598 } 8599 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8600 } 8601 } 8602 8603 @Override 8604 public void forceDexOpt(String packageName) { 8605 enforceSystemOrRoot("forceDexOpt"); 8606 8607 PackageParser.Package pkg; 8608 synchronized (mPackages) { 8609 pkg = mPackages.get(packageName); 8610 if (pkg == null) { 8611 throw new IllegalArgumentException("Unknown package: " + packageName); 8612 } 8613 } 8614 8615 synchronized (mInstallLock) { 8616 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 8617 8618 // Whoever is calling forceDexOpt wants a fully compiled package. 8619 // Don't use profiles since that may cause compilation to be skipped. 8620 final int res = performDexOptInternalWithDependenciesLI(pkg, 8621 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 8622 true /* force */); 8623 8624 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8625 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 8626 throw new IllegalStateException("Failed to dexopt: " + res); 8627 } 8628 } 8629 } 8630 8631 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 8632 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 8633 Slog.w(TAG, "Unable to update from " + oldPkg.name 8634 + " to " + newPkg.packageName 8635 + ": old package not in system partition"); 8636 return false; 8637 } else if (mPackages.get(oldPkg.name) != null) { 8638 Slog.w(TAG, "Unable to update from " + oldPkg.name 8639 + " to " + newPkg.packageName 8640 + ": old package still exists"); 8641 return false; 8642 } 8643 return true; 8644 } 8645 8646 void removeCodePathLI(File codePath) { 8647 if (codePath.isDirectory()) { 8648 try { 8649 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 8650 } catch (InstallerException e) { 8651 Slog.w(TAG, "Failed to remove code path", e); 8652 } 8653 } else { 8654 codePath.delete(); 8655 } 8656 } 8657 8658 private int[] resolveUserIds(int userId) { 8659 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 8660 } 8661 8662 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 8663 if (pkg == null) { 8664 Slog.wtf(TAG, "Package was null!", new Throwable()); 8665 return; 8666 } 8667 clearAppDataLeafLIF(pkg, userId, flags); 8668 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8669 for (int i = 0; i < childCount; i++) { 8670 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 8671 } 8672 } 8673 8674 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 8675 final PackageSetting ps; 8676 synchronized (mPackages) { 8677 ps = mSettings.mPackages.get(pkg.packageName); 8678 } 8679 for (int realUserId : resolveUserIds(userId)) { 8680 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 8681 try { 8682 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 8683 ceDataInode); 8684 } catch (InstallerException e) { 8685 Slog.w(TAG, String.valueOf(e)); 8686 } 8687 } 8688 } 8689 8690 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 8691 if (pkg == null) { 8692 Slog.wtf(TAG, "Package was null!", new Throwable()); 8693 return; 8694 } 8695 destroyAppDataLeafLIF(pkg, userId, flags); 8696 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8697 for (int i = 0; i < childCount; i++) { 8698 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 8699 } 8700 } 8701 8702 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 8703 final PackageSetting ps; 8704 synchronized (mPackages) { 8705 ps = mSettings.mPackages.get(pkg.packageName); 8706 } 8707 for (int realUserId : resolveUserIds(userId)) { 8708 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 8709 try { 8710 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 8711 ceDataInode); 8712 } catch (InstallerException e) { 8713 Slog.w(TAG, String.valueOf(e)); 8714 } 8715 } 8716 } 8717 8718 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 8719 if (pkg == null) { 8720 Slog.wtf(TAG, "Package was null!", new Throwable()); 8721 return; 8722 } 8723 destroyAppProfilesLeafLIF(pkg); 8724 destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */); 8725 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8726 for (int i = 0; i < childCount; i++) { 8727 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 8728 destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId, 8729 true /* removeBaseMarker */); 8730 } 8731 } 8732 8733 private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId, 8734 boolean removeBaseMarker) { 8735 if (pkg.isForwardLocked()) { 8736 return; 8737 } 8738 8739 for (String path : pkg.getAllCodePathsExcludingResourceOnly()) { 8740 try { 8741 path = PackageManagerServiceUtils.realpath(new File(path)); 8742 } catch (IOException e) { 8743 // TODO: Should we return early here ? 8744 Slog.w(TAG, "Failed to get canonical path", e); 8745 continue; 8746 } 8747 8748 final String useMarker = path.replace('/', '@'); 8749 for (int realUserId : resolveUserIds(userId)) { 8750 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId); 8751 if (removeBaseMarker) { 8752 File foreignUseMark = new File(profileDir, useMarker); 8753 if (foreignUseMark.exists()) { 8754 if (!foreignUseMark.delete()) { 8755 Slog.w(TAG, "Unable to delete foreign user mark for package: " 8756 + pkg.packageName); 8757 } 8758 } 8759 } 8760 8761 File[] markers = profileDir.listFiles(); 8762 if (markers != null) { 8763 final String searchString = "@" + pkg.packageName + "@"; 8764 // We also delete all markers that contain the package name we're 8765 // uninstalling. These are associated with secondary dex-files belonging 8766 // to the package. Reconstructing the path of these dex files is messy 8767 // in general. 8768 for (File marker : markers) { 8769 if (marker.getName().indexOf(searchString) > 0) { 8770 if (!marker.delete()) { 8771 Slog.w(TAG, "Unable to delete foreign user mark for package: " 8772 + pkg.packageName); 8773 } 8774 } 8775 } 8776 } 8777 } 8778 } 8779 } 8780 8781 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 8782 try { 8783 mInstaller.destroyAppProfiles(pkg.packageName); 8784 } catch (InstallerException e) { 8785 Slog.w(TAG, String.valueOf(e)); 8786 } 8787 } 8788 8789 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 8790 if (pkg == null) { 8791 Slog.wtf(TAG, "Package was null!", new Throwable()); 8792 return; 8793 } 8794 clearAppProfilesLeafLIF(pkg); 8795 // We don't remove the base foreign use marker when clearing profiles because 8796 // we will rename it when the app is updated. Unlike the actual profile contents, 8797 // the foreign use marker is good across installs. 8798 destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */); 8799 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8800 for (int i = 0; i < childCount; i++) { 8801 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 8802 } 8803 } 8804 8805 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 8806 try { 8807 mInstaller.clearAppProfiles(pkg.packageName); 8808 } catch (InstallerException e) { 8809 Slog.w(TAG, String.valueOf(e)); 8810 } 8811 } 8812 8813 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 8814 long lastUpdateTime) { 8815 // Set parent install/update time 8816 PackageSetting ps = (PackageSetting) pkg.mExtras; 8817 if (ps != null) { 8818 ps.firstInstallTime = firstInstallTime; 8819 ps.lastUpdateTime = lastUpdateTime; 8820 } 8821 // Set children install/update time 8822 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8823 for (int i = 0; i < childCount; i++) { 8824 PackageParser.Package childPkg = pkg.childPackages.get(i); 8825 ps = (PackageSetting) childPkg.mExtras; 8826 if (ps != null) { 8827 ps.firstInstallTime = firstInstallTime; 8828 ps.lastUpdateTime = lastUpdateTime; 8829 } 8830 } 8831 } 8832 8833 private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 8834 PackageParser.Package changingLib) { 8835 if (file.path != null) { 8836 usesLibraryFiles.add(file.path); 8837 return; 8838 } 8839 PackageParser.Package p = mPackages.get(file.apk); 8840 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 8841 // If we are doing this while in the middle of updating a library apk, 8842 // then we need to make sure to use that new apk for determining the 8843 // dependencies here. (We haven't yet finished committing the new apk 8844 // to the package manager state.) 8845 if (p == null || p.packageName.equals(changingLib.packageName)) { 8846 p = changingLib; 8847 } 8848 } 8849 if (p != null) { 8850 usesLibraryFiles.addAll(p.getAllCodePaths()); 8851 } 8852 } 8853 8854 private void updateSharedLibrariesLPr(PackageParser.Package pkg, 8855 PackageParser.Package changingLib) throws PackageManagerException { 8856 if (pkg == null) { 8857 return; 8858 } 8859 ArraySet<String> usesLibraryFiles = null; 8860 if (pkg.usesLibraries != null) { 8861 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries, 8862 null, null, pkg.packageName, changingLib, true, null); 8863 } 8864 if (pkg.usesStaticLibraries != null) { 8865 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries, 8866 pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests, 8867 pkg.packageName, changingLib, true, usesLibraryFiles); 8868 } 8869 if (pkg.usesOptionalLibraries != null) { 8870 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries, 8871 null, null, pkg.packageName, changingLib, false, usesLibraryFiles); 8872 } 8873 if (!ArrayUtils.isEmpty(usesLibraryFiles)) { 8874 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]); 8875 } else { 8876 pkg.usesLibraryFiles = null; 8877 } 8878 } 8879 8880 private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries, 8881 @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests, 8882 @NonNull String packageName, @Nullable PackageParser.Package changingLib, 8883 boolean required, @Nullable ArraySet<String> outUsedLibraries) 8884 throws PackageManagerException { 8885 final int libCount = requestedLibraries.size(); 8886 for (int i = 0; i < libCount; i++) { 8887 final String libName = requestedLibraries.get(i); 8888 final int libVersion = requiredVersions != null ? requiredVersions[i] 8889 : SharedLibraryInfo.VERSION_UNDEFINED; 8890 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion); 8891 if (libEntry == null) { 8892 if (required) { 8893 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8894 "Package " + packageName + " requires unavailable shared library " 8895 + libName + "; failing!"); 8896 } else { 8897 Slog.w(TAG, "Package " + packageName 8898 + " desires unavailable shared library " 8899 + libName + "; ignoring!"); 8900 } 8901 } else { 8902 if (requiredVersions != null && requiredCertDigests != null) { 8903 if (libEntry.info.getVersion() != requiredVersions[i]) { 8904 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8905 "Package " + packageName + " requires unavailable static shared" 8906 + " library " + libName + " version " 8907 + libEntry.info.getVersion() + "; failing!"); 8908 } 8909 8910 PackageParser.Package libPkg = mPackages.get(libEntry.apk); 8911 if (libPkg == null) { 8912 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8913 "Package " + packageName + " requires unavailable static shared" 8914 + " library; failing!"); 8915 } 8916 8917 String expectedCertDigest = requiredCertDigests[i]; 8918 String libCertDigest = PackageUtils.computeCertSha256Digest( 8919 libPkg.mSignatures[0]); 8920 if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) { 8921 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8922 "Package " + packageName + " requires differently signed" + 8923 " static shared library; failing!"); 8924 } 8925 } 8926 8927 if (outUsedLibraries == null) { 8928 outUsedLibraries = new ArraySet<>(); 8929 } 8930 addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib); 8931 } 8932 } 8933 return outUsedLibraries; 8934 } 8935 8936 private static boolean hasString(List<String> list, List<String> which) { 8937 if (list == null) { 8938 return false; 8939 } 8940 for (int i=list.size()-1; i>=0; i--) { 8941 for (int j=which.size()-1; j>=0; j--) { 8942 if (which.get(j).equals(list.get(i))) { 8943 return true; 8944 } 8945 } 8946 } 8947 return false; 8948 } 8949 8950 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 8951 PackageParser.Package changingPkg) { 8952 ArrayList<PackageParser.Package> res = null; 8953 for (PackageParser.Package pkg : mPackages.values()) { 8954 if (changingPkg != null 8955 && !hasString(pkg.usesLibraries, changingPkg.libraryNames) 8956 && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames) 8957 && !ArrayUtils.contains(pkg.usesStaticLibraries, 8958 changingPkg.staticSharedLibName)) { 8959 return null; 8960 } 8961 if (res == null) { 8962 res = new ArrayList<>(); 8963 } 8964 res.add(pkg); 8965 try { 8966 updateSharedLibrariesLPr(pkg, changingPkg); 8967 } catch (PackageManagerException e) { 8968 // If a system app update or an app and a required lib missing we 8969 // delete the package and for updated system apps keep the data as 8970 // it is better for the user to reinstall than to be in an limbo 8971 // state. Also libs disappearing under an app should never happen 8972 // - just in case. 8973 if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) { 8974 final int flags = pkg.isUpdatedSystemApp() 8975 ? PackageManager.DELETE_KEEP_DATA : 0; 8976 deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(), 8977 flags , null, true, null); 8978 } 8979 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 8980 } 8981 } 8982 return res; 8983 } 8984 8985 /** 8986 * Derive the value of the {@code cpuAbiOverride} based on the provided 8987 * value and an optional stored value from the package settings. 8988 */ 8989 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 8990 String cpuAbiOverride = null; 8991 8992 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 8993 cpuAbiOverride = null; 8994 } else if (abiOverride != null) { 8995 cpuAbiOverride = abiOverride; 8996 } else if (settings != null) { 8997 cpuAbiOverride = settings.cpuAbiOverrideString; 8998 } 8999 9000 return cpuAbiOverride; 9001 } 9002 9003 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 9004 final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user) 9005 throws PackageManagerException { 9006 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 9007 // If the package has children and this is the first dive in the function 9008 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 9009 // whether all packages (parent and children) would be successfully scanned 9010 // before the actual scan since scanning mutates internal state and we want 9011 // to atomically install the package and its children. 9012 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 9013 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 9014 scanFlags |= SCAN_CHECK_ONLY; 9015 } 9016 } else { 9017 scanFlags &= ~SCAN_CHECK_ONLY; 9018 } 9019 9020 final PackageParser.Package scannedPkg; 9021 try { 9022 // Scan the parent 9023 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 9024 // Scan the children 9025 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9026 for (int i = 0; i < childCount; i++) { 9027 PackageParser.Package childPkg = pkg.childPackages.get(i); 9028 scanPackageLI(childPkg, policyFlags, 9029 scanFlags, currentTime, user); 9030 } 9031 } finally { 9032 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9033 } 9034 9035 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 9036 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 9037 } 9038 9039 return scannedPkg; 9040 } 9041 9042 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 9043 int scanFlags, long currentTime, @Nullable UserHandle user) 9044 throws PackageManagerException { 9045 boolean success = false; 9046 try { 9047 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 9048 currentTime, user); 9049 success = true; 9050 return res; 9051 } finally { 9052 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 9053 // DELETE_DATA_ON_FAILURES is only used by frozen paths 9054 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 9055 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 9056 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 9057 } 9058 } 9059 } 9060 9061 /** 9062 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 9063 */ 9064 private static boolean apkHasCode(String fileName) { 9065 StrictJarFile jarFile = null; 9066 try { 9067 jarFile = new StrictJarFile(fileName, 9068 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 9069 return jarFile.findEntry("classes.dex") != null; 9070 } catch (IOException ignore) { 9071 } finally { 9072 try { 9073 if (jarFile != null) { 9074 jarFile.close(); 9075 } 9076 } catch (IOException ignore) {} 9077 } 9078 return false; 9079 } 9080 9081 /** 9082 * Enforces code policy for the package. This ensures that if an APK has 9083 * declared hasCode="true" in its manifest that the APK actually contains 9084 * code. 9085 * 9086 * @throws PackageManagerException If bytecode could not be found when it should exist 9087 */ 9088 private static void assertCodePolicy(PackageParser.Package pkg) 9089 throws PackageManagerException { 9090 final boolean shouldHaveCode = 9091 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 9092 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 9093 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 9094 "Package " + pkg.baseCodePath + " code is missing"); 9095 } 9096 9097 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 9098 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 9099 final boolean splitShouldHaveCode = 9100 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 9101 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 9102 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 9103 "Package " + pkg.splitCodePaths[i] + " code is missing"); 9104 } 9105 } 9106 } 9107 } 9108 9109 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 9110 final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user) 9111 throws PackageManagerException { 9112 if (DEBUG_PACKAGE_SCANNING) { 9113 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 9114 Log.d(TAG, "Scanning package " + pkg.packageName); 9115 } 9116 9117 applyPolicy(pkg, policyFlags); 9118 9119 assertPackageIsValid(pkg, policyFlags, scanFlags); 9120 9121 // Initialize package source and resource directories 9122 final File scanFile = new File(pkg.codePath); 9123 final File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 9124 final File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 9125 9126 SharedUserSetting suid = null; 9127 PackageSetting pkgSetting = null; 9128 9129 // Getting the package setting may have a side-effect, so if we 9130 // are only checking if scan would succeed, stash a copy of the 9131 // old setting to restore at the end. 9132 PackageSetting nonMutatedPs = null; 9133 9134 // We keep references to the derived CPU Abis from settings in oder to reuse 9135 // them in the case where we're not upgrading or booting for the first time. 9136 String primaryCpuAbiFromSettings = null; 9137 String secondaryCpuAbiFromSettings = null; 9138 9139 // writer 9140 synchronized (mPackages) { 9141 if (pkg.mSharedUserId != null) { 9142 // SIDE EFFECTS; may potentially allocate a new shared user 9143 suid = mSettings.getSharedUserLPw( 9144 pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/); 9145 if (DEBUG_PACKAGE_SCANNING) { 9146 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 9147 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 9148 + "): packages=" + suid.packages); 9149 } 9150 } 9151 9152 // Check if we are renaming from an original package name. 9153 PackageSetting origPackage = null; 9154 String realName = null; 9155 if (pkg.mOriginalPackages != null) { 9156 // This package may need to be renamed to a previously 9157 // installed name. Let's check on that... 9158 final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage); 9159 if (pkg.mOriginalPackages.contains(renamed)) { 9160 // This package had originally been installed as the 9161 // original name, and we have already taken care of 9162 // transitioning to the new one. Just update the new 9163 // one to continue using the old name. 9164 realName = pkg.mRealPackage; 9165 if (!pkg.packageName.equals(renamed)) { 9166 // Callers into this function may have already taken 9167 // care of renaming the package; only do it here if 9168 // it is not already done. 9169 pkg.setPackageName(renamed); 9170 } 9171 } else { 9172 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 9173 if ((origPackage = mSettings.getPackageLPr( 9174 pkg.mOriginalPackages.get(i))) != null) { 9175 // We do have the package already installed under its 9176 // original name... should we use it? 9177 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 9178 // New package is not compatible with original. 9179 origPackage = null; 9180 continue; 9181 } else if (origPackage.sharedUser != null) { 9182 // Make sure uid is compatible between packages. 9183 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 9184 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 9185 + " to " + pkg.packageName + ": old uid " 9186 + origPackage.sharedUser.name 9187 + " differs from " + pkg.mSharedUserId); 9188 origPackage = null; 9189 continue; 9190 } 9191 // TODO: Add case when shared user id is added [b/28144775] 9192 } else { 9193 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 9194 + pkg.packageName + " to old name " + origPackage.name); 9195 } 9196 break; 9197 } 9198 } 9199 } 9200 } 9201 9202 if (mTransferedPackages.contains(pkg.packageName)) { 9203 Slog.w(TAG, "Package " + pkg.packageName 9204 + " was transferred to another, but its .apk remains"); 9205 } 9206 9207 // See comments in nonMutatedPs declaration 9208 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 9209 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName); 9210 if (foundPs != null) { 9211 nonMutatedPs = new PackageSetting(foundPs); 9212 } 9213 } 9214 9215 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) { 9216 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName); 9217 if (foundPs != null) { 9218 primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString; 9219 secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString; 9220 } 9221 } 9222 9223 pkgSetting = mSettings.getPackageLPr(pkg.packageName); 9224 if (pkgSetting != null && pkgSetting.sharedUser != suid) { 9225 PackageManagerService.reportSettingsProblem(Log.WARN, 9226 "Package " + pkg.packageName + " shared user changed from " 9227 + (pkgSetting.sharedUser != null 9228 ? pkgSetting.sharedUser.name : "<nothing>") 9229 + " to " 9230 + (suid != null ? suid.name : "<nothing>") 9231 + "; replacing with new"); 9232 pkgSetting = null; 9233 } 9234 final PackageSetting oldPkgSetting = 9235 pkgSetting == null ? null : new PackageSetting(pkgSetting); 9236 final PackageSetting disabledPkgSetting = 9237 mSettings.getDisabledSystemPkgLPr(pkg.packageName); 9238 9239 String[] usesStaticLibraries = null; 9240 if (pkg.usesStaticLibraries != null) { 9241 usesStaticLibraries = new String[pkg.usesStaticLibraries.size()]; 9242 pkg.usesStaticLibraries.toArray(usesStaticLibraries); 9243 } 9244 9245 if (pkgSetting == null) { 9246 final String parentPackageName = (pkg.parentPackage != null) 9247 ? pkg.parentPackage.packageName : null; 9248 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 9249 // REMOVE SharedUserSetting from method; update in a separate call 9250 pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage, 9251 disabledPkgSetting, realName, suid, destCodeFile, destResourceFile, 9252 pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi, 9253 pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode, 9254 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user, 9255 true /*allowInstall*/, instantApp, parentPackageName, 9256 pkg.getChildPackageNames(), UserManagerService.getInstance(), 9257 usesStaticLibraries, pkg.usesStaticLibrariesVersions); 9258 // SIDE EFFECTS; updates system state; move elsewhere 9259 if (origPackage != null) { 9260 mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name); 9261 } 9262 mSettings.addUserToSettingLPw(pkgSetting); 9263 } else { 9264 // REMOVE SharedUserSetting from method; update in a separate call. 9265 // 9266 // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi, 9267 // secondaryCpuAbi are not known at this point so we always update them 9268 // to null here, only to reset them at a later point. 9269 Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile, 9270 pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi, 9271 pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags, 9272 pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(), 9273 UserManagerService.getInstance(), usesStaticLibraries, 9274 pkg.usesStaticLibrariesVersions); 9275 } 9276 // SIDE EFFECTS; persists system state to files on disk; move elsewhere 9277 mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting); 9278 9279 // SIDE EFFECTS; modifies system state; move elsewhere 9280 if (pkgSetting.origPackage != null) { 9281 // If we are first transitioning from an original package, 9282 // fix up the new package's name now. We need to do this after 9283 // looking up the package under its new name, so getPackageLP 9284 // can take care of fiddling things correctly. 9285 pkg.setPackageName(origPackage.name); 9286 9287 // File a report about this. 9288 String msg = "New package " + pkgSetting.realName 9289 + " renamed to replace old package " + pkgSetting.name; 9290 reportSettingsProblem(Log.WARN, msg); 9291 9292 // Make a note of it. 9293 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 9294 mTransferedPackages.add(origPackage.name); 9295 } 9296 9297 // No longer need to retain this. 9298 pkgSetting.origPackage = null; 9299 } 9300 9301 // SIDE EFFECTS; modifies system state; move elsewhere 9302 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 9303 // Make a note of it. 9304 mTransferedPackages.add(pkg.packageName); 9305 } 9306 9307 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 9308 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 9309 } 9310 9311 if ((scanFlags & SCAN_BOOTING) == 0 9312 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 9313 // Check all shared libraries and map to their actual file path. 9314 // We only do this here for apps not on a system dir, because those 9315 // are the only ones that can fail an install due to this. We 9316 // will take care of the system apps by updating all of their 9317 // library paths after the scan is done. Also during the initial 9318 // scan don't update any libs as we do this wholesale after all 9319 // apps are scanned to avoid dependency based scanning. 9320 updateSharedLibrariesLPr(pkg, null); 9321 } 9322 9323 if (mFoundPolicyFile) { 9324 SELinuxMMAC.assignSeInfoValue(pkg); 9325 } 9326 pkg.applicationInfo.uid = pkgSetting.appId; 9327 pkg.mExtras = pkgSetting; 9328 9329 9330 // Static shared libs have same package with different versions where 9331 // we internally use a synthetic package name to allow multiple versions 9332 // of the same package, therefore we need to compare signatures against 9333 // the package setting for the latest library version. 9334 PackageSetting signatureCheckPs = pkgSetting; 9335 if (pkg.applicationInfo.isStaticSharedLibrary()) { 9336 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg); 9337 if (libraryEntry != null) { 9338 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk); 9339 } 9340 } 9341 9342 if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) { 9343 if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) { 9344 // We just determined the app is signed correctly, so bring 9345 // over the latest parsed certs. 9346 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9347 } else { 9348 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 9349 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 9350 "Package " + pkg.packageName + " upgrade keys do not match the " 9351 + "previously installed version"); 9352 } else { 9353 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9354 String msg = "System package " + pkg.packageName 9355 + " signature changed; retaining data."; 9356 reportSettingsProblem(Log.WARN, msg); 9357 } 9358 } 9359 } else { 9360 try { 9361 // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService 9362 verifySignaturesLP(signatureCheckPs, pkg); 9363 // We just determined the app is signed correctly, so bring 9364 // over the latest parsed certs. 9365 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9366 } catch (PackageManagerException e) { 9367 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 9368 throw e; 9369 } 9370 // The signature has changed, but this package is in the system 9371 // image... let's recover! 9372 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9373 // However... if this package is part of a shared user, but it 9374 // doesn't match the signature of the shared user, let's fail. 9375 // What this means is that you can't change the signatures 9376 // associated with an overall shared user, which doesn't seem all 9377 // that unreasonable. 9378 if (signatureCheckPs.sharedUser != null) { 9379 if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures, 9380 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 9381 throw new PackageManagerException( 9382 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 9383 "Signature mismatch for shared user: " 9384 + pkgSetting.sharedUser); 9385 } 9386 } 9387 // File a report about this. 9388 String msg = "System package " + pkg.packageName 9389 + " signature changed; retaining data."; 9390 reportSettingsProblem(Log.WARN, msg); 9391 } 9392 } 9393 9394 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 9395 // This package wants to adopt ownership of permissions from 9396 // another package. 9397 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 9398 final String origName = pkg.mAdoptPermissions.get(i); 9399 final PackageSetting orig = mSettings.getPackageLPr(origName); 9400 if (orig != null) { 9401 if (verifyPackageUpdateLPr(orig, pkg)) { 9402 Slog.i(TAG, "Adopting permissions from " + origName + " to " 9403 + pkg.packageName); 9404 // SIDE EFFECTS; updates permissions system state; move elsewhere 9405 mSettings.transferPermissionsLPw(origName, pkg.packageName); 9406 } 9407 } 9408 } 9409 } 9410 } 9411 9412 pkg.applicationInfo.processName = fixProcessName( 9413 pkg.applicationInfo.packageName, 9414 pkg.applicationInfo.processName); 9415 9416 if (pkg != mPlatformPackage) { 9417 // Get all of our default paths setup 9418 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 9419 } 9420 9421 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 9422 9423 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 9424 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) { 9425 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi"); 9426 derivePackageAbi( 9427 pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir); 9428 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9429 9430 // Some system apps still use directory structure for native libraries 9431 // in which case we might end up not detecting abi solely based on apk 9432 // structure. Try to detect abi based on directory structure. 9433 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 9434 pkg.applicationInfo.primaryCpuAbi == null) { 9435 setBundledAppAbisAndRoots(pkg, pkgSetting); 9436 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 9437 } 9438 } else { 9439 // This is not a first boot or an upgrade, don't bother deriving the 9440 // ABI during the scan. Instead, trust the value that was stored in the 9441 // package setting. 9442 pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings; 9443 pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings; 9444 9445 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 9446 9447 if (DEBUG_ABI_SELECTION) { 9448 Slog.i(TAG, "Using ABIS and native lib paths from settings : " + 9449 pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " + 9450 pkg.applicationInfo.secondaryCpuAbi); 9451 } 9452 } 9453 } else { 9454 if ((scanFlags & SCAN_MOVE) != 0) { 9455 // We haven't run dex-opt for this move (since we've moved the compiled output too) 9456 // but we already have this packages package info in the PackageSetting. We just 9457 // use that and derive the native library path based on the new codepath. 9458 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 9459 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 9460 } 9461 9462 // Set native library paths again. For moves, the path will be updated based on the 9463 // ABIs we've determined above. For non-moves, the path will be updated based on the 9464 // ABIs we determined during compilation, but the path will depend on the final 9465 // package path (after the rename away from the stage path). 9466 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 9467 } 9468 9469 // This is a special case for the "system" package, where the ABI is 9470 // dictated by the zygote configuration (and init.rc). We should keep track 9471 // of this ABI so that we can deal with "normal" applications that run under 9472 // the same UID correctly. 9473 if (mPlatformPackage == pkg) { 9474 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 9475 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 9476 } 9477 9478 // If there's a mismatch between the abi-override in the package setting 9479 // and the abiOverride specified for the install. Warn about this because we 9480 // would've already compiled the app without taking the package setting into 9481 // account. 9482 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 9483 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 9484 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 9485 " for package " + pkg.packageName); 9486 } 9487 } 9488 9489 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9490 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9491 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 9492 9493 // Copy the derived override back to the parsed package, so that we can 9494 // update the package settings accordingly. 9495 pkg.cpuAbiOverride = cpuAbiOverride; 9496 9497 if (DEBUG_ABI_SELECTION) { 9498 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 9499 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 9500 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 9501 } 9502 9503 // Push the derived path down into PackageSettings so we know what to 9504 // clean up at uninstall time. 9505 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 9506 9507 if (DEBUG_ABI_SELECTION) { 9508 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 9509 " primary=" + pkg.applicationInfo.primaryCpuAbi + 9510 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 9511 } 9512 9513 // SIDE EFFECTS; removes DEX files from disk; move elsewhere 9514 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 9515 // We don't do this here during boot because we can do it all 9516 // at once after scanning all existing packages. 9517 // 9518 // We also do this *before* we perform dexopt on this package, so that 9519 // we can avoid redundant dexopts, and also to make sure we've got the 9520 // code and package path correct. 9521 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg); 9522 } 9523 9524 if (mFactoryTest && pkg.requestedPermissions.contains( 9525 android.Manifest.permission.FACTORY_TEST)) { 9526 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 9527 } 9528 9529 if (isSystemApp(pkg)) { 9530 pkgSetting.isOrphaned = true; 9531 } 9532 9533 // Take care of first install / last update times. 9534 final long scanFileTime = getLastModifiedTime(pkg, scanFile); 9535 if (currentTime != 0) { 9536 if (pkgSetting.firstInstallTime == 0) { 9537 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 9538 } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) { 9539 pkgSetting.lastUpdateTime = currentTime; 9540 } 9541 } else if (pkgSetting.firstInstallTime == 0) { 9542 // We need *something*. Take time time stamp of the file. 9543 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 9544 } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 9545 if (scanFileTime != pkgSetting.timeStamp) { 9546 // A package on the system image has changed; consider this 9547 // to be an update. 9548 pkgSetting.lastUpdateTime = scanFileTime; 9549 } 9550 } 9551 pkgSetting.setTimeStamp(scanFileTime); 9552 9553 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 9554 if (nonMutatedPs != null) { 9555 synchronized (mPackages) { 9556 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 9557 } 9558 } 9559 } else { 9560 final int userId = user == null ? 0 : user.getIdentifier(); 9561 // Modify state for the given package setting 9562 commitPackageSettings(pkg, pkgSetting, user, scanFlags, 9563 (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/); 9564 if (pkgSetting.getInstantApp(userId)) { 9565 mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId); 9566 } 9567 } 9568 return pkg; 9569 } 9570 9571 /** 9572 * Applies policy to the parsed package based upon the given policy flags. 9573 * Ensures the package is in a good state. 9574 * <p> 9575 * Implementation detail: This method must NOT have any side effect. It would 9576 * ideally be static, but, it requires locks to read system state. 9577 */ 9578 private void applyPolicy(PackageParser.Package pkg, int policyFlags) { 9579 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 9580 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 9581 if (pkg.applicationInfo.isDirectBootAware()) { 9582 // we're direct boot aware; set for all components 9583 for (PackageParser.Service s : pkg.services) { 9584 s.info.encryptionAware = s.info.directBootAware = true; 9585 } 9586 for (PackageParser.Provider p : pkg.providers) { 9587 p.info.encryptionAware = p.info.directBootAware = true; 9588 } 9589 for (PackageParser.Activity a : pkg.activities) { 9590 a.info.encryptionAware = a.info.directBootAware = true; 9591 } 9592 for (PackageParser.Activity r : pkg.receivers) { 9593 r.info.encryptionAware = r.info.directBootAware = true; 9594 } 9595 } 9596 } else { 9597 // Only allow system apps to be flagged as core apps. 9598 pkg.coreApp = false; 9599 // clear flags not applicable to regular apps 9600 pkg.applicationInfo.privateFlags &= 9601 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 9602 pkg.applicationInfo.privateFlags &= 9603 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 9604 } 9605 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 9606 9607 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 9608 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 9609 } 9610 9611 if (!isSystemApp(pkg)) { 9612 // Only system apps can use these features. 9613 pkg.mOriginalPackages = null; 9614 pkg.mRealPackage = null; 9615 pkg.mAdoptPermissions = null; 9616 } 9617 } 9618 9619 /** 9620 * Asserts the parsed package is valid according to the given policy. If the 9621 * package is invalid, for whatever reason, throws {@link PackgeManagerException}. 9622 * <p> 9623 * Implementation detail: This method must NOT have any side effects. It would 9624 * ideally be static, but, it requires locks to read system state. 9625 * 9626 * @throws PackageManagerException If the package fails any of the validation checks 9627 */ 9628 private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags) 9629 throws PackageManagerException { 9630 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 9631 assertCodePolicy(pkg); 9632 } 9633 9634 if (pkg.applicationInfo.getCodePath() == null || 9635 pkg.applicationInfo.getResourcePath() == null) { 9636 // Bail out. The resource and code paths haven't been set. 9637 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 9638 "Code and resource paths haven't been set correctly"); 9639 } 9640 9641 // Make sure we're not adding any bogus keyset info 9642 KeySetManagerService ksms = mSettings.mKeySetManagerService; 9643 ksms.assertScannedPackageValid(pkg); 9644 9645 synchronized (mPackages) { 9646 // The special "android" package can only be defined once 9647 if (pkg.packageName.equals("android")) { 9648 if (mAndroidApplication != null) { 9649 Slog.w(TAG, "*************************************************"); 9650 Slog.w(TAG, "Core android package being redefined. Skipping."); 9651 Slog.w(TAG, " codePath=" + pkg.codePath); 9652 Slog.w(TAG, "*************************************************"); 9653 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 9654 "Core android package being redefined. Skipping."); 9655 } 9656 } 9657 9658 // A package name must be unique; don't allow duplicates 9659 if (mPackages.containsKey(pkg.packageName)) { 9660 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 9661 "Application package " + pkg.packageName 9662 + " already installed. Skipping duplicate."); 9663 } 9664 9665 if (pkg.applicationInfo.isStaticSharedLibrary()) { 9666 // Static libs have a synthetic package name containing the version 9667 // but we still want the base name to be unique. 9668 if (mPackages.containsKey(pkg.manifestPackageName)) { 9669 throw new PackageManagerException( 9670 "Duplicate static shared lib provider package"); 9671 } 9672 9673 // Static shared libraries should have at least O target SDK 9674 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) { 9675 throw new PackageManagerException( 9676 "Packages declaring static-shared libs must target O SDK or higher"); 9677 } 9678 9679 // Package declaring static a shared lib cannot be instant apps 9680 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 9681 throw new PackageManagerException( 9682 "Packages declaring static-shared libs cannot be instant apps"); 9683 } 9684 9685 // Package declaring static a shared lib cannot be renamed since the package 9686 // name is synthetic and apps can't code around package manager internals. 9687 if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) { 9688 throw new PackageManagerException( 9689 "Packages declaring static-shared libs cannot be renamed"); 9690 } 9691 9692 // Package declaring static a shared lib cannot declare child packages 9693 if (!ArrayUtils.isEmpty(pkg.childPackages)) { 9694 throw new PackageManagerException( 9695 "Packages declaring static-shared libs cannot have child packages"); 9696 } 9697 9698 // Package declaring static a shared lib cannot declare dynamic libs 9699 if (!ArrayUtils.isEmpty(pkg.libraryNames)) { 9700 throw new PackageManagerException( 9701 "Packages declaring static-shared libs cannot declare dynamic libs"); 9702 } 9703 9704 // Package declaring static a shared lib cannot declare shared users 9705 if (pkg.mSharedUserId != null) { 9706 throw new PackageManagerException( 9707 "Packages declaring static-shared libs cannot declare shared users"); 9708 } 9709 9710 // Static shared libs cannot declare activities 9711 if (!pkg.activities.isEmpty()) { 9712 throw new PackageManagerException( 9713 "Static shared libs cannot declare activities"); 9714 } 9715 9716 // Static shared libs cannot declare services 9717 if (!pkg.services.isEmpty()) { 9718 throw new PackageManagerException( 9719 "Static shared libs cannot declare services"); 9720 } 9721 9722 // Static shared libs cannot declare providers 9723 if (!pkg.providers.isEmpty()) { 9724 throw new PackageManagerException( 9725 "Static shared libs cannot declare content providers"); 9726 } 9727 9728 // Static shared libs cannot declare receivers 9729 if (!pkg.receivers.isEmpty()) { 9730 throw new PackageManagerException( 9731 "Static shared libs cannot declare broadcast receivers"); 9732 } 9733 9734 // Static shared libs cannot declare permission groups 9735 if (!pkg.permissionGroups.isEmpty()) { 9736 throw new PackageManagerException( 9737 "Static shared libs cannot declare permission groups"); 9738 } 9739 9740 // Static shared libs cannot declare permissions 9741 if (!pkg.permissions.isEmpty()) { 9742 throw new PackageManagerException( 9743 "Static shared libs cannot declare permissions"); 9744 } 9745 9746 // Static shared libs cannot declare protected broadcasts 9747 if (pkg.protectedBroadcasts != null) { 9748 throw new PackageManagerException( 9749 "Static shared libs cannot declare protected broadcasts"); 9750 } 9751 9752 // Static shared libs cannot be overlay targets 9753 if (pkg.mOverlayTarget != null) { 9754 throw new PackageManagerException( 9755 "Static shared libs cannot be overlay targets"); 9756 } 9757 9758 // The version codes must be ordered as lib versions 9759 int minVersionCode = Integer.MIN_VALUE; 9760 int maxVersionCode = Integer.MAX_VALUE; 9761 9762 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get( 9763 pkg.staticSharedLibName); 9764 if (versionedLib != null) { 9765 final int versionCount = versionedLib.size(); 9766 for (int i = 0; i < versionCount; i++) { 9767 SharedLibraryInfo libInfo = versionedLib.valueAt(i).info; 9768 // TODO: We will change version code to long, so in the new API it is long 9769 final int libVersionCode = (int) libInfo.getDeclaringPackage() 9770 .getVersionCode(); 9771 if (libInfo.getVersion() < pkg.staticSharedLibVersion) { 9772 minVersionCode = Math.max(minVersionCode, libVersionCode + 1); 9773 } else if (libInfo.getVersion() > pkg.staticSharedLibVersion) { 9774 maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1); 9775 } else { 9776 minVersionCode = maxVersionCode = libVersionCode; 9777 break; 9778 } 9779 } 9780 } 9781 if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) { 9782 throw new PackageManagerException("Static shared" 9783 + " lib version codes must be ordered as lib versions"); 9784 } 9785 } 9786 9787 // Only privileged apps and updated privileged apps can add child packages. 9788 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 9789 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 9790 throw new PackageManagerException("Only privileged apps can add child " 9791 + "packages. Ignoring package " + pkg.packageName); 9792 } 9793 final int childCount = pkg.childPackages.size(); 9794 for (int i = 0; i < childCount; i++) { 9795 PackageParser.Package childPkg = pkg.childPackages.get(i); 9796 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 9797 childPkg.packageName)) { 9798 throw new PackageManagerException("Can't override child of " 9799 + "another disabled app. Ignoring package " + pkg.packageName); 9800 } 9801 } 9802 } 9803 9804 // If we're only installing presumed-existing packages, require that the 9805 // scanned APK is both already known and at the path previously established 9806 // for it. Previously unknown packages we pick up normally, but if we have an 9807 // a priori expectation about this package's install presence, enforce it. 9808 // With a singular exception for new system packages. When an OTA contains 9809 // a new system package, we allow the codepath to change from a system location 9810 // to the user-installed location. If we don't allow this change, any newer, 9811 // user-installed version of the application will be ignored. 9812 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 9813 if (mExpectingBetter.containsKey(pkg.packageName)) { 9814 logCriticalInfo(Log.WARN, 9815 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 9816 } else { 9817 PackageSetting known = mSettings.getPackageLPr(pkg.packageName); 9818 if (known != null) { 9819 if (DEBUG_PACKAGE_SCANNING) { 9820 Log.d(TAG, "Examining " + pkg.codePath 9821 + " and requiring known paths " + known.codePathString 9822 + " & " + known.resourcePathString); 9823 } 9824 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 9825 || !pkg.applicationInfo.getResourcePath().equals( 9826 known.resourcePathString)) { 9827 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 9828 "Application package " + pkg.packageName 9829 + " found at " + pkg.applicationInfo.getCodePath() 9830 + " but expected at " + known.codePathString 9831 + "; ignoring."); 9832 } 9833 } 9834 } 9835 } 9836 9837 // Verify that this new package doesn't have any content providers 9838 // that conflict with existing packages. Only do this if the 9839 // package isn't already installed, since we don't want to break 9840 // things that are installed. 9841 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 9842 final int N = pkg.providers.size(); 9843 int i; 9844 for (i=0; i<N; i++) { 9845 PackageParser.Provider p = pkg.providers.get(i); 9846 if (p.info.authority != null) { 9847 String names[] = p.info.authority.split(";"); 9848 for (int j = 0; j < names.length; j++) { 9849 if (mProvidersByAuthority.containsKey(names[j])) { 9850 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 9851 final String otherPackageName = 9852 ((other != null && other.getComponentName() != null) ? 9853 other.getComponentName().getPackageName() : "?"); 9854 throw new PackageManagerException( 9855 INSTALL_FAILED_CONFLICTING_PROVIDER, 9856 "Can't install because provider name " + names[j] 9857 + " (in package " + pkg.applicationInfo.packageName 9858 + ") is already used by " + otherPackageName); 9859 } 9860 } 9861 } 9862 } 9863 } 9864 } 9865 } 9866 9867 private boolean addSharedLibraryLPw(String path, String apk, String name, int version, 9868 int type, String declaringPackageName, int declaringVersionCode) { 9869 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 9870 if (versionedLib == null) { 9871 versionedLib = new SparseArray<>(); 9872 mSharedLibraries.put(name, versionedLib); 9873 if (type == SharedLibraryInfo.TYPE_STATIC) { 9874 mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib); 9875 } 9876 } else if (versionedLib.indexOfKey(version) >= 0) { 9877 return false; 9878 } 9879 SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name, 9880 version, type, declaringPackageName, declaringVersionCode); 9881 versionedLib.put(version, libEntry); 9882 return true; 9883 } 9884 9885 private boolean removeSharedLibraryLPw(String name, int version) { 9886 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 9887 if (versionedLib == null) { 9888 return false; 9889 } 9890 final int libIdx = versionedLib.indexOfKey(version); 9891 if (libIdx < 0) { 9892 return false; 9893 } 9894 SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx); 9895 versionedLib.remove(version); 9896 if (versionedLib.size() <= 0) { 9897 mSharedLibraries.remove(name); 9898 if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) { 9899 mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage() 9900 .getPackageName()); 9901 } 9902 } 9903 return true; 9904 } 9905 9906 /** 9907 * Adds a scanned package to the system. When this method is finished, the package will 9908 * be available for query, resolution, etc... 9909 */ 9910 private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting, 9911 UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException { 9912 final String pkgName = pkg.packageName; 9913 if (mCustomResolverComponentName != null && 9914 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 9915 setUpCustomResolverActivity(pkg); 9916 } 9917 9918 if (pkg.packageName.equals("android")) { 9919 synchronized (mPackages) { 9920 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 9921 // Set up information for our fall-back user intent resolution activity. 9922 mPlatformPackage = pkg; 9923 pkg.mVersionCode = mSdkVersion; 9924 mAndroidApplication = pkg.applicationInfo; 9925 if (!mResolverReplaced) { 9926 mResolveActivity.applicationInfo = mAndroidApplication; 9927 mResolveActivity.name = ResolverActivity.class.getName(); 9928 mResolveActivity.packageName = mAndroidApplication.packageName; 9929 mResolveActivity.processName = "system:ui"; 9930 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9931 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 9932 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 9933 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 9934 mResolveActivity.exported = true; 9935 mResolveActivity.enabled = true; 9936 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 9937 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 9938 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 9939 | ActivityInfo.CONFIG_SCREEN_LAYOUT 9940 | ActivityInfo.CONFIG_ORIENTATION 9941 | ActivityInfo.CONFIG_KEYBOARD 9942 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 9943 mResolveInfo.activityInfo = mResolveActivity; 9944 mResolveInfo.priority = 0; 9945 mResolveInfo.preferredOrder = 0; 9946 mResolveInfo.match = 0; 9947 mResolveComponentName = new ComponentName( 9948 mAndroidApplication.packageName, mResolveActivity.name); 9949 } 9950 } 9951 } 9952 } 9953 9954 ArrayList<PackageParser.Package> clientLibPkgs = null; 9955 // writer 9956 synchronized (mPackages) { 9957 boolean hasStaticSharedLibs = false; 9958 9959 // Any app can add new static shared libraries 9960 if (pkg.staticSharedLibName != null) { 9961 // Static shared libs don't allow renaming as they have synthetic package 9962 // names to allow install of multiple versions, so use name from manifest. 9963 if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName, 9964 pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC, 9965 pkg.manifestPackageName, pkg.mVersionCode)) { 9966 hasStaticSharedLibs = true; 9967 } else { 9968 Slog.w(TAG, "Package " + pkg.packageName + " library " 9969 + pkg.staticSharedLibName + " already exists; skipping"); 9970 } 9971 // Static shared libs cannot be updated once installed since they 9972 // use synthetic package name which includes the version code, so 9973 // not need to update other packages's shared lib dependencies. 9974 } 9975 9976 if (!hasStaticSharedLibs 9977 && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 9978 // Only system apps can add new dynamic shared libraries. 9979 if (pkg.libraryNames != null) { 9980 for (int i = 0; i < pkg.libraryNames.size(); i++) { 9981 String name = pkg.libraryNames.get(i); 9982 boolean allowed = false; 9983 if (pkg.isUpdatedSystemApp()) { 9984 // New library entries can only be added through the 9985 // system image. This is important to get rid of a lot 9986 // of nasty edge cases: for example if we allowed a non- 9987 // system update of the app to add a library, then uninstalling 9988 // the update would make the library go away, and assumptions 9989 // we made such as through app install filtering would now 9990 // have allowed apps on the device which aren't compatible 9991 // with it. Better to just have the restriction here, be 9992 // conservative, and create many fewer cases that can negatively 9993 // impact the user experience. 9994 final PackageSetting sysPs = mSettings 9995 .getDisabledSystemPkgLPr(pkg.packageName); 9996 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 9997 for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) { 9998 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 9999 allowed = true; 10000 break; 10001 } 10002 } 10003 } 10004 } else { 10005 allowed = true; 10006 } 10007 if (allowed) { 10008 if (!addSharedLibraryLPw(null, pkg.packageName, name, 10009 SharedLibraryInfo.VERSION_UNDEFINED, 10010 SharedLibraryInfo.TYPE_DYNAMIC, 10011 pkg.packageName, pkg.mVersionCode)) { 10012 Slog.w(TAG, "Package " + pkg.packageName + " library " 10013 + name + " already exists; skipping"); 10014 } 10015 } else { 10016 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 10017 + name + " that is not declared on system image; skipping"); 10018 } 10019 } 10020 10021 if ((scanFlags & SCAN_BOOTING) == 0) { 10022 // If we are not booting, we need to update any applications 10023 // that are clients of our shared library. If we are booting, 10024 // this will all be done once the scan is complete. 10025 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 10026 } 10027 } 10028 } 10029 } 10030 10031 if ((scanFlags & SCAN_BOOTING) != 0) { 10032 // No apps can run during boot scan, so they don't need to be frozen 10033 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 10034 // Caller asked to not kill app, so it's probably not frozen 10035 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 10036 // Caller asked us to ignore frozen check for some reason; they 10037 // probably didn't know the package name 10038 } else { 10039 // We're doing major surgery on this package, so it better be frozen 10040 // right now to keep it from launching 10041 checkPackageFrozen(pkgName); 10042 } 10043 10044 // Also need to kill any apps that are dependent on the library. 10045 if (clientLibPkgs != null) { 10046 for (int i=0; i<clientLibPkgs.size(); i++) { 10047 PackageParser.Package clientPkg = clientLibPkgs.get(i); 10048 killApplication(clientPkg.applicationInfo.packageName, 10049 clientPkg.applicationInfo.uid, "update lib"); 10050 } 10051 } 10052 10053 // writer 10054 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 10055 10056 synchronized (mPackages) { 10057 // We don't expect installation to fail beyond this point 10058 10059 if (pkgSetting.pkg != null) { 10060 // Note that |user| might be null during the initial boot scan. If a codePath 10061 // for an app has changed during a boot scan, it's due to an app update that's 10062 // part of the system partition and marker changes must be applied to all users. 10063 final int userId = ((user != null) ? user : UserHandle.ALL).getIdentifier(); 10064 final int[] userIds = resolveUserIds(userId); 10065 maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg, userIds); 10066 } 10067 10068 // Add the new setting to mSettings 10069 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 10070 // Add the new setting to mPackages 10071 mPackages.put(pkg.applicationInfo.packageName, pkg); 10072 // Make sure we don't accidentally delete its data. 10073 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 10074 while (iter.hasNext()) { 10075 PackageCleanItem item = iter.next(); 10076 if (pkgName.equals(item.packageName)) { 10077 iter.remove(); 10078 } 10079 } 10080 10081 // Add the package's KeySets to the global KeySetManagerService 10082 KeySetManagerService ksms = mSettings.mKeySetManagerService; 10083 ksms.addScannedPackageLPw(pkg); 10084 10085 int N = pkg.providers.size(); 10086 StringBuilder r = null; 10087 int i; 10088 for (i=0; i<N; i++) { 10089 PackageParser.Provider p = pkg.providers.get(i); 10090 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 10091 p.info.processName); 10092 mProviders.addProvider(p); 10093 p.syncable = p.info.isSyncable; 10094 if (p.info.authority != null) { 10095 String names[] = p.info.authority.split(";"); 10096 p.info.authority = null; 10097 for (int j = 0; j < names.length; j++) { 10098 if (j == 1 && p.syncable) { 10099 // We only want the first authority for a provider to possibly be 10100 // syncable, so if we already added this provider using a different 10101 // authority clear the syncable flag. We copy the provider before 10102 // changing it because the mProviders object contains a reference 10103 // to a provider that we don't want to change. 10104 // Only do this for the second authority since the resulting provider 10105 // object can be the same for all future authorities for this provider. 10106 p = new PackageParser.Provider(p); 10107 p.syncable = false; 10108 } 10109 if (!mProvidersByAuthority.containsKey(names[j])) { 10110 mProvidersByAuthority.put(names[j], p); 10111 if (p.info.authority == null) { 10112 p.info.authority = names[j]; 10113 } else { 10114 p.info.authority = p.info.authority + ";" + names[j]; 10115 } 10116 if (DEBUG_PACKAGE_SCANNING) { 10117 if (chatty) 10118 Log.d(TAG, "Registered content provider: " + names[j] 10119 + ", className = " + p.info.name + ", isSyncable = " 10120 + p.info.isSyncable); 10121 } 10122 } else { 10123 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 10124 Slog.w(TAG, "Skipping provider name " + names[j] + 10125 " (in package " + pkg.applicationInfo.packageName + 10126 "): name already used by " 10127 + ((other != null && other.getComponentName() != null) 10128 ? other.getComponentName().getPackageName() : "?")); 10129 } 10130 } 10131 } 10132 if (chatty) { 10133 if (r == null) { 10134 r = new StringBuilder(256); 10135 } else { 10136 r.append(' '); 10137 } 10138 r.append(p.info.name); 10139 } 10140 } 10141 if (r != null) { 10142 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 10143 } 10144 10145 N = pkg.services.size(); 10146 r = null; 10147 for (i=0; i<N; i++) { 10148 PackageParser.Service s = pkg.services.get(i); 10149 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 10150 s.info.processName); 10151 mServices.addService(s); 10152 if (chatty) { 10153 if (r == null) { 10154 r = new StringBuilder(256); 10155 } else { 10156 r.append(' '); 10157 } 10158 r.append(s.info.name); 10159 } 10160 } 10161 if (r != null) { 10162 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 10163 } 10164 10165 N = pkg.receivers.size(); 10166 r = null; 10167 for (i=0; i<N; i++) { 10168 PackageParser.Activity a = pkg.receivers.get(i); 10169 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 10170 a.info.processName); 10171 mReceivers.addActivity(a, "receiver"); 10172 if (chatty) { 10173 if (r == null) { 10174 r = new StringBuilder(256); 10175 } else { 10176 r.append(' '); 10177 } 10178 r.append(a.info.name); 10179 } 10180 } 10181 if (r != null) { 10182 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 10183 } 10184 10185 N = pkg.activities.size(); 10186 r = null; 10187 for (i=0; i<N; i++) { 10188 PackageParser.Activity a = pkg.activities.get(i); 10189 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 10190 a.info.processName); 10191 mActivities.addActivity(a, "activity"); 10192 if (chatty) { 10193 if (r == null) { 10194 r = new StringBuilder(256); 10195 } else { 10196 r.append(' '); 10197 } 10198 r.append(a.info.name); 10199 } 10200 } 10201 if (r != null) { 10202 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 10203 } 10204 10205 N = pkg.permissionGroups.size(); 10206 r = null; 10207 for (i=0; i<N; i++) { 10208 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 10209 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 10210 final String curPackageName = cur == null ? null : cur.info.packageName; 10211 // Dont allow ephemeral apps to define new permission groups. 10212 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 10213 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 10214 + pg.info.packageName 10215 + " ignored: instant apps cannot define new permission groups."); 10216 continue; 10217 } 10218 final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName); 10219 if (cur == null || isPackageUpdate) { 10220 mPermissionGroups.put(pg.info.name, pg); 10221 if (chatty) { 10222 if (r == null) { 10223 r = new StringBuilder(256); 10224 } else { 10225 r.append(' '); 10226 } 10227 if (isPackageUpdate) { 10228 r.append("UPD:"); 10229 } 10230 r.append(pg.info.name); 10231 } 10232 } else { 10233 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 10234 + pg.info.packageName + " ignored: original from " 10235 + cur.info.packageName); 10236 if (chatty) { 10237 if (r == null) { 10238 r = new StringBuilder(256); 10239 } else { 10240 r.append(' '); 10241 } 10242 r.append("DUP:"); 10243 r.append(pg.info.name); 10244 } 10245 } 10246 } 10247 if (r != null) { 10248 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 10249 } 10250 10251 N = pkg.permissions.size(); 10252 r = null; 10253 for (i=0; i<N; i++) { 10254 PackageParser.Permission p = pkg.permissions.get(i); 10255 10256 // Dont allow ephemeral apps to define new permissions. 10257 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 10258 Slog.w(TAG, "Permission " + p.info.name + " from package " 10259 + p.info.packageName 10260 + " ignored: instant apps cannot define new permissions."); 10261 continue; 10262 } 10263 10264 // Assume by default that we did not install this permission into the system. 10265 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 10266 10267 // Now that permission groups have a special meaning, we ignore permission 10268 // groups for legacy apps to prevent unexpected behavior. In particular, 10269 // permissions for one app being granted to someone just becase they happen 10270 // to be in a group defined by another app (before this had no implications). 10271 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 10272 p.group = mPermissionGroups.get(p.info.group); 10273 // Warn for a permission in an unknown group. 10274 if (p.info.group != null && p.group == null) { 10275 Slog.w(TAG, "Permission " + p.info.name + " from package " 10276 + p.info.packageName + " in an unknown group " + p.info.group); 10277 } 10278 } 10279 10280 ArrayMap<String, BasePermission> permissionMap = 10281 p.tree ? mSettings.mPermissionTrees 10282 : mSettings.mPermissions; 10283 BasePermission bp = permissionMap.get(p.info.name); 10284 10285 // Allow system apps to redefine non-system permissions 10286 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 10287 final boolean currentOwnerIsSystem = (bp.perm != null 10288 && isSystemApp(bp.perm.owner)); 10289 if (isSystemApp(p.owner)) { 10290 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 10291 // It's a built-in permission and no owner, take ownership now 10292 bp.packageSetting = pkgSetting; 10293 bp.perm = p; 10294 bp.uid = pkg.applicationInfo.uid; 10295 bp.sourcePackage = p.info.packageName; 10296 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 10297 } else if (!currentOwnerIsSystem) { 10298 String msg = "New decl " + p.owner + " of permission " 10299 + p.info.name + " is system; overriding " + bp.sourcePackage; 10300 reportSettingsProblem(Log.WARN, msg); 10301 bp = null; 10302 } 10303 } 10304 } 10305 10306 if (bp == null) { 10307 bp = new BasePermission(p.info.name, p.info.packageName, 10308 BasePermission.TYPE_NORMAL); 10309 permissionMap.put(p.info.name, bp); 10310 } 10311 10312 if (bp.perm == null) { 10313 if (bp.sourcePackage == null 10314 || bp.sourcePackage.equals(p.info.packageName)) { 10315 BasePermission tree = findPermissionTreeLP(p.info.name); 10316 if (tree == null 10317 || tree.sourcePackage.equals(p.info.packageName)) { 10318 bp.packageSetting = pkgSetting; 10319 bp.perm = p; 10320 bp.uid = pkg.applicationInfo.uid; 10321 bp.sourcePackage = p.info.packageName; 10322 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 10323 if (chatty) { 10324 if (r == null) { 10325 r = new StringBuilder(256); 10326 } else { 10327 r.append(' '); 10328 } 10329 r.append(p.info.name); 10330 } 10331 } else { 10332 Slog.w(TAG, "Permission " + p.info.name + " from package " 10333 + p.info.packageName + " ignored: base tree " 10334 + tree.name + " is from package " 10335 + tree.sourcePackage); 10336 } 10337 } else { 10338 Slog.w(TAG, "Permission " + p.info.name + " from package " 10339 + p.info.packageName + " ignored: original from " 10340 + bp.sourcePackage); 10341 } 10342 } else if (chatty) { 10343 if (r == null) { 10344 r = new StringBuilder(256); 10345 } else { 10346 r.append(' '); 10347 } 10348 r.append("DUP:"); 10349 r.append(p.info.name); 10350 } 10351 if (bp.perm == p) { 10352 bp.protectionLevel = p.info.protectionLevel; 10353 } 10354 } 10355 10356 if (r != null) { 10357 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 10358 } 10359 10360 N = pkg.instrumentation.size(); 10361 r = null; 10362 for (i=0; i<N; i++) { 10363 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 10364 a.info.packageName = pkg.applicationInfo.packageName; 10365 a.info.sourceDir = pkg.applicationInfo.sourceDir; 10366 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 10367 a.info.splitNames = pkg.splitNames; 10368 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 10369 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 10370 a.info.splitDependencies = pkg.applicationInfo.splitDependencies; 10371 a.info.dataDir = pkg.applicationInfo.dataDir; 10372 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 10373 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 10374 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 10375 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 10376 mInstrumentation.put(a.getComponentName(), a); 10377 if (chatty) { 10378 if (r == null) { 10379 r = new StringBuilder(256); 10380 } else { 10381 r.append(' '); 10382 } 10383 r.append(a.info.name); 10384 } 10385 } 10386 if (r != null) { 10387 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 10388 } 10389 10390 if (pkg.protectedBroadcasts != null) { 10391 N = pkg.protectedBroadcasts.size(); 10392 for (i=0; i<N; i++) { 10393 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 10394 } 10395 } 10396 } 10397 10398 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10399 } 10400 10401 private static void maybeRenameForeignDexMarkers(PackageParser.Package existing, 10402 PackageParser.Package update, int[] userIds) { 10403 if (existing.applicationInfo == null || update.applicationInfo == null) { 10404 // This isn't due to an app installation. 10405 return; 10406 } 10407 10408 final File oldCodePath = new File(existing.applicationInfo.getCodePath()); 10409 final File newCodePath = new File(update.applicationInfo.getCodePath()); 10410 10411 // The codePath hasn't changed, so there's nothing for us to do. 10412 if (Objects.equals(oldCodePath, newCodePath)) { 10413 return; 10414 } 10415 10416 File canonicalNewCodePath; 10417 try { 10418 canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath)); 10419 } catch (IOException e) { 10420 Slog.w(TAG, "Failed to get canonical path.", e); 10421 return; 10422 } 10423 10424 // This is a bit of a hack. The oldCodePath doesn't exist at this point (because 10425 // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume 10426 // that the last component of the path (i.e, the name) doesn't need canonicalization 10427 // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now 10428 // but may change in the future. Hopefully this function won't exist at that point. 10429 final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(), 10430 oldCodePath.getName()); 10431 10432 // Calculate the prefixes of the markers. These are just the paths with "/" replaced 10433 // with "@". 10434 String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@'); 10435 if (!oldMarkerPrefix.endsWith("@")) { 10436 oldMarkerPrefix += "@"; 10437 } 10438 String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@'); 10439 if (!newMarkerPrefix.endsWith("@")) { 10440 newMarkerPrefix += "@"; 10441 } 10442 10443 List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly(); 10444 List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size()); 10445 for (String updatedPath : updatedPaths) { 10446 String updatedPathName = new File(updatedPath).getName(); 10447 markerSuffixes.add(updatedPathName.replace('/', '@')); 10448 } 10449 10450 for (int userId : userIds) { 10451 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId); 10452 10453 for (String markerSuffix : markerSuffixes) { 10454 File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix); 10455 File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix); 10456 if (oldForeignUseMark.exists()) { 10457 try { 10458 Os.rename(oldForeignUseMark.getAbsolutePath(), 10459 newForeignUseMark.getAbsolutePath()); 10460 } catch (ErrnoException e) { 10461 Slog.w(TAG, "Failed to rename foreign use marker", e); 10462 oldForeignUseMark.delete(); 10463 } 10464 } 10465 } 10466 } 10467 } 10468 10469 /** 10470 * Derive the ABI of a non-system package located at {@code scanFile}. This information 10471 * is derived purely on the basis of the contents of {@code scanFile} and 10472 * {@code cpuAbiOverride}. 10473 * 10474 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 10475 */ 10476 private static void derivePackageAbi(PackageParser.Package pkg, File scanFile, 10477 String cpuAbiOverride, boolean extractLibs, 10478 File appLib32InstallDir) 10479 throws PackageManagerException { 10480 // Give ourselves some initial paths; we'll come back for another 10481 // pass once we've determined ABI below. 10482 setNativeLibraryPaths(pkg, appLib32InstallDir); 10483 10484 // We would never need to extract libs for forward-locked and external packages, 10485 // since the container service will do it for us. We shouldn't attempt to 10486 // extract libs from system app when it was not updated. 10487 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 10488 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 10489 extractLibs = false; 10490 } 10491 10492 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 10493 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 10494 10495 NativeLibraryHelper.Handle handle = null; 10496 try { 10497 handle = NativeLibraryHelper.Handle.create(pkg); 10498 // TODO(multiArch): This can be null for apps that didn't go through the 10499 // usual installation process. We can calculate it again, like we 10500 // do during install time. 10501 // 10502 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 10503 // unnecessary. 10504 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 10505 10506 // Null out the abis so that they can be recalculated. 10507 pkg.applicationInfo.primaryCpuAbi = null; 10508 pkg.applicationInfo.secondaryCpuAbi = null; 10509 if (isMultiArch(pkg.applicationInfo)) { 10510 // Warn if we've set an abiOverride for multi-lib packages.. 10511 // By definition, we need to copy both 32 and 64 bit libraries for 10512 // such packages. 10513 if (pkg.cpuAbiOverride != null 10514 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 10515 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 10516 } 10517 10518 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 10519 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 10520 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 10521 if (extractLibs) { 10522 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 10523 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 10524 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 10525 useIsaSpecificSubdirs); 10526 } else { 10527 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 10528 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 10529 } 10530 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10531 } 10532 10533 maybeThrowExceptionForMultiArchCopy( 10534 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 10535 10536 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 10537 if (extractLibs) { 10538 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 10539 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 10540 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 10541 useIsaSpecificSubdirs); 10542 } else { 10543 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 10544 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 10545 } 10546 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10547 } 10548 10549 maybeThrowExceptionForMultiArchCopy( 10550 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 10551 10552 if (abi64 >= 0) { 10553 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 10554 } 10555 10556 if (abi32 >= 0) { 10557 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 10558 if (abi64 >= 0) { 10559 if (pkg.use32bitAbi) { 10560 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 10561 pkg.applicationInfo.primaryCpuAbi = abi; 10562 } else { 10563 pkg.applicationInfo.secondaryCpuAbi = abi; 10564 } 10565 } else { 10566 pkg.applicationInfo.primaryCpuAbi = abi; 10567 } 10568 } 10569 10570 } else { 10571 String[] abiList = (cpuAbiOverride != null) ? 10572 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 10573 10574 // Enable gross and lame hacks for apps that are built with old 10575 // SDK tools. We must scan their APKs for renderscript bitcode and 10576 // not launch them if it's present. Don't bother checking on devices 10577 // that don't have 64 bit support. 10578 boolean needsRenderScriptOverride = false; 10579 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 10580 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 10581 abiList = Build.SUPPORTED_32_BIT_ABIS; 10582 needsRenderScriptOverride = true; 10583 } 10584 10585 final int copyRet; 10586 if (extractLibs) { 10587 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 10588 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 10589 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 10590 } else { 10591 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 10592 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 10593 } 10594 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10595 10596 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 10597 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 10598 "Error unpackaging native libs for app, errorCode=" + copyRet); 10599 } 10600 10601 if (copyRet >= 0) { 10602 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 10603 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 10604 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 10605 } else if (needsRenderScriptOverride) { 10606 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 10607 } 10608 } 10609 } catch (IOException ioe) { 10610 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 10611 } finally { 10612 IoUtils.closeQuietly(handle); 10613 } 10614 10615 // Now that we've calculated the ABIs and determined if it's an internal app, 10616 // we will go ahead and populate the nativeLibraryPath. 10617 setNativeLibraryPaths(pkg, appLib32InstallDir); 10618 } 10619 10620 /** 10621 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 10622 * i.e, so that all packages can be run inside a single process if required. 10623 * 10624 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 10625 * this function will either try and make the ABI for all packages in {@code packagesForUser} 10626 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 10627 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 10628 * updating a package that belongs to a shared user. 10629 * 10630 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 10631 * adds unnecessary complexity. 10632 */ 10633 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 10634 PackageParser.Package scannedPackage) { 10635 String requiredInstructionSet = null; 10636 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 10637 requiredInstructionSet = VMRuntime.getInstructionSet( 10638 scannedPackage.applicationInfo.primaryCpuAbi); 10639 } 10640 10641 PackageSetting requirer = null; 10642 for (PackageSetting ps : packagesForUser) { 10643 // If packagesForUser contains scannedPackage, we skip it. This will happen 10644 // when scannedPackage is an update of an existing package. Without this check, 10645 // we will never be able to change the ABI of any package belonging to a shared 10646 // user, even if it's compatible with other packages. 10647 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 10648 if (ps.primaryCpuAbiString == null) { 10649 continue; 10650 } 10651 10652 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 10653 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 10654 // We have a mismatch between instruction sets (say arm vs arm64) warn about 10655 // this but there's not much we can do. 10656 String errorMessage = "Instruction set mismatch, " 10657 + ((requirer == null) ? "[caller]" : requirer) 10658 + " requires " + requiredInstructionSet + " whereas " + ps 10659 + " requires " + instructionSet; 10660 Slog.w(TAG, errorMessage); 10661 } 10662 10663 if (requiredInstructionSet == null) { 10664 requiredInstructionSet = instructionSet; 10665 requirer = ps; 10666 } 10667 } 10668 } 10669 10670 if (requiredInstructionSet != null) { 10671 String adjustedAbi; 10672 if (requirer != null) { 10673 // requirer != null implies that either scannedPackage was null or that scannedPackage 10674 // did not require an ABI, in which case we have to adjust scannedPackage to match 10675 // the ABI of the set (which is the same as requirer's ABI) 10676 adjustedAbi = requirer.primaryCpuAbiString; 10677 if (scannedPackage != null) { 10678 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 10679 } 10680 } else { 10681 // requirer == null implies that we're updating all ABIs in the set to 10682 // match scannedPackage. 10683 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 10684 } 10685 10686 for (PackageSetting ps : packagesForUser) { 10687 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 10688 if (ps.primaryCpuAbiString != null) { 10689 continue; 10690 } 10691 10692 ps.primaryCpuAbiString = adjustedAbi; 10693 if (ps.pkg != null && ps.pkg.applicationInfo != null && 10694 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 10695 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 10696 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 10697 + " (requirer=" 10698 + (requirer == null ? "null" : requirer.pkg.packageName) 10699 + ", scannedPackage=" 10700 + (scannedPackage != null ? scannedPackage.packageName : "null") 10701 + ")"); 10702 try { 10703 mInstaller.rmdex(ps.codePathString, 10704 getDexCodeInstructionSet(getPreferredInstructionSet())); 10705 } catch (InstallerException ignored) { 10706 } 10707 } 10708 } 10709 } 10710 } 10711 } 10712 10713 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 10714 synchronized (mPackages) { 10715 mResolverReplaced = true; 10716 // Set up information for custom user intent resolution activity. 10717 mResolveActivity.applicationInfo = pkg.applicationInfo; 10718 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 10719 mResolveActivity.packageName = pkg.applicationInfo.packageName; 10720 mResolveActivity.processName = pkg.applicationInfo.packageName; 10721 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 10722 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 10723 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 10724 mResolveActivity.theme = 0; 10725 mResolveActivity.exported = true; 10726 mResolveActivity.enabled = true; 10727 mResolveInfo.activityInfo = mResolveActivity; 10728 mResolveInfo.priority = 0; 10729 mResolveInfo.preferredOrder = 0; 10730 mResolveInfo.match = 0; 10731 mResolveComponentName = mCustomResolverComponentName; 10732 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 10733 mResolveComponentName); 10734 } 10735 } 10736 10737 private void setUpInstantAppInstallerActivityLP(ComponentName installerComponent) { 10738 if (installerComponent == null) { 10739 if (DEBUG_EPHEMERAL) { 10740 Slog.d(TAG, "Clear ephemeral installer activity"); 10741 } 10742 mInstantAppInstallerActivity.applicationInfo = null; 10743 return; 10744 } 10745 10746 if (DEBUG_EPHEMERAL) { 10747 Slog.d(TAG, "Set ephemeral installer activity: " + installerComponent); 10748 } 10749 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 10750 // Set up information for ephemeral installer activity 10751 mInstantAppInstallerActivity.applicationInfo = pkg.applicationInfo; 10752 mInstantAppInstallerActivity.name = installerComponent.getClassName(); 10753 mInstantAppInstallerActivity.packageName = pkg.applicationInfo.packageName; 10754 mInstantAppInstallerActivity.processName = pkg.applicationInfo.packageName; 10755 mInstantAppInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 10756 mInstantAppInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS 10757 | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 10758 mInstantAppInstallerActivity.theme = 0; 10759 mInstantAppInstallerActivity.exported = true; 10760 mInstantAppInstallerActivity.enabled = true; 10761 mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity; 10762 mInstantAppInstallerInfo.priority = 0; 10763 mInstantAppInstallerInfo.preferredOrder = 1; 10764 mInstantAppInstallerInfo.isDefault = true; 10765 mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 10766 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 10767 } 10768 10769 private static String calculateBundledApkRoot(final String codePathString) { 10770 final File codePath = new File(codePathString); 10771 final File codeRoot; 10772 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 10773 codeRoot = Environment.getRootDirectory(); 10774 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 10775 codeRoot = Environment.getOemDirectory(); 10776 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 10777 codeRoot = Environment.getVendorDirectory(); 10778 } else { 10779 // Unrecognized code path; take its top real segment as the apk root: 10780 // e.g. /something/app/blah.apk => /something 10781 try { 10782 File f = codePath.getCanonicalFile(); 10783 File parent = f.getParentFile(); // non-null because codePath is a file 10784 File tmp; 10785 while ((tmp = parent.getParentFile()) != null) { 10786 f = parent; 10787 parent = tmp; 10788 } 10789 codeRoot = f; 10790 Slog.w(TAG, "Unrecognized code path " 10791 + codePath + " - using " + codeRoot); 10792 } catch (IOException e) { 10793 // Can't canonicalize the code path -- shenanigans? 10794 Slog.w(TAG, "Can't canonicalize code path " + codePath); 10795 return Environment.getRootDirectory().getPath(); 10796 } 10797 } 10798 return codeRoot.getPath(); 10799 } 10800 10801 /** 10802 * Derive and set the location of native libraries for the given package, 10803 * which varies depending on where and how the package was installed. 10804 */ 10805 private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) { 10806 final ApplicationInfo info = pkg.applicationInfo; 10807 final String codePath = pkg.codePath; 10808 final File codeFile = new File(codePath); 10809 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 10810 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 10811 10812 info.nativeLibraryRootDir = null; 10813 info.nativeLibraryRootRequiresIsa = false; 10814 info.nativeLibraryDir = null; 10815 info.secondaryNativeLibraryDir = null; 10816 10817 if (isApkFile(codeFile)) { 10818 // Monolithic install 10819 if (bundledApp) { 10820 // If "/system/lib64/apkname" exists, assume that is the per-package 10821 // native library directory to use; otherwise use "/system/lib/apkname". 10822 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 10823 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 10824 getPrimaryInstructionSet(info)); 10825 10826 // This is a bundled system app so choose the path based on the ABI. 10827 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 10828 // is just the default path. 10829 final String apkName = deriveCodePathName(codePath); 10830 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 10831 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 10832 apkName).getAbsolutePath(); 10833 10834 if (info.secondaryCpuAbi != null) { 10835 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 10836 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 10837 secondaryLibDir, apkName).getAbsolutePath(); 10838 } 10839 } else if (asecApp) { 10840 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 10841 .getAbsolutePath(); 10842 } else { 10843 final String apkName = deriveCodePathName(codePath); 10844 info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName) 10845 .getAbsolutePath(); 10846 } 10847 10848 info.nativeLibraryRootRequiresIsa = false; 10849 info.nativeLibraryDir = info.nativeLibraryRootDir; 10850 } else { 10851 // Cluster install 10852 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 10853 info.nativeLibraryRootRequiresIsa = true; 10854 10855 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 10856 getPrimaryInstructionSet(info)).getAbsolutePath(); 10857 10858 if (info.secondaryCpuAbi != null) { 10859 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 10860 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 10861 } 10862 } 10863 } 10864 10865 /** 10866 * Calculate the abis and roots for a bundled app. These can uniquely 10867 * be determined from the contents of the system partition, i.e whether 10868 * it contains 64 or 32 bit shared libraries etc. We do not validate any 10869 * of this information, and instead assume that the system was built 10870 * sensibly. 10871 */ 10872 private static void setBundledAppAbisAndRoots(PackageParser.Package pkg, 10873 PackageSetting pkgSetting) { 10874 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 10875 10876 // If "/system/lib64/apkname" exists, assume that is the per-package 10877 // native library directory to use; otherwise use "/system/lib/apkname". 10878 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 10879 setBundledAppAbi(pkg, apkRoot, apkName); 10880 // pkgSetting might be null during rescan following uninstall of updates 10881 // to a bundled app, so accommodate that possibility. The settings in 10882 // that case will be established later from the parsed package. 10883 // 10884 // If the settings aren't null, sync them up with what we've just derived. 10885 // note that apkRoot isn't stored in the package settings. 10886 if (pkgSetting != null) { 10887 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 10888 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 10889 } 10890 } 10891 10892 /** 10893 * Deduces the ABI of a bundled app and sets the relevant fields on the 10894 * parsed pkg object. 10895 * 10896 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 10897 * under which system libraries are installed. 10898 * @param apkName the name of the installed package. 10899 */ 10900 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 10901 final File codeFile = new File(pkg.codePath); 10902 10903 final boolean has64BitLibs; 10904 final boolean has32BitLibs; 10905 if (isApkFile(codeFile)) { 10906 // Monolithic install 10907 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 10908 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 10909 } else { 10910 // Cluster install 10911 final File rootDir = new File(codeFile, LIB_DIR_NAME); 10912 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 10913 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 10914 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 10915 has64BitLibs = (new File(rootDir, isa)).exists(); 10916 } else { 10917 has64BitLibs = false; 10918 } 10919 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 10920 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 10921 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 10922 has32BitLibs = (new File(rootDir, isa)).exists(); 10923 } else { 10924 has32BitLibs = false; 10925 } 10926 } 10927 10928 if (has64BitLibs && !has32BitLibs) { 10929 // The package has 64 bit libs, but not 32 bit libs. Its primary 10930 // ABI should be 64 bit. We can safely assume here that the bundled 10931 // native libraries correspond to the most preferred ABI in the list. 10932 10933 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 10934 pkg.applicationInfo.secondaryCpuAbi = null; 10935 } else if (has32BitLibs && !has64BitLibs) { 10936 // The package has 32 bit libs but not 64 bit libs. Its primary 10937 // ABI should be 32 bit. 10938 10939 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 10940 pkg.applicationInfo.secondaryCpuAbi = null; 10941 } else if (has32BitLibs && has64BitLibs) { 10942 // The application has both 64 and 32 bit bundled libraries. We check 10943 // here that the app declares multiArch support, and warn if it doesn't. 10944 // 10945 // We will be lenient here and record both ABIs. The primary will be the 10946 // ABI that's higher on the list, i.e, a device that's configured to prefer 10947 // 64 bit apps will see a 64 bit primary ABI, 10948 10949 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 10950 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 10951 } 10952 10953 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 10954 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 10955 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 10956 } else { 10957 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 10958 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 10959 } 10960 } else { 10961 pkg.applicationInfo.primaryCpuAbi = null; 10962 pkg.applicationInfo.secondaryCpuAbi = null; 10963 } 10964 } 10965 10966 private void killApplication(String pkgName, int appId, String reason) { 10967 killApplication(pkgName, appId, UserHandle.USER_ALL, reason); 10968 } 10969 10970 private void killApplication(String pkgName, int appId, int userId, String reason) { 10971 // Request the ActivityManager to kill the process(only for existing packages) 10972 // so that we do not end up in a confused state while the user is still using the older 10973 // version of the application while the new one gets installed. 10974 final long token = Binder.clearCallingIdentity(); 10975 try { 10976 IActivityManager am = ActivityManager.getService(); 10977 if (am != null) { 10978 try { 10979 am.killApplication(pkgName, appId, userId, reason); 10980 } catch (RemoteException e) { 10981 } 10982 } 10983 } finally { 10984 Binder.restoreCallingIdentity(token); 10985 } 10986 } 10987 10988 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 10989 // Remove the parent package setting 10990 PackageSetting ps = (PackageSetting) pkg.mExtras; 10991 if (ps != null) { 10992 removePackageLI(ps, chatty); 10993 } 10994 // Remove the child package setting 10995 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 10996 for (int i = 0; i < childCount; i++) { 10997 PackageParser.Package childPkg = pkg.childPackages.get(i); 10998 ps = (PackageSetting) childPkg.mExtras; 10999 if (ps != null) { 11000 removePackageLI(ps, chatty); 11001 } 11002 } 11003 } 11004 11005 void removePackageLI(PackageSetting ps, boolean chatty) { 11006 if (DEBUG_INSTALL) { 11007 if (chatty) 11008 Log.d(TAG, "Removing package " + ps.name); 11009 } 11010 11011 // writer 11012 synchronized (mPackages) { 11013 mPackages.remove(ps.name); 11014 final PackageParser.Package pkg = ps.pkg; 11015 if (pkg != null) { 11016 cleanPackageDataStructuresLILPw(pkg, chatty); 11017 } 11018 } 11019 } 11020 11021 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 11022 if (DEBUG_INSTALL) { 11023 if (chatty) 11024 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 11025 } 11026 11027 // writer 11028 synchronized (mPackages) { 11029 // Remove the parent package 11030 mPackages.remove(pkg.applicationInfo.packageName); 11031 cleanPackageDataStructuresLILPw(pkg, chatty); 11032 11033 // Remove the child packages 11034 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 11035 for (int i = 0; i < childCount; i++) { 11036 PackageParser.Package childPkg = pkg.childPackages.get(i); 11037 mPackages.remove(childPkg.applicationInfo.packageName); 11038 cleanPackageDataStructuresLILPw(childPkg, chatty); 11039 } 11040 } 11041 } 11042 11043 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 11044 int N = pkg.providers.size(); 11045 StringBuilder r = null; 11046 int i; 11047 for (i=0; i<N; i++) { 11048 PackageParser.Provider p = pkg.providers.get(i); 11049 mProviders.removeProvider(p); 11050 if (p.info.authority == null) { 11051 11052 /* There was another ContentProvider with this authority when 11053 * this app was installed so this authority is null, 11054 * Ignore it as we don't have to unregister the provider. 11055 */ 11056 continue; 11057 } 11058 String names[] = p.info.authority.split(";"); 11059 for (int j = 0; j < names.length; j++) { 11060 if (mProvidersByAuthority.get(names[j]) == p) { 11061 mProvidersByAuthority.remove(names[j]); 11062 if (DEBUG_REMOVE) { 11063 if (chatty) 11064 Log.d(TAG, "Unregistered content provider: " + names[j] 11065 + ", className = " + p.info.name + ", isSyncable = " 11066 + p.info.isSyncable); 11067 } 11068 } 11069 } 11070 if (DEBUG_REMOVE && chatty) { 11071 if (r == null) { 11072 r = new StringBuilder(256); 11073 } else { 11074 r.append(' '); 11075 } 11076 r.append(p.info.name); 11077 } 11078 } 11079 if (r != null) { 11080 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 11081 } 11082 11083 N = pkg.services.size(); 11084 r = null; 11085 for (i=0; i<N; i++) { 11086 PackageParser.Service s = pkg.services.get(i); 11087 mServices.removeService(s); 11088 if (chatty) { 11089 if (r == null) { 11090 r = new StringBuilder(256); 11091 } else { 11092 r.append(' '); 11093 } 11094 r.append(s.info.name); 11095 } 11096 } 11097 if (r != null) { 11098 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 11099 } 11100 11101 N = pkg.receivers.size(); 11102 r = null; 11103 for (i=0; i<N; i++) { 11104 PackageParser.Activity a = pkg.receivers.get(i); 11105 mReceivers.removeActivity(a, "receiver"); 11106 if (DEBUG_REMOVE && chatty) { 11107 if (r == null) { 11108 r = new StringBuilder(256); 11109 } else { 11110 r.append(' '); 11111 } 11112 r.append(a.info.name); 11113 } 11114 } 11115 if (r != null) { 11116 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 11117 } 11118 11119 N = pkg.activities.size(); 11120 r = null; 11121 for (i=0; i<N; i++) { 11122 PackageParser.Activity a = pkg.activities.get(i); 11123 mActivities.removeActivity(a, "activity"); 11124 if (DEBUG_REMOVE && chatty) { 11125 if (r == null) { 11126 r = new StringBuilder(256); 11127 } else { 11128 r.append(' '); 11129 } 11130 r.append(a.info.name); 11131 } 11132 } 11133 if (r != null) { 11134 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 11135 } 11136 11137 N = pkg.permissions.size(); 11138 r = null; 11139 for (i=0; i<N; i++) { 11140 PackageParser.Permission p = pkg.permissions.get(i); 11141 BasePermission bp = mSettings.mPermissions.get(p.info.name); 11142 if (bp == null) { 11143 bp = mSettings.mPermissionTrees.get(p.info.name); 11144 } 11145 if (bp != null && bp.perm == p) { 11146 bp.perm = null; 11147 if (DEBUG_REMOVE && chatty) { 11148 if (r == null) { 11149 r = new StringBuilder(256); 11150 } else { 11151 r.append(' '); 11152 } 11153 r.append(p.info.name); 11154 } 11155 } 11156 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 11157 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 11158 if (appOpPkgs != null) { 11159 appOpPkgs.remove(pkg.packageName); 11160 } 11161 } 11162 } 11163 if (r != null) { 11164 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 11165 } 11166 11167 N = pkg.requestedPermissions.size(); 11168 r = null; 11169 for (i=0; i<N; i++) { 11170 String perm = pkg.requestedPermissions.get(i); 11171 BasePermission bp = mSettings.mPermissions.get(perm); 11172 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 11173 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 11174 if (appOpPkgs != null) { 11175 appOpPkgs.remove(pkg.packageName); 11176 if (appOpPkgs.isEmpty()) { 11177 mAppOpPermissionPackages.remove(perm); 11178 } 11179 } 11180 } 11181 } 11182 if (r != null) { 11183 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 11184 } 11185 11186 N = pkg.instrumentation.size(); 11187 r = null; 11188 for (i=0; i<N; i++) { 11189 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 11190 mInstrumentation.remove(a.getComponentName()); 11191 if (DEBUG_REMOVE && chatty) { 11192 if (r == null) { 11193 r = new StringBuilder(256); 11194 } else { 11195 r.append(' '); 11196 } 11197 r.append(a.info.name); 11198 } 11199 } 11200 if (r != null) { 11201 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 11202 } 11203 11204 r = null; 11205 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 11206 // Only system apps can hold shared libraries. 11207 if (pkg.libraryNames != null) { 11208 for (i = 0; i < pkg.libraryNames.size(); i++) { 11209 String name = pkg.libraryNames.get(i); 11210 if (removeSharedLibraryLPw(name, 0)) { 11211 if (DEBUG_REMOVE && chatty) { 11212 if (r == null) { 11213 r = new StringBuilder(256); 11214 } else { 11215 r.append(' '); 11216 } 11217 r.append(name); 11218 } 11219 } 11220 } 11221 } 11222 } 11223 11224 r = null; 11225 11226 // Any package can hold static shared libraries. 11227 if (pkg.staticSharedLibName != null) { 11228 if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) { 11229 if (DEBUG_REMOVE && chatty) { 11230 if (r == null) { 11231 r = new StringBuilder(256); 11232 } else { 11233 r.append(' '); 11234 } 11235 r.append(pkg.staticSharedLibName); 11236 } 11237 } 11238 } 11239 11240 if (r != null) { 11241 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 11242 } 11243 } 11244 11245 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 11246 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 11247 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 11248 return true; 11249 } 11250 } 11251 return false; 11252 } 11253 11254 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 11255 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 11256 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 11257 11258 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 11259 // Update the parent permissions 11260 updatePermissionsLPw(pkg.packageName, pkg, flags); 11261 // Update the child permissions 11262 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 11263 for (int i = 0; i < childCount; i++) { 11264 PackageParser.Package childPkg = pkg.childPackages.get(i); 11265 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 11266 } 11267 } 11268 11269 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 11270 int flags) { 11271 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 11272 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 11273 } 11274 11275 private void updatePermissionsLPw(String changingPkg, 11276 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 11277 // Make sure there are no dangling permission trees. 11278 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 11279 while (it.hasNext()) { 11280 final BasePermission bp = it.next(); 11281 if (bp.packageSetting == null) { 11282 // We may not yet have parsed the package, so just see if 11283 // we still know about its settings. 11284 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 11285 } 11286 if (bp.packageSetting == null) { 11287 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 11288 + " from package " + bp.sourcePackage); 11289 it.remove(); 11290 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 11291 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 11292 Slog.i(TAG, "Removing old permission tree: " + bp.name 11293 + " from package " + bp.sourcePackage); 11294 flags |= UPDATE_PERMISSIONS_ALL; 11295 it.remove(); 11296 } 11297 } 11298 } 11299 11300 // Make sure all dynamic permissions have been assigned to a package, 11301 // and make sure there are no dangling permissions. 11302 it = mSettings.mPermissions.values().iterator(); 11303 while (it.hasNext()) { 11304 final BasePermission bp = it.next(); 11305 if (bp.type == BasePermission.TYPE_DYNAMIC) { 11306 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 11307 + bp.name + " pkg=" + bp.sourcePackage 11308 + " info=" + bp.pendingInfo); 11309 if (bp.packageSetting == null && bp.pendingInfo != null) { 11310 final BasePermission tree = findPermissionTreeLP(bp.name); 11311 if (tree != null && tree.perm != null) { 11312 bp.packageSetting = tree.packageSetting; 11313 bp.perm = new PackageParser.Permission(tree.perm.owner, 11314 new PermissionInfo(bp.pendingInfo)); 11315 bp.perm.info.packageName = tree.perm.info.packageName; 11316 bp.perm.info.name = bp.name; 11317 bp.uid = tree.uid; 11318 } 11319 } 11320 } 11321 if (bp.packageSetting == null) { 11322 // We may not yet have parsed the package, so just see if 11323 // we still know about its settings. 11324 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 11325 } 11326 if (bp.packageSetting == null) { 11327 Slog.w(TAG, "Removing dangling permission: " + bp.name 11328 + " from package " + bp.sourcePackage); 11329 it.remove(); 11330 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 11331 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 11332 Slog.i(TAG, "Removing old permission: " + bp.name 11333 + " from package " + bp.sourcePackage); 11334 flags |= UPDATE_PERMISSIONS_ALL; 11335 it.remove(); 11336 } 11337 } 11338 } 11339 11340 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 11341 // Now update the permissions for all packages, in particular 11342 // replace the granted permissions of the system packages. 11343 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 11344 for (PackageParser.Package pkg : mPackages.values()) { 11345 if (pkg != pkgInfo) { 11346 // Only replace for packages on requested volume 11347 final String volumeUuid = getVolumeUuidForPackage(pkg); 11348 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 11349 && Objects.equals(replaceVolumeUuid, volumeUuid); 11350 grantPermissionsLPw(pkg, replace, changingPkg); 11351 } 11352 } 11353 } 11354 11355 if (pkgInfo != null) { 11356 // Only replace for packages on requested volume 11357 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 11358 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 11359 && Objects.equals(replaceVolumeUuid, volumeUuid); 11360 grantPermissionsLPw(pkgInfo, replace, changingPkg); 11361 } 11362 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11363 } 11364 11365 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 11366 String packageOfInterest) { 11367 // IMPORTANT: There are two types of permissions: install and runtime. 11368 // Install time permissions are granted when the app is installed to 11369 // all device users and users added in the future. Runtime permissions 11370 // are granted at runtime explicitly to specific users. Normal and signature 11371 // protected permissions are install time permissions. Dangerous permissions 11372 // are install permissions if the app's target SDK is Lollipop MR1 or older, 11373 // otherwise they are runtime permissions. This function does not manage 11374 // runtime permissions except for the case an app targeting Lollipop MR1 11375 // being upgraded to target a newer SDK, in which case dangerous permissions 11376 // are transformed from install time to runtime ones. 11377 11378 final PackageSetting ps = (PackageSetting) pkg.mExtras; 11379 if (ps == null) { 11380 return; 11381 } 11382 11383 PermissionsState permissionsState = ps.getPermissionsState(); 11384 PermissionsState origPermissions = permissionsState; 11385 11386 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 11387 11388 boolean runtimePermissionsRevoked = false; 11389 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 11390 11391 boolean changedInstallPermission = false; 11392 11393 if (replace) { 11394 ps.installPermissionsFixed = false; 11395 if (!ps.isSharedUser()) { 11396 origPermissions = new PermissionsState(permissionsState); 11397 permissionsState.reset(); 11398 } else { 11399 // We need to know only about runtime permission changes since the 11400 // calling code always writes the install permissions state but 11401 // the runtime ones are written only if changed. The only cases of 11402 // changed runtime permissions here are promotion of an install to 11403 // runtime and revocation of a runtime from a shared user. 11404 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 11405 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 11406 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 11407 runtimePermissionsRevoked = true; 11408 } 11409 } 11410 } 11411 11412 permissionsState.setGlobalGids(mGlobalGids); 11413 11414 final int N = pkg.requestedPermissions.size(); 11415 for (int i=0; i<N; i++) { 11416 final String name = pkg.requestedPermissions.get(i); 11417 final BasePermission bp = mSettings.mPermissions.get(name); 11418 11419 if (DEBUG_INSTALL) { 11420 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 11421 } 11422 11423 if (bp == null || bp.packageSetting == null) { 11424 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 11425 Slog.w(TAG, "Unknown permission " + name 11426 + " in package " + pkg.packageName); 11427 } 11428 continue; 11429 } 11430 11431 11432 // Limit ephemeral apps to ephemeral allowed permissions. 11433 if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) { 11434 Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package " 11435 + pkg.packageName); 11436 continue; 11437 } 11438 11439 final String perm = bp.name; 11440 boolean allowedSig = false; 11441 int grant = GRANT_DENIED; 11442 11443 // Keep track of app op permissions. 11444 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 11445 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 11446 if (pkgs == null) { 11447 pkgs = new ArraySet<>(); 11448 mAppOpPermissionPackages.put(bp.name, pkgs); 11449 } 11450 pkgs.add(pkg.packageName); 11451 } 11452 11453 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 11454 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 11455 >= Build.VERSION_CODES.M; 11456 switch (level) { 11457 case PermissionInfo.PROTECTION_NORMAL: { 11458 // For all apps normal permissions are install time ones. 11459 grant = GRANT_INSTALL; 11460 } break; 11461 11462 case PermissionInfo.PROTECTION_DANGEROUS: { 11463 // If a permission review is required for legacy apps we represent 11464 // their permissions as always granted runtime ones since we need 11465 // to keep the review required permission flag per user while an 11466 // install permission's state is shared across all users. 11467 if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) { 11468 // For legacy apps dangerous permissions are install time ones. 11469 grant = GRANT_INSTALL; 11470 } else if (origPermissions.hasInstallPermission(bp.name)) { 11471 // For legacy apps that became modern, install becomes runtime. 11472 grant = GRANT_UPGRADE; 11473 } else if (mPromoteSystemApps 11474 && isSystemApp(ps) 11475 && mExistingSystemPackages.contains(ps.name)) { 11476 // For legacy system apps, install becomes runtime. 11477 // We cannot check hasInstallPermission() for system apps since those 11478 // permissions were granted implicitly and not persisted pre-M. 11479 grant = GRANT_UPGRADE; 11480 } else { 11481 // For modern apps keep runtime permissions unchanged. 11482 grant = GRANT_RUNTIME; 11483 } 11484 } break; 11485 11486 case PermissionInfo.PROTECTION_SIGNATURE: { 11487 // For all apps signature permissions are install time ones. 11488 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 11489 if (allowedSig) { 11490 grant = GRANT_INSTALL; 11491 } 11492 } break; 11493 } 11494 11495 if (DEBUG_INSTALL) { 11496 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 11497 } 11498 11499 if (grant != GRANT_DENIED) { 11500 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 11501 // If this is an existing, non-system package, then 11502 // we can't add any new permissions to it. 11503 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 11504 // Except... if this is a permission that was added 11505 // to the platform (note: need to only do this when 11506 // updating the platform). 11507 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 11508 grant = GRANT_DENIED; 11509 } 11510 } 11511 } 11512 11513 switch (grant) { 11514 case GRANT_INSTALL: { 11515 // Revoke this as runtime permission to handle the case of 11516 // a runtime permission being downgraded to an install one. 11517 // Also in permission review mode we keep dangerous permissions 11518 // for legacy apps 11519 for (int userId : UserManagerService.getInstance().getUserIds()) { 11520 if (origPermissions.getRuntimePermissionState( 11521 bp.name, userId) != null) { 11522 // Revoke the runtime permission and clear the flags. 11523 origPermissions.revokeRuntimePermission(bp, userId); 11524 origPermissions.updatePermissionFlags(bp, userId, 11525 PackageManager.MASK_PERMISSION_FLAGS, 0); 11526 // If we revoked a permission permission, we have to write. 11527 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11528 changedRuntimePermissionUserIds, userId); 11529 } 11530 } 11531 // Grant an install permission. 11532 if (permissionsState.grantInstallPermission(bp) != 11533 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11534 changedInstallPermission = true; 11535 } 11536 } break; 11537 11538 case GRANT_RUNTIME: { 11539 // Grant previously granted runtime permissions. 11540 for (int userId : UserManagerService.getInstance().getUserIds()) { 11541 PermissionState permissionState = origPermissions 11542 .getRuntimePermissionState(bp.name, userId); 11543 int flags = permissionState != null 11544 ? permissionState.getFlags() : 0; 11545 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 11546 // Don't propagate the permission in a permission review mode if 11547 // the former was revoked, i.e. marked to not propagate on upgrade. 11548 // Note that in a permission review mode install permissions are 11549 // represented as constantly granted runtime ones since we need to 11550 // keep a per user state associated with the permission. Also the 11551 // revoke on upgrade flag is no longer applicable and is reset. 11552 final boolean revokeOnUpgrade = (flags & PackageManager 11553 .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 11554 if (revokeOnUpgrade) { 11555 flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 11556 // Since we changed the flags, we have to write. 11557 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11558 changedRuntimePermissionUserIds, userId); 11559 } 11560 if (!mPermissionReviewRequired || !revokeOnUpgrade) { 11561 if (permissionsState.grantRuntimePermission(bp, userId) == 11562 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11563 // If we cannot put the permission as it was, 11564 // we have to write. 11565 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11566 changedRuntimePermissionUserIds, userId); 11567 } 11568 } 11569 11570 // If the app supports runtime permissions no need for a review. 11571 if (mPermissionReviewRequired 11572 && appSupportsRuntimePermissions 11573 && (flags & PackageManager 11574 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 11575 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 11576 // Since we changed the flags, we have to write. 11577 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11578 changedRuntimePermissionUserIds, userId); 11579 } 11580 } else if (mPermissionReviewRequired 11581 && !appSupportsRuntimePermissions) { 11582 // For legacy apps that need a permission review, every new 11583 // runtime permission is granted but it is pending a review. 11584 // We also need to review only platform defined runtime 11585 // permissions as these are the only ones the platform knows 11586 // how to disable the API to simulate revocation as legacy 11587 // apps don't expect to run with revoked permissions. 11588 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 11589 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 11590 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 11591 // We changed the flags, hence have to write. 11592 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11593 changedRuntimePermissionUserIds, userId); 11594 } 11595 } 11596 if (permissionsState.grantRuntimePermission(bp, userId) 11597 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 11598 // We changed the permission, hence have to write. 11599 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11600 changedRuntimePermissionUserIds, userId); 11601 } 11602 } 11603 // Propagate the permission flags. 11604 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 11605 } 11606 } break; 11607 11608 case GRANT_UPGRADE: { 11609 // Grant runtime permissions for a previously held install permission. 11610 PermissionState permissionState = origPermissions 11611 .getInstallPermissionState(bp.name); 11612 final int flags = permissionState != null ? permissionState.getFlags() : 0; 11613 11614 if (origPermissions.revokeInstallPermission(bp) 11615 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 11616 // We will be transferring the permission flags, so clear them. 11617 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 11618 PackageManager.MASK_PERMISSION_FLAGS, 0); 11619 changedInstallPermission = true; 11620 } 11621 11622 // If the permission is not to be promoted to runtime we ignore it and 11623 // also its other flags as they are not applicable to install permissions. 11624 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 11625 for (int userId : currentUserIds) { 11626 if (permissionsState.grantRuntimePermission(bp, userId) != 11627 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11628 // Transfer the permission flags. 11629 permissionsState.updatePermissionFlags(bp, userId, 11630 flags, flags); 11631 // If we granted the permission, we have to write. 11632 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11633 changedRuntimePermissionUserIds, userId); 11634 } 11635 } 11636 } 11637 } break; 11638 11639 default: { 11640 if (packageOfInterest == null 11641 || packageOfInterest.equals(pkg.packageName)) { 11642 Slog.w(TAG, "Not granting permission " + perm 11643 + " to package " + pkg.packageName 11644 + " because it was previously installed without"); 11645 } 11646 } break; 11647 } 11648 } else { 11649 if (permissionsState.revokeInstallPermission(bp) != 11650 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11651 // Also drop the permission flags. 11652 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 11653 PackageManager.MASK_PERMISSION_FLAGS, 0); 11654 changedInstallPermission = true; 11655 Slog.i(TAG, "Un-granting permission " + perm 11656 + " from package " + pkg.packageName 11657 + " (protectionLevel=" + bp.protectionLevel 11658 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 11659 + ")"); 11660 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 11661 // Don't print warning for app op permissions, since it is fine for them 11662 // not to be granted, there is a UI for the user to decide. 11663 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 11664 Slog.w(TAG, "Not granting permission " + perm 11665 + " to package " + pkg.packageName 11666 + " (protectionLevel=" + bp.protectionLevel 11667 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 11668 + ")"); 11669 } 11670 } 11671 } 11672 } 11673 11674 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 11675 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 11676 // This is the first that we have heard about this package, so the 11677 // permissions we have now selected are fixed until explicitly 11678 // changed. 11679 ps.installPermissionsFixed = true; 11680 } 11681 11682 // Persist the runtime permissions state for users with changes. If permissions 11683 // were revoked because no app in the shared user declares them we have to 11684 // write synchronously to avoid losing runtime permissions state. 11685 for (int userId : changedRuntimePermissionUserIds) { 11686 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 11687 } 11688 } 11689 11690 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 11691 boolean allowed = false; 11692 final int NP = PackageParser.NEW_PERMISSIONS.length; 11693 for (int ip=0; ip<NP; ip++) { 11694 final PackageParser.NewPermissionInfo npi 11695 = PackageParser.NEW_PERMISSIONS[ip]; 11696 if (npi.name.equals(perm) 11697 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 11698 allowed = true; 11699 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 11700 + pkg.packageName); 11701 break; 11702 } 11703 } 11704 return allowed; 11705 } 11706 11707 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 11708 BasePermission bp, PermissionsState origPermissions) { 11709 boolean privilegedPermission = (bp.protectionLevel 11710 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0; 11711 boolean privappPermissionsDisable = 11712 RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE; 11713 boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage); 11714 boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName); 11715 if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp() 11716 && !platformPackage && platformPermission) { 11717 ArraySet<String> wlPermissions = SystemConfig.getInstance() 11718 .getPrivAppPermissions(pkg.packageName); 11719 boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm); 11720 if (!whitelisted) { 11721 Slog.w(TAG, "Privileged permission " + perm + " for package " 11722 + pkg.packageName + " - not in privapp-permissions whitelist"); 11723 // Only report violations for apps on system image 11724 if (!mSystemReady && !pkg.isUpdatedSystemApp()) { 11725 if (mPrivappPermissionsViolations == null) { 11726 mPrivappPermissionsViolations = new ArraySet<>(); 11727 } 11728 mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm); 11729 } 11730 if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) { 11731 return false; 11732 } 11733 } 11734 } 11735 boolean allowed = (compareSignatures( 11736 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 11737 == PackageManager.SIGNATURE_MATCH) 11738 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 11739 == PackageManager.SIGNATURE_MATCH); 11740 if (!allowed && privilegedPermission) { 11741 if (isSystemApp(pkg)) { 11742 // For updated system applications, a system permission 11743 // is granted only if it had been defined by the original application. 11744 if (pkg.isUpdatedSystemApp()) { 11745 final PackageSetting sysPs = mSettings 11746 .getDisabledSystemPkgLPr(pkg.packageName); 11747 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 11748 // If the original was granted this permission, we take 11749 // that grant decision as read and propagate it to the 11750 // update. 11751 if (sysPs.isPrivileged()) { 11752 allowed = true; 11753 } 11754 } else { 11755 // The system apk may have been updated with an older 11756 // version of the one on the data partition, but which 11757 // granted a new system permission that it didn't have 11758 // before. In this case we do want to allow the app to 11759 // now get the new permission if the ancestral apk is 11760 // privileged to get it. 11761 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 11762 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 11763 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 11764 allowed = true; 11765 break; 11766 } 11767 } 11768 } 11769 // Also if a privileged parent package on the system image or any of 11770 // its children requested a privileged permission, the updated child 11771 // packages can also get the permission. 11772 if (pkg.parentPackage != null) { 11773 final PackageSetting disabledSysParentPs = mSettings 11774 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 11775 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 11776 && disabledSysParentPs.isPrivileged()) { 11777 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 11778 allowed = true; 11779 } else if (disabledSysParentPs.pkg.childPackages != null) { 11780 final int count = disabledSysParentPs.pkg.childPackages.size(); 11781 for (int i = 0; i < count; i++) { 11782 PackageParser.Package disabledSysChildPkg = 11783 disabledSysParentPs.pkg.childPackages.get(i); 11784 if (isPackageRequestingPermission(disabledSysChildPkg, 11785 perm)) { 11786 allowed = true; 11787 break; 11788 } 11789 } 11790 } 11791 } 11792 } 11793 } 11794 } else { 11795 allowed = isPrivilegedApp(pkg); 11796 } 11797 } 11798 } 11799 if (!allowed) { 11800 if (!allowed && (bp.protectionLevel 11801 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 11802 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 11803 // If this was a previously normal/dangerous permission that got moved 11804 // to a system permission as part of the runtime permission redesign, then 11805 // we still want to blindly grant it to old apps. 11806 allowed = true; 11807 } 11808 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 11809 && pkg.packageName.equals(mRequiredInstallerPackage)) { 11810 // If this permission is to be granted to the system installer and 11811 // this app is an installer, then it gets the permission. 11812 allowed = true; 11813 } 11814 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 11815 && pkg.packageName.equals(mRequiredVerifierPackage)) { 11816 // If this permission is to be granted to the system verifier and 11817 // this app is a verifier, then it gets the permission. 11818 allowed = true; 11819 } 11820 if (!allowed && (bp.protectionLevel 11821 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 11822 && isSystemApp(pkg)) { 11823 // Any pre-installed system app is allowed to get this permission. 11824 allowed = true; 11825 } 11826 if (!allowed && (bp.protectionLevel 11827 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 11828 // For development permissions, a development permission 11829 // is granted only if it was already granted. 11830 allowed = origPermissions.hasInstallPermission(perm); 11831 } 11832 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 11833 && pkg.packageName.equals(mSetupWizardPackage)) { 11834 // If this permission is to be granted to the system setup wizard and 11835 // this app is a setup wizard, then it gets the permission. 11836 allowed = true; 11837 } 11838 } 11839 return allowed; 11840 } 11841 11842 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 11843 final int permCount = pkg.requestedPermissions.size(); 11844 for (int j = 0; j < permCount; j++) { 11845 String requestedPermission = pkg.requestedPermissions.get(j); 11846 if (permission.equals(requestedPermission)) { 11847 return true; 11848 } 11849 } 11850 return false; 11851 } 11852 11853 final class ActivityIntentResolver 11854 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 11855 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 11856 boolean defaultOnly, int userId) { 11857 if (!sUserManager.exists(userId)) return null; 11858 mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0); 11859 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 11860 } 11861 11862 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 11863 int userId) { 11864 if (!sUserManager.exists(userId)) return null; 11865 mFlags = flags; 11866 return super.queryIntent(intent, resolvedType, 11867 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 11868 userId); 11869 } 11870 11871 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 11872 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 11873 if (!sUserManager.exists(userId)) return null; 11874 if (packageActivities == null) { 11875 return null; 11876 } 11877 mFlags = flags; 11878 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 11879 final int N = packageActivities.size(); 11880 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 11881 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 11882 11883 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 11884 for (int i = 0; i < N; ++i) { 11885 intentFilters = packageActivities.get(i).intents; 11886 if (intentFilters != null && intentFilters.size() > 0) { 11887 PackageParser.ActivityIntentInfo[] array = 11888 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 11889 intentFilters.toArray(array); 11890 listCut.add(array); 11891 } 11892 } 11893 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 11894 } 11895 11896 /** 11897 * Finds a privileged activity that matches the specified activity names. 11898 */ 11899 private PackageParser.Activity findMatchingActivity( 11900 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 11901 for (PackageParser.Activity sysActivity : activityList) { 11902 if (sysActivity.info.name.equals(activityInfo.name)) { 11903 return sysActivity; 11904 } 11905 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 11906 return sysActivity; 11907 } 11908 if (sysActivity.info.targetActivity != null) { 11909 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 11910 return sysActivity; 11911 } 11912 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 11913 return sysActivity; 11914 } 11915 } 11916 } 11917 return null; 11918 } 11919 11920 public class IterGenerator<E> { 11921 public Iterator<E> generate(ActivityIntentInfo info) { 11922 return null; 11923 } 11924 } 11925 11926 public class ActionIterGenerator extends IterGenerator<String> { 11927 @Override 11928 public Iterator<String> generate(ActivityIntentInfo info) { 11929 return info.actionsIterator(); 11930 } 11931 } 11932 11933 public class CategoriesIterGenerator extends IterGenerator<String> { 11934 @Override 11935 public Iterator<String> generate(ActivityIntentInfo info) { 11936 return info.categoriesIterator(); 11937 } 11938 } 11939 11940 public class SchemesIterGenerator extends IterGenerator<String> { 11941 @Override 11942 public Iterator<String> generate(ActivityIntentInfo info) { 11943 return info.schemesIterator(); 11944 } 11945 } 11946 11947 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 11948 @Override 11949 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 11950 return info.authoritiesIterator(); 11951 } 11952 } 11953 11954 /** 11955 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 11956 * MODIFIED. Do not pass in a list that should not be changed. 11957 */ 11958 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 11959 IterGenerator<T> generator, Iterator<T> searchIterator) { 11960 // loop through the set of actions; every one must be found in the intent filter 11961 while (searchIterator.hasNext()) { 11962 // we must have at least one filter in the list to consider a match 11963 if (intentList.size() == 0) { 11964 break; 11965 } 11966 11967 final T searchAction = searchIterator.next(); 11968 11969 // loop through the set of intent filters 11970 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 11971 while (intentIter.hasNext()) { 11972 final ActivityIntentInfo intentInfo = intentIter.next(); 11973 boolean selectionFound = false; 11974 11975 // loop through the intent filter's selection criteria; at least one 11976 // of them must match the searched criteria 11977 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 11978 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 11979 final T intentSelection = intentSelectionIter.next(); 11980 if (intentSelection != null && intentSelection.equals(searchAction)) { 11981 selectionFound = true; 11982 break; 11983 } 11984 } 11985 11986 // the selection criteria wasn't found in this filter's set; this filter 11987 // is not a potential match 11988 if (!selectionFound) { 11989 intentIter.remove(); 11990 } 11991 } 11992 } 11993 } 11994 11995 private boolean isProtectedAction(ActivityIntentInfo filter) { 11996 final Iterator<String> actionsIter = filter.actionsIterator(); 11997 while (actionsIter != null && actionsIter.hasNext()) { 11998 final String filterAction = actionsIter.next(); 11999 if (PROTECTED_ACTIONS.contains(filterAction)) { 12000 return true; 12001 } 12002 } 12003 return false; 12004 } 12005 12006 /** 12007 * Adjusts the priority of the given intent filter according to policy. 12008 * <p> 12009 * <ul> 12010 * <li>The priority for non privileged applications is capped to '0'</li> 12011 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 12012 * <li>The priority for unbundled updates to privileged applications is capped to the 12013 * priority defined on the system partition</li> 12014 * </ul> 12015 * <p> 12016 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 12017 * allowed to obtain any priority on any action. 12018 */ 12019 private void adjustPriority( 12020 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 12021 // nothing to do; priority is fine as-is 12022 if (intent.getPriority() <= 0) { 12023 return; 12024 } 12025 12026 final ActivityInfo activityInfo = intent.activity.info; 12027 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 12028 12029 final boolean privilegedApp = 12030 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 12031 if (!privilegedApp) { 12032 // non-privileged applications can never define a priority >0 12033 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 12034 + " package: " + applicationInfo.packageName 12035 + " activity: " + intent.activity.className 12036 + " origPrio: " + intent.getPriority()); 12037 intent.setPriority(0); 12038 return; 12039 } 12040 12041 if (systemActivities == null) { 12042 // the system package is not disabled; we're parsing the system partition 12043 if (isProtectedAction(intent)) { 12044 if (mDeferProtectedFilters) { 12045 // We can't deal with these just yet. No component should ever obtain a 12046 // >0 priority for a protected actions, with ONE exception -- the setup 12047 // wizard. The setup wizard, however, cannot be known until we're able to 12048 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 12049 // until all intent filters have been processed. Chicken, meet egg. 12050 // Let the filter temporarily have a high priority and rectify the 12051 // priorities after all system packages have been scanned. 12052 mProtectedFilters.add(intent); 12053 if (DEBUG_FILTERS) { 12054 Slog.i(TAG, "Protected action; save for later;" 12055 + " package: " + applicationInfo.packageName 12056 + " activity: " + intent.activity.className 12057 + " origPrio: " + intent.getPriority()); 12058 } 12059 return; 12060 } else { 12061 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 12062 Slog.i(TAG, "No setup wizard;" 12063 + " All protected intents capped to priority 0"); 12064 } 12065 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 12066 if (DEBUG_FILTERS) { 12067 Slog.i(TAG, "Found setup wizard;" 12068 + " allow priority " + intent.getPriority() + ";" 12069 + " package: " + intent.activity.info.packageName 12070 + " activity: " + intent.activity.className 12071 + " priority: " + intent.getPriority()); 12072 } 12073 // setup wizard gets whatever it wants 12074 return; 12075 } 12076 Slog.w(TAG, "Protected action; cap priority to 0;" 12077 + " package: " + intent.activity.info.packageName 12078 + " activity: " + intent.activity.className 12079 + " origPrio: " + intent.getPriority()); 12080 intent.setPriority(0); 12081 return; 12082 } 12083 } 12084 // privileged apps on the system image get whatever priority they request 12085 return; 12086 } 12087 12088 // privileged app unbundled update ... try to find the same activity 12089 final PackageParser.Activity foundActivity = 12090 findMatchingActivity(systemActivities, activityInfo); 12091 if (foundActivity == null) { 12092 // this is a new activity; it cannot obtain >0 priority 12093 if (DEBUG_FILTERS) { 12094 Slog.i(TAG, "New activity; cap priority to 0;" 12095 + " package: " + applicationInfo.packageName 12096 + " activity: " + intent.activity.className 12097 + " origPrio: " + intent.getPriority()); 12098 } 12099 intent.setPriority(0); 12100 return; 12101 } 12102 12103 // found activity, now check for filter equivalence 12104 12105 // a shallow copy is enough; we modify the list, not its contents 12106 final List<ActivityIntentInfo> intentListCopy = 12107 new ArrayList<>(foundActivity.intents); 12108 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 12109 12110 // find matching action subsets 12111 final Iterator<String> actionsIterator = intent.actionsIterator(); 12112 if (actionsIterator != null) { 12113 getIntentListSubset( 12114 intentListCopy, new ActionIterGenerator(), actionsIterator); 12115 if (intentListCopy.size() == 0) { 12116 // no more intents to match; we're not equivalent 12117 if (DEBUG_FILTERS) { 12118 Slog.i(TAG, "Mismatched action; cap priority to 0;" 12119 + " package: " + applicationInfo.packageName 12120 + " activity: " + intent.activity.className 12121 + " origPrio: " + intent.getPriority()); 12122 } 12123 intent.setPriority(0); 12124 return; 12125 } 12126 } 12127 12128 // find matching category subsets 12129 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 12130 if (categoriesIterator != null) { 12131 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 12132 categoriesIterator); 12133 if (intentListCopy.size() == 0) { 12134 // no more intents to match; we're not equivalent 12135 if (DEBUG_FILTERS) { 12136 Slog.i(TAG, "Mismatched category; cap priority to 0;" 12137 + " package: " + applicationInfo.packageName 12138 + " activity: " + intent.activity.className 12139 + " origPrio: " + intent.getPriority()); 12140 } 12141 intent.setPriority(0); 12142 return; 12143 } 12144 } 12145 12146 // find matching schemes subsets 12147 final Iterator<String> schemesIterator = intent.schemesIterator(); 12148 if (schemesIterator != null) { 12149 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 12150 schemesIterator); 12151 if (intentListCopy.size() == 0) { 12152 // no more intents to match; we're not equivalent 12153 if (DEBUG_FILTERS) { 12154 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 12155 + " package: " + applicationInfo.packageName 12156 + " activity: " + intent.activity.className 12157 + " origPrio: " + intent.getPriority()); 12158 } 12159 intent.setPriority(0); 12160 return; 12161 } 12162 } 12163 12164 // find matching authorities subsets 12165 final Iterator<IntentFilter.AuthorityEntry> 12166 authoritiesIterator = intent.authoritiesIterator(); 12167 if (authoritiesIterator != null) { 12168 getIntentListSubset(intentListCopy, 12169 new AuthoritiesIterGenerator(), 12170 authoritiesIterator); 12171 if (intentListCopy.size() == 0) { 12172 // no more intents to match; we're not equivalent 12173 if (DEBUG_FILTERS) { 12174 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 12175 + " package: " + applicationInfo.packageName 12176 + " activity: " + intent.activity.className 12177 + " origPrio: " + intent.getPriority()); 12178 } 12179 intent.setPriority(0); 12180 return; 12181 } 12182 } 12183 12184 // we found matching filter(s); app gets the max priority of all intents 12185 int cappedPriority = 0; 12186 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 12187 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 12188 } 12189 if (intent.getPriority() > cappedPriority) { 12190 if (DEBUG_FILTERS) { 12191 Slog.i(TAG, "Found matching filter(s);" 12192 + " cap priority to " + cappedPriority + ";" 12193 + " package: " + applicationInfo.packageName 12194 + " activity: " + intent.activity.className 12195 + " origPrio: " + intent.getPriority()); 12196 } 12197 intent.setPriority(cappedPriority); 12198 return; 12199 } 12200 // all this for nothing; the requested priority was <= what was on the system 12201 } 12202 12203 public final void addActivity(PackageParser.Activity a, String type) { 12204 mActivities.put(a.getComponentName(), a); 12205 if (DEBUG_SHOW_INFO) 12206 Log.v( 12207 TAG, " " + type + " " + 12208 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 12209 if (DEBUG_SHOW_INFO) 12210 Log.v(TAG, " Class=" + a.info.name); 12211 final int NI = a.intents.size(); 12212 for (int j=0; j<NI; j++) { 12213 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 12214 if ("activity".equals(type)) { 12215 final PackageSetting ps = 12216 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 12217 final List<PackageParser.Activity> systemActivities = 12218 ps != null && ps.pkg != null ? ps.pkg.activities : null; 12219 adjustPriority(systemActivities, intent); 12220 } 12221 if (DEBUG_SHOW_INFO) { 12222 Log.v(TAG, " IntentFilter:"); 12223 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12224 } 12225 if (!intent.debugCheck()) { 12226 Log.w(TAG, "==> For Activity " + a.info.name); 12227 } 12228 addFilter(intent); 12229 } 12230 } 12231 12232 public final void removeActivity(PackageParser.Activity a, String type) { 12233 mActivities.remove(a.getComponentName()); 12234 if (DEBUG_SHOW_INFO) { 12235 Log.v(TAG, " " + type + " " 12236 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 12237 : a.info.name) + ":"); 12238 Log.v(TAG, " Class=" + a.info.name); 12239 } 12240 final int NI = a.intents.size(); 12241 for (int j=0; j<NI; j++) { 12242 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 12243 if (DEBUG_SHOW_INFO) { 12244 Log.v(TAG, " IntentFilter:"); 12245 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12246 } 12247 removeFilter(intent); 12248 } 12249 } 12250 12251 @Override 12252 protected boolean allowFilterResult( 12253 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 12254 ActivityInfo filterAi = filter.activity.info; 12255 for (int i=dest.size()-1; i>=0; i--) { 12256 ActivityInfo destAi = dest.get(i).activityInfo; 12257 if (destAi.name == filterAi.name 12258 && destAi.packageName == filterAi.packageName) { 12259 return false; 12260 } 12261 } 12262 return true; 12263 } 12264 12265 @Override 12266 protected ActivityIntentInfo[] newArray(int size) { 12267 return new ActivityIntentInfo[size]; 12268 } 12269 12270 @Override 12271 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 12272 if (!sUserManager.exists(userId)) return true; 12273 PackageParser.Package p = filter.activity.owner; 12274 if (p != null) { 12275 PackageSetting ps = (PackageSetting)p.mExtras; 12276 if (ps != null) { 12277 // System apps are never considered stopped for purposes of 12278 // filtering, because there may be no way for the user to 12279 // actually re-launch them. 12280 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 12281 && ps.getStopped(userId); 12282 } 12283 } 12284 return false; 12285 } 12286 12287 @Override 12288 protected boolean isPackageForFilter(String packageName, 12289 PackageParser.ActivityIntentInfo info) { 12290 return packageName.equals(info.activity.owner.packageName); 12291 } 12292 12293 @Override 12294 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 12295 int match, int userId) { 12296 if (!sUserManager.exists(userId)) return null; 12297 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 12298 return null; 12299 } 12300 final PackageParser.Activity activity = info.activity; 12301 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 12302 if (ps == null) { 12303 return null; 12304 } 12305 final PackageUserState userState = ps.readUserState(userId); 12306 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 12307 userState, userId); 12308 if (ai == null) { 12309 return null; 12310 } 12311 final boolean matchVisibleToInstantApp = 12312 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 12313 final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 12314 // throw out filters that aren't visible to ephemeral apps 12315 if (matchVisibleToInstantApp 12316 && !(info.isVisibleToInstantApp() || userState.instantApp)) { 12317 return null; 12318 } 12319 // throw out ephemeral filters if we're not explicitly requesting them 12320 if (!isInstantApp && userState.instantApp) { 12321 return null; 12322 } 12323 final ResolveInfo res = new ResolveInfo(); 12324 res.activityInfo = ai; 12325 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 12326 res.filter = info; 12327 } 12328 if (info != null) { 12329 res.handleAllWebDataURI = info.handleAllWebDataURI(); 12330 } 12331 res.priority = info.getPriority(); 12332 res.preferredOrder = activity.owner.mPreferredOrder; 12333 //System.out.println("Result: " + res.activityInfo.className + 12334 // " = " + res.priority); 12335 res.match = match; 12336 res.isDefault = info.hasDefault; 12337 res.labelRes = info.labelRes; 12338 res.nonLocalizedLabel = info.nonLocalizedLabel; 12339 if (userNeedsBadging(userId)) { 12340 res.noResourceId = true; 12341 } else { 12342 res.icon = info.icon; 12343 } 12344 res.iconResourceId = info.icon; 12345 res.system = res.activityInfo.applicationInfo.isSystemApp(); 12346 res.instantAppAvailable = userState.instantApp; 12347 return res; 12348 } 12349 12350 @Override 12351 protected void sortResults(List<ResolveInfo> results) { 12352 Collections.sort(results, mResolvePrioritySorter); 12353 } 12354 12355 @Override 12356 protected void dumpFilter(PrintWriter out, String prefix, 12357 PackageParser.ActivityIntentInfo filter) { 12358 out.print(prefix); out.print( 12359 Integer.toHexString(System.identityHashCode(filter.activity))); 12360 out.print(' '); 12361 filter.activity.printComponentShortName(out); 12362 out.print(" filter "); 12363 out.println(Integer.toHexString(System.identityHashCode(filter))); 12364 } 12365 12366 @Override 12367 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 12368 return filter.activity; 12369 } 12370 12371 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12372 PackageParser.Activity activity = (PackageParser.Activity)label; 12373 out.print(prefix); out.print( 12374 Integer.toHexString(System.identityHashCode(activity))); 12375 out.print(' '); 12376 activity.printComponentShortName(out); 12377 if (count > 1) { 12378 out.print(" ("); out.print(count); out.print(" filters)"); 12379 } 12380 out.println(); 12381 } 12382 12383 // Keys are String (activity class name), values are Activity. 12384 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 12385 = new ArrayMap<ComponentName, PackageParser.Activity>(); 12386 private int mFlags; 12387 } 12388 12389 private final class ServiceIntentResolver 12390 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 12391 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12392 boolean defaultOnly, int userId) { 12393 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 12394 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 12395 } 12396 12397 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12398 int userId) { 12399 if (!sUserManager.exists(userId)) return null; 12400 mFlags = flags; 12401 return super.queryIntent(intent, resolvedType, 12402 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12403 userId); 12404 } 12405 12406 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12407 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 12408 if (!sUserManager.exists(userId)) return null; 12409 if (packageServices == null) { 12410 return null; 12411 } 12412 mFlags = flags; 12413 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 12414 final int N = packageServices.size(); 12415 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 12416 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 12417 12418 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 12419 for (int i = 0; i < N; ++i) { 12420 intentFilters = packageServices.get(i).intents; 12421 if (intentFilters != null && intentFilters.size() > 0) { 12422 PackageParser.ServiceIntentInfo[] array = 12423 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 12424 intentFilters.toArray(array); 12425 listCut.add(array); 12426 } 12427 } 12428 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 12429 } 12430 12431 public final void addService(PackageParser.Service s) { 12432 mServices.put(s.getComponentName(), s); 12433 if (DEBUG_SHOW_INFO) { 12434 Log.v(TAG, " " 12435 + (s.info.nonLocalizedLabel != null 12436 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 12437 Log.v(TAG, " Class=" + s.info.name); 12438 } 12439 final int NI = s.intents.size(); 12440 int j; 12441 for (j=0; j<NI; j++) { 12442 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 12443 if (DEBUG_SHOW_INFO) { 12444 Log.v(TAG, " IntentFilter:"); 12445 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12446 } 12447 if (!intent.debugCheck()) { 12448 Log.w(TAG, "==> For Service " + s.info.name); 12449 } 12450 addFilter(intent); 12451 } 12452 } 12453 12454 public final void removeService(PackageParser.Service s) { 12455 mServices.remove(s.getComponentName()); 12456 if (DEBUG_SHOW_INFO) { 12457 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 12458 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 12459 Log.v(TAG, " Class=" + s.info.name); 12460 } 12461 final int NI = s.intents.size(); 12462 int j; 12463 for (j=0; j<NI; j++) { 12464 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 12465 if (DEBUG_SHOW_INFO) { 12466 Log.v(TAG, " IntentFilter:"); 12467 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12468 } 12469 removeFilter(intent); 12470 } 12471 } 12472 12473 @Override 12474 protected boolean allowFilterResult( 12475 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 12476 ServiceInfo filterSi = filter.service.info; 12477 for (int i=dest.size()-1; i>=0; i--) { 12478 ServiceInfo destAi = dest.get(i).serviceInfo; 12479 if (destAi.name == filterSi.name 12480 && destAi.packageName == filterSi.packageName) { 12481 return false; 12482 } 12483 } 12484 return true; 12485 } 12486 12487 @Override 12488 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 12489 return new PackageParser.ServiceIntentInfo[size]; 12490 } 12491 12492 @Override 12493 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 12494 if (!sUserManager.exists(userId)) return true; 12495 PackageParser.Package p = filter.service.owner; 12496 if (p != null) { 12497 PackageSetting ps = (PackageSetting)p.mExtras; 12498 if (ps != null) { 12499 // System apps are never considered stopped for purposes of 12500 // filtering, because there may be no way for the user to 12501 // actually re-launch them. 12502 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 12503 && ps.getStopped(userId); 12504 } 12505 } 12506 return false; 12507 } 12508 12509 @Override 12510 protected boolean isPackageForFilter(String packageName, 12511 PackageParser.ServiceIntentInfo info) { 12512 return packageName.equals(info.service.owner.packageName); 12513 } 12514 12515 @Override 12516 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 12517 int match, int userId) { 12518 if (!sUserManager.exists(userId)) return null; 12519 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 12520 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 12521 return null; 12522 } 12523 final PackageParser.Service service = info.service; 12524 PackageSetting ps = (PackageSetting) service.owner.mExtras; 12525 if (ps == null) { 12526 return null; 12527 } 12528 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 12529 ps.readUserState(userId), userId); 12530 if (si == null) { 12531 return null; 12532 } 12533 final ResolveInfo res = new ResolveInfo(); 12534 res.serviceInfo = si; 12535 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 12536 res.filter = filter; 12537 } 12538 res.priority = info.getPriority(); 12539 res.preferredOrder = service.owner.mPreferredOrder; 12540 res.match = match; 12541 res.isDefault = info.hasDefault; 12542 res.labelRes = info.labelRes; 12543 res.nonLocalizedLabel = info.nonLocalizedLabel; 12544 res.icon = info.icon; 12545 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 12546 return res; 12547 } 12548 12549 @Override 12550 protected void sortResults(List<ResolveInfo> results) { 12551 Collections.sort(results, mResolvePrioritySorter); 12552 } 12553 12554 @Override 12555 protected void dumpFilter(PrintWriter out, String prefix, 12556 PackageParser.ServiceIntentInfo filter) { 12557 out.print(prefix); out.print( 12558 Integer.toHexString(System.identityHashCode(filter.service))); 12559 out.print(' '); 12560 filter.service.printComponentShortName(out); 12561 out.print(" filter "); 12562 out.println(Integer.toHexString(System.identityHashCode(filter))); 12563 } 12564 12565 @Override 12566 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 12567 return filter.service; 12568 } 12569 12570 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12571 PackageParser.Service service = (PackageParser.Service)label; 12572 out.print(prefix); out.print( 12573 Integer.toHexString(System.identityHashCode(service))); 12574 out.print(' '); 12575 service.printComponentShortName(out); 12576 if (count > 1) { 12577 out.print(" ("); out.print(count); out.print(" filters)"); 12578 } 12579 out.println(); 12580 } 12581 12582// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 12583// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 12584// final List<ResolveInfo> retList = Lists.newArrayList(); 12585// while (i.hasNext()) { 12586// final ResolveInfo resolveInfo = (ResolveInfo) i; 12587// if (isEnabledLP(resolveInfo.serviceInfo)) { 12588// retList.add(resolveInfo); 12589// } 12590// } 12591// return retList; 12592// } 12593 12594 // Keys are String (activity class name), values are Activity. 12595 private final ArrayMap<ComponentName, PackageParser.Service> mServices 12596 = new ArrayMap<ComponentName, PackageParser.Service>(); 12597 private int mFlags; 12598 } 12599 12600 private final class ProviderIntentResolver 12601 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 12602 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12603 boolean defaultOnly, int userId) { 12604 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 12605 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 12606 } 12607 12608 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12609 int userId) { 12610 if (!sUserManager.exists(userId)) 12611 return null; 12612 mFlags = flags; 12613 return super.queryIntent(intent, resolvedType, 12614 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12615 userId); 12616 } 12617 12618 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12619 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 12620 if (!sUserManager.exists(userId)) 12621 return null; 12622 if (packageProviders == null) { 12623 return null; 12624 } 12625 mFlags = flags; 12626 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 12627 final int N = packageProviders.size(); 12628 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 12629 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 12630 12631 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 12632 for (int i = 0; i < N; ++i) { 12633 intentFilters = packageProviders.get(i).intents; 12634 if (intentFilters != null && intentFilters.size() > 0) { 12635 PackageParser.ProviderIntentInfo[] array = 12636 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 12637 intentFilters.toArray(array); 12638 listCut.add(array); 12639 } 12640 } 12641 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 12642 } 12643 12644 public final void addProvider(PackageParser.Provider p) { 12645 if (mProviders.containsKey(p.getComponentName())) { 12646 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 12647 return; 12648 } 12649 12650 mProviders.put(p.getComponentName(), p); 12651 if (DEBUG_SHOW_INFO) { 12652 Log.v(TAG, " " 12653 + (p.info.nonLocalizedLabel != null 12654 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 12655 Log.v(TAG, " Class=" + p.info.name); 12656 } 12657 final int NI = p.intents.size(); 12658 int j; 12659 for (j = 0; j < NI; j++) { 12660 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 12661 if (DEBUG_SHOW_INFO) { 12662 Log.v(TAG, " IntentFilter:"); 12663 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12664 } 12665 if (!intent.debugCheck()) { 12666 Log.w(TAG, "==> For Provider " + p.info.name); 12667 } 12668 addFilter(intent); 12669 } 12670 } 12671 12672 public final void removeProvider(PackageParser.Provider p) { 12673 mProviders.remove(p.getComponentName()); 12674 if (DEBUG_SHOW_INFO) { 12675 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 12676 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 12677 Log.v(TAG, " Class=" + p.info.name); 12678 } 12679 final int NI = p.intents.size(); 12680 int j; 12681 for (j = 0; j < NI; j++) { 12682 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 12683 if (DEBUG_SHOW_INFO) { 12684 Log.v(TAG, " IntentFilter:"); 12685 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12686 } 12687 removeFilter(intent); 12688 } 12689 } 12690 12691 @Override 12692 protected boolean allowFilterResult( 12693 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 12694 ProviderInfo filterPi = filter.provider.info; 12695 for (int i = dest.size() - 1; i >= 0; i--) { 12696 ProviderInfo destPi = dest.get(i).providerInfo; 12697 if (destPi.name == filterPi.name 12698 && destPi.packageName == filterPi.packageName) { 12699 return false; 12700 } 12701 } 12702 return true; 12703 } 12704 12705 @Override 12706 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 12707 return new PackageParser.ProviderIntentInfo[size]; 12708 } 12709 12710 @Override 12711 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 12712 if (!sUserManager.exists(userId)) 12713 return true; 12714 PackageParser.Package p = filter.provider.owner; 12715 if (p != null) { 12716 PackageSetting ps = (PackageSetting) p.mExtras; 12717 if (ps != null) { 12718 // System apps are never considered stopped for purposes of 12719 // filtering, because there may be no way for the user to 12720 // actually re-launch them. 12721 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 12722 && ps.getStopped(userId); 12723 } 12724 } 12725 return false; 12726 } 12727 12728 @Override 12729 protected boolean isPackageForFilter(String packageName, 12730 PackageParser.ProviderIntentInfo info) { 12731 return packageName.equals(info.provider.owner.packageName); 12732 } 12733 12734 @Override 12735 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 12736 int match, int userId) { 12737 if (!sUserManager.exists(userId)) 12738 return null; 12739 final PackageParser.ProviderIntentInfo info = filter; 12740 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 12741 return null; 12742 } 12743 final PackageParser.Provider provider = info.provider; 12744 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 12745 if (ps == null) { 12746 return null; 12747 } 12748 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 12749 ps.readUserState(userId), userId); 12750 if (pi == null) { 12751 return null; 12752 } 12753 final ResolveInfo res = new ResolveInfo(); 12754 res.providerInfo = pi; 12755 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 12756 res.filter = filter; 12757 } 12758 res.priority = info.getPriority(); 12759 res.preferredOrder = provider.owner.mPreferredOrder; 12760 res.match = match; 12761 res.isDefault = info.hasDefault; 12762 res.labelRes = info.labelRes; 12763 res.nonLocalizedLabel = info.nonLocalizedLabel; 12764 res.icon = info.icon; 12765 res.system = res.providerInfo.applicationInfo.isSystemApp(); 12766 return res; 12767 } 12768 12769 @Override 12770 protected void sortResults(List<ResolveInfo> results) { 12771 Collections.sort(results, mResolvePrioritySorter); 12772 } 12773 12774 @Override 12775 protected void dumpFilter(PrintWriter out, String prefix, 12776 PackageParser.ProviderIntentInfo filter) { 12777 out.print(prefix); 12778 out.print( 12779 Integer.toHexString(System.identityHashCode(filter.provider))); 12780 out.print(' '); 12781 filter.provider.printComponentShortName(out); 12782 out.print(" filter "); 12783 out.println(Integer.toHexString(System.identityHashCode(filter))); 12784 } 12785 12786 @Override 12787 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 12788 return filter.provider; 12789 } 12790 12791 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12792 PackageParser.Provider provider = (PackageParser.Provider)label; 12793 out.print(prefix); out.print( 12794 Integer.toHexString(System.identityHashCode(provider))); 12795 out.print(' '); 12796 provider.printComponentShortName(out); 12797 if (count > 1) { 12798 out.print(" ("); out.print(count); out.print(" filters)"); 12799 } 12800 out.println(); 12801 } 12802 12803 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 12804 = new ArrayMap<ComponentName, PackageParser.Provider>(); 12805 private int mFlags; 12806 } 12807 12808 static final class EphemeralIntentResolver 12809 extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> { 12810 /** 12811 * The result that has the highest defined order. Ordering applies on a 12812 * per-package basis. Mapping is from package name to Pair of order and 12813 * EphemeralResolveInfo. 12814 * <p> 12815 * NOTE: This is implemented as a field variable for convenience and efficiency. 12816 * By having a field variable, we're able to track filter ordering as soon as 12817 * a non-zero order is defined. Otherwise, multiple loops across the result set 12818 * would be needed to apply ordering. If the intent resolver becomes re-entrant, 12819 * this needs to be contained entirely within {@link #filterResults()}. 12820 */ 12821 final ArrayMap<String, Pair<Integer, EphemeralResolveInfo>> mOrderResult = new ArrayMap<>(); 12822 12823 @Override 12824 protected AuxiliaryResolveInfo[] newArray(int size) { 12825 return new AuxiliaryResolveInfo[size]; 12826 } 12827 12828 @Override 12829 protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) { 12830 return true; 12831 } 12832 12833 @Override 12834 protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match, 12835 int userId) { 12836 if (!sUserManager.exists(userId)) { 12837 return null; 12838 } 12839 final String packageName = responseObj.resolveInfo.getPackageName(); 12840 final Integer order = responseObj.getOrder(); 12841 final Pair<Integer, EphemeralResolveInfo> lastOrderResult = 12842 mOrderResult.get(packageName); 12843 // ordering is enabled and this item's order isn't high enough 12844 if (lastOrderResult != null && lastOrderResult.first >= order) { 12845 return null; 12846 } 12847 final EphemeralResolveInfo res = responseObj.resolveInfo; 12848 if (order > 0) { 12849 // non-zero order, enable ordering 12850 mOrderResult.put(packageName, new Pair<>(order, res)); 12851 } 12852 return responseObj; 12853 } 12854 12855 @Override 12856 protected void filterResults(List<AuxiliaryResolveInfo> results) { 12857 // only do work if ordering is enabled [most of the time it won't be] 12858 if (mOrderResult.size() == 0) { 12859 return; 12860 } 12861 int resultSize = results.size(); 12862 for (int i = 0; i < resultSize; i++) { 12863 final EphemeralResolveInfo info = results.get(i).resolveInfo; 12864 final String packageName = info.getPackageName(); 12865 final Pair<Integer, EphemeralResolveInfo> savedInfo = mOrderResult.get(packageName); 12866 if (savedInfo == null) { 12867 // package doesn't having ordering 12868 continue; 12869 } 12870 if (savedInfo.second == info) { 12871 // circled back to the highest ordered item; remove from order list 12872 mOrderResult.remove(savedInfo); 12873 if (mOrderResult.size() == 0) { 12874 // no more ordered items 12875 break; 12876 } 12877 continue; 12878 } 12879 // item has a worse order, remove it from the result list 12880 results.remove(i); 12881 resultSize--; 12882 i--; 12883 } 12884 } 12885 } 12886 12887 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 12888 new Comparator<ResolveInfo>() { 12889 public int compare(ResolveInfo r1, ResolveInfo r2) { 12890 int v1 = r1.priority; 12891 int v2 = r2.priority; 12892 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 12893 if (v1 != v2) { 12894 return (v1 > v2) ? -1 : 1; 12895 } 12896 v1 = r1.preferredOrder; 12897 v2 = r2.preferredOrder; 12898 if (v1 != v2) { 12899 return (v1 > v2) ? -1 : 1; 12900 } 12901 if (r1.isDefault != r2.isDefault) { 12902 return r1.isDefault ? -1 : 1; 12903 } 12904 v1 = r1.match; 12905 v2 = r2.match; 12906 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 12907 if (v1 != v2) { 12908 return (v1 > v2) ? -1 : 1; 12909 } 12910 if (r1.system != r2.system) { 12911 return r1.system ? -1 : 1; 12912 } 12913 if (r1.activityInfo != null) { 12914 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 12915 } 12916 if (r1.serviceInfo != null) { 12917 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 12918 } 12919 if (r1.providerInfo != null) { 12920 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 12921 } 12922 return 0; 12923 } 12924 }; 12925 12926 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 12927 new Comparator<ProviderInfo>() { 12928 public int compare(ProviderInfo p1, ProviderInfo p2) { 12929 final int v1 = p1.initOrder; 12930 final int v2 = p2.initOrder; 12931 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 12932 } 12933 }; 12934 12935 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 12936 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 12937 final int[] userIds) { 12938 mHandler.post(new Runnable() { 12939 @Override 12940 public void run() { 12941 try { 12942 final IActivityManager am = ActivityManager.getService(); 12943 if (am == null) return; 12944 final int[] resolvedUserIds; 12945 if (userIds == null) { 12946 resolvedUserIds = am.getRunningUserIds(); 12947 } else { 12948 resolvedUserIds = userIds; 12949 } 12950 for (int id : resolvedUserIds) { 12951 final Intent intent = new Intent(action, 12952 pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null); 12953 if (extras != null) { 12954 intent.putExtras(extras); 12955 } 12956 if (targetPkg != null) { 12957 intent.setPackage(targetPkg); 12958 } 12959 // Modify the UID when posting to other users 12960 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 12961 if (uid > 0 && UserHandle.getUserId(uid) != id) { 12962 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 12963 intent.putExtra(Intent.EXTRA_UID, uid); 12964 } 12965 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 12966 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 12967 if (DEBUG_BROADCASTS) { 12968 RuntimeException here = new RuntimeException("here"); 12969 here.fillInStackTrace(); 12970 Slog.d(TAG, "Sending to user " + id + ": " 12971 + intent.toShortString(false, true, false, false) 12972 + " " + intent.getExtras(), here); 12973 } 12974 am.broadcastIntent(null, intent, null, finishedReceiver, 12975 0, null, null, null, android.app.AppOpsManager.OP_NONE, 12976 null, finishedReceiver != null, false, id); 12977 } 12978 } catch (RemoteException ex) { 12979 } 12980 } 12981 }); 12982 } 12983 12984 /** 12985 * Check if the external storage media is available. This is true if there 12986 * is a mounted external storage medium or if the external storage is 12987 * emulated. 12988 */ 12989 private boolean isExternalMediaAvailable() { 12990 return mMediaMounted || Environment.isExternalStorageEmulated(); 12991 } 12992 12993 @Override 12994 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 12995 // writer 12996 synchronized (mPackages) { 12997 if (!isExternalMediaAvailable()) { 12998 // If the external storage is no longer mounted at this point, 12999 // the caller may not have been able to delete all of this 13000 // packages files and can not delete any more. Bail. 13001 return null; 13002 } 13003 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 13004 if (lastPackage != null) { 13005 pkgs.remove(lastPackage); 13006 } 13007 if (pkgs.size() > 0) { 13008 return pkgs.get(0); 13009 } 13010 } 13011 return null; 13012 } 13013 13014 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 13015 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 13016 userId, andCode ? 1 : 0, packageName); 13017 if (mSystemReady) { 13018 msg.sendToTarget(); 13019 } else { 13020 if (mPostSystemReadyMessages == null) { 13021 mPostSystemReadyMessages = new ArrayList<>(); 13022 } 13023 mPostSystemReadyMessages.add(msg); 13024 } 13025 } 13026 13027 void startCleaningPackages() { 13028 // reader 13029 if (!isExternalMediaAvailable()) { 13030 return; 13031 } 13032 synchronized (mPackages) { 13033 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 13034 return; 13035 } 13036 } 13037 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 13038 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 13039 IActivityManager am = ActivityManager.getService(); 13040 if (am != null) { 13041 try { 13042 am.startService(null, intent, null, -1, null, mContext.getOpPackageName(), 13043 UserHandle.USER_SYSTEM); 13044 } catch (RemoteException e) { 13045 } 13046 } 13047 } 13048 13049 @Override 13050 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 13051 int installFlags, String installerPackageName, int userId) { 13052 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 13053 13054 final int callingUid = Binder.getCallingUid(); 13055 enforceCrossUserPermission(callingUid, userId, 13056 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 13057 13058 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 13059 try { 13060 if (observer != null) { 13061 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 13062 } 13063 } catch (RemoteException re) { 13064 } 13065 return; 13066 } 13067 13068 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 13069 installFlags |= PackageManager.INSTALL_FROM_ADB; 13070 13071 } else { 13072 // Caller holds INSTALL_PACKAGES permission, so we're less strict 13073 // about installerPackageName. 13074 13075 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 13076 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 13077 } 13078 13079 UserHandle user; 13080 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 13081 user = UserHandle.ALL; 13082 } else { 13083 user = new UserHandle(userId); 13084 } 13085 13086 // Only system components can circumvent runtime permissions when installing. 13087 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 13088 && mContext.checkCallingOrSelfPermission(Manifest.permission 13089 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 13090 throw new SecurityException("You need the " 13091 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 13092 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 13093 } 13094 13095 if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0 13096 || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 13097 throw new IllegalArgumentException( 13098 "New installs into ASEC containers no longer supported"); 13099 } 13100 13101 final File originFile = new File(originPath); 13102 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 13103 13104 final Message msg = mHandler.obtainMessage(INIT_COPY); 13105 final VerificationInfo verificationInfo = new VerificationInfo( 13106 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 13107 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 13108 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 13109 null /*packageAbiOverride*/, null /*grantedPermissions*/, 13110 null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN); 13111 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 13112 msg.obj = params; 13113 13114 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 13115 System.identityHashCode(msg.obj)); 13116 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 13117 System.identityHashCode(msg.obj)); 13118 13119 mHandler.sendMessage(msg); 13120 } 13121 13122 13123 /** 13124 * Ensure that the install reason matches what we know about the package installer (e.g. whether 13125 * it is acting on behalf on an enterprise or the user). 13126 * 13127 * Note that the ordering of the conditionals in this method is important. The checks we perform 13128 * are as follows, in this order: 13129 * 13130 * 1) If the install is being performed by a system app, we can trust the app to have set the 13131 * install reason correctly. Thus, we pass through the install reason unchanged, no matter 13132 * what it is. 13133 * 2) If the install is being performed by a device or profile owner app, the install reason 13134 * should be enterprise policy. However, we cannot be sure that the device or profile owner 13135 * set the install reason correctly. If the app targets an older SDK version where install 13136 * reasons did not exist yet, or if the app author simply forgot, the install reason may be 13137 * unset or wrong. Thus, we force the install reason to be enterprise policy. 13138 * 3) In all other cases, the install is being performed by a regular app that is neither part 13139 * of the system nor a device or profile owner. We have no reason to believe that this app is 13140 * acting on behalf of the enterprise admin. Thus, we check whether the install reason was 13141 * set to enterprise policy and if so, change it to unknown instead. 13142 */ 13143 private int fixUpInstallReason(String installerPackageName, int installerUid, 13144 int installReason) { 13145 if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid) 13146 == PERMISSION_GRANTED) { 13147 // If the install is being performed by a system app, we trust that app to have set the 13148 // install reason correctly. 13149 return installReason; 13150 } 13151 13152 final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 13153 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 13154 if (dpm != null) { 13155 ComponentName owner = null; 13156 try { 13157 owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */); 13158 if (owner == null) { 13159 owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid)); 13160 } 13161 } catch (RemoteException e) { 13162 } 13163 if (owner != null && owner.getPackageName().equals(installerPackageName)) { 13164 // If the install is being performed by a device or profile owner, the install 13165 // reason should be enterprise policy. 13166 return PackageManager.INSTALL_REASON_POLICY; 13167 } 13168 } 13169 13170 if (installReason == PackageManager.INSTALL_REASON_POLICY) { 13171 // If the install is being performed by a regular app (i.e. neither system app nor 13172 // device or profile owner), we have no reason to believe that the app is acting on 13173 // behalf of an enterprise. If the app set the install reason to enterprise policy, 13174 // change it to unknown instead. 13175 return PackageManager.INSTALL_REASON_UNKNOWN; 13176 } 13177 13178 // If the install is being performed by a regular app and the install reason was set to any 13179 // value but enterprise policy, leave the install reason unchanged. 13180 return installReason; 13181 } 13182 13183 void installStage(String packageName, File stagedDir, String stagedCid, 13184 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 13185 String installerPackageName, int installerUid, UserHandle user, 13186 Certificate[][] certificates) { 13187 if (DEBUG_EPHEMERAL) { 13188 if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) { 13189 Slog.d(TAG, "Ephemeral install of " + packageName); 13190 } 13191 } 13192 final VerificationInfo verificationInfo = new VerificationInfo( 13193 sessionParams.originatingUri, sessionParams.referrerUri, 13194 sessionParams.originatingUid, installerUid); 13195 13196 final OriginInfo origin; 13197 if (stagedDir != null) { 13198 origin = OriginInfo.fromStagedFile(stagedDir); 13199 } else { 13200 origin = OriginInfo.fromStagedContainer(stagedCid); 13201 } 13202 13203 final Message msg = mHandler.obtainMessage(INIT_COPY); 13204 final int installReason = fixUpInstallReason(installerPackageName, installerUid, 13205 sessionParams.installReason); 13206 final InstallParams params = new InstallParams(origin, null, observer, 13207 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 13208 verificationInfo, user, sessionParams.abiOverride, 13209 sessionParams.grantedRuntimePermissions, certificates, installReason); 13210 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 13211 msg.obj = params; 13212 13213 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 13214 System.identityHashCode(msg.obj)); 13215 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 13216 System.identityHashCode(msg.obj)); 13217 13218 mHandler.sendMessage(msg); 13219 } 13220 13221 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 13222 int userId) { 13223 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 13224 sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId); 13225 } 13226 13227 private void sendPackageAddedForNewUsers(String packageName, boolean isSystem, 13228 int appId, int... userIds) { 13229 if (ArrayUtils.isEmpty(userIds)) { 13230 return; 13231 } 13232 Bundle extras = new Bundle(1); 13233 // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast 13234 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId)); 13235 13236 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 13237 packageName, extras, 0, null, null, userIds); 13238 if (isSystem) { 13239 mHandler.post(() -> { 13240 for (int userId : userIds) { 13241 sendBootCompletedBroadcastToSystemApp(packageName, userId); 13242 } 13243 } 13244 ); 13245 } 13246 } 13247 13248 /** 13249 * The just-installed/enabled app is bundled on the system, so presumed to be able to run 13250 * automatically without needing an explicit launch. 13251 * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones. 13252 */ 13253 private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) { 13254 // If user is not running, the app didn't miss any broadcast 13255 if (!mUserManagerInternal.isUserRunning(userId)) { 13256 return; 13257 } 13258 final IActivityManager am = ActivityManager.getService(); 13259 try { 13260 // Deliver LOCKED_BOOT_COMPLETED first 13261 Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED) 13262 .setPackage(packageName); 13263 final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED}; 13264 am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions, 13265 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 13266 13267 // Deliver BOOT_COMPLETED only if user is unlocked 13268 if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) { 13269 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName); 13270 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions, 13271 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 13272 } 13273 } catch (RemoteException e) { 13274 throw e.rethrowFromSystemServer(); 13275 } 13276 } 13277 13278 @Override 13279 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 13280 int userId) { 13281 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13282 PackageSetting pkgSetting; 13283 final int uid = Binder.getCallingUid(); 13284 enforceCrossUserPermission(uid, userId, 13285 true /* requireFullPermission */, true /* checkShell */, 13286 "setApplicationHiddenSetting for user " + userId); 13287 13288 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 13289 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 13290 return false; 13291 } 13292 13293 long callingId = Binder.clearCallingIdentity(); 13294 try { 13295 boolean sendAdded = false; 13296 boolean sendRemoved = false; 13297 // writer 13298 synchronized (mPackages) { 13299 pkgSetting = mSettings.mPackages.get(packageName); 13300 if (pkgSetting == null) { 13301 return false; 13302 } 13303 // Do not allow "android" is being disabled 13304 if ("android".equals(packageName)) { 13305 Slog.w(TAG, "Cannot hide package: android"); 13306 return false; 13307 } 13308 // Cannot hide static shared libs as they are considered 13309 // a part of the using app (emulating static linking). Also 13310 // static libs are installed always on internal storage. 13311 PackageParser.Package pkg = mPackages.get(packageName); 13312 if (pkg != null && pkg.staticSharedLibName != null) { 13313 Slog.w(TAG, "Cannot hide package: " + packageName 13314 + " providing static shared library: " 13315 + pkg.staticSharedLibName); 13316 return false; 13317 } 13318 // Only allow protected packages to hide themselves. 13319 if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId) 13320 && mProtectedPackages.isPackageStateProtected(userId, packageName)) { 13321 Slog.w(TAG, "Not hiding protected package: " + packageName); 13322 return false; 13323 } 13324 13325 if (pkgSetting.getHidden(userId) != hidden) { 13326 pkgSetting.setHidden(hidden, userId); 13327 mSettings.writePackageRestrictionsLPr(userId); 13328 if (hidden) { 13329 sendRemoved = true; 13330 } else { 13331 sendAdded = true; 13332 } 13333 } 13334 } 13335 if (sendAdded) { 13336 sendPackageAddedForUser(packageName, pkgSetting, userId); 13337 return true; 13338 } 13339 if (sendRemoved) { 13340 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 13341 "hiding pkg"); 13342 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 13343 return true; 13344 } 13345 } finally { 13346 Binder.restoreCallingIdentity(callingId); 13347 } 13348 return false; 13349 } 13350 13351 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 13352 int userId) { 13353 final PackageRemovedInfo info = new PackageRemovedInfo(); 13354 info.removedPackage = packageName; 13355 info.removedUsers = new int[] {userId}; 13356 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 13357 info.sendPackageRemovedBroadcasts(true /*killApp*/); 13358 } 13359 13360 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 13361 if (pkgList.length > 0) { 13362 Bundle extras = new Bundle(1); 13363 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 13364 13365 sendPackageBroadcast( 13366 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 13367 : Intent.ACTION_PACKAGES_UNSUSPENDED, 13368 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 13369 new int[] {userId}); 13370 } 13371 } 13372 13373 /** 13374 * Returns true if application is not found or there was an error. Otherwise it returns 13375 * the hidden state of the package for the given user. 13376 */ 13377 @Override 13378 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 13379 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13380 enforceCrossUserPermission(Binder.getCallingUid(), userId, 13381 true /* requireFullPermission */, false /* checkShell */, 13382 "getApplicationHidden for user " + userId); 13383 PackageSetting pkgSetting; 13384 long callingId = Binder.clearCallingIdentity(); 13385 try { 13386 // writer 13387 synchronized (mPackages) { 13388 pkgSetting = mSettings.mPackages.get(packageName); 13389 if (pkgSetting == null) { 13390 return true; 13391 } 13392 return pkgSetting.getHidden(userId); 13393 } 13394 } finally { 13395 Binder.restoreCallingIdentity(callingId); 13396 } 13397 } 13398 13399 /** 13400 * @hide 13401 */ 13402 @Override 13403 public int installExistingPackageAsUser(String packageName, int userId, int installFlags, 13404 int installReason) { 13405 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 13406 null); 13407 PackageSetting pkgSetting; 13408 final int uid = Binder.getCallingUid(); 13409 enforceCrossUserPermission(uid, userId, 13410 true /* requireFullPermission */, true /* checkShell */, 13411 "installExistingPackage for user " + userId); 13412 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 13413 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 13414 } 13415 13416 long callingId = Binder.clearCallingIdentity(); 13417 try { 13418 boolean installed = false; 13419 final boolean instantApp = 13420 (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 13421 final boolean fullApp = 13422 (installFlags & PackageManager.INSTALL_FULL_APP) != 0; 13423 13424 // writer 13425 synchronized (mPackages) { 13426 pkgSetting = mSettings.mPackages.get(packageName); 13427 if (pkgSetting == null) { 13428 return PackageManager.INSTALL_FAILED_INVALID_URI; 13429 } 13430 if (!pkgSetting.getInstalled(userId)) { 13431 pkgSetting.setInstalled(true, userId); 13432 pkgSetting.setHidden(false, userId); 13433 pkgSetting.setInstallReason(installReason, userId); 13434 mSettings.writePackageRestrictionsLPr(userId); 13435 mSettings.writeKernelMappingLPr(pkgSetting); 13436 installed = true; 13437 } else if (fullApp && pkgSetting.getInstantApp(userId)) { 13438 // upgrade app from instant to full; we don't allow app downgrade 13439 installed = true; 13440 } 13441 setInstantAppForUser(pkgSetting, userId, instantApp, fullApp); 13442 } 13443 13444 if (installed) { 13445 if (pkgSetting.pkg != null) { 13446 synchronized (mInstallLock) { 13447 // We don't need to freeze for a brand new install 13448 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 13449 } 13450 } 13451 sendPackageAddedForUser(packageName, pkgSetting, userId); 13452 synchronized (mPackages) { 13453 updateSequenceNumberLP(packageName, new int[]{ userId }); 13454 } 13455 } 13456 } finally { 13457 Binder.restoreCallingIdentity(callingId); 13458 } 13459 13460 return PackageManager.INSTALL_SUCCEEDED; 13461 } 13462 13463 void setInstantAppForUser(PackageSetting pkgSetting, int userId, 13464 boolean instantApp, boolean fullApp) { 13465 // no state specified; do nothing 13466 if (!instantApp && !fullApp) { 13467 return; 13468 } 13469 if (userId != UserHandle.USER_ALL) { 13470 if (instantApp && !pkgSetting.getInstantApp(userId)) { 13471 pkgSetting.setInstantApp(true /*instantApp*/, userId); 13472 } else if (fullApp && pkgSetting.getInstantApp(userId)) { 13473 pkgSetting.setInstantApp(false /*instantApp*/, userId); 13474 } 13475 } else { 13476 for (int currentUserId : sUserManager.getUserIds()) { 13477 if (instantApp && !pkgSetting.getInstantApp(currentUserId)) { 13478 pkgSetting.setInstantApp(true /*instantApp*/, currentUserId); 13479 } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) { 13480 pkgSetting.setInstantApp(false /*instantApp*/, currentUserId); 13481 } 13482 } 13483 } 13484 } 13485 13486 boolean isUserRestricted(int userId, String restrictionKey) { 13487 Bundle restrictions = sUserManager.getUserRestrictions(userId); 13488 if (restrictions.getBoolean(restrictionKey, false)) { 13489 Log.w(TAG, "User is restricted: " + restrictionKey); 13490 return true; 13491 } 13492 return false; 13493 } 13494 13495 @Override 13496 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 13497 int userId) { 13498 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13499 enforceCrossUserPermission(Binder.getCallingUid(), userId, 13500 true /* requireFullPermission */, true /* checkShell */, 13501 "setPackagesSuspended for user " + userId); 13502 13503 if (ArrayUtils.isEmpty(packageNames)) { 13504 return packageNames; 13505 } 13506 13507 // List of package names for whom the suspended state has changed. 13508 List<String> changedPackages = new ArrayList<>(packageNames.length); 13509 // List of package names for whom the suspended state is not set as requested in this 13510 // method. 13511 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 13512 long callingId = Binder.clearCallingIdentity(); 13513 try { 13514 for (int i = 0; i < packageNames.length; i++) { 13515 String packageName = packageNames[i]; 13516 boolean changed = false; 13517 final int appId; 13518 synchronized (mPackages) { 13519 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 13520 if (pkgSetting == null) { 13521 Slog.w(TAG, "Could not find package setting for package \"" + packageName 13522 + "\". Skipping suspending/un-suspending."); 13523 unactionedPackages.add(packageName); 13524 continue; 13525 } 13526 appId = pkgSetting.appId; 13527 if (pkgSetting.getSuspended(userId) != suspended) { 13528 if (!canSuspendPackageForUserLocked(packageName, userId)) { 13529 unactionedPackages.add(packageName); 13530 continue; 13531 } 13532 pkgSetting.setSuspended(suspended, userId); 13533 mSettings.writePackageRestrictionsLPr(userId); 13534 changed = true; 13535 changedPackages.add(packageName); 13536 } 13537 } 13538 13539 if (changed && suspended) { 13540 killApplication(packageName, UserHandle.getUid(userId, appId), 13541 "suspending package"); 13542 } 13543 } 13544 } finally { 13545 Binder.restoreCallingIdentity(callingId); 13546 } 13547 13548 if (!changedPackages.isEmpty()) { 13549 sendPackagesSuspendedForUser(changedPackages.toArray( 13550 new String[changedPackages.size()]), userId, suspended); 13551 } 13552 13553 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 13554 } 13555 13556 @Override 13557 public boolean isPackageSuspendedForUser(String packageName, int userId) { 13558 enforceCrossUserPermission(Binder.getCallingUid(), userId, 13559 true /* requireFullPermission */, false /* checkShell */, 13560 "isPackageSuspendedForUser for user " + userId); 13561 synchronized (mPackages) { 13562 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 13563 if (pkgSetting == null) { 13564 throw new IllegalArgumentException("Unknown target package: " + packageName); 13565 } 13566 return pkgSetting.getSuspended(userId); 13567 } 13568 } 13569 13570 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 13571 if (isPackageDeviceAdmin(packageName, userId)) { 13572 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13573 + "\": has an active device admin"); 13574 return false; 13575 } 13576 13577 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 13578 if (packageName.equals(activeLauncherPackageName)) { 13579 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13580 + "\": contains the active launcher"); 13581 return false; 13582 } 13583 13584 if (packageName.equals(mRequiredInstallerPackage)) { 13585 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13586 + "\": required for package installation"); 13587 return false; 13588 } 13589 13590 if (packageName.equals(mRequiredUninstallerPackage)) { 13591 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13592 + "\": required for package uninstallation"); 13593 return false; 13594 } 13595 13596 if (packageName.equals(mRequiredVerifierPackage)) { 13597 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13598 + "\": required for package verification"); 13599 return false; 13600 } 13601 13602 if (packageName.equals(getDefaultDialerPackageName(userId))) { 13603 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13604 + "\": is the default dialer"); 13605 return false; 13606 } 13607 13608 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 13609 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13610 + "\": protected package"); 13611 return false; 13612 } 13613 13614 // Cannot suspend static shared libs as they are considered 13615 // a part of the using app (emulating static linking). Also 13616 // static libs are installed always on internal storage. 13617 PackageParser.Package pkg = mPackages.get(packageName); 13618 if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) { 13619 Slog.w(TAG, "Cannot suspend package: " + packageName 13620 + " providing static shared library: " 13621 + pkg.staticSharedLibName); 13622 return false; 13623 } 13624 13625 return true; 13626 } 13627 13628 private String getActiveLauncherPackageName(int userId) { 13629 Intent intent = new Intent(Intent.ACTION_MAIN); 13630 intent.addCategory(Intent.CATEGORY_HOME); 13631 ResolveInfo resolveInfo = resolveIntent( 13632 intent, 13633 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 13634 PackageManager.MATCH_DEFAULT_ONLY, 13635 userId); 13636 13637 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 13638 } 13639 13640 private String getDefaultDialerPackageName(int userId) { 13641 synchronized (mPackages) { 13642 return mSettings.getDefaultDialerPackageNameLPw(userId); 13643 } 13644 } 13645 13646 @Override 13647 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 13648 mContext.enforceCallingOrSelfPermission( 13649 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13650 "Only package verification agents can verify applications"); 13651 13652 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 13653 final PackageVerificationResponse response = new PackageVerificationResponse( 13654 verificationCode, Binder.getCallingUid()); 13655 msg.arg1 = id; 13656 msg.obj = response; 13657 mHandler.sendMessage(msg); 13658 } 13659 13660 @Override 13661 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 13662 long millisecondsToDelay) { 13663 mContext.enforceCallingOrSelfPermission( 13664 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13665 "Only package verification agents can extend verification timeouts"); 13666 13667 final PackageVerificationState state = mPendingVerification.get(id); 13668 final PackageVerificationResponse response = new PackageVerificationResponse( 13669 verificationCodeAtTimeout, Binder.getCallingUid()); 13670 13671 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 13672 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 13673 } 13674 if (millisecondsToDelay < 0) { 13675 millisecondsToDelay = 0; 13676 } 13677 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 13678 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 13679 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 13680 } 13681 13682 if ((state != null) && !state.timeoutExtended()) { 13683 state.extendTimeout(); 13684 13685 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 13686 msg.arg1 = id; 13687 msg.obj = response; 13688 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 13689 } 13690 } 13691 13692 private void broadcastPackageVerified(int verificationId, Uri packageUri, 13693 int verificationCode, UserHandle user) { 13694 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 13695 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 13696 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 13697 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 13698 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 13699 13700 mContext.sendBroadcastAsUser(intent, user, 13701 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 13702 } 13703 13704 private ComponentName matchComponentForVerifier(String packageName, 13705 List<ResolveInfo> receivers) { 13706 ActivityInfo targetReceiver = null; 13707 13708 final int NR = receivers.size(); 13709 for (int i = 0; i < NR; i++) { 13710 final ResolveInfo info = receivers.get(i); 13711 if (info.activityInfo == null) { 13712 continue; 13713 } 13714 13715 if (packageName.equals(info.activityInfo.packageName)) { 13716 targetReceiver = info.activityInfo; 13717 break; 13718 } 13719 } 13720 13721 if (targetReceiver == null) { 13722 return null; 13723 } 13724 13725 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 13726 } 13727 13728 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 13729 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 13730 if (pkgInfo.verifiers.length == 0) { 13731 return null; 13732 } 13733 13734 final int N = pkgInfo.verifiers.length; 13735 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 13736 for (int i = 0; i < N; i++) { 13737 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 13738 13739 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 13740 receivers); 13741 if (comp == null) { 13742 continue; 13743 } 13744 13745 final int verifierUid = getUidForVerifier(verifierInfo); 13746 if (verifierUid == -1) { 13747 continue; 13748 } 13749 13750 if (DEBUG_VERIFY) { 13751 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 13752 + " with the correct signature"); 13753 } 13754 sufficientVerifiers.add(comp); 13755 verificationState.addSufficientVerifier(verifierUid); 13756 } 13757 13758 return sufficientVerifiers; 13759 } 13760 13761 private int getUidForVerifier(VerifierInfo verifierInfo) { 13762 synchronized (mPackages) { 13763 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 13764 if (pkg == null) { 13765 return -1; 13766 } else if (pkg.mSignatures.length != 1) { 13767 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 13768 + " has more than one signature; ignoring"); 13769 return -1; 13770 } 13771 13772 /* 13773 * If the public key of the package's signature does not match 13774 * our expected public key, then this is a different package and 13775 * we should skip. 13776 */ 13777 13778 final byte[] expectedPublicKey; 13779 try { 13780 final Signature verifierSig = pkg.mSignatures[0]; 13781 final PublicKey publicKey = verifierSig.getPublicKey(); 13782 expectedPublicKey = publicKey.getEncoded(); 13783 } catch (CertificateException e) { 13784 return -1; 13785 } 13786 13787 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 13788 13789 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 13790 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 13791 + " does not have the expected public key; ignoring"); 13792 return -1; 13793 } 13794 13795 return pkg.applicationInfo.uid; 13796 } 13797 } 13798 13799 @Override 13800 public void finishPackageInstall(int token, boolean didLaunch) { 13801 enforceSystemOrRoot("Only the system is allowed to finish installs"); 13802 13803 if (DEBUG_INSTALL) { 13804 Slog.v(TAG, "BM finishing package install for " + token); 13805 } 13806 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 13807 13808 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 13809 mHandler.sendMessage(msg); 13810 } 13811 13812 /** 13813 * Get the verification agent timeout. 13814 * 13815 * @return verification timeout in milliseconds 13816 */ 13817 private long getVerificationTimeout() { 13818 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 13819 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 13820 DEFAULT_VERIFICATION_TIMEOUT); 13821 } 13822 13823 /** 13824 * Get the default verification agent response code. 13825 * 13826 * @return default verification response code 13827 */ 13828 private int getDefaultVerificationResponse() { 13829 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13830 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 13831 DEFAULT_VERIFICATION_RESPONSE); 13832 } 13833 13834 /** 13835 * Check whether or not package verification has been enabled. 13836 * 13837 * @return true if verification should be performed 13838 */ 13839 private boolean isVerificationEnabled(int userId, int installFlags) { 13840 if (!DEFAULT_VERIFY_ENABLE) { 13841 return false; 13842 } 13843 // Ephemeral apps don't get the full verification treatment 13844 if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) { 13845 if (DEBUG_EPHEMERAL) { 13846 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 13847 } 13848 return false; 13849 } 13850 13851 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 13852 13853 // Check if installing from ADB 13854 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 13855 // Do not run verification in a test harness environment 13856 if (ActivityManager.isRunningInTestHarness()) { 13857 return false; 13858 } 13859 if (ensureVerifyAppsEnabled) { 13860 return true; 13861 } 13862 // Check if the developer does not want package verification for ADB installs 13863 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13864 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 13865 return false; 13866 } 13867 } 13868 13869 if (ensureVerifyAppsEnabled) { 13870 return true; 13871 } 13872 13873 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13874 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 13875 } 13876 13877 @Override 13878 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 13879 throws RemoteException { 13880 mContext.enforceCallingOrSelfPermission( 13881 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 13882 "Only intentfilter verification agents can verify applications"); 13883 13884 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 13885 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 13886 Binder.getCallingUid(), verificationCode, failedDomains); 13887 msg.arg1 = id; 13888 msg.obj = response; 13889 mHandler.sendMessage(msg); 13890 } 13891 13892 @Override 13893 public int getIntentVerificationStatus(String packageName, int userId) { 13894 synchronized (mPackages) { 13895 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 13896 } 13897 } 13898 13899 @Override 13900 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 13901 mContext.enforceCallingOrSelfPermission( 13902 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13903 13904 boolean result = false; 13905 synchronized (mPackages) { 13906 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 13907 } 13908 if (result) { 13909 scheduleWritePackageRestrictionsLocked(userId); 13910 } 13911 return result; 13912 } 13913 13914 @Override 13915 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 13916 String packageName) { 13917 synchronized (mPackages) { 13918 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 13919 } 13920 } 13921 13922 @Override 13923 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 13924 if (TextUtils.isEmpty(packageName)) { 13925 return ParceledListSlice.emptyList(); 13926 } 13927 synchronized (mPackages) { 13928 PackageParser.Package pkg = mPackages.get(packageName); 13929 if (pkg == null || pkg.activities == null) { 13930 return ParceledListSlice.emptyList(); 13931 } 13932 final int count = pkg.activities.size(); 13933 ArrayList<IntentFilter> result = new ArrayList<>(); 13934 for (int n=0; n<count; n++) { 13935 PackageParser.Activity activity = pkg.activities.get(n); 13936 if (activity.intents != null && activity.intents.size() > 0) { 13937 result.addAll(activity.intents); 13938 } 13939 } 13940 return new ParceledListSlice<>(result); 13941 } 13942 } 13943 13944 @Override 13945 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 13946 mContext.enforceCallingOrSelfPermission( 13947 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13948 13949 synchronized (mPackages) { 13950 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 13951 if (packageName != null) { 13952 result |= updateIntentVerificationStatus(packageName, 13953 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 13954 userId); 13955 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 13956 packageName, userId); 13957 } 13958 return result; 13959 } 13960 } 13961 13962 @Override 13963 public String getDefaultBrowserPackageName(int userId) { 13964 synchronized (mPackages) { 13965 return mSettings.getDefaultBrowserPackageNameLPw(userId); 13966 } 13967 } 13968 13969 /** 13970 * Get the "allow unknown sources" setting. 13971 * 13972 * @return the current "allow unknown sources" setting 13973 */ 13974 private int getUnknownSourcesSettings() { 13975 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 13976 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 13977 -1); 13978 } 13979 13980 @Override 13981 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 13982 final int uid = Binder.getCallingUid(); 13983 // writer 13984 synchronized (mPackages) { 13985 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 13986 if (targetPackageSetting == null) { 13987 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 13988 } 13989 13990 PackageSetting installerPackageSetting; 13991 if (installerPackageName != null) { 13992 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 13993 if (installerPackageSetting == null) { 13994 throw new IllegalArgumentException("Unknown installer package: " 13995 + installerPackageName); 13996 } 13997 } else { 13998 installerPackageSetting = null; 13999 } 14000 14001 Signature[] callerSignature; 14002 Object obj = mSettings.getUserIdLPr(uid); 14003 if (obj != null) { 14004 if (obj instanceof SharedUserSetting) { 14005 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 14006 } else if (obj instanceof PackageSetting) { 14007 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 14008 } else { 14009 throw new SecurityException("Bad object " + obj + " for uid " + uid); 14010 } 14011 } else { 14012 throw new SecurityException("Unknown calling UID: " + uid); 14013 } 14014 14015 // Verify: can't set installerPackageName to a package that is 14016 // not signed with the same cert as the caller. 14017 if (installerPackageSetting != null) { 14018 if (compareSignatures(callerSignature, 14019 installerPackageSetting.signatures.mSignatures) 14020 != PackageManager.SIGNATURE_MATCH) { 14021 throw new SecurityException( 14022 "Caller does not have same cert as new installer package " 14023 + installerPackageName); 14024 } 14025 } 14026 14027 // Verify: if target already has an installer package, it must 14028 // be signed with the same cert as the caller. 14029 if (targetPackageSetting.installerPackageName != null) { 14030 PackageSetting setting = mSettings.mPackages.get( 14031 targetPackageSetting.installerPackageName); 14032 // If the currently set package isn't valid, then it's always 14033 // okay to change it. 14034 if (setting != null) { 14035 if (compareSignatures(callerSignature, 14036 setting.signatures.mSignatures) 14037 != PackageManager.SIGNATURE_MATCH) { 14038 throw new SecurityException( 14039 "Caller does not have same cert as old installer package " 14040 + targetPackageSetting.installerPackageName); 14041 } 14042 } 14043 } 14044 14045 // Okay! 14046 targetPackageSetting.installerPackageName = installerPackageName; 14047 if (installerPackageName != null) { 14048 mSettings.mInstallerPackages.add(installerPackageName); 14049 } 14050 scheduleWriteSettingsLocked(); 14051 } 14052 } 14053 14054 @Override 14055 public void setApplicationCategoryHint(String packageName, int categoryHint, 14056 String callerPackageName) { 14057 mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(), 14058 callerPackageName); 14059 synchronized (mPackages) { 14060 PackageSetting ps = mSettings.mPackages.get(packageName); 14061 if (ps == null) { 14062 throw new IllegalArgumentException("Unknown target package " + packageName); 14063 } 14064 14065 if (!Objects.equals(callerPackageName, ps.installerPackageName)) { 14066 throw new IllegalArgumentException("Calling package " + callerPackageName 14067 + " is not installer for " + packageName); 14068 } 14069 14070 if (ps.categoryHint != categoryHint) { 14071 ps.categoryHint = categoryHint; 14072 scheduleWriteSettingsLocked(); 14073 } 14074 } 14075 } 14076 14077 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 14078 // Queue up an async operation since the package installation may take a little while. 14079 mHandler.post(new Runnable() { 14080 public void run() { 14081 mHandler.removeCallbacks(this); 14082 // Result object to be returned 14083 PackageInstalledInfo res = new PackageInstalledInfo(); 14084 res.setReturnCode(currentStatus); 14085 res.uid = -1; 14086 res.pkg = null; 14087 res.removedInfo = null; 14088 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14089 args.doPreInstall(res.returnCode); 14090 synchronized (mInstallLock) { 14091 installPackageTracedLI(args, res); 14092 } 14093 args.doPostInstall(res.returnCode, res.uid); 14094 } 14095 14096 // A restore should be performed at this point if (a) the install 14097 // succeeded, (b) the operation is not an update, and (c) the new 14098 // package has not opted out of backup participation. 14099 final boolean update = res.removedInfo != null 14100 && res.removedInfo.removedPackage != null; 14101 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 14102 boolean doRestore = !update 14103 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 14104 14105 // Set up the post-install work request bookkeeping. This will be used 14106 // and cleaned up by the post-install event handling regardless of whether 14107 // there's a restore pass performed. Token values are >= 1. 14108 int token; 14109 if (mNextInstallToken < 0) mNextInstallToken = 1; 14110 token = mNextInstallToken++; 14111 14112 PostInstallData data = new PostInstallData(args, res); 14113 mRunningInstalls.put(token, data); 14114 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 14115 14116 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 14117 // Pass responsibility to the Backup Manager. It will perform a 14118 // restore if appropriate, then pass responsibility back to the 14119 // Package Manager to run the post-install observer callbacks 14120 // and broadcasts. 14121 IBackupManager bm = IBackupManager.Stub.asInterface( 14122 ServiceManager.getService(Context.BACKUP_SERVICE)); 14123 if (bm != null) { 14124 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 14125 + " to BM for possible restore"); 14126 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 14127 try { 14128 // TODO: http://b/22388012 14129 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 14130 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 14131 } else { 14132 doRestore = false; 14133 } 14134 } catch (RemoteException e) { 14135 // can't happen; the backup manager is local 14136 } catch (Exception e) { 14137 Slog.e(TAG, "Exception trying to enqueue restore", e); 14138 doRestore = false; 14139 } 14140 } else { 14141 Slog.e(TAG, "Backup Manager not found!"); 14142 doRestore = false; 14143 } 14144 } 14145 14146 if (!doRestore) { 14147 // No restore possible, or the Backup Manager was mysteriously not 14148 // available -- just fire the post-install work request directly. 14149 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 14150 14151 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 14152 14153 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 14154 mHandler.sendMessage(msg); 14155 } 14156 } 14157 }); 14158 } 14159 14160 /** 14161 * Callback from PackageSettings whenever an app is first transitioned out of the 14162 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 14163 * the app was "launched" for a restoreAtInstall operation. Therefore we check 14164 * here whether the app is the target of an ongoing install, and only send the 14165 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 14166 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 14167 * handling. 14168 */ 14169 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 14170 // Serialize this with the rest of the install-process message chain. In the 14171 // restore-at-install case, this Runnable will necessarily run before the 14172 // POST_INSTALL message is processed, so the contents of mRunningInstalls 14173 // are coherent. In the non-restore case, the app has already completed install 14174 // and been launched through some other means, so it is not in a problematic 14175 // state for observers to see the FIRST_LAUNCH signal. 14176 mHandler.post(new Runnable() { 14177 @Override 14178 public void run() { 14179 for (int i = 0; i < mRunningInstalls.size(); i++) { 14180 final PostInstallData data = mRunningInstalls.valueAt(i); 14181 if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14182 continue; 14183 } 14184 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 14185 // right package; but is it for the right user? 14186 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 14187 if (userId == data.res.newUsers[uIndex]) { 14188 if (DEBUG_BACKUP) { 14189 Slog.i(TAG, "Package " + pkgName 14190 + " being restored so deferring FIRST_LAUNCH"); 14191 } 14192 return; 14193 } 14194 } 14195 } 14196 } 14197 // didn't find it, so not being restored 14198 if (DEBUG_BACKUP) { 14199 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 14200 } 14201 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 14202 } 14203 }); 14204 } 14205 14206 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 14207 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 14208 installerPkg, null, userIds); 14209 } 14210 14211 private abstract class HandlerParams { 14212 private static final int MAX_RETRIES = 4; 14213 14214 /** 14215 * Number of times startCopy() has been attempted and had a non-fatal 14216 * error. 14217 */ 14218 private int mRetries = 0; 14219 14220 /** User handle for the user requesting the information or installation. */ 14221 private final UserHandle mUser; 14222 String traceMethod; 14223 int traceCookie; 14224 14225 HandlerParams(UserHandle user) { 14226 mUser = user; 14227 } 14228 14229 UserHandle getUser() { 14230 return mUser; 14231 } 14232 14233 HandlerParams setTraceMethod(String traceMethod) { 14234 this.traceMethod = traceMethod; 14235 return this; 14236 } 14237 14238 HandlerParams setTraceCookie(int traceCookie) { 14239 this.traceCookie = traceCookie; 14240 return this; 14241 } 14242 14243 final boolean startCopy() { 14244 boolean res; 14245 try { 14246 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 14247 14248 if (++mRetries > MAX_RETRIES) { 14249 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 14250 mHandler.sendEmptyMessage(MCS_GIVE_UP); 14251 handleServiceError(); 14252 return false; 14253 } else { 14254 handleStartCopy(); 14255 res = true; 14256 } 14257 } catch (RemoteException e) { 14258 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 14259 mHandler.sendEmptyMessage(MCS_RECONNECT); 14260 res = false; 14261 } 14262 handleReturnCode(); 14263 return res; 14264 } 14265 14266 final void serviceError() { 14267 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 14268 handleServiceError(); 14269 handleReturnCode(); 14270 } 14271 14272 abstract void handleStartCopy() throws RemoteException; 14273 abstract void handleServiceError(); 14274 abstract void handleReturnCode(); 14275 } 14276 14277 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 14278 for (File path : paths) { 14279 try { 14280 mcs.clearDirectory(path.getAbsolutePath()); 14281 } catch (RemoteException e) { 14282 } 14283 } 14284 } 14285 14286 static class OriginInfo { 14287 /** 14288 * Location where install is coming from, before it has been 14289 * copied/renamed into place. This could be a single monolithic APK 14290 * file, or a cluster directory. This location may be untrusted. 14291 */ 14292 final File file; 14293 final String cid; 14294 14295 /** 14296 * Flag indicating that {@link #file} or {@link #cid} has already been 14297 * staged, meaning downstream users don't need to defensively copy the 14298 * contents. 14299 */ 14300 final boolean staged; 14301 14302 /** 14303 * Flag indicating that {@link #file} or {@link #cid} is an already 14304 * installed app that is being moved. 14305 */ 14306 final boolean existing; 14307 14308 final String resolvedPath; 14309 final File resolvedFile; 14310 14311 static OriginInfo fromNothing() { 14312 return new OriginInfo(null, null, false, false); 14313 } 14314 14315 static OriginInfo fromUntrustedFile(File file) { 14316 return new OriginInfo(file, null, false, false); 14317 } 14318 14319 static OriginInfo fromExistingFile(File file) { 14320 return new OriginInfo(file, null, false, true); 14321 } 14322 14323 static OriginInfo fromStagedFile(File file) { 14324 return new OriginInfo(file, null, true, false); 14325 } 14326 14327 static OriginInfo fromStagedContainer(String cid) { 14328 return new OriginInfo(null, cid, true, false); 14329 } 14330 14331 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 14332 this.file = file; 14333 this.cid = cid; 14334 this.staged = staged; 14335 this.existing = existing; 14336 14337 if (cid != null) { 14338 resolvedPath = PackageHelper.getSdDir(cid); 14339 resolvedFile = new File(resolvedPath); 14340 } else if (file != null) { 14341 resolvedPath = file.getAbsolutePath(); 14342 resolvedFile = file; 14343 } else { 14344 resolvedPath = null; 14345 resolvedFile = null; 14346 } 14347 } 14348 } 14349 14350 static class MoveInfo { 14351 final int moveId; 14352 final String fromUuid; 14353 final String toUuid; 14354 final String packageName; 14355 final String dataAppName; 14356 final int appId; 14357 final String seinfo; 14358 final int targetSdkVersion; 14359 14360 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 14361 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 14362 this.moveId = moveId; 14363 this.fromUuid = fromUuid; 14364 this.toUuid = toUuid; 14365 this.packageName = packageName; 14366 this.dataAppName = dataAppName; 14367 this.appId = appId; 14368 this.seinfo = seinfo; 14369 this.targetSdkVersion = targetSdkVersion; 14370 } 14371 } 14372 14373 static class VerificationInfo { 14374 /** A constant used to indicate that a uid value is not present. */ 14375 public static final int NO_UID = -1; 14376 14377 /** URI referencing where the package was downloaded from. */ 14378 final Uri originatingUri; 14379 14380 /** HTTP referrer URI associated with the originatingURI. */ 14381 final Uri referrer; 14382 14383 /** UID of the application that the install request originated from. */ 14384 final int originatingUid; 14385 14386 /** UID of application requesting the install */ 14387 final int installerUid; 14388 14389 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 14390 this.originatingUri = originatingUri; 14391 this.referrer = referrer; 14392 this.originatingUid = originatingUid; 14393 this.installerUid = installerUid; 14394 } 14395 } 14396 14397 class InstallParams extends HandlerParams { 14398 final OriginInfo origin; 14399 final MoveInfo move; 14400 final IPackageInstallObserver2 observer; 14401 int installFlags; 14402 final String installerPackageName; 14403 final String volumeUuid; 14404 private InstallArgs mArgs; 14405 private int mRet; 14406 final String packageAbiOverride; 14407 final String[] grantedRuntimePermissions; 14408 final VerificationInfo verificationInfo; 14409 final Certificate[][] certificates; 14410 final int installReason; 14411 14412 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 14413 int installFlags, String installerPackageName, String volumeUuid, 14414 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 14415 String[] grantedPermissions, Certificate[][] certificates, int installReason) { 14416 super(user); 14417 this.origin = origin; 14418 this.move = move; 14419 this.observer = observer; 14420 this.installFlags = installFlags; 14421 this.installerPackageName = installerPackageName; 14422 this.volumeUuid = volumeUuid; 14423 this.verificationInfo = verificationInfo; 14424 this.packageAbiOverride = packageAbiOverride; 14425 this.grantedRuntimePermissions = grantedPermissions; 14426 this.certificates = certificates; 14427 this.installReason = installReason; 14428 } 14429 14430 @Override 14431 public String toString() { 14432 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 14433 + " file=" + origin.file + " cid=" + origin.cid + "}"; 14434 } 14435 14436 private int installLocationPolicy(PackageInfoLite pkgLite) { 14437 String packageName = pkgLite.packageName; 14438 int installLocation = pkgLite.installLocation; 14439 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14440 // reader 14441 synchronized (mPackages) { 14442 // Currently installed package which the new package is attempting to replace or 14443 // null if no such package is installed. 14444 PackageParser.Package installedPkg = mPackages.get(packageName); 14445 // Package which currently owns the data which the new package will own if installed. 14446 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 14447 // will be null whereas dataOwnerPkg will contain information about the package 14448 // which was uninstalled while keeping its data. 14449 PackageParser.Package dataOwnerPkg = installedPkg; 14450 if (dataOwnerPkg == null) { 14451 PackageSetting ps = mSettings.mPackages.get(packageName); 14452 if (ps != null) { 14453 dataOwnerPkg = ps.pkg; 14454 } 14455 } 14456 14457 if (dataOwnerPkg != null) { 14458 // If installed, the package will get access to data left on the device by its 14459 // predecessor. As a security measure, this is permited only if this is not a 14460 // version downgrade or if the predecessor package is marked as debuggable and 14461 // a downgrade is explicitly requested. 14462 // 14463 // On debuggable platform builds, downgrades are permitted even for 14464 // non-debuggable packages to make testing easier. Debuggable platform builds do 14465 // not offer security guarantees and thus it's OK to disable some security 14466 // mechanisms to make debugging/testing easier on those builds. However, even on 14467 // debuggable builds downgrades of packages are permitted only if requested via 14468 // installFlags. This is because we aim to keep the behavior of debuggable 14469 // platform builds as close as possible to the behavior of non-debuggable 14470 // platform builds. 14471 final boolean downgradeRequested = 14472 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 14473 final boolean packageDebuggable = 14474 (dataOwnerPkg.applicationInfo.flags 14475 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 14476 final boolean downgradePermitted = 14477 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 14478 if (!downgradePermitted) { 14479 try { 14480 checkDowngrade(dataOwnerPkg, pkgLite); 14481 } catch (PackageManagerException e) { 14482 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 14483 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 14484 } 14485 } 14486 } 14487 14488 if (installedPkg != null) { 14489 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14490 // Check for updated system application. 14491 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 14492 if (onSd) { 14493 Slog.w(TAG, "Cannot install update to system app on sdcard"); 14494 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 14495 } 14496 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14497 } else { 14498 if (onSd) { 14499 // Install flag overrides everything. 14500 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14501 } 14502 // If current upgrade specifies particular preference 14503 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 14504 // Application explicitly specified internal. 14505 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14506 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 14507 // App explictly prefers external. Let policy decide 14508 } else { 14509 // Prefer previous location 14510 if (isExternal(installedPkg)) { 14511 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14512 } 14513 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14514 } 14515 } 14516 } else { 14517 // Invalid install. Return error code 14518 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 14519 } 14520 } 14521 } 14522 // All the special cases have been taken care of. 14523 // Return result based on recommended install location. 14524 if (onSd) { 14525 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14526 } 14527 return pkgLite.recommendedInstallLocation; 14528 } 14529 14530 /* 14531 * Invoke remote method to get package information and install 14532 * location values. Override install location based on default 14533 * policy if needed and then create install arguments based 14534 * on the install location. 14535 */ 14536 public void handleStartCopy() throws RemoteException { 14537 int ret = PackageManager.INSTALL_SUCCEEDED; 14538 14539 // If we're already staged, we've firmly committed to an install location 14540 if (origin.staged) { 14541 if (origin.file != null) { 14542 installFlags |= PackageManager.INSTALL_INTERNAL; 14543 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 14544 } else if (origin.cid != null) { 14545 installFlags |= PackageManager.INSTALL_EXTERNAL; 14546 installFlags &= ~PackageManager.INSTALL_INTERNAL; 14547 } else { 14548 throw new IllegalStateException("Invalid stage location"); 14549 } 14550 } 14551 14552 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14553 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 14554 final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 14555 PackageInfoLite pkgLite = null; 14556 14557 if (onInt && onSd) { 14558 // Check if both bits are set. 14559 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 14560 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14561 } else if (onSd && ephemeral) { 14562 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 14563 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14564 } else { 14565 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 14566 packageAbiOverride); 14567 14568 if (DEBUG_EPHEMERAL && ephemeral) { 14569 Slog.v(TAG, "pkgLite for install: " + pkgLite); 14570 } 14571 14572 /* 14573 * If we have too little free space, try to free cache 14574 * before giving up. 14575 */ 14576 if (!origin.staged && pkgLite.recommendedInstallLocation 14577 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 14578 // TODO: focus freeing disk space on the target device 14579 final StorageManager storage = StorageManager.from(mContext); 14580 final long lowThreshold = storage.getStorageLowBytes( 14581 Environment.getDataDirectory()); 14582 14583 final long sizeBytes = mContainerService.calculateInstalledSize( 14584 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 14585 14586 try { 14587 mInstaller.freeCache(null, sizeBytes + lowThreshold, 0); 14588 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 14589 installFlags, packageAbiOverride); 14590 } catch (InstallerException e) { 14591 Slog.w(TAG, "Failed to free cache", e); 14592 } 14593 14594 /* 14595 * The cache free must have deleted the file we 14596 * downloaded to install. 14597 * 14598 * TODO: fix the "freeCache" call to not delete 14599 * the file we care about. 14600 */ 14601 if (pkgLite.recommendedInstallLocation 14602 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 14603 pkgLite.recommendedInstallLocation 14604 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 14605 } 14606 } 14607 } 14608 14609 if (ret == PackageManager.INSTALL_SUCCEEDED) { 14610 int loc = pkgLite.recommendedInstallLocation; 14611 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 14612 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14613 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 14614 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 14615 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 14616 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 14617 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 14618 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 14619 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 14620 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 14621 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 14622 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 14623 } else { 14624 // Override with defaults if needed. 14625 loc = installLocationPolicy(pkgLite); 14626 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 14627 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 14628 } else if (!onSd && !onInt) { 14629 // Override install location with flags 14630 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 14631 // Set the flag to install on external media. 14632 installFlags |= PackageManager.INSTALL_EXTERNAL; 14633 installFlags &= ~PackageManager.INSTALL_INTERNAL; 14634 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 14635 if (DEBUG_EPHEMERAL) { 14636 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 14637 } 14638 installFlags |= PackageManager.INSTALL_INSTANT_APP; 14639 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 14640 |PackageManager.INSTALL_INTERNAL); 14641 } else { 14642 // Make sure the flag for installing on external 14643 // media is unset 14644 installFlags |= PackageManager.INSTALL_INTERNAL; 14645 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 14646 } 14647 } 14648 } 14649 } 14650 14651 final InstallArgs args = createInstallArgs(this); 14652 mArgs = args; 14653 14654 if (ret == PackageManager.INSTALL_SUCCEEDED) { 14655 // TODO: http://b/22976637 14656 // Apps installed for "all" users use the device owner to verify the app 14657 UserHandle verifierUser = getUser(); 14658 if (verifierUser == UserHandle.ALL) { 14659 verifierUser = UserHandle.SYSTEM; 14660 } 14661 14662 /* 14663 * Determine if we have any installed package verifiers. If we 14664 * do, then we'll defer to them to verify the packages. 14665 */ 14666 final int requiredUid = mRequiredVerifierPackage == null ? -1 14667 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 14668 verifierUser.getIdentifier()); 14669 if (!origin.existing && requiredUid != -1 14670 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 14671 final Intent verification = new Intent( 14672 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 14673 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 14674 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 14675 PACKAGE_MIME_TYPE); 14676 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 14677 14678 // Query all live verifiers based on current user state 14679 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 14680 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 14681 14682 if (DEBUG_VERIFY) { 14683 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 14684 + verification.toString() + " with " + pkgLite.verifiers.length 14685 + " optional verifiers"); 14686 } 14687 14688 final int verificationId = mPendingVerificationToken++; 14689 14690 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 14691 14692 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 14693 installerPackageName); 14694 14695 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 14696 installFlags); 14697 14698 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 14699 pkgLite.packageName); 14700 14701 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 14702 pkgLite.versionCode); 14703 14704 if (verificationInfo != null) { 14705 if (verificationInfo.originatingUri != null) { 14706 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 14707 verificationInfo.originatingUri); 14708 } 14709 if (verificationInfo.referrer != null) { 14710 verification.putExtra(Intent.EXTRA_REFERRER, 14711 verificationInfo.referrer); 14712 } 14713 if (verificationInfo.originatingUid >= 0) { 14714 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 14715 verificationInfo.originatingUid); 14716 } 14717 if (verificationInfo.installerUid >= 0) { 14718 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 14719 verificationInfo.installerUid); 14720 } 14721 } 14722 14723 final PackageVerificationState verificationState = new PackageVerificationState( 14724 requiredUid, args); 14725 14726 mPendingVerification.append(verificationId, verificationState); 14727 14728 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 14729 receivers, verificationState); 14730 14731 DeviceIdleController.LocalService idleController = getDeviceIdleController(); 14732 final long idleDuration = getVerificationTimeout(); 14733 14734 /* 14735 * If any sufficient verifiers were listed in the package 14736 * manifest, attempt to ask them. 14737 */ 14738 if (sufficientVerifiers != null) { 14739 final int N = sufficientVerifiers.size(); 14740 if (N == 0) { 14741 Slog.i(TAG, "Additional verifiers required, but none installed."); 14742 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 14743 } else { 14744 for (int i = 0; i < N; i++) { 14745 final ComponentName verifierComponent = sufficientVerifiers.get(i); 14746 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 14747 verifierComponent.getPackageName(), idleDuration, 14748 verifierUser.getIdentifier(), false, "package verifier"); 14749 14750 final Intent sufficientIntent = new Intent(verification); 14751 sufficientIntent.setComponent(verifierComponent); 14752 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 14753 } 14754 } 14755 } 14756 14757 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 14758 mRequiredVerifierPackage, receivers); 14759 if (ret == PackageManager.INSTALL_SUCCEEDED 14760 && mRequiredVerifierPackage != null) { 14761 Trace.asyncTraceBegin( 14762 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 14763 /* 14764 * Send the intent to the required verification agent, 14765 * but only start the verification timeout after the 14766 * target BroadcastReceivers have run. 14767 */ 14768 verification.setComponent(requiredVerifierComponent); 14769 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 14770 requiredVerifierComponent.getPackageName(), idleDuration, 14771 verifierUser.getIdentifier(), false, "package verifier"); 14772 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 14773 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 14774 new BroadcastReceiver() { 14775 @Override 14776 public void onReceive(Context context, Intent intent) { 14777 final Message msg = mHandler 14778 .obtainMessage(CHECK_PENDING_VERIFICATION); 14779 msg.arg1 = verificationId; 14780 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 14781 } 14782 }, null, 0, null, null); 14783 14784 /* 14785 * We don't want the copy to proceed until verification 14786 * succeeds, so null out this field. 14787 */ 14788 mArgs = null; 14789 } 14790 } else { 14791 /* 14792 * No package verification is enabled, so immediately start 14793 * the remote call to initiate copy using temporary file. 14794 */ 14795 ret = args.copyApk(mContainerService, true); 14796 } 14797 } 14798 14799 mRet = ret; 14800 } 14801 14802 @Override 14803 void handleReturnCode() { 14804 // If mArgs is null, then MCS couldn't be reached. When it 14805 // reconnects, it will try again to install. At that point, this 14806 // will succeed. 14807 if (mArgs != null) { 14808 processPendingInstall(mArgs, mRet); 14809 } 14810 } 14811 14812 @Override 14813 void handleServiceError() { 14814 mArgs = createInstallArgs(this); 14815 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 14816 } 14817 14818 public boolean isForwardLocked() { 14819 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 14820 } 14821 } 14822 14823 /** 14824 * Used during creation of InstallArgs 14825 * 14826 * @param installFlags package installation flags 14827 * @return true if should be installed on external storage 14828 */ 14829 private static boolean installOnExternalAsec(int installFlags) { 14830 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 14831 return false; 14832 } 14833 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 14834 return true; 14835 } 14836 return false; 14837 } 14838 14839 /** 14840 * Used during creation of InstallArgs 14841 * 14842 * @param installFlags package installation flags 14843 * @return true if should be installed as forward locked 14844 */ 14845 private static boolean installForwardLocked(int installFlags) { 14846 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 14847 } 14848 14849 private InstallArgs createInstallArgs(InstallParams params) { 14850 if (params.move != null) { 14851 return new MoveInstallArgs(params); 14852 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 14853 return new AsecInstallArgs(params); 14854 } else { 14855 return new FileInstallArgs(params); 14856 } 14857 } 14858 14859 /** 14860 * Create args that describe an existing installed package. Typically used 14861 * when cleaning up old installs, or used as a move source. 14862 */ 14863 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 14864 String resourcePath, String[] instructionSets) { 14865 final boolean isInAsec; 14866 if (installOnExternalAsec(installFlags)) { 14867 /* Apps on SD card are always in ASEC containers. */ 14868 isInAsec = true; 14869 } else if (installForwardLocked(installFlags) 14870 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 14871 /* 14872 * Forward-locked apps are only in ASEC containers if they're the 14873 * new style 14874 */ 14875 isInAsec = true; 14876 } else { 14877 isInAsec = false; 14878 } 14879 14880 if (isInAsec) { 14881 return new AsecInstallArgs(codePath, instructionSets, 14882 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 14883 } else { 14884 return new FileInstallArgs(codePath, resourcePath, instructionSets); 14885 } 14886 } 14887 14888 static abstract class InstallArgs { 14889 /** @see InstallParams#origin */ 14890 final OriginInfo origin; 14891 /** @see InstallParams#move */ 14892 final MoveInfo move; 14893 14894 final IPackageInstallObserver2 observer; 14895 // Always refers to PackageManager flags only 14896 final int installFlags; 14897 final String installerPackageName; 14898 final String volumeUuid; 14899 final UserHandle user; 14900 final String abiOverride; 14901 final String[] installGrantPermissions; 14902 /** If non-null, drop an async trace when the install completes */ 14903 final String traceMethod; 14904 final int traceCookie; 14905 final Certificate[][] certificates; 14906 final int installReason; 14907 14908 // The list of instruction sets supported by this app. This is currently 14909 // only used during the rmdex() phase to clean up resources. We can get rid of this 14910 // if we move dex files under the common app path. 14911 /* nullable */ String[] instructionSets; 14912 14913 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 14914 int installFlags, String installerPackageName, String volumeUuid, 14915 UserHandle user, String[] instructionSets, 14916 String abiOverride, String[] installGrantPermissions, 14917 String traceMethod, int traceCookie, Certificate[][] certificates, 14918 int installReason) { 14919 this.origin = origin; 14920 this.move = move; 14921 this.installFlags = installFlags; 14922 this.observer = observer; 14923 this.installerPackageName = installerPackageName; 14924 this.volumeUuid = volumeUuid; 14925 this.user = user; 14926 this.instructionSets = instructionSets; 14927 this.abiOverride = abiOverride; 14928 this.installGrantPermissions = installGrantPermissions; 14929 this.traceMethod = traceMethod; 14930 this.traceCookie = traceCookie; 14931 this.certificates = certificates; 14932 this.installReason = installReason; 14933 } 14934 14935 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 14936 abstract int doPreInstall(int status); 14937 14938 /** 14939 * Rename package into final resting place. All paths on the given 14940 * scanned package should be updated to reflect the rename. 14941 */ 14942 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 14943 abstract int doPostInstall(int status, int uid); 14944 14945 /** @see PackageSettingBase#codePathString */ 14946 abstract String getCodePath(); 14947 /** @see PackageSettingBase#resourcePathString */ 14948 abstract String getResourcePath(); 14949 14950 // Need installer lock especially for dex file removal. 14951 abstract void cleanUpResourcesLI(); 14952 abstract boolean doPostDeleteLI(boolean delete); 14953 14954 /** 14955 * Called before the source arguments are copied. This is used mostly 14956 * for MoveParams when it needs to read the source file to put it in the 14957 * destination. 14958 */ 14959 int doPreCopy() { 14960 return PackageManager.INSTALL_SUCCEEDED; 14961 } 14962 14963 /** 14964 * Called after the source arguments are copied. This is used mostly for 14965 * MoveParams when it needs to read the source file to put it in the 14966 * destination. 14967 */ 14968 int doPostCopy(int uid) { 14969 return PackageManager.INSTALL_SUCCEEDED; 14970 } 14971 14972 protected boolean isFwdLocked() { 14973 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 14974 } 14975 14976 protected boolean isExternalAsec() { 14977 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14978 } 14979 14980 protected boolean isEphemeral() { 14981 return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 14982 } 14983 14984 UserHandle getUser() { 14985 return user; 14986 } 14987 } 14988 14989 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 14990 if (!allCodePaths.isEmpty()) { 14991 if (instructionSets == null) { 14992 throw new IllegalStateException("instructionSet == null"); 14993 } 14994 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 14995 for (String codePath : allCodePaths) { 14996 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 14997 try { 14998 mInstaller.rmdex(codePath, dexCodeInstructionSet); 14999 } catch (InstallerException ignored) { 15000 } 15001 } 15002 } 15003 } 15004 } 15005 15006 /** 15007 * Logic to handle installation of non-ASEC applications, including copying 15008 * and renaming logic. 15009 */ 15010 class FileInstallArgs extends InstallArgs { 15011 private File codeFile; 15012 private File resourceFile; 15013 15014 // Example topology: 15015 // /data/app/com.example/base.apk 15016 // /data/app/com.example/split_foo.apk 15017 // /data/app/com.example/lib/arm/libfoo.so 15018 // /data/app/com.example/lib/arm64/libfoo.so 15019 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 15020 15021 /** New install */ 15022 FileInstallArgs(InstallParams params) { 15023 super(params.origin, params.move, params.observer, params.installFlags, 15024 params.installerPackageName, params.volumeUuid, 15025 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 15026 params.grantedRuntimePermissions, 15027 params.traceMethod, params.traceCookie, params.certificates, 15028 params.installReason); 15029 if (isFwdLocked()) { 15030 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 15031 } 15032 } 15033 15034 /** Existing install */ 15035 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 15036 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 15037 null, null, null, 0, null /*certificates*/, 15038 PackageManager.INSTALL_REASON_UNKNOWN); 15039 this.codeFile = (codePath != null) ? new File(codePath) : null; 15040 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 15041 } 15042 15043 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 15044 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 15045 try { 15046 return doCopyApk(imcs, temp); 15047 } finally { 15048 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15049 } 15050 } 15051 15052 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 15053 if (origin.staged) { 15054 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 15055 codeFile = origin.file; 15056 resourceFile = origin.file; 15057 return PackageManager.INSTALL_SUCCEEDED; 15058 } 15059 15060 try { 15061 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 15062 final File tempDir = 15063 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 15064 codeFile = tempDir; 15065 resourceFile = tempDir; 15066 } catch (IOException e) { 15067 Slog.w(TAG, "Failed to create copy file: " + e); 15068 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 15069 } 15070 15071 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 15072 @Override 15073 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 15074 if (!FileUtils.isValidExtFilename(name)) { 15075 throw new IllegalArgumentException("Invalid filename: " + name); 15076 } 15077 try { 15078 final File file = new File(codeFile, name); 15079 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 15080 O_RDWR | O_CREAT, 0644); 15081 Os.chmod(file.getAbsolutePath(), 0644); 15082 return new ParcelFileDescriptor(fd); 15083 } catch (ErrnoException e) { 15084 throw new RemoteException("Failed to open: " + e.getMessage()); 15085 } 15086 } 15087 }; 15088 15089 int ret = PackageManager.INSTALL_SUCCEEDED; 15090 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 15091 if (ret != PackageManager.INSTALL_SUCCEEDED) { 15092 Slog.e(TAG, "Failed to copy package"); 15093 return ret; 15094 } 15095 15096 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 15097 NativeLibraryHelper.Handle handle = null; 15098 try { 15099 handle = NativeLibraryHelper.Handle.create(codeFile); 15100 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 15101 abiOverride); 15102 } catch (IOException e) { 15103 Slog.e(TAG, "Copying native libraries failed", e); 15104 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15105 } finally { 15106 IoUtils.closeQuietly(handle); 15107 } 15108 15109 return ret; 15110 } 15111 15112 int doPreInstall(int status) { 15113 if (status != PackageManager.INSTALL_SUCCEEDED) { 15114 cleanUp(); 15115 } 15116 return status; 15117 } 15118 15119 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15120 if (status != PackageManager.INSTALL_SUCCEEDED) { 15121 cleanUp(); 15122 return false; 15123 } 15124 15125 final File targetDir = codeFile.getParentFile(); 15126 final File beforeCodeFile = codeFile; 15127 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 15128 15129 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 15130 try { 15131 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 15132 } catch (ErrnoException e) { 15133 Slog.w(TAG, "Failed to rename", e); 15134 return false; 15135 } 15136 15137 if (!SELinux.restoreconRecursive(afterCodeFile)) { 15138 Slog.w(TAG, "Failed to restorecon"); 15139 return false; 15140 } 15141 15142 // Reflect the rename internally 15143 codeFile = afterCodeFile; 15144 resourceFile = afterCodeFile; 15145 15146 // Reflect the rename in scanned details 15147 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 15148 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 15149 afterCodeFile, pkg.baseCodePath)); 15150 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 15151 afterCodeFile, pkg.splitCodePaths)); 15152 15153 // Reflect the rename in app info 15154 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15155 pkg.setApplicationInfoCodePath(pkg.codePath); 15156 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15157 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15158 pkg.setApplicationInfoResourcePath(pkg.codePath); 15159 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15160 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15161 15162 return true; 15163 } 15164 15165 int doPostInstall(int status, int uid) { 15166 if (status != PackageManager.INSTALL_SUCCEEDED) { 15167 cleanUp(); 15168 } 15169 return status; 15170 } 15171 15172 @Override 15173 String getCodePath() { 15174 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 15175 } 15176 15177 @Override 15178 String getResourcePath() { 15179 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 15180 } 15181 15182 private boolean cleanUp() { 15183 if (codeFile == null || !codeFile.exists()) { 15184 return false; 15185 } 15186 15187 removeCodePathLI(codeFile); 15188 15189 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 15190 resourceFile.delete(); 15191 } 15192 15193 return true; 15194 } 15195 15196 void cleanUpResourcesLI() { 15197 // Try enumerating all code paths before deleting 15198 List<String> allCodePaths = Collections.EMPTY_LIST; 15199 if (codeFile != null && codeFile.exists()) { 15200 try { 15201 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 15202 allCodePaths = pkg.getAllCodePaths(); 15203 } catch (PackageParserException e) { 15204 // Ignored; we tried our best 15205 } 15206 } 15207 15208 cleanUp(); 15209 removeDexFiles(allCodePaths, instructionSets); 15210 } 15211 15212 boolean doPostDeleteLI(boolean delete) { 15213 // XXX err, shouldn't we respect the delete flag? 15214 cleanUpResourcesLI(); 15215 return true; 15216 } 15217 } 15218 15219 private boolean isAsecExternal(String cid) { 15220 final String asecPath = PackageHelper.getSdFilesystem(cid); 15221 return !asecPath.startsWith(mAsecInternalPath); 15222 } 15223 15224 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 15225 PackageManagerException { 15226 if (copyRet < 0) { 15227 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 15228 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 15229 throw new PackageManagerException(copyRet, message); 15230 } 15231 } 15232 } 15233 15234 /** 15235 * Extract the StorageManagerService "container ID" from the full code path of an 15236 * .apk. 15237 */ 15238 static String cidFromCodePath(String fullCodePath) { 15239 int eidx = fullCodePath.lastIndexOf("/"); 15240 String subStr1 = fullCodePath.substring(0, eidx); 15241 int sidx = subStr1.lastIndexOf("/"); 15242 return subStr1.substring(sidx+1, eidx); 15243 } 15244 15245 /** 15246 * Logic to handle installation of ASEC applications, including copying and 15247 * renaming logic. 15248 */ 15249 class AsecInstallArgs extends InstallArgs { 15250 static final String RES_FILE_NAME = "pkg.apk"; 15251 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 15252 15253 String cid; 15254 String packagePath; 15255 String resourcePath; 15256 15257 /** New install */ 15258 AsecInstallArgs(InstallParams params) { 15259 super(params.origin, params.move, params.observer, params.installFlags, 15260 params.installerPackageName, params.volumeUuid, 15261 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 15262 params.grantedRuntimePermissions, 15263 params.traceMethod, params.traceCookie, params.certificates, 15264 params.installReason); 15265 } 15266 15267 /** Existing install */ 15268 AsecInstallArgs(String fullCodePath, String[] instructionSets, 15269 boolean isExternal, boolean isForwardLocked) { 15270 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 15271 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 15272 instructionSets, null, null, null, 0, null /*certificates*/, 15273 PackageManager.INSTALL_REASON_UNKNOWN); 15274 // Hackily pretend we're still looking at a full code path 15275 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 15276 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 15277 } 15278 15279 // Extract cid from fullCodePath 15280 int eidx = fullCodePath.lastIndexOf("/"); 15281 String subStr1 = fullCodePath.substring(0, eidx); 15282 int sidx = subStr1.lastIndexOf("/"); 15283 cid = subStr1.substring(sidx+1, eidx); 15284 setMountPath(subStr1); 15285 } 15286 15287 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 15288 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 15289 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 15290 instructionSets, null, null, null, 0, null /*certificates*/, 15291 PackageManager.INSTALL_REASON_UNKNOWN); 15292 this.cid = cid; 15293 setMountPath(PackageHelper.getSdDir(cid)); 15294 } 15295 15296 void createCopyFile() { 15297 cid = mInstallerService.allocateExternalStageCidLegacy(); 15298 } 15299 15300 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 15301 if (origin.staged && origin.cid != null) { 15302 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 15303 cid = origin.cid; 15304 setMountPath(PackageHelper.getSdDir(cid)); 15305 return PackageManager.INSTALL_SUCCEEDED; 15306 } 15307 15308 if (temp) { 15309 createCopyFile(); 15310 } else { 15311 /* 15312 * Pre-emptively destroy the container since it's destroyed if 15313 * copying fails due to it existing anyway. 15314 */ 15315 PackageHelper.destroySdDir(cid); 15316 } 15317 15318 final String newMountPath = imcs.copyPackageToContainer( 15319 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 15320 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 15321 15322 if (newMountPath != null) { 15323 setMountPath(newMountPath); 15324 return PackageManager.INSTALL_SUCCEEDED; 15325 } else { 15326 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15327 } 15328 } 15329 15330 @Override 15331 String getCodePath() { 15332 return packagePath; 15333 } 15334 15335 @Override 15336 String getResourcePath() { 15337 return resourcePath; 15338 } 15339 15340 int doPreInstall(int status) { 15341 if (status != PackageManager.INSTALL_SUCCEEDED) { 15342 // Destroy container 15343 PackageHelper.destroySdDir(cid); 15344 } else { 15345 boolean mounted = PackageHelper.isContainerMounted(cid); 15346 if (!mounted) { 15347 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 15348 Process.SYSTEM_UID); 15349 if (newMountPath != null) { 15350 setMountPath(newMountPath); 15351 } else { 15352 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15353 } 15354 } 15355 } 15356 return status; 15357 } 15358 15359 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15360 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 15361 String newMountPath = null; 15362 if (PackageHelper.isContainerMounted(cid)) { 15363 // Unmount the container 15364 if (!PackageHelper.unMountSdDir(cid)) { 15365 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 15366 return false; 15367 } 15368 } 15369 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 15370 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 15371 " which might be stale. Will try to clean up."); 15372 // Clean up the stale container and proceed to recreate. 15373 if (!PackageHelper.destroySdDir(newCacheId)) { 15374 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 15375 return false; 15376 } 15377 // Successfully cleaned up stale container. Try to rename again. 15378 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 15379 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 15380 + " inspite of cleaning it up."); 15381 return false; 15382 } 15383 } 15384 if (!PackageHelper.isContainerMounted(newCacheId)) { 15385 Slog.w(TAG, "Mounting container " + newCacheId); 15386 newMountPath = PackageHelper.mountSdDir(newCacheId, 15387 getEncryptKey(), Process.SYSTEM_UID); 15388 } else { 15389 newMountPath = PackageHelper.getSdDir(newCacheId); 15390 } 15391 if (newMountPath == null) { 15392 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 15393 return false; 15394 } 15395 Log.i(TAG, "Succesfully renamed " + cid + 15396 " to " + newCacheId + 15397 " at new path: " + newMountPath); 15398 cid = newCacheId; 15399 15400 final File beforeCodeFile = new File(packagePath); 15401 setMountPath(newMountPath); 15402 final File afterCodeFile = new File(packagePath); 15403 15404 // Reflect the rename in scanned details 15405 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 15406 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 15407 afterCodeFile, pkg.baseCodePath)); 15408 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 15409 afterCodeFile, pkg.splitCodePaths)); 15410 15411 // Reflect the rename in app info 15412 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15413 pkg.setApplicationInfoCodePath(pkg.codePath); 15414 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15415 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15416 pkg.setApplicationInfoResourcePath(pkg.codePath); 15417 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15418 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15419 15420 return true; 15421 } 15422 15423 private void setMountPath(String mountPath) { 15424 final File mountFile = new File(mountPath); 15425 15426 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 15427 if (monolithicFile.exists()) { 15428 packagePath = monolithicFile.getAbsolutePath(); 15429 if (isFwdLocked()) { 15430 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 15431 } else { 15432 resourcePath = packagePath; 15433 } 15434 } else { 15435 packagePath = mountFile.getAbsolutePath(); 15436 resourcePath = packagePath; 15437 } 15438 } 15439 15440 int doPostInstall(int status, int uid) { 15441 if (status != PackageManager.INSTALL_SUCCEEDED) { 15442 cleanUp(); 15443 } else { 15444 final int groupOwner; 15445 final String protectedFile; 15446 if (isFwdLocked()) { 15447 groupOwner = UserHandle.getSharedAppGid(uid); 15448 protectedFile = RES_FILE_NAME; 15449 } else { 15450 groupOwner = -1; 15451 protectedFile = null; 15452 } 15453 15454 if (uid < Process.FIRST_APPLICATION_UID 15455 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 15456 Slog.e(TAG, "Failed to finalize " + cid); 15457 PackageHelper.destroySdDir(cid); 15458 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15459 } 15460 15461 boolean mounted = PackageHelper.isContainerMounted(cid); 15462 if (!mounted) { 15463 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 15464 } 15465 } 15466 return status; 15467 } 15468 15469 private void cleanUp() { 15470 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 15471 15472 // Destroy secure container 15473 PackageHelper.destroySdDir(cid); 15474 } 15475 15476 private List<String> getAllCodePaths() { 15477 final File codeFile = new File(getCodePath()); 15478 if (codeFile != null && codeFile.exists()) { 15479 try { 15480 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 15481 return pkg.getAllCodePaths(); 15482 } catch (PackageParserException e) { 15483 // Ignored; we tried our best 15484 } 15485 } 15486 return Collections.EMPTY_LIST; 15487 } 15488 15489 void cleanUpResourcesLI() { 15490 // Enumerate all code paths before deleting 15491 cleanUpResourcesLI(getAllCodePaths()); 15492 } 15493 15494 private void cleanUpResourcesLI(List<String> allCodePaths) { 15495 cleanUp(); 15496 removeDexFiles(allCodePaths, instructionSets); 15497 } 15498 15499 String getPackageName() { 15500 return getAsecPackageName(cid); 15501 } 15502 15503 boolean doPostDeleteLI(boolean delete) { 15504 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 15505 final List<String> allCodePaths = getAllCodePaths(); 15506 boolean mounted = PackageHelper.isContainerMounted(cid); 15507 if (mounted) { 15508 // Unmount first 15509 if (PackageHelper.unMountSdDir(cid)) { 15510 mounted = false; 15511 } 15512 } 15513 if (!mounted && delete) { 15514 cleanUpResourcesLI(allCodePaths); 15515 } 15516 return !mounted; 15517 } 15518 15519 @Override 15520 int doPreCopy() { 15521 if (isFwdLocked()) { 15522 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 15523 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 15524 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15525 } 15526 } 15527 15528 return PackageManager.INSTALL_SUCCEEDED; 15529 } 15530 15531 @Override 15532 int doPostCopy(int uid) { 15533 if (isFwdLocked()) { 15534 if (uid < Process.FIRST_APPLICATION_UID 15535 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 15536 RES_FILE_NAME)) { 15537 Slog.e(TAG, "Failed to finalize " + cid); 15538 PackageHelper.destroySdDir(cid); 15539 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15540 } 15541 } 15542 15543 return PackageManager.INSTALL_SUCCEEDED; 15544 } 15545 } 15546 15547 /** 15548 * Logic to handle movement of existing installed applications. 15549 */ 15550 class MoveInstallArgs extends InstallArgs { 15551 private File codeFile; 15552 private File resourceFile; 15553 15554 /** New install */ 15555 MoveInstallArgs(InstallParams params) { 15556 super(params.origin, params.move, params.observer, params.installFlags, 15557 params.installerPackageName, params.volumeUuid, 15558 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 15559 params.grantedRuntimePermissions, 15560 params.traceMethod, params.traceCookie, params.certificates, 15561 params.installReason); 15562 } 15563 15564 int copyApk(IMediaContainerService imcs, boolean temp) { 15565 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 15566 + move.fromUuid + " to " + move.toUuid); 15567 synchronized (mInstaller) { 15568 try { 15569 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 15570 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 15571 } catch (InstallerException e) { 15572 Slog.w(TAG, "Failed to move app", e); 15573 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15574 } 15575 } 15576 15577 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 15578 resourceFile = codeFile; 15579 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 15580 15581 return PackageManager.INSTALL_SUCCEEDED; 15582 } 15583 15584 int doPreInstall(int status) { 15585 if (status != PackageManager.INSTALL_SUCCEEDED) { 15586 cleanUp(move.toUuid); 15587 } 15588 return status; 15589 } 15590 15591 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15592 if (status != PackageManager.INSTALL_SUCCEEDED) { 15593 cleanUp(move.toUuid); 15594 return false; 15595 } 15596 15597 // Reflect the move in app info 15598 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15599 pkg.setApplicationInfoCodePath(pkg.codePath); 15600 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15601 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15602 pkg.setApplicationInfoResourcePath(pkg.codePath); 15603 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15604 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15605 15606 return true; 15607 } 15608 15609 int doPostInstall(int status, int uid) { 15610 if (status == PackageManager.INSTALL_SUCCEEDED) { 15611 cleanUp(move.fromUuid); 15612 } else { 15613 cleanUp(move.toUuid); 15614 } 15615 return status; 15616 } 15617 15618 @Override 15619 String getCodePath() { 15620 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 15621 } 15622 15623 @Override 15624 String getResourcePath() { 15625 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 15626 } 15627 15628 private boolean cleanUp(String volumeUuid) { 15629 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 15630 move.dataAppName); 15631 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 15632 final int[] userIds = sUserManager.getUserIds(); 15633 synchronized (mInstallLock) { 15634 // Clean up both app data and code 15635 // All package moves are frozen until finished 15636 for (int userId : userIds) { 15637 try { 15638 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 15639 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 15640 } catch (InstallerException e) { 15641 Slog.w(TAG, String.valueOf(e)); 15642 } 15643 } 15644 removeCodePathLI(codeFile); 15645 } 15646 return true; 15647 } 15648 15649 void cleanUpResourcesLI() { 15650 throw new UnsupportedOperationException(); 15651 } 15652 15653 boolean doPostDeleteLI(boolean delete) { 15654 throw new UnsupportedOperationException(); 15655 } 15656 } 15657 15658 static String getAsecPackageName(String packageCid) { 15659 int idx = packageCid.lastIndexOf("-"); 15660 if (idx == -1) { 15661 return packageCid; 15662 } 15663 return packageCid.substring(0, idx); 15664 } 15665 15666 // Utility method used to create code paths based on package name and available index. 15667 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 15668 String idxStr = ""; 15669 int idx = 1; 15670 // Fall back to default value of idx=1 if prefix is not 15671 // part of oldCodePath 15672 if (oldCodePath != null) { 15673 String subStr = oldCodePath; 15674 // Drop the suffix right away 15675 if (suffix != null && subStr.endsWith(suffix)) { 15676 subStr = subStr.substring(0, subStr.length() - suffix.length()); 15677 } 15678 // If oldCodePath already contains prefix find out the 15679 // ending index to either increment or decrement. 15680 int sidx = subStr.lastIndexOf(prefix); 15681 if (sidx != -1) { 15682 subStr = subStr.substring(sidx + prefix.length()); 15683 if (subStr != null) { 15684 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 15685 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 15686 } 15687 try { 15688 idx = Integer.parseInt(subStr); 15689 if (idx <= 1) { 15690 idx++; 15691 } else { 15692 idx--; 15693 } 15694 } catch(NumberFormatException e) { 15695 } 15696 } 15697 } 15698 } 15699 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 15700 return prefix + idxStr; 15701 } 15702 15703 private File getNextCodePath(File targetDir, String packageName) { 15704 File result; 15705 SecureRandom random = new SecureRandom(); 15706 byte[] bytes = new byte[16]; 15707 do { 15708 random.nextBytes(bytes); 15709 String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP); 15710 result = new File(targetDir, packageName + "-" + suffix); 15711 } while (result.exists()); 15712 return result; 15713 } 15714 15715 // Utility method that returns the relative package path with respect 15716 // to the installation directory. Like say for /data/data/com.test-1.apk 15717 // string com.test-1 is returned. 15718 static String deriveCodePathName(String codePath) { 15719 if (codePath == null) { 15720 return null; 15721 } 15722 final File codeFile = new File(codePath); 15723 final String name = codeFile.getName(); 15724 if (codeFile.isDirectory()) { 15725 return name; 15726 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 15727 final int lastDot = name.lastIndexOf('.'); 15728 return name.substring(0, lastDot); 15729 } else { 15730 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 15731 return null; 15732 } 15733 } 15734 15735 static class PackageInstalledInfo { 15736 String name; 15737 int uid; 15738 // The set of users that originally had this package installed. 15739 int[] origUsers; 15740 // The set of users that now have this package installed. 15741 int[] newUsers; 15742 PackageParser.Package pkg; 15743 int returnCode; 15744 String returnMsg; 15745 PackageRemovedInfo removedInfo; 15746 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 15747 15748 public void setError(int code, String msg) { 15749 setReturnCode(code); 15750 setReturnMessage(msg); 15751 Slog.w(TAG, msg); 15752 } 15753 15754 public void setError(String msg, PackageParserException e) { 15755 setReturnCode(e.error); 15756 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 15757 Slog.w(TAG, msg, e); 15758 } 15759 15760 public void setError(String msg, PackageManagerException e) { 15761 returnCode = e.error; 15762 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 15763 Slog.w(TAG, msg, e); 15764 } 15765 15766 public void setReturnCode(int returnCode) { 15767 this.returnCode = returnCode; 15768 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15769 for (int i = 0; i < childCount; i++) { 15770 addedChildPackages.valueAt(i).returnCode = returnCode; 15771 } 15772 } 15773 15774 private void setReturnMessage(String returnMsg) { 15775 this.returnMsg = returnMsg; 15776 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15777 for (int i = 0; i < childCount; i++) { 15778 addedChildPackages.valueAt(i).returnMsg = returnMsg; 15779 } 15780 } 15781 15782 // In some error cases we want to convey more info back to the observer 15783 String origPackage; 15784 String origPermission; 15785 } 15786 15787 /* 15788 * Install a non-existing package. 15789 */ 15790 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 15791 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 15792 PackageInstalledInfo res, int installReason) { 15793 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 15794 15795 // Remember this for later, in case we need to rollback this install 15796 String pkgName = pkg.packageName; 15797 15798 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 15799 15800 synchronized(mPackages) { 15801 final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName); 15802 if (renamedPackage != null) { 15803 // A package with the same name is already installed, though 15804 // it has been renamed to an older name. The package we 15805 // are trying to install should be installed as an update to 15806 // the existing one, but that has not been requested, so bail. 15807 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 15808 + " without first uninstalling package running as " 15809 + renamedPackage); 15810 return; 15811 } 15812 if (mPackages.containsKey(pkgName)) { 15813 // Don't allow installation over an existing package with the same name. 15814 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 15815 + " without first uninstalling."); 15816 return; 15817 } 15818 } 15819 15820 try { 15821 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 15822 System.currentTimeMillis(), user); 15823 15824 updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason); 15825 15826 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 15827 prepareAppDataAfterInstallLIF(newPackage); 15828 15829 } else { 15830 // Remove package from internal structures, but keep around any 15831 // data that might have already existed 15832 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 15833 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 15834 } 15835 } catch (PackageManagerException e) { 15836 res.setError("Package couldn't be installed in " + pkg.codePath, e); 15837 } 15838 15839 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15840 } 15841 15842 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 15843 // Can't rotate keys during boot or if sharedUser. 15844 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 15845 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 15846 return false; 15847 } 15848 // app is using upgradeKeySets; make sure all are valid 15849 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15850 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 15851 for (int i = 0; i < upgradeKeySets.length; i++) { 15852 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 15853 Slog.wtf(TAG, "Package " 15854 + (oldPs.name != null ? oldPs.name : "<null>") 15855 + " contains upgrade-key-set reference to unknown key-set: " 15856 + upgradeKeySets[i] 15857 + " reverting to signatures check."); 15858 return false; 15859 } 15860 } 15861 return true; 15862 } 15863 15864 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 15865 // Upgrade keysets are being used. Determine if new package has a superset of the 15866 // required keys. 15867 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 15868 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15869 for (int i = 0; i < upgradeKeySets.length; i++) { 15870 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 15871 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 15872 return true; 15873 } 15874 } 15875 return false; 15876 } 15877 15878 private static void updateDigest(MessageDigest digest, File file) throws IOException { 15879 try (DigestInputStream digestStream = 15880 new DigestInputStream(new FileInputStream(file), digest)) { 15881 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 15882 } 15883 } 15884 15885 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 15886 UserHandle user, String installerPackageName, PackageInstalledInfo res, 15887 int installReason) { 15888 final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 15889 15890 final PackageParser.Package oldPackage; 15891 final String pkgName = pkg.packageName; 15892 final int[] allUsers; 15893 final int[] installedUsers; 15894 15895 synchronized(mPackages) { 15896 oldPackage = mPackages.get(pkgName); 15897 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 15898 15899 // don't allow upgrade to target a release SDK from a pre-release SDK 15900 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 15901 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 15902 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 15903 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 15904 if (oldTargetsPreRelease 15905 && !newTargetsPreRelease 15906 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 15907 Slog.w(TAG, "Can't install package targeting released sdk"); 15908 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 15909 return; 15910 } 15911 15912 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15913 15914 // don't allow an upgrade from full to ephemeral 15915 if (isInstantApp && !ps.getInstantApp(user.getIdentifier())) { 15916 // can't downgrade from full to instant 15917 Slog.w(TAG, "Can't replace app with instant app: " + pkgName); 15918 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 15919 return; 15920 } 15921 15922 // verify signatures are valid 15923 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 15924 if (!checkUpgradeKeySetLP(ps, pkg)) { 15925 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 15926 "New package not signed by keys specified by upgrade-keysets: " 15927 + pkgName); 15928 return; 15929 } 15930 } else { 15931 // default to original signature matching 15932 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 15933 != PackageManager.SIGNATURE_MATCH) { 15934 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 15935 "New package has a different signature: " + pkgName); 15936 return; 15937 } 15938 } 15939 15940 // don't allow a system upgrade unless the upgrade hash matches 15941 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 15942 byte[] digestBytes = null; 15943 try { 15944 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 15945 updateDigest(digest, new File(pkg.baseCodePath)); 15946 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 15947 for (String path : pkg.splitCodePaths) { 15948 updateDigest(digest, new File(path)); 15949 } 15950 } 15951 digestBytes = digest.digest(); 15952 } catch (NoSuchAlgorithmException | IOException e) { 15953 res.setError(INSTALL_FAILED_INVALID_APK, 15954 "Could not compute hash: " + pkgName); 15955 return; 15956 } 15957 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 15958 res.setError(INSTALL_FAILED_INVALID_APK, 15959 "New package fails restrict-update check: " + pkgName); 15960 return; 15961 } 15962 // retain upgrade restriction 15963 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 15964 } 15965 15966 // Check for shared user id changes 15967 String invalidPackageName = 15968 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 15969 if (invalidPackageName != null) { 15970 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 15971 "Package " + invalidPackageName + " tried to change user " 15972 + oldPackage.mSharedUserId); 15973 return; 15974 } 15975 15976 // In case of rollback, remember per-user/profile install state 15977 allUsers = sUserManager.getUserIds(); 15978 installedUsers = ps.queryInstalledUsers(allUsers, true); 15979 } 15980 15981 // Update what is removed 15982 res.removedInfo = new PackageRemovedInfo(); 15983 res.removedInfo.uid = oldPackage.applicationInfo.uid; 15984 res.removedInfo.removedPackage = oldPackage.packageName; 15985 res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null; 15986 res.removedInfo.isUpdate = true; 15987 res.removedInfo.origUsers = installedUsers; 15988 final PackageSetting ps = mSettings.getPackageLPr(pkgName); 15989 res.removedInfo.installReasons = new SparseArray<>(installedUsers.length); 15990 for (int i = 0; i < installedUsers.length; i++) { 15991 final int userId = installedUsers[i]; 15992 res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId)); 15993 } 15994 15995 final int childCount = (oldPackage.childPackages != null) 15996 ? oldPackage.childPackages.size() : 0; 15997 for (int i = 0; i < childCount; i++) { 15998 boolean childPackageUpdated = false; 15999 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 16000 final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 16001 if (res.addedChildPackages != null) { 16002 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 16003 if (childRes != null) { 16004 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 16005 childRes.removedInfo.removedPackage = childPkg.packageName; 16006 childRes.removedInfo.isUpdate = true; 16007 childRes.removedInfo.installReasons = res.removedInfo.installReasons; 16008 childPackageUpdated = true; 16009 } 16010 } 16011 if (!childPackageUpdated) { 16012 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 16013 childRemovedRes.removedPackage = childPkg.packageName; 16014 childRemovedRes.isUpdate = false; 16015 childRemovedRes.dataRemoved = true; 16016 synchronized (mPackages) { 16017 if (childPs != null) { 16018 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 16019 } 16020 } 16021 if (res.removedInfo.removedChildPackages == null) { 16022 res.removedInfo.removedChildPackages = new ArrayMap<>(); 16023 } 16024 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 16025 } 16026 } 16027 16028 boolean sysPkg = (isSystemApp(oldPackage)); 16029 if (sysPkg) { 16030 // Set the system/privileged flags as needed 16031 final boolean privileged = 16032 (oldPackage.applicationInfo.privateFlags 16033 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 16034 final int systemPolicyFlags = policyFlags 16035 | PackageParser.PARSE_IS_SYSTEM 16036 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 16037 16038 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 16039 user, allUsers, installerPackageName, res, installReason); 16040 } else { 16041 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 16042 user, allUsers, installerPackageName, res, installReason); 16043 } 16044 } 16045 16046 public List<String> getPreviousCodePaths(String packageName) { 16047 final PackageSetting ps = mSettings.mPackages.get(packageName); 16048 final List<String> result = new ArrayList<String>(); 16049 if (ps != null && ps.oldCodePaths != null) { 16050 result.addAll(ps.oldCodePaths); 16051 } 16052 return result; 16053 } 16054 16055 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 16056 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 16057 int[] allUsers, String installerPackageName, PackageInstalledInfo res, 16058 int installReason) { 16059 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 16060 + deletedPackage); 16061 16062 String pkgName = deletedPackage.packageName; 16063 boolean deletedPkg = true; 16064 boolean addedPkg = false; 16065 boolean updatedSettings = false; 16066 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 16067 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 16068 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 16069 16070 final long origUpdateTime = (pkg.mExtras != null) 16071 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 16072 16073 // First delete the existing package while retaining the data directory 16074 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 16075 res.removedInfo, true, pkg)) { 16076 // If the existing package wasn't successfully deleted 16077 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 16078 deletedPkg = false; 16079 } else { 16080 // Successfully deleted the old package; proceed with replace. 16081 16082 // If deleted package lived in a container, give users a chance to 16083 // relinquish resources before killing. 16084 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 16085 if (DEBUG_INSTALL) { 16086 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 16087 } 16088 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 16089 final ArrayList<String> pkgList = new ArrayList<String>(1); 16090 pkgList.add(deletedPackage.applicationInfo.packageName); 16091 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 16092 } 16093 16094 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 16095 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16096 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 16097 16098 try { 16099 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 16100 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 16101 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 16102 installReason); 16103 16104 // Update the in-memory copy of the previous code paths. 16105 PackageSetting ps = mSettings.mPackages.get(pkgName); 16106 if (!killApp) { 16107 if (ps.oldCodePaths == null) { 16108 ps.oldCodePaths = new ArraySet<>(); 16109 } 16110 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 16111 if (deletedPackage.splitCodePaths != null) { 16112 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 16113 } 16114 } else { 16115 ps.oldCodePaths = null; 16116 } 16117 if (ps.childPackageNames != null) { 16118 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 16119 final String childPkgName = ps.childPackageNames.get(i); 16120 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 16121 childPs.oldCodePaths = ps.oldCodePaths; 16122 } 16123 } 16124 // set instant app status, but, only if it's explicitly specified 16125 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 16126 final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0; 16127 setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp); 16128 prepareAppDataAfterInstallLIF(newPackage); 16129 addedPkg = true; 16130 } catch (PackageManagerException e) { 16131 res.setError("Package couldn't be installed in " + pkg.codePath, e); 16132 } 16133 } 16134 16135 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 16136 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 16137 16138 // Revert all internal state mutations and added folders for the failed install 16139 if (addedPkg) { 16140 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 16141 res.removedInfo, true, null); 16142 } 16143 16144 // Restore the old package 16145 if (deletedPkg) { 16146 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 16147 File restoreFile = new File(deletedPackage.codePath); 16148 // Parse old package 16149 boolean oldExternal = isExternal(deletedPackage); 16150 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 16151 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 16152 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 16153 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 16154 try { 16155 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 16156 null); 16157 } catch (PackageManagerException e) { 16158 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 16159 + e.getMessage()); 16160 return; 16161 } 16162 16163 synchronized (mPackages) { 16164 // Ensure the installer package name up to date 16165 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 16166 16167 // Update permissions for restored package 16168 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 16169 16170 mSettings.writeLPr(); 16171 } 16172 16173 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 16174 } 16175 } else { 16176 synchronized (mPackages) { 16177 PackageSetting ps = mSettings.getPackageLPr(pkg.packageName); 16178 if (ps != null) { 16179 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 16180 if (res.removedInfo.removedChildPackages != null) { 16181 final int childCount = res.removedInfo.removedChildPackages.size(); 16182 // Iterate in reverse as we may modify the collection 16183 for (int i = childCount - 1; i >= 0; i--) { 16184 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 16185 if (res.addedChildPackages.containsKey(childPackageName)) { 16186 res.removedInfo.removedChildPackages.removeAt(i); 16187 } else { 16188 PackageRemovedInfo childInfo = res.removedInfo 16189 .removedChildPackages.valueAt(i); 16190 childInfo.removedForAllUsers = mPackages.get( 16191 childInfo.removedPackage) == null; 16192 } 16193 } 16194 } 16195 } 16196 } 16197 } 16198 } 16199 16200 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 16201 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 16202 int[] allUsers, String installerPackageName, PackageInstalledInfo res, 16203 int installReason) { 16204 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 16205 + ", old=" + deletedPackage); 16206 16207 final boolean disabledSystem; 16208 16209 // Remove existing system package 16210 removePackageLI(deletedPackage, true); 16211 16212 synchronized (mPackages) { 16213 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 16214 } 16215 if (!disabledSystem) { 16216 // We didn't need to disable the .apk as a current system package, 16217 // which means we are replacing another update that is already 16218 // installed. We need to make sure to delete the older one's .apk. 16219 res.removedInfo.args = createInstallArgsForExisting(0, 16220 deletedPackage.applicationInfo.getCodePath(), 16221 deletedPackage.applicationInfo.getResourcePath(), 16222 getAppDexInstructionSets(deletedPackage.applicationInfo)); 16223 } else { 16224 res.removedInfo.args = null; 16225 } 16226 16227 // Successfully disabled the old package. Now proceed with re-installation 16228 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 16229 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16230 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 16231 16232 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16233 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 16234 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 16235 16236 PackageParser.Package newPackage = null; 16237 try { 16238 // Add the package to the internal data structures 16239 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 16240 16241 // Set the update and install times 16242 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 16243 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 16244 System.currentTimeMillis()); 16245 16246 // Update the package dynamic state if succeeded 16247 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 16248 // Now that the install succeeded make sure we remove data 16249 // directories for any child package the update removed. 16250 final int deletedChildCount = (deletedPackage.childPackages != null) 16251 ? deletedPackage.childPackages.size() : 0; 16252 final int newChildCount = (newPackage.childPackages != null) 16253 ? newPackage.childPackages.size() : 0; 16254 for (int i = 0; i < deletedChildCount; i++) { 16255 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 16256 boolean childPackageDeleted = true; 16257 for (int j = 0; j < newChildCount; j++) { 16258 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 16259 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 16260 childPackageDeleted = false; 16261 break; 16262 } 16263 } 16264 if (childPackageDeleted) { 16265 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 16266 deletedChildPkg.packageName); 16267 if (ps != null && res.removedInfo.removedChildPackages != null) { 16268 PackageRemovedInfo removedChildRes = res.removedInfo 16269 .removedChildPackages.get(deletedChildPkg.packageName); 16270 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 16271 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 16272 } 16273 } 16274 } 16275 16276 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 16277 installReason); 16278 prepareAppDataAfterInstallLIF(newPackage); 16279 } 16280 } catch (PackageManagerException e) { 16281 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 16282 res.setError("Package couldn't be installed in " + pkg.codePath, e); 16283 } 16284 16285 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 16286 // Re installation failed. Restore old information 16287 // Remove new pkg information 16288 if (newPackage != null) { 16289 removeInstalledPackageLI(newPackage, true); 16290 } 16291 // Add back the old system package 16292 try { 16293 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 16294 } catch (PackageManagerException e) { 16295 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 16296 } 16297 16298 synchronized (mPackages) { 16299 if (disabledSystem) { 16300 enableSystemPackageLPw(deletedPackage); 16301 } 16302 16303 // Ensure the installer package name up to date 16304 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 16305 16306 // Update permissions for restored package 16307 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 16308 16309 mSettings.writeLPr(); 16310 } 16311 16312 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 16313 + " after failed upgrade"); 16314 } 16315 } 16316 16317 /** 16318 * Checks whether the parent or any of the child packages have a change shared 16319 * user. For a package to be a valid update the shred users of the parent and 16320 * the children should match. We may later support changing child shared users. 16321 * @param oldPkg The updated package. 16322 * @param newPkg The update package. 16323 * @return The shared user that change between the versions. 16324 */ 16325 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 16326 PackageParser.Package newPkg) { 16327 // Check parent shared user 16328 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 16329 return newPkg.packageName; 16330 } 16331 // Check child shared users 16332 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 16333 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 16334 for (int i = 0; i < newChildCount; i++) { 16335 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 16336 // If this child was present, did it have the same shared user? 16337 for (int j = 0; j < oldChildCount; j++) { 16338 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 16339 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 16340 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 16341 return newChildPkg.packageName; 16342 } 16343 } 16344 } 16345 return null; 16346 } 16347 16348 private void removeNativeBinariesLI(PackageSetting ps) { 16349 // Remove the lib path for the parent package 16350 if (ps != null) { 16351 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 16352 // Remove the lib path for the child packages 16353 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 16354 for (int i = 0; i < childCount; i++) { 16355 PackageSetting childPs = null; 16356 synchronized (mPackages) { 16357 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 16358 } 16359 if (childPs != null) { 16360 NativeLibraryHelper.removeNativeBinariesLI(childPs 16361 .legacyNativeLibraryPathString); 16362 } 16363 } 16364 } 16365 } 16366 16367 private void enableSystemPackageLPw(PackageParser.Package pkg) { 16368 // Enable the parent package 16369 mSettings.enableSystemPackageLPw(pkg.packageName); 16370 // Enable the child packages 16371 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16372 for (int i = 0; i < childCount; i++) { 16373 PackageParser.Package childPkg = pkg.childPackages.get(i); 16374 mSettings.enableSystemPackageLPw(childPkg.packageName); 16375 } 16376 } 16377 16378 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 16379 PackageParser.Package newPkg) { 16380 // Disable the parent package (parent always replaced) 16381 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 16382 // Disable the child packages 16383 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 16384 for (int i = 0; i < childCount; i++) { 16385 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 16386 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 16387 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 16388 } 16389 return disabled; 16390 } 16391 16392 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 16393 String installerPackageName) { 16394 // Enable the parent package 16395 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 16396 // Enable the child packages 16397 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16398 for (int i = 0; i < childCount; i++) { 16399 PackageParser.Package childPkg = pkg.childPackages.get(i); 16400 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 16401 } 16402 } 16403 16404 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 16405 // Collect all used permissions in the UID 16406 ArraySet<String> usedPermissions = new ArraySet<>(); 16407 final int packageCount = su.packages.size(); 16408 for (int i = 0; i < packageCount; i++) { 16409 PackageSetting ps = su.packages.valueAt(i); 16410 if (ps.pkg == null) { 16411 continue; 16412 } 16413 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 16414 for (int j = 0; j < requestedPermCount; j++) { 16415 String permission = ps.pkg.requestedPermissions.get(j); 16416 BasePermission bp = mSettings.mPermissions.get(permission); 16417 if (bp != null) { 16418 usedPermissions.add(permission); 16419 } 16420 } 16421 } 16422 16423 PermissionsState permissionsState = su.getPermissionsState(); 16424 // Prune install permissions 16425 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 16426 final int installPermCount = installPermStates.size(); 16427 for (int i = installPermCount - 1; i >= 0; i--) { 16428 PermissionState permissionState = installPermStates.get(i); 16429 if (!usedPermissions.contains(permissionState.getName())) { 16430 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 16431 if (bp != null) { 16432 permissionsState.revokeInstallPermission(bp); 16433 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 16434 PackageManager.MASK_PERMISSION_FLAGS, 0); 16435 } 16436 } 16437 } 16438 16439 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 16440 16441 // Prune runtime permissions 16442 for (int userId : allUserIds) { 16443 List<PermissionState> runtimePermStates = permissionsState 16444 .getRuntimePermissionStates(userId); 16445 final int runtimePermCount = runtimePermStates.size(); 16446 for (int i = runtimePermCount - 1; i >= 0; i--) { 16447 PermissionState permissionState = runtimePermStates.get(i); 16448 if (!usedPermissions.contains(permissionState.getName())) { 16449 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 16450 if (bp != null) { 16451 permissionsState.revokeRuntimePermission(bp, userId); 16452 permissionsState.updatePermissionFlags(bp, userId, 16453 PackageManager.MASK_PERMISSION_FLAGS, 0); 16454 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 16455 runtimePermissionChangedUserIds, userId); 16456 } 16457 } 16458 } 16459 } 16460 16461 return runtimePermissionChangedUserIds; 16462 } 16463 16464 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 16465 int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) { 16466 // Update the parent package setting 16467 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 16468 res, user, installReason); 16469 // Update the child packages setting 16470 final int childCount = (newPackage.childPackages != null) 16471 ? newPackage.childPackages.size() : 0; 16472 for (int i = 0; i < childCount; i++) { 16473 PackageParser.Package childPackage = newPackage.childPackages.get(i); 16474 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 16475 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 16476 childRes.origUsers, childRes, user, installReason); 16477 } 16478 } 16479 16480 private void updateSettingsInternalLI(PackageParser.Package newPackage, 16481 String installerPackageName, int[] allUsers, int[] installedForUsers, 16482 PackageInstalledInfo res, UserHandle user, int installReason) { 16483 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 16484 16485 String pkgName = newPackage.packageName; 16486 synchronized (mPackages) { 16487 //write settings. the installStatus will be incomplete at this stage. 16488 //note that the new package setting would have already been 16489 //added to mPackages. It hasn't been persisted yet. 16490 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 16491 // TODO: Remove this write? It's also written at the end of this method 16492 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 16493 mSettings.writeLPr(); 16494 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16495 } 16496 16497 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 16498 synchronized (mPackages) { 16499 updatePermissionsLPw(newPackage.packageName, newPackage, 16500 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 16501 ? UPDATE_PERMISSIONS_ALL : 0)); 16502 // For system-bundled packages, we assume that installing an upgraded version 16503 // of the package implies that the user actually wants to run that new code, 16504 // so we enable the package. 16505 PackageSetting ps = mSettings.mPackages.get(pkgName); 16506 final int userId = user.getIdentifier(); 16507 if (ps != null) { 16508 if (isSystemApp(newPackage)) { 16509 if (DEBUG_INSTALL) { 16510 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 16511 } 16512 // Enable system package for requested users 16513 if (res.origUsers != null) { 16514 for (int origUserId : res.origUsers) { 16515 if (userId == UserHandle.USER_ALL || userId == origUserId) { 16516 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 16517 origUserId, installerPackageName); 16518 } 16519 } 16520 } 16521 // Also convey the prior install/uninstall state 16522 if (allUsers != null && installedForUsers != null) { 16523 for (int currentUserId : allUsers) { 16524 final boolean installed = ArrayUtils.contains( 16525 installedForUsers, currentUserId); 16526 if (DEBUG_INSTALL) { 16527 Slog.d(TAG, " user " + currentUserId + " => " + installed); 16528 } 16529 ps.setInstalled(installed, currentUserId); 16530 } 16531 // these install state changes will be persisted in the 16532 // upcoming call to mSettings.writeLPr(). 16533 } 16534 } 16535 // It's implied that when a user requests installation, they want the app to be 16536 // installed and enabled. 16537 if (userId != UserHandle.USER_ALL) { 16538 ps.setInstalled(true, userId); 16539 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 16540 } 16541 16542 // When replacing an existing package, preserve the original install reason for all 16543 // users that had the package installed before. 16544 final Set<Integer> previousUserIds = new ArraySet<>(); 16545 if (res.removedInfo != null && res.removedInfo.installReasons != null) { 16546 final int installReasonCount = res.removedInfo.installReasons.size(); 16547 for (int i = 0; i < installReasonCount; i++) { 16548 final int previousUserId = res.removedInfo.installReasons.keyAt(i); 16549 final int previousInstallReason = res.removedInfo.installReasons.valueAt(i); 16550 ps.setInstallReason(previousInstallReason, previousUserId); 16551 previousUserIds.add(previousUserId); 16552 } 16553 } 16554 16555 // Set install reason for users that are having the package newly installed. 16556 if (userId == UserHandle.USER_ALL) { 16557 for (int currentUserId : sUserManager.getUserIds()) { 16558 if (!previousUserIds.contains(currentUserId)) { 16559 ps.setInstallReason(installReason, currentUserId); 16560 } 16561 } 16562 } else if (!previousUserIds.contains(userId)) { 16563 ps.setInstallReason(installReason, userId); 16564 } 16565 mSettings.writeKernelMappingLPr(ps); 16566 } 16567 res.name = pkgName; 16568 res.uid = newPackage.applicationInfo.uid; 16569 res.pkg = newPackage; 16570 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 16571 mSettings.setInstallerPackageName(pkgName, installerPackageName); 16572 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16573 //to update install status 16574 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 16575 mSettings.writeLPr(); 16576 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16577 } 16578 16579 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16580 } 16581 16582 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 16583 try { 16584 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 16585 installPackageLI(args, res); 16586 } finally { 16587 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16588 } 16589 } 16590 16591 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 16592 final int installFlags = args.installFlags; 16593 final String installerPackageName = args.installerPackageName; 16594 final String volumeUuid = args.volumeUuid; 16595 final File tmpPackageFile = new File(args.getCodePath()); 16596 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 16597 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 16598 || (args.volumeUuid != null)); 16599 final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0); 16600 final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0); 16601 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 16602 boolean replace = false; 16603 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 16604 if (args.move != null) { 16605 // moving a complete application; perform an initial scan on the new install location 16606 scanFlags |= SCAN_INITIAL; 16607 } 16608 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 16609 scanFlags |= SCAN_DONT_KILL_APP; 16610 } 16611 if (instantApp) { 16612 scanFlags |= SCAN_AS_INSTANT_APP; 16613 } 16614 if (fullApp) { 16615 scanFlags |= SCAN_AS_FULL_APP; 16616 } 16617 16618 // Result object to be returned 16619 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16620 16621 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 16622 16623 // Sanity check 16624 if (instantApp && (forwardLocked || onExternal)) { 16625 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 16626 + " external=" + onExternal); 16627 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 16628 return; 16629 } 16630 16631 // Retrieve PackageSettings and parse package 16632 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 16633 | PackageParser.PARSE_ENFORCE_CODE 16634 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 16635 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 16636 | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0) 16637 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 16638 PackageParser pp = new PackageParser(); 16639 pp.setSeparateProcesses(mSeparateProcesses); 16640 pp.setDisplayMetrics(mMetrics); 16641 16642 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 16643 final PackageParser.Package pkg; 16644 try { 16645 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 16646 } catch (PackageParserException e) { 16647 res.setError("Failed parse during installPackageLI", e); 16648 return; 16649 } finally { 16650 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16651 } 16652 16653// // Ephemeral apps must have target SDK >= O. 16654// // TODO: Update conditional and error message when O gets locked down 16655// if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) { 16656// res.setError(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID, 16657// "Ephemeral apps must have target SDK version of at least O"); 16658// return; 16659// } 16660 16661 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16662 // Static shared libraries have synthetic package names 16663 renameStaticSharedLibraryPackage(pkg); 16664 16665 // No static shared libs on external storage 16666 if (onExternal) { 16667 Slog.i(TAG, "Static shared libs can only be installed on internal storage."); 16668 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 16669 "Packages declaring static-shared libs cannot be updated"); 16670 return; 16671 } 16672 } 16673 16674 // If we are installing a clustered package add results for the children 16675 if (pkg.childPackages != null) { 16676 synchronized (mPackages) { 16677 final int childCount = pkg.childPackages.size(); 16678 for (int i = 0; i < childCount; i++) { 16679 PackageParser.Package childPkg = pkg.childPackages.get(i); 16680 PackageInstalledInfo childRes = new PackageInstalledInfo(); 16681 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16682 childRes.pkg = childPkg; 16683 childRes.name = childPkg.packageName; 16684 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 16685 if (childPs != null) { 16686 childRes.origUsers = childPs.queryInstalledUsers( 16687 sUserManager.getUserIds(), true); 16688 } 16689 if ((mPackages.containsKey(childPkg.packageName))) { 16690 childRes.removedInfo = new PackageRemovedInfo(); 16691 childRes.removedInfo.removedPackage = childPkg.packageName; 16692 } 16693 if (res.addedChildPackages == null) { 16694 res.addedChildPackages = new ArrayMap<>(); 16695 } 16696 res.addedChildPackages.put(childPkg.packageName, childRes); 16697 } 16698 } 16699 } 16700 16701 // If package doesn't declare API override, mark that we have an install 16702 // time CPU ABI override. 16703 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 16704 pkg.cpuAbiOverride = args.abiOverride; 16705 } 16706 16707 String pkgName = res.name = pkg.packageName; 16708 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 16709 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 16710 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 16711 return; 16712 } 16713 } 16714 16715 try { 16716 // either use what we've been given or parse directly from the APK 16717 if (args.certificates != null) { 16718 try { 16719 PackageParser.populateCertificates(pkg, args.certificates); 16720 } catch (PackageParserException e) { 16721 // there was something wrong with the certificates we were given; 16722 // try to pull them from the APK 16723 PackageParser.collectCertificates(pkg, parseFlags); 16724 } 16725 } else { 16726 PackageParser.collectCertificates(pkg, parseFlags); 16727 } 16728 } catch (PackageParserException e) { 16729 res.setError("Failed collect during installPackageLI", e); 16730 return; 16731 } 16732 16733 // Get rid of all references to package scan path via parser. 16734 pp = null; 16735 String oldCodePath = null; 16736 boolean systemApp = false; 16737 synchronized (mPackages) { 16738 // Check if installing already existing package 16739 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 16740 String oldName = mSettings.getRenamedPackageLPr(pkgName); 16741 if (pkg.mOriginalPackages != null 16742 && pkg.mOriginalPackages.contains(oldName) 16743 && mPackages.containsKey(oldName)) { 16744 // This package is derived from an original package, 16745 // and this device has been updating from that original 16746 // name. We must continue using the original name, so 16747 // rename the new package here. 16748 pkg.setPackageName(oldName); 16749 pkgName = pkg.packageName; 16750 replace = true; 16751 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 16752 + oldName + " pkgName=" + pkgName); 16753 } else if (mPackages.containsKey(pkgName)) { 16754 // This package, under its official name, already exists 16755 // on the device; we should replace it. 16756 replace = true; 16757 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 16758 } 16759 16760 // Child packages are installed through the parent package 16761 if (pkg.parentPackage != null) { 16762 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 16763 "Package " + pkg.packageName + " is child of package " 16764 + pkg.parentPackage.parentPackage + ". Child packages " 16765 + "can be updated only through the parent package."); 16766 return; 16767 } 16768 16769 if (replace) { 16770 // Prevent apps opting out from runtime permissions 16771 PackageParser.Package oldPackage = mPackages.get(pkgName); 16772 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 16773 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 16774 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 16775 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 16776 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 16777 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 16778 + " doesn't support runtime permissions but the old" 16779 + " target SDK " + oldTargetSdk + " does."); 16780 return; 16781 } 16782 16783 // Prevent installing of child packages 16784 if (oldPackage.parentPackage != null) { 16785 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 16786 "Package " + pkg.packageName + " is child of package " 16787 + oldPackage.parentPackage + ". Child packages " 16788 + "can be updated only through the parent package."); 16789 return; 16790 } 16791 } 16792 } 16793 16794 PackageSetting ps = mSettings.mPackages.get(pkgName); 16795 if (ps != null) { 16796 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 16797 16798 // Static shared libs have same package with different versions where 16799 // we internally use a synthetic package name to allow multiple versions 16800 // of the same package, therefore we need to compare signatures against 16801 // the package setting for the latest library version. 16802 PackageSetting signatureCheckPs = ps; 16803 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16804 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg); 16805 if (libraryEntry != null) { 16806 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk); 16807 } 16808 } 16809 16810 // Quick sanity check that we're signed correctly if updating; 16811 // we'll check this again later when scanning, but we want to 16812 // bail early here before tripping over redefined permissions. 16813 if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) { 16814 if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) { 16815 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 16816 + pkg.packageName + " upgrade keys do not match the " 16817 + "previously installed version"); 16818 return; 16819 } 16820 } else { 16821 try { 16822 verifySignaturesLP(signatureCheckPs, pkg); 16823 } catch (PackageManagerException e) { 16824 res.setError(e.error, e.getMessage()); 16825 return; 16826 } 16827 } 16828 16829 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 16830 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 16831 systemApp = (ps.pkg.applicationInfo.flags & 16832 ApplicationInfo.FLAG_SYSTEM) != 0; 16833 } 16834 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 16835 } 16836 16837 int N = pkg.permissions.size(); 16838 for (int i = N-1; i >= 0; i--) { 16839 PackageParser.Permission perm = pkg.permissions.get(i); 16840 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 16841 16842 // Don't allow anyone but the platform to define ephemeral permissions. 16843 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_EPHEMERAL) != 0 16844 && !PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) { 16845 Slog.w(TAG, "Package " + pkg.packageName 16846 + " attempting to delcare ephemeral permission " 16847 + perm.info.name + "; Removing ephemeral."); 16848 perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_EPHEMERAL; 16849 } 16850 // Check whether the newly-scanned package wants to define an already-defined perm 16851 if (bp != null) { 16852 // If the defining package is signed with our cert, it's okay. This 16853 // also includes the "updating the same package" case, of course. 16854 // "updating same package" could also involve key-rotation. 16855 final boolean sigsOk; 16856 if (bp.sourcePackage.equals(pkg.packageName) 16857 && (bp.packageSetting instanceof PackageSetting) 16858 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 16859 scanFlags))) { 16860 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 16861 } else { 16862 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 16863 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 16864 } 16865 if (!sigsOk) { 16866 // If the owning package is the system itself, we log but allow 16867 // install to proceed; we fail the install on all other permission 16868 // redefinitions. 16869 if (!bp.sourcePackage.equals("android")) { 16870 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 16871 + pkg.packageName + " attempting to redeclare permission " 16872 + perm.info.name + " already owned by " + bp.sourcePackage); 16873 res.origPermission = perm.info.name; 16874 res.origPackage = bp.sourcePackage; 16875 return; 16876 } else { 16877 Slog.w(TAG, "Package " + pkg.packageName 16878 + " attempting to redeclare system permission " 16879 + perm.info.name + "; ignoring new declaration"); 16880 pkg.permissions.remove(i); 16881 } 16882 } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) { 16883 // Prevent apps to change protection level to dangerous from any other 16884 // type as this would allow a privilege escalation where an app adds a 16885 // normal/signature permission in other app's group and later redefines 16886 // it as dangerous leading to the group auto-grant. 16887 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE) 16888 == PermissionInfo.PROTECTION_DANGEROUS) { 16889 if (bp != null && !bp.isRuntime()) { 16890 Slog.w(TAG, "Package " + pkg.packageName + " trying to change a " 16891 + "non-runtime permission " + perm.info.name 16892 + " to runtime; keeping old protection level"); 16893 perm.info.protectionLevel = bp.protectionLevel; 16894 } 16895 } 16896 } 16897 } 16898 } 16899 } 16900 16901 if (systemApp) { 16902 if (onExternal) { 16903 // Abort update; system app can't be replaced with app on sdcard 16904 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 16905 "Cannot install updates to system apps on sdcard"); 16906 return; 16907 } else if (instantApp) { 16908 // Abort update; system app can't be replaced with an instant app 16909 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID, 16910 "Cannot update a system app with an instant app"); 16911 return; 16912 } 16913 } 16914 16915 if (args.move != null) { 16916 // We did an in-place move, so dex is ready to roll 16917 scanFlags |= SCAN_NO_DEX; 16918 scanFlags |= SCAN_MOVE; 16919 16920 synchronized (mPackages) { 16921 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16922 if (ps == null) { 16923 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 16924 "Missing settings for moved package " + pkgName); 16925 } 16926 16927 // We moved the entire application as-is, so bring over the 16928 // previously derived ABI information. 16929 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 16930 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 16931 } 16932 16933 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 16934 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 16935 scanFlags |= SCAN_NO_DEX; 16936 16937 try { 16938 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 16939 args.abiOverride : pkg.cpuAbiOverride); 16940 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 16941 true /*extractLibs*/, mAppLib32InstallDir); 16942 } catch (PackageManagerException pme) { 16943 Slog.e(TAG, "Error deriving application ABI", pme); 16944 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 16945 return; 16946 } 16947 16948 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 16949 // Do not run PackageDexOptimizer through the local performDexOpt 16950 // method because `pkg` may not be in `mPackages` yet. 16951 // 16952 // Also, don't fail application installs if the dexopt step fails. 16953 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 16954 null /* instructionSets */, false /* checkProfiles */, 16955 getCompilerFilterForReason(REASON_INSTALL), 16956 getOrCreateCompilerPackageStats(pkg), 16957 mDexManager.isUsedByOtherApps(pkg.packageName)); 16958 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16959 16960 // Notify BackgroundDexOptJobService that the package has been changed. 16961 // If this is an update of a package which used to fail to compile, 16962 // BDOS will remove it from its blacklist. 16963 // TODO: Layering violation 16964 BackgroundDexOptJobService.notifyPackageChanged(pkg.packageName); 16965 } 16966 16967 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 16968 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 16969 return; 16970 } 16971 16972 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 16973 16974 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 16975 "installPackageLI")) { 16976 if (replace) { 16977 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16978 // Static libs have a synthetic package name containing the version 16979 // and cannot be updated as an update would get a new package name, 16980 // unless this is the exact same version code which is useful for 16981 // development. 16982 PackageParser.Package existingPkg = mPackages.get(pkg.packageName); 16983 if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) { 16984 res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring " 16985 + "static-shared libs cannot be updated"); 16986 return; 16987 } 16988 } 16989 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 16990 installerPackageName, res, args.installReason); 16991 } else { 16992 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 16993 args.user, installerPackageName, volumeUuid, res, args.installReason); 16994 } 16995 } 16996 synchronized (mPackages) { 16997 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16998 if (ps != null) { 16999 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 17000 } 17001 17002 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 17003 for (int i = 0; i < childCount; i++) { 17004 PackageParser.Package childPkg = pkg.childPackages.get(i); 17005 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 17006 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 17007 if (childPs != null) { 17008 childRes.newUsers = childPs.queryInstalledUsers( 17009 sUserManager.getUserIds(), true); 17010 } 17011 } 17012 17013 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 17014 updateSequenceNumberLP(pkgName, res.newUsers); 17015 } 17016 } 17017 } 17018 17019 private void startIntentFilterVerifications(int userId, boolean replacing, 17020 PackageParser.Package pkg) { 17021 if (mIntentFilterVerifierComponent == null) { 17022 Slog.w(TAG, "No IntentFilter verification will not be done as " 17023 + "there is no IntentFilterVerifier available!"); 17024 return; 17025 } 17026 17027 final int verifierUid = getPackageUid( 17028 mIntentFilterVerifierComponent.getPackageName(), 17029 MATCH_DEBUG_TRIAGED_MISSING, 17030 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 17031 17032 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 17033 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 17034 mHandler.sendMessage(msg); 17035 17036 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 17037 for (int i = 0; i < childCount; i++) { 17038 PackageParser.Package childPkg = pkg.childPackages.get(i); 17039 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 17040 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 17041 mHandler.sendMessage(msg); 17042 } 17043 } 17044 17045 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 17046 PackageParser.Package pkg) { 17047 int size = pkg.activities.size(); 17048 if (size == 0) { 17049 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17050 "No activity, so no need to verify any IntentFilter!"); 17051 return; 17052 } 17053 17054 final boolean hasDomainURLs = hasDomainURLs(pkg); 17055 if (!hasDomainURLs) { 17056 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17057 "No domain URLs, so no need to verify any IntentFilter!"); 17058 return; 17059 } 17060 17061 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 17062 + " if any IntentFilter from the " + size 17063 + " Activities needs verification ..."); 17064 17065 int count = 0; 17066 final String packageName = pkg.packageName; 17067 17068 synchronized (mPackages) { 17069 // If this is a new install and we see that we've already run verification for this 17070 // package, we have nothing to do: it means the state was restored from backup. 17071 if (!replacing) { 17072 IntentFilterVerificationInfo ivi = 17073 mSettings.getIntentFilterVerificationLPr(packageName); 17074 if (ivi != null) { 17075 if (DEBUG_DOMAIN_VERIFICATION) { 17076 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 17077 + ivi.getStatusString()); 17078 } 17079 return; 17080 } 17081 } 17082 17083 // If any filters need to be verified, then all need to be. 17084 boolean needToVerify = false; 17085 for (PackageParser.Activity a : pkg.activities) { 17086 for (ActivityIntentInfo filter : a.intents) { 17087 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 17088 if (DEBUG_DOMAIN_VERIFICATION) { 17089 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 17090 } 17091 needToVerify = true; 17092 break; 17093 } 17094 } 17095 } 17096 17097 if (needToVerify) { 17098 final int verificationId = mIntentFilterVerificationToken++; 17099 for (PackageParser.Activity a : pkg.activities) { 17100 for (ActivityIntentInfo filter : a.intents) { 17101 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 17102 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17103 "Verification needed for IntentFilter:" + filter.toString()); 17104 mIntentFilterVerifier.addOneIntentFilterVerification( 17105 verifierUid, userId, verificationId, filter, packageName); 17106 count++; 17107 } 17108 } 17109 } 17110 } 17111 } 17112 17113 if (count > 0) { 17114 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 17115 + " IntentFilter verification" + (count > 1 ? "s" : "") 17116 + " for userId:" + userId); 17117 mIntentFilterVerifier.startVerifications(userId); 17118 } else { 17119 if (DEBUG_DOMAIN_VERIFICATION) { 17120 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 17121 } 17122 } 17123 } 17124 17125 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 17126 final ComponentName cn = filter.activity.getComponentName(); 17127 final String packageName = cn.getPackageName(); 17128 17129 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 17130 packageName); 17131 if (ivi == null) { 17132 return true; 17133 } 17134 int status = ivi.getStatus(); 17135 switch (status) { 17136 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 17137 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 17138 return true; 17139 17140 default: 17141 // Nothing to do 17142 return false; 17143 } 17144 } 17145 17146 private static boolean isMultiArch(ApplicationInfo info) { 17147 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 17148 } 17149 17150 private static boolean isExternal(PackageParser.Package pkg) { 17151 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 17152 } 17153 17154 private static boolean isExternal(PackageSetting ps) { 17155 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 17156 } 17157 17158 private static boolean isSystemApp(PackageParser.Package pkg) { 17159 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 17160 } 17161 17162 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 17163 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 17164 } 17165 17166 private static boolean hasDomainURLs(PackageParser.Package pkg) { 17167 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 17168 } 17169 17170 private static boolean isSystemApp(PackageSetting ps) { 17171 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 17172 } 17173 17174 private static boolean isUpdatedSystemApp(PackageSetting ps) { 17175 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 17176 } 17177 17178 private int packageFlagsToInstallFlags(PackageSetting ps) { 17179 int installFlags = 0; 17180 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 17181 // This existing package was an external ASEC install when we have 17182 // the external flag without a UUID 17183 installFlags |= PackageManager.INSTALL_EXTERNAL; 17184 } 17185 if (ps.isForwardLocked()) { 17186 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 17187 } 17188 return installFlags; 17189 } 17190 17191 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 17192 if (isExternal(pkg)) { 17193 if (TextUtils.isEmpty(pkg.volumeUuid)) { 17194 return StorageManager.UUID_PRIMARY_PHYSICAL; 17195 } else { 17196 return pkg.volumeUuid; 17197 } 17198 } else { 17199 return StorageManager.UUID_PRIVATE_INTERNAL; 17200 } 17201 } 17202 17203 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 17204 if (isExternal(pkg)) { 17205 if (TextUtils.isEmpty(pkg.volumeUuid)) { 17206 return mSettings.getExternalVersion(); 17207 } else { 17208 return mSettings.findOrCreateVersion(pkg.volumeUuid); 17209 } 17210 } else { 17211 return mSettings.getInternalVersion(); 17212 } 17213 } 17214 17215 private void deleteTempPackageFiles() { 17216 final FilenameFilter filter = new FilenameFilter() { 17217 public boolean accept(File dir, String name) { 17218 return name.startsWith("vmdl") && name.endsWith(".tmp"); 17219 } 17220 }; 17221 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 17222 file.delete(); 17223 } 17224 } 17225 17226 @Override 17227 public void deletePackageAsUser(String packageName, int versionCode, 17228 IPackageDeleteObserver observer, int userId, int flags) { 17229 deletePackageVersioned(new VersionedPackage(packageName, versionCode), 17230 new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags); 17231 } 17232 17233 @Override 17234 public void deletePackageVersioned(VersionedPackage versionedPackage, 17235 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 17236 mContext.enforceCallingOrSelfPermission( 17237 android.Manifest.permission.DELETE_PACKAGES, null); 17238 Preconditions.checkNotNull(versionedPackage); 17239 Preconditions.checkNotNull(observer); 17240 Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(), 17241 PackageManager.VERSION_CODE_HIGHEST, 17242 Integer.MAX_VALUE, "versionCode must be >= -1"); 17243 17244 final String packageName = versionedPackage.getPackageName(); 17245 // TODO: We will change version code to long, so in the new API it is long 17246 final int versionCode = (int) versionedPackage.getVersionCode(); 17247 final String internalPackageName; 17248 synchronized (mPackages) { 17249 // Normalize package name to handle renamed packages and static libs 17250 internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(), 17251 // TODO: We will change version code to long, so in the new API it is long 17252 (int) versionedPackage.getVersionCode()); 17253 } 17254 17255 final int uid = Binder.getCallingUid(); 17256 if (!isOrphaned(internalPackageName) 17257 && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) { 17258 try { 17259 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 17260 intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null)); 17261 intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder()); 17262 observer.onUserActionRequired(intent); 17263 } catch (RemoteException re) { 17264 } 17265 return; 17266 } 17267 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 17268 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 17269 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 17270 mContext.enforceCallingOrSelfPermission( 17271 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 17272 "deletePackage for user " + userId); 17273 } 17274 17275 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 17276 try { 17277 observer.onPackageDeleted(packageName, 17278 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 17279 } catch (RemoteException re) { 17280 } 17281 return; 17282 } 17283 17284 if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) { 17285 try { 17286 observer.onPackageDeleted(packageName, 17287 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 17288 } catch (RemoteException re) { 17289 } 17290 return; 17291 } 17292 17293 if (DEBUG_REMOVE) { 17294 Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId 17295 + " deleteAllUsers: " + deleteAllUsers + " version=" 17296 + (versionCode == PackageManager.VERSION_CODE_HIGHEST 17297 ? "VERSION_CODE_HIGHEST" : versionCode)); 17298 } 17299 // Queue up an async operation since the package deletion may take a little while. 17300 mHandler.post(new Runnable() { 17301 public void run() { 17302 mHandler.removeCallbacks(this); 17303 int returnCode; 17304 if (!deleteAllUsers) { 17305 returnCode = deletePackageX(internalPackageName, versionCode, 17306 userId, deleteFlags); 17307 } else { 17308 int[] blockUninstallUserIds = getBlockUninstallForUsers( 17309 internalPackageName, users); 17310 // If nobody is blocking uninstall, proceed with delete for all users 17311 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 17312 returnCode = deletePackageX(internalPackageName, versionCode, 17313 userId, deleteFlags); 17314 } else { 17315 // Otherwise uninstall individually for users with blockUninstalls=false 17316 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 17317 for (int userId : users) { 17318 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 17319 returnCode = deletePackageX(internalPackageName, versionCode, 17320 userId, userFlags); 17321 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 17322 Slog.w(TAG, "Package delete failed for user " + userId 17323 + ", returnCode " + returnCode); 17324 } 17325 } 17326 } 17327 // The app has only been marked uninstalled for certain users. 17328 // We still need to report that delete was blocked 17329 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 17330 } 17331 } 17332 try { 17333 observer.onPackageDeleted(packageName, returnCode, null); 17334 } catch (RemoteException e) { 17335 Log.i(TAG, "Observer no longer exists."); 17336 } //end catch 17337 } //end run 17338 }); 17339 } 17340 17341 private String resolveExternalPackageNameLPr(PackageParser.Package pkg) { 17342 if (pkg.staticSharedLibName != null) { 17343 return pkg.manifestPackageName; 17344 } 17345 return pkg.packageName; 17346 } 17347 17348 private String resolveInternalPackageNameLPr(String packageName, int versionCode) { 17349 // Handle renamed packages 17350 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 17351 packageName = normalizedPackageName != null ? normalizedPackageName : packageName; 17352 17353 // Is this a static library? 17354 SparseArray<SharedLibraryEntry> versionedLib = 17355 mStaticLibsByDeclaringPackage.get(packageName); 17356 if (versionedLib == null || versionedLib.size() <= 0) { 17357 return packageName; 17358 } 17359 17360 // Figure out which lib versions the caller can see 17361 SparseIntArray versionsCallerCanSee = null; 17362 final int callingAppId = UserHandle.getAppId(Binder.getCallingUid()); 17363 if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID 17364 && callingAppId != Process.ROOT_UID) { 17365 versionsCallerCanSee = new SparseIntArray(); 17366 String libName = versionedLib.valueAt(0).info.getName(); 17367 String[] uidPackages = getPackagesForUid(Binder.getCallingUid()); 17368 if (uidPackages != null) { 17369 for (String uidPackage : uidPackages) { 17370 PackageSetting ps = mSettings.getPackageLPr(uidPackage); 17371 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 17372 if (libIdx >= 0) { 17373 final int libVersion = ps.usesStaticLibrariesVersions[libIdx]; 17374 versionsCallerCanSee.append(libVersion, libVersion); 17375 } 17376 } 17377 } 17378 } 17379 17380 // Caller can see nothing - done 17381 if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) { 17382 return packageName; 17383 } 17384 17385 // Find the version the caller can see and the app version code 17386 SharedLibraryEntry highestVersion = null; 17387 final int versionCount = versionedLib.size(); 17388 for (int i = 0; i < versionCount; i++) { 17389 SharedLibraryEntry libEntry = versionedLib.valueAt(i); 17390 if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey( 17391 libEntry.info.getVersion()) < 0) { 17392 continue; 17393 } 17394 // TODO: We will change version code to long, so in the new API it is long 17395 final int libVersionCode = (int) libEntry.info.getDeclaringPackage().getVersionCode(); 17396 if (versionCode != PackageManager.VERSION_CODE_HIGHEST) { 17397 if (libVersionCode == versionCode) { 17398 return libEntry.apk; 17399 } 17400 } else if (highestVersion == null) { 17401 highestVersion = libEntry; 17402 } else if (libVersionCode > highestVersion.info 17403 .getDeclaringPackage().getVersionCode()) { 17404 highestVersion = libEntry; 17405 } 17406 } 17407 17408 if (highestVersion != null) { 17409 return highestVersion.apk; 17410 } 17411 17412 return packageName; 17413 } 17414 17415 private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) { 17416 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID 17417 || callingUid == Process.SYSTEM_UID) { 17418 return true; 17419 } 17420 final int callingUserId = UserHandle.getUserId(callingUid); 17421 // If the caller installed the pkgName, then allow it to silently uninstall. 17422 if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) { 17423 return true; 17424 } 17425 17426 // Allow package verifier to silently uninstall. 17427 if (mRequiredVerifierPackage != null && 17428 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) { 17429 return true; 17430 } 17431 17432 // Allow package uninstaller to silently uninstall. 17433 if (mRequiredUninstallerPackage != null && 17434 callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) { 17435 return true; 17436 } 17437 17438 // Allow storage manager to silently uninstall. 17439 if (mStorageManagerPackage != null && 17440 callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) { 17441 return true; 17442 } 17443 return false; 17444 } 17445 17446 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 17447 int[] result = EMPTY_INT_ARRAY; 17448 for (int userId : userIds) { 17449 if (getBlockUninstallForUser(packageName, userId)) { 17450 result = ArrayUtils.appendInt(result, userId); 17451 } 17452 } 17453 return result; 17454 } 17455 17456 @Override 17457 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 17458 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 17459 } 17460 17461 private boolean isPackageDeviceAdmin(String packageName, int userId) { 17462 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 17463 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 17464 try { 17465 if (dpm != null) { 17466 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 17467 /* callingUserOnly =*/ false); 17468 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 17469 : deviceOwnerComponentName.getPackageName(); 17470 // Does the package contains the device owner? 17471 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 17472 // this check is probably not needed, since DO should be registered as a device 17473 // admin on some user too. (Original bug for this: b/17657954) 17474 if (packageName.equals(deviceOwnerPackageName)) { 17475 return true; 17476 } 17477 // Does it contain a device admin for any user? 17478 int[] users; 17479 if (userId == UserHandle.USER_ALL) { 17480 users = sUserManager.getUserIds(); 17481 } else { 17482 users = new int[]{userId}; 17483 } 17484 for (int i = 0; i < users.length; ++i) { 17485 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 17486 return true; 17487 } 17488 } 17489 } 17490 } catch (RemoteException e) { 17491 } 17492 return false; 17493 } 17494 17495 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 17496 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 17497 } 17498 17499 /** 17500 * This method is an internal method that could be get invoked either 17501 * to delete an installed package or to clean up a failed installation. 17502 * After deleting an installed package, a broadcast is sent to notify any 17503 * listeners that the package has been removed. For cleaning up a failed 17504 * installation, the broadcast is not necessary since the package's 17505 * installation wouldn't have sent the initial broadcast either 17506 * The key steps in deleting a package are 17507 * deleting the package information in internal structures like mPackages, 17508 * deleting the packages base directories through installd 17509 * updating mSettings to reflect current status 17510 * persisting settings for later use 17511 * sending a broadcast if necessary 17512 */ 17513 private int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) { 17514 final PackageRemovedInfo info = new PackageRemovedInfo(); 17515 final boolean res; 17516 17517 final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 17518 ? UserHandle.USER_ALL : userId; 17519 17520 if (isPackageDeviceAdmin(packageName, removeUser)) { 17521 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 17522 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 17523 } 17524 17525 PackageSetting uninstalledPs = null; 17526 17527 // for the uninstall-updates case and restricted profiles, remember the per- 17528 // user handle installed state 17529 int[] allUsers; 17530 synchronized (mPackages) { 17531 uninstalledPs = mSettings.mPackages.get(packageName); 17532 if (uninstalledPs == null) { 17533 Slog.w(TAG, "Not removing non-existent package " + packageName); 17534 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17535 } 17536 17537 if (versionCode != PackageManager.VERSION_CODE_HIGHEST 17538 && uninstalledPs.versionCode != versionCode) { 17539 Slog.w(TAG, "Not removing package " + packageName + " with versionCode " 17540 + uninstalledPs.versionCode + " != " + versionCode); 17541 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17542 } 17543 17544 // Static shared libs can be declared by any package, so let us not 17545 // allow removing a package if it provides a lib others depend on. 17546 PackageParser.Package pkg = mPackages.get(packageName); 17547 if (pkg != null && pkg.staticSharedLibName != null) { 17548 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName, 17549 pkg.staticSharedLibVersion); 17550 if (libEntry != null) { 17551 List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr( 17552 libEntry.info, 0, userId); 17553 if (!ArrayUtils.isEmpty(libClientPackages)) { 17554 Slog.w(TAG, "Not removing package " + pkg.manifestPackageName 17555 + " hosting lib " + libEntry.info.getName() + " version " 17556 + libEntry.info.getVersion() + " used by " + libClientPackages); 17557 return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY; 17558 } 17559 } 17560 } 17561 17562 allUsers = sUserManager.getUserIds(); 17563 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 17564 } 17565 17566 final int freezeUser; 17567 if (isUpdatedSystemApp(uninstalledPs) 17568 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) { 17569 // We're downgrading a system app, which will apply to all users, so 17570 // freeze them all during the downgrade 17571 freezeUser = UserHandle.USER_ALL; 17572 } else { 17573 freezeUser = removeUser; 17574 } 17575 17576 synchronized (mInstallLock) { 17577 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 17578 try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser, 17579 deleteFlags, "deletePackageX")) { 17580 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers, 17581 deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null); 17582 } 17583 synchronized (mPackages) { 17584 if (res) { 17585 mInstantAppRegistry.onPackageUninstalledLPw(uninstalledPs.pkg, 17586 info.removedUsers); 17587 updateSequenceNumberLP(packageName, info.removedUsers); 17588 } 17589 } 17590 } 17591 17592 if (res) { 17593 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 17594 info.sendPackageRemovedBroadcasts(killApp); 17595 info.sendSystemPackageUpdatedBroadcasts(); 17596 info.sendSystemPackageAppearedBroadcasts(); 17597 } 17598 // Force a gc here. 17599 Runtime.getRuntime().gc(); 17600 // Delete the resources here after sending the broadcast to let 17601 // other processes clean up before deleting resources. 17602 if (info.args != null) { 17603 synchronized (mInstallLock) { 17604 info.args.doPostDeleteLI(true); 17605 } 17606 } 17607 17608 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17609 } 17610 17611 class PackageRemovedInfo { 17612 String removedPackage; 17613 int uid = -1; 17614 int removedAppId = -1; 17615 int[] origUsers; 17616 int[] removedUsers = null; 17617 SparseArray<Integer> installReasons; 17618 boolean isRemovedPackageSystemUpdate = false; 17619 boolean isUpdate; 17620 boolean dataRemoved; 17621 boolean removedForAllUsers; 17622 boolean isStaticSharedLib; 17623 // Clean up resources deleted packages. 17624 InstallArgs args = null; 17625 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 17626 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 17627 17628 void sendPackageRemovedBroadcasts(boolean killApp) { 17629 sendPackageRemovedBroadcastInternal(killApp); 17630 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 17631 for (int i = 0; i < childCount; i++) { 17632 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 17633 childInfo.sendPackageRemovedBroadcastInternal(killApp); 17634 } 17635 } 17636 17637 void sendSystemPackageUpdatedBroadcasts() { 17638 if (isRemovedPackageSystemUpdate) { 17639 sendSystemPackageUpdatedBroadcastsInternal(); 17640 final int childCount = (removedChildPackages != null) 17641 ? removedChildPackages.size() : 0; 17642 for (int i = 0; i < childCount; i++) { 17643 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 17644 if (childInfo.isRemovedPackageSystemUpdate) { 17645 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 17646 } 17647 } 17648 } 17649 } 17650 17651 void sendSystemPackageAppearedBroadcasts() { 17652 final int packageCount = (appearedChildPackages != null) 17653 ? appearedChildPackages.size() : 0; 17654 for (int i = 0; i < packageCount; i++) { 17655 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 17656 sendPackageAddedForNewUsers(installedInfo.name, true, 17657 UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers); 17658 } 17659 } 17660 17661 private void sendSystemPackageUpdatedBroadcastsInternal() { 17662 Bundle extras = new Bundle(2); 17663 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 17664 extras.putBoolean(Intent.EXTRA_REPLACING, true); 17665 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 17666 extras, 0, null, null, null); 17667 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 17668 extras, 0, null, null, null); 17669 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 17670 null, 0, removedPackage, null, null); 17671 } 17672 17673 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 17674 // Don't send static shared library removal broadcasts as these 17675 // libs are visible only the the apps that depend on them an one 17676 // cannot remove the library if it has a dependency. 17677 if (isStaticSharedLib) { 17678 return; 17679 } 17680 Bundle extras = new Bundle(2); 17681 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 17682 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 17683 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 17684 if (isUpdate || isRemovedPackageSystemUpdate) { 17685 extras.putBoolean(Intent.EXTRA_REPLACING, true); 17686 } 17687 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 17688 if (removedPackage != null) { 17689 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 17690 extras, 0, null, null, removedUsers); 17691 if (dataRemoved && !isRemovedPackageSystemUpdate) { 17692 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 17693 removedPackage, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, 17694 null, null, removedUsers); 17695 } 17696 } 17697 if (removedAppId >= 0) { 17698 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 17699 removedUsers); 17700 } 17701 } 17702 } 17703 17704 /* 17705 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 17706 * flag is not set, the data directory is removed as well. 17707 * make sure this flag is set for partially installed apps. If not its meaningless to 17708 * delete a partially installed application. 17709 */ 17710 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 17711 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 17712 String packageName = ps.name; 17713 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 17714 // Retrieve object to delete permissions for shared user later on 17715 final PackageParser.Package deletedPkg; 17716 final PackageSetting deletedPs; 17717 // reader 17718 synchronized (mPackages) { 17719 deletedPkg = mPackages.get(packageName); 17720 deletedPs = mSettings.mPackages.get(packageName); 17721 if (outInfo != null) { 17722 outInfo.removedPackage = packageName; 17723 outInfo.isStaticSharedLib = deletedPkg != null 17724 && deletedPkg.staticSharedLibName != null; 17725 outInfo.removedUsers = deletedPs != null 17726 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 17727 : null; 17728 } 17729 } 17730 17731 removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0); 17732 17733 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 17734 final PackageParser.Package resolvedPkg; 17735 if (deletedPkg != null) { 17736 resolvedPkg = deletedPkg; 17737 } else { 17738 // We don't have a parsed package when it lives on an ejected 17739 // adopted storage device, so fake something together 17740 resolvedPkg = new PackageParser.Package(ps.name); 17741 resolvedPkg.setVolumeUuid(ps.volumeUuid); 17742 } 17743 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 17744 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 17745 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 17746 if (outInfo != null) { 17747 outInfo.dataRemoved = true; 17748 } 17749 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 17750 } 17751 17752 int removedAppId = -1; 17753 17754 // writer 17755 synchronized (mPackages) { 17756 boolean installedStateChanged = false; 17757 if (deletedPs != null) { 17758 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 17759 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 17760 clearDefaultBrowserIfNeeded(packageName); 17761 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 17762 removedAppId = mSettings.removePackageLPw(packageName); 17763 if (outInfo != null) { 17764 outInfo.removedAppId = removedAppId; 17765 } 17766 updatePermissionsLPw(deletedPs.name, null, 0); 17767 if (deletedPs.sharedUser != null) { 17768 // Remove permissions associated with package. Since runtime 17769 // permissions are per user we have to kill the removed package 17770 // or packages running under the shared user of the removed 17771 // package if revoking the permissions requested only by the removed 17772 // package is successful and this causes a change in gids. 17773 for (int userId : UserManagerService.getInstance().getUserIds()) { 17774 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 17775 userId); 17776 if (userIdToKill == UserHandle.USER_ALL 17777 || userIdToKill >= UserHandle.USER_SYSTEM) { 17778 // If gids changed for this user, kill all affected packages. 17779 mHandler.post(new Runnable() { 17780 @Override 17781 public void run() { 17782 // This has to happen with no lock held. 17783 killApplication(deletedPs.name, deletedPs.appId, 17784 KILL_APP_REASON_GIDS_CHANGED); 17785 } 17786 }); 17787 break; 17788 } 17789 } 17790 } 17791 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 17792 } 17793 // make sure to preserve per-user disabled state if this removal was just 17794 // a downgrade of a system app to the factory package 17795 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 17796 if (DEBUG_REMOVE) { 17797 Slog.d(TAG, "Propagating install state across downgrade"); 17798 } 17799 for (int userId : allUserHandles) { 17800 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 17801 if (DEBUG_REMOVE) { 17802 Slog.d(TAG, " user " + userId + " => " + installed); 17803 } 17804 if (installed != ps.getInstalled(userId)) { 17805 installedStateChanged = true; 17806 } 17807 ps.setInstalled(installed, userId); 17808 } 17809 } 17810 } 17811 // can downgrade to reader 17812 if (writeSettings) { 17813 // Save settings now 17814 mSettings.writeLPr(); 17815 } 17816 if (installedStateChanged) { 17817 mSettings.writeKernelMappingLPr(ps); 17818 } 17819 } 17820 if (removedAppId != -1) { 17821 // A user ID was deleted here. Go through all users and remove it 17822 // from KeyStore. 17823 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId); 17824 } 17825 } 17826 17827 static boolean locationIsPrivileged(File path) { 17828 try { 17829 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 17830 .getCanonicalPath(); 17831 return path.getCanonicalPath().startsWith(privilegedAppDir); 17832 } catch (IOException e) { 17833 Slog.e(TAG, "Unable to access code path " + path); 17834 } 17835 return false; 17836 } 17837 17838 /* 17839 * Tries to delete system package. 17840 */ 17841 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 17842 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 17843 boolean writeSettings) { 17844 if (deletedPs.parentPackageName != null) { 17845 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 17846 return false; 17847 } 17848 17849 final boolean applyUserRestrictions 17850 = (allUserHandles != null) && (outInfo.origUsers != null); 17851 final PackageSetting disabledPs; 17852 // Confirm if the system package has been updated 17853 // An updated system app can be deleted. This will also have to restore 17854 // the system pkg from system partition 17855 // reader 17856 synchronized (mPackages) { 17857 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 17858 } 17859 17860 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 17861 + " disabledPs=" + disabledPs); 17862 17863 if (disabledPs == null) { 17864 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 17865 return false; 17866 } else if (DEBUG_REMOVE) { 17867 Slog.d(TAG, "Deleting system pkg from data partition"); 17868 } 17869 17870 if (DEBUG_REMOVE) { 17871 if (applyUserRestrictions) { 17872 Slog.d(TAG, "Remembering install states:"); 17873 for (int userId : allUserHandles) { 17874 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 17875 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 17876 } 17877 } 17878 } 17879 17880 // Delete the updated package 17881 outInfo.isRemovedPackageSystemUpdate = true; 17882 if (outInfo.removedChildPackages != null) { 17883 final int childCount = (deletedPs.childPackageNames != null) 17884 ? deletedPs.childPackageNames.size() : 0; 17885 for (int i = 0; i < childCount; i++) { 17886 String childPackageName = deletedPs.childPackageNames.get(i); 17887 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 17888 .contains(childPackageName)) { 17889 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 17890 childPackageName); 17891 if (childInfo != null) { 17892 childInfo.isRemovedPackageSystemUpdate = true; 17893 } 17894 } 17895 } 17896 } 17897 17898 if (disabledPs.versionCode < deletedPs.versionCode) { 17899 // Delete data for downgrades 17900 flags &= ~PackageManager.DELETE_KEEP_DATA; 17901 } else { 17902 // Preserve data by setting flag 17903 flags |= PackageManager.DELETE_KEEP_DATA; 17904 } 17905 17906 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 17907 outInfo, writeSettings, disabledPs.pkg); 17908 if (!ret) { 17909 return false; 17910 } 17911 17912 // writer 17913 synchronized (mPackages) { 17914 // Reinstate the old system package 17915 enableSystemPackageLPw(disabledPs.pkg); 17916 // Remove any native libraries from the upgraded package. 17917 removeNativeBinariesLI(deletedPs); 17918 } 17919 17920 // Install the system package 17921 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 17922 int parseFlags = mDefParseFlags 17923 | PackageParser.PARSE_MUST_BE_APK 17924 | PackageParser.PARSE_IS_SYSTEM 17925 | PackageParser.PARSE_IS_SYSTEM_DIR; 17926 if (locationIsPrivileged(disabledPs.codePath)) { 17927 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 17928 } 17929 17930 final PackageParser.Package newPkg; 17931 try { 17932 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */, 17933 0 /* currentTime */, null); 17934 } catch (PackageManagerException e) { 17935 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 17936 + e.getMessage()); 17937 return false; 17938 } 17939 17940 try { 17941 // update shared libraries for the newly re-installed system package 17942 updateSharedLibrariesLPr(newPkg, null); 17943 } catch (PackageManagerException e) { 17944 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 17945 } 17946 17947 prepareAppDataAfterInstallLIF(newPkg); 17948 17949 // writer 17950 synchronized (mPackages) { 17951 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 17952 17953 // Propagate the permissions state as we do not want to drop on the floor 17954 // runtime permissions. The update permissions method below will take 17955 // care of removing obsolete permissions and grant install permissions. 17956 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 17957 updatePermissionsLPw(newPkg.packageName, newPkg, 17958 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 17959 17960 if (applyUserRestrictions) { 17961 boolean installedStateChanged = false; 17962 if (DEBUG_REMOVE) { 17963 Slog.d(TAG, "Propagating install state across reinstall"); 17964 } 17965 for (int userId : allUserHandles) { 17966 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 17967 if (DEBUG_REMOVE) { 17968 Slog.d(TAG, " user " + userId + " => " + installed); 17969 } 17970 if (installed != ps.getInstalled(userId)) { 17971 installedStateChanged = true; 17972 } 17973 ps.setInstalled(installed, userId); 17974 17975 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 17976 } 17977 // Regardless of writeSettings we need to ensure that this restriction 17978 // state propagation is persisted 17979 mSettings.writeAllUsersPackageRestrictionsLPr(); 17980 if (installedStateChanged) { 17981 mSettings.writeKernelMappingLPr(ps); 17982 } 17983 } 17984 // can downgrade to reader here 17985 if (writeSettings) { 17986 mSettings.writeLPr(); 17987 } 17988 } 17989 return true; 17990 } 17991 17992 private boolean deleteInstalledPackageLIF(PackageSetting ps, 17993 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 17994 PackageRemovedInfo outInfo, boolean writeSettings, 17995 PackageParser.Package replacingPackage) { 17996 synchronized (mPackages) { 17997 if (outInfo != null) { 17998 outInfo.uid = ps.appId; 17999 } 18000 18001 if (outInfo != null && outInfo.removedChildPackages != null) { 18002 final int childCount = (ps.childPackageNames != null) 18003 ? ps.childPackageNames.size() : 0; 18004 for (int i = 0; i < childCount; i++) { 18005 String childPackageName = ps.childPackageNames.get(i); 18006 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 18007 if (childPs == null) { 18008 return false; 18009 } 18010 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 18011 childPackageName); 18012 if (childInfo != null) { 18013 childInfo.uid = childPs.appId; 18014 } 18015 } 18016 } 18017 } 18018 18019 // Delete package data from internal structures and also remove data if flag is set 18020 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 18021 18022 // Delete the child packages data 18023 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 18024 for (int i = 0; i < childCount; i++) { 18025 PackageSetting childPs; 18026 synchronized (mPackages) { 18027 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 18028 } 18029 if (childPs != null) { 18030 PackageRemovedInfo childOutInfo = (outInfo != null 18031 && outInfo.removedChildPackages != null) 18032 ? outInfo.removedChildPackages.get(childPs.name) : null; 18033 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 18034 && (replacingPackage != null 18035 && !replacingPackage.hasChildPackage(childPs.name)) 18036 ? flags & ~DELETE_KEEP_DATA : flags; 18037 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 18038 deleteFlags, writeSettings); 18039 } 18040 } 18041 18042 // Delete application code and resources only for parent packages 18043 if (ps.parentPackageName == null) { 18044 if (deleteCodeAndResources && (outInfo != null)) { 18045 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 18046 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 18047 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 18048 } 18049 } 18050 18051 return true; 18052 } 18053 18054 @Override 18055 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 18056 int userId) { 18057 mContext.enforceCallingOrSelfPermission( 18058 android.Manifest.permission.DELETE_PACKAGES, null); 18059 synchronized (mPackages) { 18060 PackageSetting ps = mSettings.mPackages.get(packageName); 18061 if (ps == null) { 18062 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 18063 return false; 18064 } 18065 // Cannot block uninstall of static shared libs as they are 18066 // considered a part of the using app (emulating static linking). 18067 // Also static libs are installed always on internal storage. 18068 PackageParser.Package pkg = mPackages.get(packageName); 18069 if (pkg != null && pkg.staticSharedLibName != null) { 18070 Slog.w(TAG, "Cannot block uninstall of package: " + packageName 18071 + " providing static shared library: " + pkg.staticSharedLibName); 18072 return false; 18073 } 18074 if (!ps.getInstalled(userId)) { 18075 // Can't block uninstall for an app that is not installed or enabled. 18076 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 18077 return false; 18078 } 18079 ps.setBlockUninstall(blockUninstall, userId); 18080 mSettings.writePackageRestrictionsLPr(userId); 18081 } 18082 return true; 18083 } 18084 18085 @Override 18086 public boolean getBlockUninstallForUser(String packageName, int userId) { 18087 synchronized (mPackages) { 18088 PackageSetting ps = mSettings.mPackages.get(packageName); 18089 if (ps == null) { 18090 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 18091 return false; 18092 } 18093 return ps.getBlockUninstall(userId); 18094 } 18095 } 18096 18097 @Override 18098 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 18099 int callingUid = Binder.getCallingUid(); 18100 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 18101 throw new SecurityException( 18102 "setRequiredForSystemUser can only be run by the system or root"); 18103 } 18104 synchronized (mPackages) { 18105 PackageSetting ps = mSettings.mPackages.get(packageName); 18106 if (ps == null) { 18107 Log.w(TAG, "Package doesn't exist: " + packageName); 18108 return false; 18109 } 18110 if (systemUserApp) { 18111 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 18112 } else { 18113 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 18114 } 18115 mSettings.writeLPr(); 18116 } 18117 return true; 18118 } 18119 18120 /* 18121 * This method handles package deletion in general 18122 */ 18123 private boolean deletePackageLIF(String packageName, UserHandle user, 18124 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 18125 PackageRemovedInfo outInfo, boolean writeSettings, 18126 PackageParser.Package replacingPackage) { 18127 if (packageName == null) { 18128 Slog.w(TAG, "Attempt to delete null packageName."); 18129 return false; 18130 } 18131 18132 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 18133 18134 PackageSetting ps; 18135 synchronized (mPackages) { 18136 ps = mSettings.mPackages.get(packageName); 18137 if (ps == null) { 18138 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 18139 return false; 18140 } 18141 18142 if (ps.parentPackageName != null && (!isSystemApp(ps) 18143 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 18144 if (DEBUG_REMOVE) { 18145 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 18146 + ((user == null) ? UserHandle.USER_ALL : user)); 18147 } 18148 final int removedUserId = (user != null) ? user.getIdentifier() 18149 : UserHandle.USER_ALL; 18150 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 18151 return false; 18152 } 18153 markPackageUninstalledForUserLPw(ps, user); 18154 scheduleWritePackageRestrictionsLocked(user); 18155 return true; 18156 } 18157 } 18158 18159 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 18160 && user.getIdentifier() != UserHandle.USER_ALL)) { 18161 // The caller is asking that the package only be deleted for a single 18162 // user. To do this, we just mark its uninstalled state and delete 18163 // its data. If this is a system app, we only allow this to happen if 18164 // they have set the special DELETE_SYSTEM_APP which requests different 18165 // semantics than normal for uninstalling system apps. 18166 markPackageUninstalledForUserLPw(ps, user); 18167 18168 if (!isSystemApp(ps)) { 18169 // Do not uninstall the APK if an app should be cached 18170 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 18171 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 18172 // Other user still have this package installed, so all 18173 // we need to do is clear this user's data and save that 18174 // it is uninstalled. 18175 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 18176 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 18177 return false; 18178 } 18179 scheduleWritePackageRestrictionsLocked(user); 18180 return true; 18181 } else { 18182 // We need to set it back to 'installed' so the uninstall 18183 // broadcasts will be sent correctly. 18184 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 18185 ps.setInstalled(true, user.getIdentifier()); 18186 mSettings.writeKernelMappingLPr(ps); 18187 } 18188 } else { 18189 // This is a system app, so we assume that the 18190 // other users still have this package installed, so all 18191 // we need to do is clear this user's data and save that 18192 // it is uninstalled. 18193 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 18194 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 18195 return false; 18196 } 18197 scheduleWritePackageRestrictionsLocked(user); 18198 return true; 18199 } 18200 } 18201 18202 // If we are deleting a composite package for all users, keep track 18203 // of result for each child. 18204 if (ps.childPackageNames != null && outInfo != null) { 18205 synchronized (mPackages) { 18206 final int childCount = ps.childPackageNames.size(); 18207 outInfo.removedChildPackages = new ArrayMap<>(childCount); 18208 for (int i = 0; i < childCount; i++) { 18209 String childPackageName = ps.childPackageNames.get(i); 18210 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 18211 childInfo.removedPackage = childPackageName; 18212 outInfo.removedChildPackages.put(childPackageName, childInfo); 18213 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 18214 if (childPs != null) { 18215 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 18216 } 18217 } 18218 } 18219 } 18220 18221 boolean ret = false; 18222 if (isSystemApp(ps)) { 18223 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 18224 // When an updated system application is deleted we delete the existing resources 18225 // as well and fall back to existing code in system partition 18226 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 18227 } else { 18228 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 18229 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 18230 outInfo, writeSettings, replacingPackage); 18231 } 18232 18233 // Take a note whether we deleted the package for all users 18234 if (outInfo != null) { 18235 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 18236 if (outInfo.removedChildPackages != null) { 18237 synchronized (mPackages) { 18238 final int childCount = outInfo.removedChildPackages.size(); 18239 for (int i = 0; i < childCount; i++) { 18240 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 18241 if (childInfo != null) { 18242 childInfo.removedForAllUsers = mPackages.get( 18243 childInfo.removedPackage) == null; 18244 } 18245 } 18246 } 18247 } 18248 // If we uninstalled an update to a system app there may be some 18249 // child packages that appeared as they are declared in the system 18250 // app but were not declared in the update. 18251 if (isSystemApp(ps)) { 18252 synchronized (mPackages) { 18253 PackageSetting updatedPs = mSettings.getPackageLPr(ps.name); 18254 final int childCount = (updatedPs.childPackageNames != null) 18255 ? updatedPs.childPackageNames.size() : 0; 18256 for (int i = 0; i < childCount; i++) { 18257 String childPackageName = updatedPs.childPackageNames.get(i); 18258 if (outInfo.removedChildPackages == null 18259 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 18260 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 18261 if (childPs == null) { 18262 continue; 18263 } 18264 PackageInstalledInfo installRes = new PackageInstalledInfo(); 18265 installRes.name = childPackageName; 18266 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 18267 installRes.pkg = mPackages.get(childPackageName); 18268 installRes.uid = childPs.pkg.applicationInfo.uid; 18269 if (outInfo.appearedChildPackages == null) { 18270 outInfo.appearedChildPackages = new ArrayMap<>(); 18271 } 18272 outInfo.appearedChildPackages.put(childPackageName, installRes); 18273 } 18274 } 18275 } 18276 } 18277 } 18278 18279 return ret; 18280 } 18281 18282 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 18283 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 18284 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 18285 for (int nextUserId : userIds) { 18286 if (DEBUG_REMOVE) { 18287 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 18288 } 18289 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 18290 false /*installed*/, 18291 true /*stopped*/, 18292 true /*notLaunched*/, 18293 false /*hidden*/, 18294 false /*suspended*/, 18295 false /*instantApp*/, 18296 null /*lastDisableAppCaller*/, 18297 null /*enabledComponents*/, 18298 null /*disabledComponents*/, 18299 false /*blockUninstall*/, 18300 ps.readUserState(nextUserId).domainVerificationStatus, 18301 0, PackageManager.INSTALL_REASON_UNKNOWN); 18302 } 18303 mSettings.writeKernelMappingLPr(ps); 18304 } 18305 18306 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 18307 PackageRemovedInfo outInfo) { 18308 final PackageParser.Package pkg; 18309 synchronized (mPackages) { 18310 pkg = mPackages.get(ps.name); 18311 } 18312 18313 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 18314 : new int[] {userId}; 18315 for (int nextUserId : userIds) { 18316 if (DEBUG_REMOVE) { 18317 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 18318 + nextUserId); 18319 } 18320 18321 destroyAppDataLIF(pkg, userId, 18322 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18323 destroyAppProfilesLIF(pkg, userId); 18324 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 18325 schedulePackageCleaning(ps.name, nextUserId, false); 18326 synchronized (mPackages) { 18327 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 18328 scheduleWritePackageRestrictionsLocked(nextUserId); 18329 } 18330 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 18331 } 18332 } 18333 18334 if (outInfo != null) { 18335 outInfo.removedPackage = ps.name; 18336 outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null; 18337 outInfo.removedAppId = ps.appId; 18338 outInfo.removedUsers = userIds; 18339 } 18340 18341 return true; 18342 } 18343 18344 private final class ClearStorageConnection implements ServiceConnection { 18345 IMediaContainerService mContainerService; 18346 18347 @Override 18348 public void onServiceConnected(ComponentName name, IBinder service) { 18349 synchronized (this) { 18350 mContainerService = IMediaContainerService.Stub 18351 .asInterface(Binder.allowBlocking(service)); 18352 notifyAll(); 18353 } 18354 } 18355 18356 @Override 18357 public void onServiceDisconnected(ComponentName name) { 18358 } 18359 } 18360 18361 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 18362 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 18363 18364 final boolean mounted; 18365 if (Environment.isExternalStorageEmulated()) { 18366 mounted = true; 18367 } else { 18368 final String status = Environment.getExternalStorageState(); 18369 18370 mounted = status.equals(Environment.MEDIA_MOUNTED) 18371 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 18372 } 18373 18374 if (!mounted) { 18375 return; 18376 } 18377 18378 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 18379 int[] users; 18380 if (userId == UserHandle.USER_ALL) { 18381 users = sUserManager.getUserIds(); 18382 } else { 18383 users = new int[] { userId }; 18384 } 18385 final ClearStorageConnection conn = new ClearStorageConnection(); 18386 if (mContext.bindServiceAsUser( 18387 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 18388 try { 18389 for (int curUser : users) { 18390 long timeout = SystemClock.uptimeMillis() + 5000; 18391 synchronized (conn) { 18392 long now; 18393 while (conn.mContainerService == null && 18394 (now = SystemClock.uptimeMillis()) < timeout) { 18395 try { 18396 conn.wait(timeout - now); 18397 } catch (InterruptedException e) { 18398 } 18399 } 18400 } 18401 if (conn.mContainerService == null) { 18402 return; 18403 } 18404 18405 final UserEnvironment userEnv = new UserEnvironment(curUser); 18406 clearDirectory(conn.mContainerService, 18407 userEnv.buildExternalStorageAppCacheDirs(packageName)); 18408 if (allData) { 18409 clearDirectory(conn.mContainerService, 18410 userEnv.buildExternalStorageAppDataDirs(packageName)); 18411 clearDirectory(conn.mContainerService, 18412 userEnv.buildExternalStorageAppMediaDirs(packageName)); 18413 } 18414 } 18415 } finally { 18416 mContext.unbindService(conn); 18417 } 18418 } 18419 } 18420 18421 @Override 18422 public void clearApplicationProfileData(String packageName) { 18423 enforceSystemOrRoot("Only the system can clear all profile data"); 18424 18425 final PackageParser.Package pkg; 18426 synchronized (mPackages) { 18427 pkg = mPackages.get(packageName); 18428 } 18429 18430 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 18431 synchronized (mInstallLock) { 18432 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 18433 destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL, 18434 true /* removeBaseMarker */); 18435 } 18436 } 18437 } 18438 18439 @Override 18440 public void clearApplicationUserData(final String packageName, 18441 final IPackageDataObserver observer, final int userId) { 18442 mContext.enforceCallingOrSelfPermission( 18443 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 18444 18445 enforceCrossUserPermission(Binder.getCallingUid(), userId, 18446 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 18447 18448 if (mProtectedPackages.isPackageDataProtected(userId, packageName)) { 18449 throw new SecurityException("Cannot clear data for a protected package: " 18450 + packageName); 18451 } 18452 // Queue up an async operation since the package deletion may take a little while. 18453 mHandler.post(new Runnable() { 18454 public void run() { 18455 mHandler.removeCallbacks(this); 18456 final boolean succeeded; 18457 try (PackageFreezer freezer = freezePackage(packageName, 18458 "clearApplicationUserData")) { 18459 synchronized (mInstallLock) { 18460 succeeded = clearApplicationUserDataLIF(packageName, userId); 18461 } 18462 clearExternalStorageDataSync(packageName, userId, true); 18463 synchronized (mPackages) { 18464 mInstantAppRegistry.deleteInstantApplicationMetadataLPw( 18465 packageName, userId); 18466 } 18467 } 18468 if (succeeded) { 18469 // invoke DeviceStorageMonitor's update method to clear any notifications 18470 DeviceStorageMonitorInternal dsm = LocalServices 18471 .getService(DeviceStorageMonitorInternal.class); 18472 if (dsm != null) { 18473 dsm.checkMemory(); 18474 } 18475 } 18476 if(observer != null) { 18477 try { 18478 observer.onRemoveCompleted(packageName, succeeded); 18479 } catch (RemoteException e) { 18480 Log.i(TAG, "Observer no longer exists."); 18481 } 18482 } //end if observer 18483 } //end run 18484 }); 18485 } 18486 18487 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 18488 if (packageName == null) { 18489 Slog.w(TAG, "Attempt to delete null packageName."); 18490 return false; 18491 } 18492 18493 // Try finding details about the requested package 18494 PackageParser.Package pkg; 18495 synchronized (mPackages) { 18496 pkg = mPackages.get(packageName); 18497 if (pkg == null) { 18498 final PackageSetting ps = mSettings.mPackages.get(packageName); 18499 if (ps != null) { 18500 pkg = ps.pkg; 18501 } 18502 } 18503 18504 if (pkg == null) { 18505 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 18506 return false; 18507 } 18508 18509 PackageSetting ps = (PackageSetting) pkg.mExtras; 18510 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 18511 } 18512 18513 clearAppDataLIF(pkg, userId, 18514 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18515 18516 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 18517 removeKeystoreDataIfNeeded(userId, appId); 18518 18519 UserManagerInternal umInternal = getUserManagerInternal(); 18520 final int flags; 18521 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 18522 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18523 } else if (umInternal.isUserRunning(userId)) { 18524 flags = StorageManager.FLAG_STORAGE_DE; 18525 } else { 18526 flags = 0; 18527 } 18528 prepareAppDataContentsLIF(pkg, userId, flags); 18529 18530 return true; 18531 } 18532 18533 /** 18534 * Reverts user permission state changes (permissions and flags) in 18535 * all packages for a given user. 18536 * 18537 * @param userId The device user for which to do a reset. 18538 */ 18539 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 18540 final int packageCount = mPackages.size(); 18541 for (int i = 0; i < packageCount; i++) { 18542 PackageParser.Package pkg = mPackages.valueAt(i); 18543 PackageSetting ps = (PackageSetting) pkg.mExtras; 18544 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 18545 } 18546 } 18547 18548 private void resetNetworkPolicies(int userId) { 18549 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 18550 } 18551 18552 /** 18553 * Reverts user permission state changes (permissions and flags). 18554 * 18555 * @param ps The package for which to reset. 18556 * @param userId The device user for which to do a reset. 18557 */ 18558 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 18559 final PackageSetting ps, final int userId) { 18560 if (ps.pkg == null) { 18561 return; 18562 } 18563 18564 // These are flags that can change base on user actions. 18565 final int userSettableMask = FLAG_PERMISSION_USER_SET 18566 | FLAG_PERMISSION_USER_FIXED 18567 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 18568 | FLAG_PERMISSION_REVIEW_REQUIRED; 18569 18570 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 18571 | FLAG_PERMISSION_POLICY_FIXED; 18572 18573 boolean writeInstallPermissions = false; 18574 boolean writeRuntimePermissions = false; 18575 18576 final int permissionCount = ps.pkg.requestedPermissions.size(); 18577 for (int i = 0; i < permissionCount; i++) { 18578 String permission = ps.pkg.requestedPermissions.get(i); 18579 18580 BasePermission bp = mSettings.mPermissions.get(permission); 18581 if (bp == null) { 18582 continue; 18583 } 18584 18585 // If shared user we just reset the state to which only this app contributed. 18586 if (ps.sharedUser != null) { 18587 boolean used = false; 18588 final int packageCount = ps.sharedUser.packages.size(); 18589 for (int j = 0; j < packageCount; j++) { 18590 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 18591 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 18592 && pkg.pkg.requestedPermissions.contains(permission)) { 18593 used = true; 18594 break; 18595 } 18596 } 18597 if (used) { 18598 continue; 18599 } 18600 } 18601 18602 PermissionsState permissionsState = ps.getPermissionsState(); 18603 18604 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 18605 18606 // Always clear the user settable flags. 18607 final boolean hasInstallState = permissionsState.getInstallPermissionState( 18608 bp.name) != null; 18609 // If permission review is enabled and this is a legacy app, mark the 18610 // permission as requiring a review as this is the initial state. 18611 int flags = 0; 18612 if (mPermissionReviewRequired 18613 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 18614 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 18615 } 18616 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 18617 if (hasInstallState) { 18618 writeInstallPermissions = true; 18619 } else { 18620 writeRuntimePermissions = true; 18621 } 18622 } 18623 18624 // Below is only runtime permission handling. 18625 if (!bp.isRuntime()) { 18626 continue; 18627 } 18628 18629 // Never clobber system or policy. 18630 if ((oldFlags & policyOrSystemFlags) != 0) { 18631 continue; 18632 } 18633 18634 // If this permission was granted by default, make sure it is. 18635 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 18636 if (permissionsState.grantRuntimePermission(bp, userId) 18637 != PERMISSION_OPERATION_FAILURE) { 18638 writeRuntimePermissions = true; 18639 } 18640 // If permission review is enabled the permissions for a legacy apps 18641 // are represented as constantly granted runtime ones, so don't revoke. 18642 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 18643 // Otherwise, reset the permission. 18644 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 18645 switch (revokeResult) { 18646 case PERMISSION_OPERATION_SUCCESS: 18647 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 18648 writeRuntimePermissions = true; 18649 final int appId = ps.appId; 18650 mHandler.post(new Runnable() { 18651 @Override 18652 public void run() { 18653 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 18654 } 18655 }); 18656 } break; 18657 } 18658 } 18659 } 18660 18661 // Synchronously write as we are taking permissions away. 18662 if (writeRuntimePermissions) { 18663 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 18664 } 18665 18666 // Synchronously write as we are taking permissions away. 18667 if (writeInstallPermissions) { 18668 mSettings.writeLPr(); 18669 } 18670 } 18671 18672 /** 18673 * Remove entries from the keystore daemon. Will only remove it if the 18674 * {@code appId} is valid. 18675 */ 18676 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 18677 if (appId < 0) { 18678 return; 18679 } 18680 18681 final KeyStore keyStore = KeyStore.getInstance(); 18682 if (keyStore != null) { 18683 if (userId == UserHandle.USER_ALL) { 18684 for (final int individual : sUserManager.getUserIds()) { 18685 keyStore.clearUid(UserHandle.getUid(individual, appId)); 18686 } 18687 } else { 18688 keyStore.clearUid(UserHandle.getUid(userId, appId)); 18689 } 18690 } else { 18691 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 18692 } 18693 } 18694 18695 @Override 18696 public void deleteApplicationCacheFiles(final String packageName, 18697 final IPackageDataObserver observer) { 18698 final int userId = UserHandle.getCallingUserId(); 18699 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 18700 } 18701 18702 @Override 18703 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 18704 final IPackageDataObserver observer) { 18705 mContext.enforceCallingOrSelfPermission( 18706 android.Manifest.permission.DELETE_CACHE_FILES, null); 18707 enforceCrossUserPermission(Binder.getCallingUid(), userId, 18708 /* requireFullPermission= */ true, /* checkShell= */ false, 18709 "delete application cache files"); 18710 18711 final PackageParser.Package pkg; 18712 synchronized (mPackages) { 18713 pkg = mPackages.get(packageName); 18714 } 18715 18716 // Queue up an async operation since the package deletion may take a little while. 18717 mHandler.post(new Runnable() { 18718 public void run() { 18719 synchronized (mInstallLock) { 18720 final int flags = StorageManager.FLAG_STORAGE_DE 18721 | StorageManager.FLAG_STORAGE_CE; 18722 // We're only clearing cache files, so we don't care if the 18723 // app is unfrozen and still able to run 18724 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 18725 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 18726 } 18727 clearExternalStorageDataSync(packageName, userId, false); 18728 if (observer != null) { 18729 try { 18730 observer.onRemoveCompleted(packageName, true); 18731 } catch (RemoteException e) { 18732 Log.i(TAG, "Observer no longer exists."); 18733 } 18734 } 18735 } 18736 }); 18737 } 18738 18739 @Override 18740 public void getPackageSizeInfo(final String packageName, int userHandle, 18741 final IPackageStatsObserver observer) { 18742 Slog.w(TAG, "Shame on you for calling a hidden API. Shame!"); 18743 try { 18744 observer.onGetStatsCompleted(null, false); 18745 } catch (Throwable ignored) { 18746 } 18747 } 18748 18749 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 18750 final PackageSetting ps; 18751 synchronized (mPackages) { 18752 ps = mSettings.mPackages.get(packageName); 18753 if (ps == null) { 18754 Slog.w(TAG, "Failed to find settings for " + packageName); 18755 return false; 18756 } 18757 } 18758 18759 final String[] packageNames = { packageName }; 18760 final long[] ceDataInodes = { ps.getCeDataInode(userId) }; 18761 final String[] codePaths = { ps.codePathString }; 18762 18763 try { 18764 mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0, 18765 ps.appId, ceDataInodes, codePaths, stats); 18766 18767 // For now, ignore code size of packages on system partition 18768 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 18769 stats.codeSize = 0; 18770 } 18771 18772 // External clients expect these to be tracked separately 18773 stats.dataSize -= stats.cacheSize; 18774 18775 } catch (InstallerException e) { 18776 Slog.w(TAG, String.valueOf(e)); 18777 return false; 18778 } 18779 18780 return true; 18781 } 18782 18783 private int getUidTargetSdkVersionLockedLPr(int uid) { 18784 Object obj = mSettings.getUserIdLPr(uid); 18785 if (obj instanceof SharedUserSetting) { 18786 final SharedUserSetting sus = (SharedUserSetting) obj; 18787 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 18788 final Iterator<PackageSetting> it = sus.packages.iterator(); 18789 while (it.hasNext()) { 18790 final PackageSetting ps = it.next(); 18791 if (ps.pkg != null) { 18792 int v = ps.pkg.applicationInfo.targetSdkVersion; 18793 if (v < vers) vers = v; 18794 } 18795 } 18796 return vers; 18797 } else if (obj instanceof PackageSetting) { 18798 final PackageSetting ps = (PackageSetting) obj; 18799 if (ps.pkg != null) { 18800 return ps.pkg.applicationInfo.targetSdkVersion; 18801 } 18802 } 18803 return Build.VERSION_CODES.CUR_DEVELOPMENT; 18804 } 18805 18806 @Override 18807 public void addPreferredActivity(IntentFilter filter, int match, 18808 ComponentName[] set, ComponentName activity, int userId) { 18809 addPreferredActivityInternal(filter, match, set, activity, true, userId, 18810 "Adding preferred"); 18811 } 18812 18813 private void addPreferredActivityInternal(IntentFilter filter, int match, 18814 ComponentName[] set, ComponentName activity, boolean always, int userId, 18815 String opname) { 18816 // writer 18817 int callingUid = Binder.getCallingUid(); 18818 enforceCrossUserPermission(callingUid, userId, 18819 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 18820 if (filter.countActions() == 0) { 18821 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 18822 return; 18823 } 18824 synchronized (mPackages) { 18825 if (mContext.checkCallingOrSelfPermission( 18826 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 18827 != PackageManager.PERMISSION_GRANTED) { 18828 if (getUidTargetSdkVersionLockedLPr(callingUid) 18829 < Build.VERSION_CODES.FROYO) { 18830 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 18831 + callingUid); 18832 return; 18833 } 18834 mContext.enforceCallingOrSelfPermission( 18835 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 18836 } 18837 18838 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 18839 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 18840 + userId + ":"); 18841 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18842 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 18843 scheduleWritePackageRestrictionsLocked(userId); 18844 postPreferredActivityChangedBroadcast(userId); 18845 } 18846 } 18847 18848 private void postPreferredActivityChangedBroadcast(int userId) { 18849 mHandler.post(() -> { 18850 final IActivityManager am = ActivityManager.getService(); 18851 if (am == null) { 18852 return; 18853 } 18854 18855 final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED); 18856 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 18857 try { 18858 am.broadcastIntent(null, intent, null, null, 18859 0, null, null, null, android.app.AppOpsManager.OP_NONE, 18860 null, false, false, userId); 18861 } catch (RemoteException e) { 18862 } 18863 }); 18864 } 18865 18866 @Override 18867 public void replacePreferredActivity(IntentFilter filter, int match, 18868 ComponentName[] set, ComponentName activity, int userId) { 18869 if (filter.countActions() != 1) { 18870 throw new IllegalArgumentException( 18871 "replacePreferredActivity expects filter to have only 1 action."); 18872 } 18873 if (filter.countDataAuthorities() != 0 18874 || filter.countDataPaths() != 0 18875 || filter.countDataSchemes() > 1 18876 || filter.countDataTypes() != 0) { 18877 throw new IllegalArgumentException( 18878 "replacePreferredActivity expects filter to have no data authorities, " + 18879 "paths, or types; and at most one scheme."); 18880 } 18881 18882 final int callingUid = Binder.getCallingUid(); 18883 enforceCrossUserPermission(callingUid, userId, 18884 true /* requireFullPermission */, false /* checkShell */, 18885 "replace preferred activity"); 18886 synchronized (mPackages) { 18887 if (mContext.checkCallingOrSelfPermission( 18888 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 18889 != PackageManager.PERMISSION_GRANTED) { 18890 if (getUidTargetSdkVersionLockedLPr(callingUid) 18891 < Build.VERSION_CODES.FROYO) { 18892 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 18893 + Binder.getCallingUid()); 18894 return; 18895 } 18896 mContext.enforceCallingOrSelfPermission( 18897 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 18898 } 18899 18900 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 18901 if (pir != null) { 18902 // Get all of the existing entries that exactly match this filter. 18903 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 18904 if (existing != null && existing.size() == 1) { 18905 PreferredActivity cur = existing.get(0); 18906 if (DEBUG_PREFERRED) { 18907 Slog.i(TAG, "Checking replace of preferred:"); 18908 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18909 if (!cur.mPref.mAlways) { 18910 Slog.i(TAG, " -- CUR; not mAlways!"); 18911 } else { 18912 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 18913 Slog.i(TAG, " -- CUR: mSet=" 18914 + Arrays.toString(cur.mPref.mSetComponents)); 18915 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 18916 Slog.i(TAG, " -- NEW: mMatch=" 18917 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 18918 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 18919 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 18920 } 18921 } 18922 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 18923 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 18924 && cur.mPref.sameSet(set)) { 18925 // Setting the preferred activity to what it happens to be already 18926 if (DEBUG_PREFERRED) { 18927 Slog.i(TAG, "Replacing with same preferred activity " 18928 + cur.mPref.mShortComponent + " for user " 18929 + userId + ":"); 18930 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18931 } 18932 return; 18933 } 18934 } 18935 18936 if (existing != null) { 18937 if (DEBUG_PREFERRED) { 18938 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 18939 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18940 } 18941 for (int i = 0; i < existing.size(); i++) { 18942 PreferredActivity pa = existing.get(i); 18943 if (DEBUG_PREFERRED) { 18944 Slog.i(TAG, "Removing existing preferred activity " 18945 + pa.mPref.mComponent + ":"); 18946 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 18947 } 18948 pir.removeFilter(pa); 18949 } 18950 } 18951 } 18952 addPreferredActivityInternal(filter, match, set, activity, true, userId, 18953 "Replacing preferred"); 18954 } 18955 } 18956 18957 @Override 18958 public void clearPackagePreferredActivities(String packageName) { 18959 final int uid = Binder.getCallingUid(); 18960 // writer 18961 synchronized (mPackages) { 18962 PackageParser.Package pkg = mPackages.get(packageName); 18963 if (pkg == null || pkg.applicationInfo.uid != uid) { 18964 if (mContext.checkCallingOrSelfPermission( 18965 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 18966 != PackageManager.PERMISSION_GRANTED) { 18967 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 18968 < Build.VERSION_CODES.FROYO) { 18969 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 18970 + Binder.getCallingUid()); 18971 return; 18972 } 18973 mContext.enforceCallingOrSelfPermission( 18974 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 18975 } 18976 } 18977 18978 int user = UserHandle.getCallingUserId(); 18979 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 18980 scheduleWritePackageRestrictionsLocked(user); 18981 } 18982 } 18983 } 18984 18985 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 18986 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 18987 ArrayList<PreferredActivity> removed = null; 18988 boolean changed = false; 18989 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18990 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 18991 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18992 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 18993 continue; 18994 } 18995 Iterator<PreferredActivity> it = pir.filterIterator(); 18996 while (it.hasNext()) { 18997 PreferredActivity pa = it.next(); 18998 // Mark entry for removal only if it matches the package name 18999 // and the entry is of type "always". 19000 if (packageName == null || 19001 (pa.mPref.mComponent.getPackageName().equals(packageName) 19002 && pa.mPref.mAlways)) { 19003 if (removed == null) { 19004 removed = new ArrayList<PreferredActivity>(); 19005 } 19006 removed.add(pa); 19007 } 19008 } 19009 if (removed != null) { 19010 for (int j=0; j<removed.size(); j++) { 19011 PreferredActivity pa = removed.get(j); 19012 pir.removeFilter(pa); 19013 } 19014 changed = true; 19015 } 19016 } 19017 if (changed) { 19018 postPreferredActivityChangedBroadcast(userId); 19019 } 19020 return changed; 19021 } 19022 19023 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 19024 private void clearIntentFilterVerificationsLPw(int userId) { 19025 final int packageCount = mPackages.size(); 19026 for (int i = 0; i < packageCount; i++) { 19027 PackageParser.Package pkg = mPackages.valueAt(i); 19028 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 19029 } 19030 } 19031 19032 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 19033 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 19034 if (userId == UserHandle.USER_ALL) { 19035 if (mSettings.removeIntentFilterVerificationLPw(packageName, 19036 sUserManager.getUserIds())) { 19037 for (int oneUserId : sUserManager.getUserIds()) { 19038 scheduleWritePackageRestrictionsLocked(oneUserId); 19039 } 19040 } 19041 } else { 19042 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 19043 scheduleWritePackageRestrictionsLocked(userId); 19044 } 19045 } 19046 } 19047 19048 void clearDefaultBrowserIfNeeded(String packageName) { 19049 for (int oneUserId : sUserManager.getUserIds()) { 19050 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 19051 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 19052 if (packageName.equals(defaultBrowserPackageName)) { 19053 setDefaultBrowserPackageName(null, oneUserId); 19054 } 19055 } 19056 } 19057 19058 @Override 19059 public void resetApplicationPreferences(int userId) { 19060 mContext.enforceCallingOrSelfPermission( 19061 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 19062 final long identity = Binder.clearCallingIdentity(); 19063 // writer 19064 try { 19065 synchronized (mPackages) { 19066 clearPackagePreferredActivitiesLPw(null, userId); 19067 mSettings.applyDefaultPreferredAppsLPw(this, userId); 19068 // TODO: We have to reset the default SMS and Phone. This requires 19069 // significant refactoring to keep all default apps in the package 19070 // manager (cleaner but more work) or have the services provide 19071 // callbacks to the package manager to request a default app reset. 19072 applyFactoryDefaultBrowserLPw(userId); 19073 clearIntentFilterVerificationsLPw(userId); 19074 primeDomainVerificationsLPw(userId); 19075 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 19076 scheduleWritePackageRestrictionsLocked(userId); 19077 } 19078 resetNetworkPolicies(userId); 19079 } finally { 19080 Binder.restoreCallingIdentity(identity); 19081 } 19082 } 19083 19084 @Override 19085 public int getPreferredActivities(List<IntentFilter> outFilters, 19086 List<ComponentName> outActivities, String packageName) { 19087 19088 int num = 0; 19089 final int userId = UserHandle.getCallingUserId(); 19090 // reader 19091 synchronized (mPackages) { 19092 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 19093 if (pir != null) { 19094 final Iterator<PreferredActivity> it = pir.filterIterator(); 19095 while (it.hasNext()) { 19096 final PreferredActivity pa = it.next(); 19097 if (packageName == null 19098 || (pa.mPref.mComponent.getPackageName().equals(packageName) 19099 && pa.mPref.mAlways)) { 19100 if (outFilters != null) { 19101 outFilters.add(new IntentFilter(pa)); 19102 } 19103 if (outActivities != null) { 19104 outActivities.add(pa.mPref.mComponent); 19105 } 19106 } 19107 } 19108 } 19109 } 19110 19111 return num; 19112 } 19113 19114 @Override 19115 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 19116 int userId) { 19117 int callingUid = Binder.getCallingUid(); 19118 if (callingUid != Process.SYSTEM_UID) { 19119 throw new SecurityException( 19120 "addPersistentPreferredActivity can only be run by the system"); 19121 } 19122 if (filter.countActions() == 0) { 19123 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 19124 return; 19125 } 19126 synchronized (mPackages) { 19127 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 19128 ":"); 19129 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19130 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 19131 new PersistentPreferredActivity(filter, activity)); 19132 scheduleWritePackageRestrictionsLocked(userId); 19133 postPreferredActivityChangedBroadcast(userId); 19134 } 19135 } 19136 19137 @Override 19138 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 19139 int callingUid = Binder.getCallingUid(); 19140 if (callingUid != Process.SYSTEM_UID) { 19141 throw new SecurityException( 19142 "clearPackagePersistentPreferredActivities can only be run by the system"); 19143 } 19144 ArrayList<PersistentPreferredActivity> removed = null; 19145 boolean changed = false; 19146 synchronized (mPackages) { 19147 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 19148 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 19149 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 19150 .valueAt(i); 19151 if (userId != thisUserId) { 19152 continue; 19153 } 19154 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 19155 while (it.hasNext()) { 19156 PersistentPreferredActivity ppa = it.next(); 19157 // Mark entry for removal only if it matches the package name. 19158 if (ppa.mComponent.getPackageName().equals(packageName)) { 19159 if (removed == null) { 19160 removed = new ArrayList<PersistentPreferredActivity>(); 19161 } 19162 removed.add(ppa); 19163 } 19164 } 19165 if (removed != null) { 19166 for (int j=0; j<removed.size(); j++) { 19167 PersistentPreferredActivity ppa = removed.get(j); 19168 ppir.removeFilter(ppa); 19169 } 19170 changed = true; 19171 } 19172 } 19173 19174 if (changed) { 19175 scheduleWritePackageRestrictionsLocked(userId); 19176 postPreferredActivityChangedBroadcast(userId); 19177 } 19178 } 19179 } 19180 19181 /** 19182 * Common machinery for picking apart a restored XML blob and passing 19183 * it to a caller-supplied functor to be applied to the running system. 19184 */ 19185 private void restoreFromXml(XmlPullParser parser, int userId, 19186 String expectedStartTag, BlobXmlRestorer functor) 19187 throws IOException, XmlPullParserException { 19188 int type; 19189 while ((type = parser.next()) != XmlPullParser.START_TAG 19190 && type != XmlPullParser.END_DOCUMENT) { 19191 } 19192 if (type != XmlPullParser.START_TAG) { 19193 // oops didn't find a start tag?! 19194 if (DEBUG_BACKUP) { 19195 Slog.e(TAG, "Didn't find start tag during restore"); 19196 } 19197 return; 19198 } 19199Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 19200 // this is supposed to be TAG_PREFERRED_BACKUP 19201 if (!expectedStartTag.equals(parser.getName())) { 19202 if (DEBUG_BACKUP) { 19203 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 19204 } 19205 return; 19206 } 19207 19208 // skip interfering stuff, then we're aligned with the backing implementation 19209 while ((type = parser.next()) == XmlPullParser.TEXT) { } 19210Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 19211 functor.apply(parser, userId); 19212 } 19213 19214 private interface BlobXmlRestorer { 19215 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 19216 } 19217 19218 /** 19219 * Non-Binder method, support for the backup/restore mechanism: write the 19220 * full set of preferred activities in its canonical XML format. Returns the 19221 * XML output as a byte array, or null if there is none. 19222 */ 19223 @Override 19224 public byte[] getPreferredActivityBackup(int userId) { 19225 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19226 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 19227 } 19228 19229 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19230 try { 19231 final XmlSerializer serializer = new FastXmlSerializer(); 19232 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19233 serializer.startDocument(null, true); 19234 serializer.startTag(null, TAG_PREFERRED_BACKUP); 19235 19236 synchronized (mPackages) { 19237 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 19238 } 19239 19240 serializer.endTag(null, TAG_PREFERRED_BACKUP); 19241 serializer.endDocument(); 19242 serializer.flush(); 19243 } catch (Exception e) { 19244 if (DEBUG_BACKUP) { 19245 Slog.e(TAG, "Unable to write preferred activities for backup", e); 19246 } 19247 return null; 19248 } 19249 19250 return dataStream.toByteArray(); 19251 } 19252 19253 @Override 19254 public void restorePreferredActivities(byte[] backup, int userId) { 19255 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19256 throw new SecurityException("Only the system may call restorePreferredActivities()"); 19257 } 19258 19259 try { 19260 final XmlPullParser parser = Xml.newPullParser(); 19261 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19262 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 19263 new BlobXmlRestorer() { 19264 @Override 19265 public void apply(XmlPullParser parser, int userId) 19266 throws XmlPullParserException, IOException { 19267 synchronized (mPackages) { 19268 mSettings.readPreferredActivitiesLPw(parser, userId); 19269 } 19270 } 19271 } ); 19272 } catch (Exception e) { 19273 if (DEBUG_BACKUP) { 19274 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19275 } 19276 } 19277 } 19278 19279 /** 19280 * Non-Binder method, support for the backup/restore mechanism: write the 19281 * default browser (etc) settings in its canonical XML format. Returns the default 19282 * browser XML representation as a byte array, or null if there is none. 19283 */ 19284 @Override 19285 public byte[] getDefaultAppsBackup(int userId) { 19286 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19287 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 19288 } 19289 19290 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19291 try { 19292 final XmlSerializer serializer = new FastXmlSerializer(); 19293 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19294 serializer.startDocument(null, true); 19295 serializer.startTag(null, TAG_DEFAULT_APPS); 19296 19297 synchronized (mPackages) { 19298 mSettings.writeDefaultAppsLPr(serializer, userId); 19299 } 19300 19301 serializer.endTag(null, TAG_DEFAULT_APPS); 19302 serializer.endDocument(); 19303 serializer.flush(); 19304 } catch (Exception e) { 19305 if (DEBUG_BACKUP) { 19306 Slog.e(TAG, "Unable to write default apps for backup", e); 19307 } 19308 return null; 19309 } 19310 19311 return dataStream.toByteArray(); 19312 } 19313 19314 @Override 19315 public void restoreDefaultApps(byte[] backup, int userId) { 19316 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19317 throw new SecurityException("Only the system may call restoreDefaultApps()"); 19318 } 19319 19320 try { 19321 final XmlPullParser parser = Xml.newPullParser(); 19322 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19323 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 19324 new BlobXmlRestorer() { 19325 @Override 19326 public void apply(XmlPullParser parser, int userId) 19327 throws XmlPullParserException, IOException { 19328 synchronized (mPackages) { 19329 mSettings.readDefaultAppsLPw(parser, userId); 19330 } 19331 } 19332 } ); 19333 } catch (Exception e) { 19334 if (DEBUG_BACKUP) { 19335 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 19336 } 19337 } 19338 } 19339 19340 @Override 19341 public byte[] getIntentFilterVerificationBackup(int userId) { 19342 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19343 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 19344 } 19345 19346 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19347 try { 19348 final XmlSerializer serializer = new FastXmlSerializer(); 19349 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19350 serializer.startDocument(null, true); 19351 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 19352 19353 synchronized (mPackages) { 19354 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 19355 } 19356 19357 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 19358 serializer.endDocument(); 19359 serializer.flush(); 19360 } catch (Exception e) { 19361 if (DEBUG_BACKUP) { 19362 Slog.e(TAG, "Unable to write default apps for backup", e); 19363 } 19364 return null; 19365 } 19366 19367 return dataStream.toByteArray(); 19368 } 19369 19370 @Override 19371 public void restoreIntentFilterVerification(byte[] backup, int userId) { 19372 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19373 throw new SecurityException("Only the system may call restorePreferredActivities()"); 19374 } 19375 19376 try { 19377 final XmlPullParser parser = Xml.newPullParser(); 19378 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19379 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 19380 new BlobXmlRestorer() { 19381 @Override 19382 public void apply(XmlPullParser parser, int userId) 19383 throws XmlPullParserException, IOException { 19384 synchronized (mPackages) { 19385 mSettings.readAllDomainVerificationsLPr(parser, userId); 19386 mSettings.writeLPr(); 19387 } 19388 } 19389 } ); 19390 } catch (Exception e) { 19391 if (DEBUG_BACKUP) { 19392 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19393 } 19394 } 19395 } 19396 19397 @Override 19398 public byte[] getPermissionGrantBackup(int userId) { 19399 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19400 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 19401 } 19402 19403 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19404 try { 19405 final XmlSerializer serializer = new FastXmlSerializer(); 19406 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19407 serializer.startDocument(null, true); 19408 serializer.startTag(null, TAG_PERMISSION_BACKUP); 19409 19410 synchronized (mPackages) { 19411 serializeRuntimePermissionGrantsLPr(serializer, userId); 19412 } 19413 19414 serializer.endTag(null, TAG_PERMISSION_BACKUP); 19415 serializer.endDocument(); 19416 serializer.flush(); 19417 } catch (Exception e) { 19418 if (DEBUG_BACKUP) { 19419 Slog.e(TAG, "Unable to write default apps for backup", e); 19420 } 19421 return null; 19422 } 19423 19424 return dataStream.toByteArray(); 19425 } 19426 19427 @Override 19428 public void restorePermissionGrants(byte[] backup, int userId) { 19429 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19430 throw new SecurityException("Only the system may call restorePermissionGrants()"); 19431 } 19432 19433 try { 19434 final XmlPullParser parser = Xml.newPullParser(); 19435 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19436 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 19437 new BlobXmlRestorer() { 19438 @Override 19439 public void apply(XmlPullParser parser, int userId) 19440 throws XmlPullParserException, IOException { 19441 synchronized (mPackages) { 19442 processRestoredPermissionGrantsLPr(parser, userId); 19443 } 19444 } 19445 } ); 19446 } catch (Exception e) { 19447 if (DEBUG_BACKUP) { 19448 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19449 } 19450 } 19451 } 19452 19453 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 19454 throws IOException { 19455 serializer.startTag(null, TAG_ALL_GRANTS); 19456 19457 final int N = mSettings.mPackages.size(); 19458 for (int i = 0; i < N; i++) { 19459 final PackageSetting ps = mSettings.mPackages.valueAt(i); 19460 boolean pkgGrantsKnown = false; 19461 19462 PermissionsState packagePerms = ps.getPermissionsState(); 19463 19464 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 19465 final int grantFlags = state.getFlags(); 19466 // only look at grants that are not system/policy fixed 19467 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 19468 final boolean isGranted = state.isGranted(); 19469 // And only back up the user-twiddled state bits 19470 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 19471 final String packageName = mSettings.mPackages.keyAt(i); 19472 if (!pkgGrantsKnown) { 19473 serializer.startTag(null, TAG_GRANT); 19474 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 19475 pkgGrantsKnown = true; 19476 } 19477 19478 final boolean userSet = 19479 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 19480 final boolean userFixed = 19481 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 19482 final boolean revoke = 19483 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 19484 19485 serializer.startTag(null, TAG_PERMISSION); 19486 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 19487 if (isGranted) { 19488 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 19489 } 19490 if (userSet) { 19491 serializer.attribute(null, ATTR_USER_SET, "true"); 19492 } 19493 if (userFixed) { 19494 serializer.attribute(null, ATTR_USER_FIXED, "true"); 19495 } 19496 if (revoke) { 19497 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 19498 } 19499 serializer.endTag(null, TAG_PERMISSION); 19500 } 19501 } 19502 } 19503 19504 if (pkgGrantsKnown) { 19505 serializer.endTag(null, TAG_GRANT); 19506 } 19507 } 19508 19509 serializer.endTag(null, TAG_ALL_GRANTS); 19510 } 19511 19512 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 19513 throws XmlPullParserException, IOException { 19514 String pkgName = null; 19515 int outerDepth = parser.getDepth(); 19516 int type; 19517 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 19518 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 19519 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 19520 continue; 19521 } 19522 19523 final String tagName = parser.getName(); 19524 if (tagName.equals(TAG_GRANT)) { 19525 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 19526 if (DEBUG_BACKUP) { 19527 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 19528 } 19529 } else if (tagName.equals(TAG_PERMISSION)) { 19530 19531 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 19532 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 19533 19534 int newFlagSet = 0; 19535 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 19536 newFlagSet |= FLAG_PERMISSION_USER_SET; 19537 } 19538 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 19539 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 19540 } 19541 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 19542 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 19543 } 19544 if (DEBUG_BACKUP) { 19545 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 19546 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 19547 } 19548 final PackageSetting ps = mSettings.mPackages.get(pkgName); 19549 if (ps != null) { 19550 // Already installed so we apply the grant immediately 19551 if (DEBUG_BACKUP) { 19552 Slog.v(TAG, " + already installed; applying"); 19553 } 19554 PermissionsState perms = ps.getPermissionsState(); 19555 BasePermission bp = mSettings.mPermissions.get(permName); 19556 if (bp != null) { 19557 if (isGranted) { 19558 perms.grantRuntimePermission(bp, userId); 19559 } 19560 if (newFlagSet != 0) { 19561 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 19562 } 19563 } 19564 } else { 19565 // Need to wait for post-restore install to apply the grant 19566 if (DEBUG_BACKUP) { 19567 Slog.v(TAG, " - not yet installed; saving for later"); 19568 } 19569 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 19570 isGranted, newFlagSet, userId); 19571 } 19572 } else { 19573 PackageManagerService.reportSettingsProblem(Log.WARN, 19574 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 19575 XmlUtils.skipCurrentTag(parser); 19576 } 19577 } 19578 19579 scheduleWriteSettingsLocked(); 19580 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 19581 } 19582 19583 @Override 19584 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 19585 int sourceUserId, int targetUserId, int flags) { 19586 mContext.enforceCallingOrSelfPermission( 19587 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 19588 int callingUid = Binder.getCallingUid(); 19589 enforceOwnerRights(ownerPackage, callingUid); 19590 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 19591 if (intentFilter.countActions() == 0) { 19592 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 19593 return; 19594 } 19595 synchronized (mPackages) { 19596 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 19597 ownerPackage, targetUserId, flags); 19598 CrossProfileIntentResolver resolver = 19599 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 19600 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 19601 // We have all those whose filter is equal. Now checking if the rest is equal as well. 19602 if (existing != null) { 19603 int size = existing.size(); 19604 for (int i = 0; i < size; i++) { 19605 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 19606 return; 19607 } 19608 } 19609 } 19610 resolver.addFilter(newFilter); 19611 scheduleWritePackageRestrictionsLocked(sourceUserId); 19612 } 19613 } 19614 19615 @Override 19616 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 19617 mContext.enforceCallingOrSelfPermission( 19618 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 19619 int callingUid = Binder.getCallingUid(); 19620 enforceOwnerRights(ownerPackage, callingUid); 19621 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 19622 synchronized (mPackages) { 19623 CrossProfileIntentResolver resolver = 19624 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 19625 ArraySet<CrossProfileIntentFilter> set = 19626 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 19627 for (CrossProfileIntentFilter filter : set) { 19628 if (filter.getOwnerPackage().equals(ownerPackage)) { 19629 resolver.removeFilter(filter); 19630 } 19631 } 19632 scheduleWritePackageRestrictionsLocked(sourceUserId); 19633 } 19634 } 19635 19636 // Enforcing that callingUid is owning pkg on userId 19637 private void enforceOwnerRights(String pkg, int callingUid) { 19638 // The system owns everything. 19639 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 19640 return; 19641 } 19642 int callingUserId = UserHandle.getUserId(callingUid); 19643 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 19644 if (pi == null) { 19645 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 19646 + callingUserId); 19647 } 19648 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 19649 throw new SecurityException("Calling uid " + callingUid 19650 + " does not own package " + pkg); 19651 } 19652 } 19653 19654 @Override 19655 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 19656 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 19657 } 19658 19659 /** 19660 * Report the 'Home' activity which is currently set as "always use this one". If non is set 19661 * then reports the most likely home activity or null if there are more than one. 19662 */ 19663 public ComponentName getDefaultHomeActivity(int userId) { 19664 List<ResolveInfo> allHomeCandidates = new ArrayList<>(); 19665 ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId); 19666 if (cn != null) { 19667 return cn; 19668 } 19669 19670 // Find the launcher with the highest priority and return that component if there are no 19671 // other home activity with the same priority. 19672 int lastPriority = Integer.MIN_VALUE; 19673 ComponentName lastComponent = null; 19674 final int size = allHomeCandidates.size(); 19675 for (int i = 0; i < size; i++) { 19676 final ResolveInfo ri = allHomeCandidates.get(i); 19677 if (ri.priority > lastPriority) { 19678 lastComponent = ri.activityInfo.getComponentName(); 19679 lastPriority = ri.priority; 19680 } else if (ri.priority == lastPriority) { 19681 // Two components found with same priority. 19682 lastComponent = null; 19683 } 19684 } 19685 return lastComponent; 19686 } 19687 19688 private Intent getHomeIntent() { 19689 Intent intent = new Intent(Intent.ACTION_MAIN); 19690 intent.addCategory(Intent.CATEGORY_HOME); 19691 intent.addCategory(Intent.CATEGORY_DEFAULT); 19692 return intent; 19693 } 19694 19695 private IntentFilter getHomeFilter() { 19696 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 19697 filter.addCategory(Intent.CATEGORY_HOME); 19698 filter.addCategory(Intent.CATEGORY_DEFAULT); 19699 return filter; 19700 } 19701 19702 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 19703 int userId) { 19704 Intent intent = getHomeIntent(); 19705 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 19706 PackageManager.GET_META_DATA, userId); 19707 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 19708 true, false, false, userId); 19709 19710 allHomeCandidates.clear(); 19711 if (list != null) { 19712 for (ResolveInfo ri : list) { 19713 allHomeCandidates.add(ri); 19714 } 19715 } 19716 return (preferred == null || preferred.activityInfo == null) 19717 ? null 19718 : new ComponentName(preferred.activityInfo.packageName, 19719 preferred.activityInfo.name); 19720 } 19721 19722 @Override 19723 public void setHomeActivity(ComponentName comp, int userId) { 19724 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 19725 getHomeActivitiesAsUser(homeActivities, userId); 19726 19727 boolean found = false; 19728 19729 final int size = homeActivities.size(); 19730 final ComponentName[] set = new ComponentName[size]; 19731 for (int i = 0; i < size; i++) { 19732 final ResolveInfo candidate = homeActivities.get(i); 19733 final ActivityInfo info = candidate.activityInfo; 19734 final ComponentName activityName = new ComponentName(info.packageName, info.name); 19735 set[i] = activityName; 19736 if (!found && activityName.equals(comp)) { 19737 found = true; 19738 } 19739 } 19740 if (!found) { 19741 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 19742 + userId); 19743 } 19744 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 19745 set, comp, userId); 19746 } 19747 19748 private @Nullable String getSetupWizardPackageName() { 19749 final Intent intent = new Intent(Intent.ACTION_MAIN); 19750 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 19751 19752 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 19753 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 19754 | MATCH_DISABLED_COMPONENTS, 19755 UserHandle.myUserId()); 19756 if (matches.size() == 1) { 19757 return matches.get(0).getComponentInfo().packageName; 19758 } else { 19759 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 19760 + ": matches=" + matches); 19761 return null; 19762 } 19763 } 19764 19765 private @Nullable String getStorageManagerPackageName() { 19766 final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE); 19767 19768 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 19769 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 19770 | MATCH_DISABLED_COMPONENTS, 19771 UserHandle.myUserId()); 19772 if (matches.size() == 1) { 19773 return matches.get(0).getComponentInfo().packageName; 19774 } else { 19775 Slog.e(TAG, "There should probably be exactly one storage manager; found " 19776 + matches.size() + ": matches=" + matches); 19777 return null; 19778 } 19779 } 19780 19781 @Override 19782 public void setApplicationEnabledSetting(String appPackageName, 19783 int newState, int flags, int userId, String callingPackage) { 19784 if (!sUserManager.exists(userId)) return; 19785 if (callingPackage == null) { 19786 callingPackage = Integer.toString(Binder.getCallingUid()); 19787 } 19788 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 19789 } 19790 19791 @Override 19792 public void setComponentEnabledSetting(ComponentName componentName, 19793 int newState, int flags, int userId) { 19794 if (!sUserManager.exists(userId)) return; 19795 setEnabledSetting(componentName.getPackageName(), 19796 componentName.getClassName(), newState, flags, userId, null); 19797 } 19798 19799 private void setEnabledSetting(final String packageName, String className, int newState, 19800 final int flags, int userId, String callingPackage) { 19801 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 19802 || newState == COMPONENT_ENABLED_STATE_ENABLED 19803 || newState == COMPONENT_ENABLED_STATE_DISABLED 19804 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 19805 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 19806 throw new IllegalArgumentException("Invalid new component state: " 19807 + newState); 19808 } 19809 PackageSetting pkgSetting; 19810 final int uid = Binder.getCallingUid(); 19811 final int permission; 19812 if (uid == Process.SYSTEM_UID) { 19813 permission = PackageManager.PERMISSION_GRANTED; 19814 } else { 19815 permission = mContext.checkCallingOrSelfPermission( 19816 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 19817 } 19818 enforceCrossUserPermission(uid, userId, 19819 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 19820 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 19821 boolean sendNow = false; 19822 boolean isApp = (className == null); 19823 String componentName = isApp ? packageName : className; 19824 int packageUid = -1; 19825 ArrayList<String> components; 19826 19827 // writer 19828 synchronized (mPackages) { 19829 pkgSetting = mSettings.mPackages.get(packageName); 19830 if (pkgSetting == null) { 19831 if (className == null) { 19832 throw new IllegalArgumentException("Unknown package: " + packageName); 19833 } 19834 throw new IllegalArgumentException( 19835 "Unknown component: " + packageName + "/" + className); 19836 } 19837 } 19838 19839 // Limit who can change which apps 19840 if (!UserHandle.isSameApp(uid, pkgSetting.appId)) { 19841 // Don't allow apps that don't have permission to modify other apps 19842 if (!allowedByPermission) { 19843 throw new SecurityException( 19844 "Permission Denial: attempt to change component state from pid=" 19845 + Binder.getCallingPid() 19846 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 19847 } 19848 // Don't allow changing protected packages. 19849 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 19850 throw new SecurityException("Cannot disable a protected package: " + packageName); 19851 } 19852 } 19853 19854 synchronized (mPackages) { 19855 if (uid == Process.SHELL_UID 19856 && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) { 19857 // Shell can only change whole packages between ENABLED and DISABLED_USER states 19858 // unless it is a test package. 19859 int oldState = pkgSetting.getEnabled(userId); 19860 if (className == null 19861 && 19862 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 19863 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 19864 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 19865 && 19866 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 19867 || newState == COMPONENT_ENABLED_STATE_DEFAULT 19868 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 19869 // ok 19870 } else { 19871 throw new SecurityException( 19872 "Shell cannot change component state for " + packageName + "/" 19873 + className + " to " + newState); 19874 } 19875 } 19876 if (className == null) { 19877 // We're dealing with an application/package level state change 19878 if (pkgSetting.getEnabled(userId) == newState) { 19879 // Nothing to do 19880 return; 19881 } 19882 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 19883 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 19884 // Don't care about who enables an app. 19885 callingPackage = null; 19886 } 19887 pkgSetting.setEnabled(newState, userId, callingPackage); 19888 // pkgSetting.pkg.mSetEnabled = newState; 19889 } else { 19890 // We're dealing with a component level state change 19891 // First, verify that this is a valid class name. 19892 PackageParser.Package pkg = pkgSetting.pkg; 19893 if (pkg == null || !pkg.hasComponentClassName(className)) { 19894 if (pkg != null && 19895 pkg.applicationInfo.targetSdkVersion >= 19896 Build.VERSION_CODES.JELLY_BEAN) { 19897 throw new IllegalArgumentException("Component class " + className 19898 + " does not exist in " + packageName); 19899 } else { 19900 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 19901 + className + " does not exist in " + packageName); 19902 } 19903 } 19904 switch (newState) { 19905 case COMPONENT_ENABLED_STATE_ENABLED: 19906 if (!pkgSetting.enableComponentLPw(className, userId)) { 19907 return; 19908 } 19909 break; 19910 case COMPONENT_ENABLED_STATE_DISABLED: 19911 if (!pkgSetting.disableComponentLPw(className, userId)) { 19912 return; 19913 } 19914 break; 19915 case COMPONENT_ENABLED_STATE_DEFAULT: 19916 if (!pkgSetting.restoreComponentLPw(className, userId)) { 19917 return; 19918 } 19919 break; 19920 default: 19921 Slog.e(TAG, "Invalid new component state: " + newState); 19922 return; 19923 } 19924 } 19925 scheduleWritePackageRestrictionsLocked(userId); 19926 updateSequenceNumberLP(packageName, new int[] { userId }); 19927 components = mPendingBroadcasts.get(userId, packageName); 19928 final boolean newPackage = components == null; 19929 if (newPackage) { 19930 components = new ArrayList<String>(); 19931 } 19932 if (!components.contains(componentName)) { 19933 components.add(componentName); 19934 } 19935 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 19936 sendNow = true; 19937 // Purge entry from pending broadcast list if another one exists already 19938 // since we are sending one right away. 19939 mPendingBroadcasts.remove(userId, packageName); 19940 } else { 19941 if (newPackage) { 19942 mPendingBroadcasts.put(userId, packageName, components); 19943 } 19944 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 19945 // Schedule a message 19946 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 19947 } 19948 } 19949 } 19950 19951 long callingId = Binder.clearCallingIdentity(); 19952 try { 19953 if (sendNow) { 19954 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 19955 sendPackageChangedBroadcast(packageName, 19956 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 19957 } 19958 } finally { 19959 Binder.restoreCallingIdentity(callingId); 19960 } 19961 } 19962 19963 @Override 19964 public void flushPackageRestrictionsAsUser(int userId) { 19965 if (!sUserManager.exists(userId)) { 19966 return; 19967 } 19968 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 19969 false /* checkShell */, "flushPackageRestrictions"); 19970 synchronized (mPackages) { 19971 mSettings.writePackageRestrictionsLPr(userId); 19972 mDirtyUsers.remove(userId); 19973 if (mDirtyUsers.isEmpty()) { 19974 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 19975 } 19976 } 19977 } 19978 19979 private void sendPackageChangedBroadcast(String packageName, 19980 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 19981 if (DEBUG_INSTALL) 19982 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 19983 + componentNames); 19984 Bundle extras = new Bundle(4); 19985 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 19986 String nameList[] = new String[componentNames.size()]; 19987 componentNames.toArray(nameList); 19988 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 19989 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 19990 extras.putInt(Intent.EXTRA_UID, packageUid); 19991 // If this is not reporting a change of the overall package, then only send it 19992 // to registered receivers. We don't want to launch a swath of apps for every 19993 // little component state change. 19994 final int flags = !componentNames.contains(packageName) 19995 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 19996 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 19997 new int[] {UserHandle.getUserId(packageUid)}); 19998 } 19999 20000 @Override 20001 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 20002 if (!sUserManager.exists(userId)) return; 20003 final int uid = Binder.getCallingUid(); 20004 final int permission = mContext.checkCallingOrSelfPermission( 20005 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 20006 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 20007 enforceCrossUserPermission(uid, userId, 20008 true /* requireFullPermission */, true /* checkShell */, "stop package"); 20009 // writer 20010 synchronized (mPackages) { 20011 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 20012 allowedByPermission, uid, userId)) { 20013 scheduleWritePackageRestrictionsLocked(userId); 20014 } 20015 } 20016 } 20017 20018 @Override 20019 public String getInstallerPackageName(String packageName) { 20020 // reader 20021 synchronized (mPackages) { 20022 return mSettings.getInstallerPackageNameLPr(packageName); 20023 } 20024 } 20025 20026 public boolean isOrphaned(String packageName) { 20027 // reader 20028 synchronized (mPackages) { 20029 return mSettings.isOrphaned(packageName); 20030 } 20031 } 20032 20033 @Override 20034 public int getApplicationEnabledSetting(String packageName, int userId) { 20035 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 20036 int uid = Binder.getCallingUid(); 20037 enforceCrossUserPermission(uid, userId, 20038 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 20039 // reader 20040 synchronized (mPackages) { 20041 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 20042 } 20043 } 20044 20045 @Override 20046 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 20047 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 20048 int uid = Binder.getCallingUid(); 20049 enforceCrossUserPermission(uid, userId, 20050 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 20051 // reader 20052 synchronized (mPackages) { 20053 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 20054 } 20055 } 20056 20057 @Override 20058 public void enterSafeMode() { 20059 enforceSystemOrRoot("Only the system can request entering safe mode"); 20060 20061 if (!mSystemReady) { 20062 mSafeMode = true; 20063 } 20064 } 20065 20066 @Override 20067 public void systemReady() { 20068 mSystemReady = true; 20069 20070 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 20071 // disabled after already being started. 20072 CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this, 20073 mContext.getContentResolver(), UserHandle.USER_SYSTEM); 20074 20075 // Read the compatibilty setting when the system is ready. 20076 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 20077 mContext.getContentResolver(), 20078 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 20079 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 20080 if (DEBUG_SETTINGS) { 20081 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 20082 } 20083 20084 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 20085 20086 synchronized (mPackages) { 20087 // Verify that all of the preferred activity components actually 20088 // exist. It is possible for applications to be updated and at 20089 // that point remove a previously declared activity component that 20090 // had been set as a preferred activity. We try to clean this up 20091 // the next time we encounter that preferred activity, but it is 20092 // possible for the user flow to never be able to return to that 20093 // situation so here we do a sanity check to make sure we haven't 20094 // left any junk around. 20095 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 20096 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 20097 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 20098 removed.clear(); 20099 for (PreferredActivity pa : pir.filterSet()) { 20100 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 20101 removed.add(pa); 20102 } 20103 } 20104 if (removed.size() > 0) { 20105 for (int r=0; r<removed.size(); r++) { 20106 PreferredActivity pa = removed.get(r); 20107 Slog.w(TAG, "Removing dangling preferred activity: " 20108 + pa.mPref.mComponent); 20109 pir.removeFilter(pa); 20110 } 20111 mSettings.writePackageRestrictionsLPr( 20112 mSettings.mPreferredActivities.keyAt(i)); 20113 } 20114 } 20115 20116 for (int userId : UserManagerService.getInstance().getUserIds()) { 20117 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 20118 grantPermissionsUserIds = ArrayUtils.appendInt( 20119 grantPermissionsUserIds, userId); 20120 } 20121 } 20122 } 20123 sUserManager.systemReady(); 20124 20125 // If we upgraded grant all default permissions before kicking off. 20126 for (int userId : grantPermissionsUserIds) { 20127 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 20128 } 20129 20130 // If we did not grant default permissions, we preload from this the 20131 // default permission exceptions lazily to ensure we don't hit the 20132 // disk on a new user creation. 20133 if (grantPermissionsUserIds == EMPTY_INT_ARRAY) { 20134 mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions(); 20135 } 20136 20137 // Kick off any messages waiting for system ready 20138 if (mPostSystemReadyMessages != null) { 20139 for (Message msg : mPostSystemReadyMessages) { 20140 msg.sendToTarget(); 20141 } 20142 mPostSystemReadyMessages = null; 20143 } 20144 20145 // Watch for external volumes that come and go over time 20146 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20147 storage.registerListener(mStorageListener); 20148 20149 mInstallerService.systemReady(); 20150 mPackageDexOptimizer.systemReady(); 20151 20152 StorageManagerInternal StorageManagerInternal = LocalServices.getService( 20153 StorageManagerInternal.class); 20154 StorageManagerInternal.addExternalStoragePolicy( 20155 new StorageManagerInternal.ExternalStorageMountPolicy() { 20156 @Override 20157 public int getMountMode(int uid, String packageName) { 20158 if (Process.isIsolated(uid)) { 20159 return Zygote.MOUNT_EXTERNAL_NONE; 20160 } 20161 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 20162 return Zygote.MOUNT_EXTERNAL_DEFAULT; 20163 } 20164 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 20165 return Zygote.MOUNT_EXTERNAL_DEFAULT; 20166 } 20167 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 20168 return Zygote.MOUNT_EXTERNAL_READ; 20169 } 20170 return Zygote.MOUNT_EXTERNAL_WRITE; 20171 } 20172 20173 @Override 20174 public boolean hasExternalStorage(int uid, String packageName) { 20175 return true; 20176 } 20177 }); 20178 20179 // Now that we're mostly running, clean up stale users and apps 20180 sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 20181 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 20182 20183 if (mPrivappPermissionsViolations != null) { 20184 Slog.wtf(TAG,"Signature|privileged permissions not in " 20185 + "privapp-permissions whitelist: " + mPrivappPermissionsViolations); 20186 mPrivappPermissionsViolations = null; 20187 } 20188 } 20189 20190 public void waitForAppDataPrepared() { 20191 if (mPrepareAppDataFuture == null) { 20192 return; 20193 } 20194 ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData"); 20195 mPrepareAppDataFuture = null; 20196 } 20197 20198 @Override 20199 public boolean isSafeMode() { 20200 return mSafeMode; 20201 } 20202 20203 @Override 20204 public boolean hasSystemUidErrors() { 20205 return mHasSystemUidErrors; 20206 } 20207 20208 static String arrayToString(int[] array) { 20209 StringBuffer buf = new StringBuffer(128); 20210 buf.append('['); 20211 if (array != null) { 20212 for (int i=0; i<array.length; i++) { 20213 if (i > 0) buf.append(", "); 20214 buf.append(array[i]); 20215 } 20216 } 20217 buf.append(']'); 20218 return buf.toString(); 20219 } 20220 20221 static class DumpState { 20222 public static final int DUMP_LIBS = 1 << 0; 20223 public static final int DUMP_FEATURES = 1 << 1; 20224 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 20225 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 20226 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 20227 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 20228 public static final int DUMP_PERMISSIONS = 1 << 6; 20229 public static final int DUMP_PACKAGES = 1 << 7; 20230 public static final int DUMP_SHARED_USERS = 1 << 8; 20231 public static final int DUMP_MESSAGES = 1 << 9; 20232 public static final int DUMP_PROVIDERS = 1 << 10; 20233 public static final int DUMP_VERIFIERS = 1 << 11; 20234 public static final int DUMP_PREFERRED = 1 << 12; 20235 public static final int DUMP_PREFERRED_XML = 1 << 13; 20236 public static final int DUMP_KEYSETS = 1 << 14; 20237 public static final int DUMP_VERSION = 1 << 15; 20238 public static final int DUMP_INSTALLS = 1 << 16; 20239 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 20240 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 20241 public static final int DUMP_FROZEN = 1 << 19; 20242 public static final int DUMP_DEXOPT = 1 << 20; 20243 public static final int DUMP_COMPILER_STATS = 1 << 21; 20244 public static final int DUMP_ENABLED_OVERLAYS = 1 << 22; 20245 20246 public static final int OPTION_SHOW_FILTERS = 1 << 0; 20247 20248 private int mTypes; 20249 20250 private int mOptions; 20251 20252 private boolean mTitlePrinted; 20253 20254 private SharedUserSetting mSharedUser; 20255 20256 public boolean isDumping(int type) { 20257 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 20258 return true; 20259 } 20260 20261 return (mTypes & type) != 0; 20262 } 20263 20264 public void setDump(int type) { 20265 mTypes |= type; 20266 } 20267 20268 public boolean isOptionEnabled(int option) { 20269 return (mOptions & option) != 0; 20270 } 20271 20272 public void setOptionEnabled(int option) { 20273 mOptions |= option; 20274 } 20275 20276 public boolean onTitlePrinted() { 20277 final boolean printed = mTitlePrinted; 20278 mTitlePrinted = true; 20279 return printed; 20280 } 20281 20282 public boolean getTitlePrinted() { 20283 return mTitlePrinted; 20284 } 20285 20286 public void setTitlePrinted(boolean enabled) { 20287 mTitlePrinted = enabled; 20288 } 20289 20290 public SharedUserSetting getSharedUser() { 20291 return mSharedUser; 20292 } 20293 20294 public void setSharedUser(SharedUserSetting user) { 20295 mSharedUser = user; 20296 } 20297 } 20298 20299 @Override 20300 public void onShellCommand(FileDescriptor in, FileDescriptor out, 20301 FileDescriptor err, String[] args, ShellCallback callback, 20302 ResultReceiver resultReceiver) { 20303 (new PackageManagerShellCommand(this)).exec( 20304 this, in, out, err, args, callback, resultReceiver); 20305 } 20306 20307 @Override 20308 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 20309 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 20310 != PackageManager.PERMISSION_GRANTED) { 20311 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 20312 + Binder.getCallingPid() 20313 + ", uid=" + Binder.getCallingUid() 20314 + " without permission " 20315 + android.Manifest.permission.DUMP); 20316 return; 20317 } 20318 20319 DumpState dumpState = new DumpState(); 20320 boolean fullPreferred = false; 20321 boolean checkin = false; 20322 20323 String packageName = null; 20324 ArraySet<String> permissionNames = null; 20325 20326 int opti = 0; 20327 while (opti < args.length) { 20328 String opt = args[opti]; 20329 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 20330 break; 20331 } 20332 opti++; 20333 20334 if ("-a".equals(opt)) { 20335 // Right now we only know how to print all. 20336 } else if ("-h".equals(opt)) { 20337 pw.println("Package manager dump options:"); 20338 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 20339 pw.println(" --checkin: dump for a checkin"); 20340 pw.println(" -f: print details of intent filters"); 20341 pw.println(" -h: print this help"); 20342 pw.println(" cmd may be one of:"); 20343 pw.println(" l[ibraries]: list known shared libraries"); 20344 pw.println(" f[eatures]: list device features"); 20345 pw.println(" k[eysets]: print known keysets"); 20346 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 20347 pw.println(" perm[issions]: dump permissions"); 20348 pw.println(" permission [name ...]: dump declaration and use of given permission"); 20349 pw.println(" pref[erred]: print preferred package settings"); 20350 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 20351 pw.println(" prov[iders]: dump content providers"); 20352 pw.println(" p[ackages]: dump installed packages"); 20353 pw.println(" s[hared-users]: dump shared user IDs"); 20354 pw.println(" m[essages]: print collected runtime messages"); 20355 pw.println(" v[erifiers]: print package verifier info"); 20356 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 20357 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 20358 pw.println(" version: print database version info"); 20359 pw.println(" write: write current settings now"); 20360 pw.println(" installs: details about install sessions"); 20361 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 20362 pw.println(" dexopt: dump dexopt state"); 20363 pw.println(" compiler-stats: dump compiler statistics"); 20364 pw.println(" enabled-overlays: dump list of enabled overlay packages"); 20365 pw.println(" <package.name>: info about given package"); 20366 return; 20367 } else if ("--checkin".equals(opt)) { 20368 checkin = true; 20369 } else if ("-f".equals(opt)) { 20370 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 20371 } else if ("--proto".equals(opt)) { 20372 dumpProto(fd); 20373 return; 20374 } else { 20375 pw.println("Unknown argument: " + opt + "; use -h for help"); 20376 } 20377 } 20378 20379 // Is the caller requesting to dump a particular piece of data? 20380 if (opti < args.length) { 20381 String cmd = args[opti]; 20382 opti++; 20383 // Is this a package name? 20384 if ("android".equals(cmd) || cmd.contains(".")) { 20385 packageName = cmd; 20386 // When dumping a single package, we always dump all of its 20387 // filter information since the amount of data will be reasonable. 20388 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 20389 } else if ("check-permission".equals(cmd)) { 20390 if (opti >= args.length) { 20391 pw.println("Error: check-permission missing permission argument"); 20392 return; 20393 } 20394 String perm = args[opti]; 20395 opti++; 20396 if (opti >= args.length) { 20397 pw.println("Error: check-permission missing package argument"); 20398 return; 20399 } 20400 20401 String pkg = args[opti]; 20402 opti++; 20403 int user = UserHandle.getUserId(Binder.getCallingUid()); 20404 if (opti < args.length) { 20405 try { 20406 user = Integer.parseInt(args[opti]); 20407 } catch (NumberFormatException e) { 20408 pw.println("Error: check-permission user argument is not a number: " 20409 + args[opti]); 20410 return; 20411 } 20412 } 20413 20414 // Normalize package name to handle renamed packages and static libs 20415 pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST); 20416 20417 pw.println(checkPermission(perm, pkg, user)); 20418 return; 20419 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 20420 dumpState.setDump(DumpState.DUMP_LIBS); 20421 } else if ("f".equals(cmd) || "features".equals(cmd)) { 20422 dumpState.setDump(DumpState.DUMP_FEATURES); 20423 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 20424 if (opti >= args.length) { 20425 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 20426 | DumpState.DUMP_SERVICE_RESOLVERS 20427 | DumpState.DUMP_RECEIVER_RESOLVERS 20428 | DumpState.DUMP_CONTENT_RESOLVERS); 20429 } else { 20430 while (opti < args.length) { 20431 String name = args[opti]; 20432 if ("a".equals(name) || "activity".equals(name)) { 20433 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 20434 } else if ("s".equals(name) || "service".equals(name)) { 20435 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 20436 } else if ("r".equals(name) || "receiver".equals(name)) { 20437 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 20438 } else if ("c".equals(name) || "content".equals(name)) { 20439 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 20440 } else { 20441 pw.println("Error: unknown resolver table type: " + name); 20442 return; 20443 } 20444 opti++; 20445 } 20446 } 20447 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 20448 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 20449 } else if ("permission".equals(cmd)) { 20450 if (opti >= args.length) { 20451 pw.println("Error: permission requires permission name"); 20452 return; 20453 } 20454 permissionNames = new ArraySet<>(); 20455 while (opti < args.length) { 20456 permissionNames.add(args[opti]); 20457 opti++; 20458 } 20459 dumpState.setDump(DumpState.DUMP_PERMISSIONS 20460 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 20461 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 20462 dumpState.setDump(DumpState.DUMP_PREFERRED); 20463 } else if ("preferred-xml".equals(cmd)) { 20464 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 20465 if (opti < args.length && "--full".equals(args[opti])) { 20466 fullPreferred = true; 20467 opti++; 20468 } 20469 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 20470 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 20471 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 20472 dumpState.setDump(DumpState.DUMP_PACKAGES); 20473 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 20474 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 20475 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 20476 dumpState.setDump(DumpState.DUMP_PROVIDERS); 20477 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 20478 dumpState.setDump(DumpState.DUMP_MESSAGES); 20479 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 20480 dumpState.setDump(DumpState.DUMP_VERIFIERS); 20481 } else if ("i".equals(cmd) || "ifv".equals(cmd) 20482 || "intent-filter-verifiers".equals(cmd)) { 20483 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 20484 } else if ("version".equals(cmd)) { 20485 dumpState.setDump(DumpState.DUMP_VERSION); 20486 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 20487 dumpState.setDump(DumpState.DUMP_KEYSETS); 20488 } else if ("installs".equals(cmd)) { 20489 dumpState.setDump(DumpState.DUMP_INSTALLS); 20490 } else if ("frozen".equals(cmd)) { 20491 dumpState.setDump(DumpState.DUMP_FROZEN); 20492 } else if ("dexopt".equals(cmd)) { 20493 dumpState.setDump(DumpState.DUMP_DEXOPT); 20494 } else if ("compiler-stats".equals(cmd)) { 20495 dumpState.setDump(DumpState.DUMP_COMPILER_STATS); 20496 } else if ("enabled-overlays".equals(cmd)) { 20497 dumpState.setDump(DumpState.DUMP_ENABLED_OVERLAYS); 20498 } else if ("write".equals(cmd)) { 20499 synchronized (mPackages) { 20500 mSettings.writeLPr(); 20501 pw.println("Settings written."); 20502 return; 20503 } 20504 } 20505 } 20506 20507 if (checkin) { 20508 pw.println("vers,1"); 20509 } 20510 20511 // reader 20512 synchronized (mPackages) { 20513 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 20514 if (!checkin) { 20515 if (dumpState.onTitlePrinted()) 20516 pw.println(); 20517 pw.println("Database versions:"); 20518 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 20519 } 20520 } 20521 20522 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 20523 if (!checkin) { 20524 if (dumpState.onTitlePrinted()) 20525 pw.println(); 20526 pw.println("Verifiers:"); 20527 pw.print(" Required: "); 20528 pw.print(mRequiredVerifierPackage); 20529 pw.print(" (uid="); 20530 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 20531 UserHandle.USER_SYSTEM)); 20532 pw.println(")"); 20533 } else if (mRequiredVerifierPackage != null) { 20534 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 20535 pw.print(","); 20536 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 20537 UserHandle.USER_SYSTEM)); 20538 } 20539 } 20540 20541 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 20542 packageName == null) { 20543 if (mIntentFilterVerifierComponent != null) { 20544 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 20545 if (!checkin) { 20546 if (dumpState.onTitlePrinted()) 20547 pw.println(); 20548 pw.println("Intent Filter Verifier:"); 20549 pw.print(" Using: "); 20550 pw.print(verifierPackageName); 20551 pw.print(" (uid="); 20552 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 20553 UserHandle.USER_SYSTEM)); 20554 pw.println(")"); 20555 } else if (verifierPackageName != null) { 20556 pw.print("ifv,"); pw.print(verifierPackageName); 20557 pw.print(","); 20558 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 20559 UserHandle.USER_SYSTEM)); 20560 } 20561 } else { 20562 pw.println(); 20563 pw.println("No Intent Filter Verifier available!"); 20564 } 20565 } 20566 20567 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 20568 boolean printedHeader = false; 20569 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 20570 while (it.hasNext()) { 20571 String libName = it.next(); 20572 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName); 20573 if (versionedLib == null) { 20574 continue; 20575 } 20576 final int versionCount = versionedLib.size(); 20577 for (int i = 0; i < versionCount; i++) { 20578 SharedLibraryEntry libEntry = versionedLib.valueAt(i); 20579 if (!checkin) { 20580 if (!printedHeader) { 20581 if (dumpState.onTitlePrinted()) 20582 pw.println(); 20583 pw.println("Libraries:"); 20584 printedHeader = true; 20585 } 20586 pw.print(" "); 20587 } else { 20588 pw.print("lib,"); 20589 } 20590 pw.print(libEntry.info.getName()); 20591 if (libEntry.info.isStatic()) { 20592 pw.print(" version=" + libEntry.info.getVersion()); 20593 } 20594 if (!checkin) { 20595 pw.print(" -> "); 20596 } 20597 if (libEntry.path != null) { 20598 pw.print(" (jar) "); 20599 pw.print(libEntry.path); 20600 } else { 20601 pw.print(" (apk) "); 20602 pw.print(libEntry.apk); 20603 } 20604 pw.println(); 20605 } 20606 } 20607 } 20608 20609 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 20610 if (dumpState.onTitlePrinted()) 20611 pw.println(); 20612 if (!checkin) { 20613 pw.println("Features:"); 20614 } 20615 20616 synchronized (mAvailableFeatures) { 20617 for (FeatureInfo feat : mAvailableFeatures.values()) { 20618 if (checkin) { 20619 pw.print("feat,"); 20620 pw.print(feat.name); 20621 pw.print(","); 20622 pw.println(feat.version); 20623 } else { 20624 pw.print(" "); 20625 pw.print(feat.name); 20626 if (feat.version > 0) { 20627 pw.print(" version="); 20628 pw.print(feat.version); 20629 } 20630 pw.println(); 20631 } 20632 } 20633 } 20634 } 20635 20636 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 20637 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 20638 : "Activity Resolver Table:", " ", packageName, 20639 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20640 dumpState.setTitlePrinted(true); 20641 } 20642 } 20643 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 20644 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 20645 : "Receiver Resolver Table:", " ", packageName, 20646 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20647 dumpState.setTitlePrinted(true); 20648 } 20649 } 20650 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 20651 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 20652 : "Service Resolver Table:", " ", packageName, 20653 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20654 dumpState.setTitlePrinted(true); 20655 } 20656 } 20657 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 20658 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 20659 : "Provider Resolver Table:", " ", packageName, 20660 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20661 dumpState.setTitlePrinted(true); 20662 } 20663 } 20664 20665 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 20666 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 20667 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 20668 int user = mSettings.mPreferredActivities.keyAt(i); 20669 if (pir.dump(pw, 20670 dumpState.getTitlePrinted() 20671 ? "\nPreferred Activities User " + user + ":" 20672 : "Preferred Activities User " + user + ":", " ", 20673 packageName, true, false)) { 20674 dumpState.setTitlePrinted(true); 20675 } 20676 } 20677 } 20678 20679 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 20680 pw.flush(); 20681 FileOutputStream fout = new FileOutputStream(fd); 20682 BufferedOutputStream str = new BufferedOutputStream(fout); 20683 XmlSerializer serializer = new FastXmlSerializer(); 20684 try { 20685 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 20686 serializer.startDocument(null, true); 20687 serializer.setFeature( 20688 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 20689 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 20690 serializer.endDocument(); 20691 serializer.flush(); 20692 } catch (IllegalArgumentException e) { 20693 pw.println("Failed writing: " + e); 20694 } catch (IllegalStateException e) { 20695 pw.println("Failed writing: " + e); 20696 } catch (IOException e) { 20697 pw.println("Failed writing: " + e); 20698 } 20699 } 20700 20701 if (!checkin 20702 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 20703 && packageName == null) { 20704 pw.println(); 20705 int count = mSettings.mPackages.size(); 20706 if (count == 0) { 20707 pw.println("No applications!"); 20708 pw.println(); 20709 } else { 20710 final String prefix = " "; 20711 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 20712 if (allPackageSettings.size() == 0) { 20713 pw.println("No domain preferred apps!"); 20714 pw.println(); 20715 } else { 20716 pw.println("App verification status:"); 20717 pw.println(); 20718 count = 0; 20719 for (PackageSetting ps : allPackageSettings) { 20720 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 20721 if (ivi == null || ivi.getPackageName() == null) continue; 20722 pw.println(prefix + "Package: " + ivi.getPackageName()); 20723 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 20724 pw.println(prefix + "Status: " + ivi.getStatusString()); 20725 pw.println(); 20726 count++; 20727 } 20728 if (count == 0) { 20729 pw.println(prefix + "No app verification established."); 20730 pw.println(); 20731 } 20732 for (int userId : sUserManager.getUserIds()) { 20733 pw.println("App linkages for user " + userId + ":"); 20734 pw.println(); 20735 count = 0; 20736 for (PackageSetting ps : allPackageSettings) { 20737 final long status = ps.getDomainVerificationStatusForUser(userId); 20738 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 20739 && !DEBUG_DOMAIN_VERIFICATION) { 20740 continue; 20741 } 20742 pw.println(prefix + "Package: " + ps.name); 20743 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 20744 String statusStr = IntentFilterVerificationInfo. 20745 getStatusStringFromValue(status); 20746 pw.println(prefix + "Status: " + statusStr); 20747 pw.println(); 20748 count++; 20749 } 20750 if (count == 0) { 20751 pw.println(prefix + "No configured app linkages."); 20752 pw.println(); 20753 } 20754 } 20755 } 20756 } 20757 } 20758 20759 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 20760 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 20761 if (packageName == null && permissionNames == null) { 20762 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 20763 if (iperm == 0) { 20764 if (dumpState.onTitlePrinted()) 20765 pw.println(); 20766 pw.println("AppOp Permissions:"); 20767 } 20768 pw.print(" AppOp Permission "); 20769 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 20770 pw.println(":"); 20771 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 20772 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 20773 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 20774 } 20775 } 20776 } 20777 } 20778 20779 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 20780 boolean printedSomething = false; 20781 for (PackageParser.Provider p : mProviders.mProviders.values()) { 20782 if (packageName != null && !packageName.equals(p.info.packageName)) { 20783 continue; 20784 } 20785 if (!printedSomething) { 20786 if (dumpState.onTitlePrinted()) 20787 pw.println(); 20788 pw.println("Registered ContentProviders:"); 20789 printedSomething = true; 20790 } 20791 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 20792 pw.print(" "); pw.println(p.toString()); 20793 } 20794 printedSomething = false; 20795 for (Map.Entry<String, PackageParser.Provider> entry : 20796 mProvidersByAuthority.entrySet()) { 20797 PackageParser.Provider p = entry.getValue(); 20798 if (packageName != null && !packageName.equals(p.info.packageName)) { 20799 continue; 20800 } 20801 if (!printedSomething) { 20802 if (dumpState.onTitlePrinted()) 20803 pw.println(); 20804 pw.println("ContentProvider Authorities:"); 20805 printedSomething = true; 20806 } 20807 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 20808 pw.print(" "); pw.println(p.toString()); 20809 if (p.info != null && p.info.applicationInfo != null) { 20810 final String appInfo = p.info.applicationInfo.toString(); 20811 pw.print(" applicationInfo="); pw.println(appInfo); 20812 } 20813 } 20814 } 20815 20816 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 20817 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 20818 } 20819 20820 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 20821 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 20822 } 20823 20824 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 20825 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 20826 } 20827 20828 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 20829 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 20830 } 20831 20832 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 20833 // XXX should handle packageName != null by dumping only install data that 20834 // the given package is involved with. 20835 if (dumpState.onTitlePrinted()) pw.println(); 20836 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 20837 } 20838 20839 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 20840 // XXX should handle packageName != null by dumping only install data that 20841 // the given package is involved with. 20842 if (dumpState.onTitlePrinted()) pw.println(); 20843 20844 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 20845 ipw.println(); 20846 ipw.println("Frozen packages:"); 20847 ipw.increaseIndent(); 20848 if (mFrozenPackages.size() == 0) { 20849 ipw.println("(none)"); 20850 } else { 20851 for (int i = 0; i < mFrozenPackages.size(); i++) { 20852 ipw.println(mFrozenPackages.valueAt(i)); 20853 } 20854 } 20855 ipw.decreaseIndent(); 20856 } 20857 20858 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 20859 if (dumpState.onTitlePrinted()) pw.println(); 20860 dumpDexoptStateLPr(pw, packageName); 20861 } 20862 20863 if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) { 20864 if (dumpState.onTitlePrinted()) pw.println(); 20865 dumpCompilerStatsLPr(pw, packageName); 20866 } 20867 20868 if (!checkin && dumpState.isDumping(DumpState.DUMP_ENABLED_OVERLAYS)) { 20869 if (dumpState.onTitlePrinted()) pw.println(); 20870 dumpEnabledOverlaysLPr(pw); 20871 } 20872 20873 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 20874 if (dumpState.onTitlePrinted()) pw.println(); 20875 mSettings.dumpReadMessagesLPr(pw, dumpState); 20876 20877 pw.println(); 20878 pw.println("Package warning messages:"); 20879 BufferedReader in = null; 20880 String line = null; 20881 try { 20882 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 20883 while ((line = in.readLine()) != null) { 20884 if (line.contains("ignored: updated version")) continue; 20885 pw.println(line); 20886 } 20887 } catch (IOException ignored) { 20888 } finally { 20889 IoUtils.closeQuietly(in); 20890 } 20891 } 20892 20893 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 20894 BufferedReader in = null; 20895 String line = null; 20896 try { 20897 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 20898 while ((line = in.readLine()) != null) { 20899 if (line.contains("ignored: updated version")) continue; 20900 pw.print("msg,"); 20901 pw.println(line); 20902 } 20903 } catch (IOException ignored) { 20904 } finally { 20905 IoUtils.closeQuietly(in); 20906 } 20907 } 20908 } 20909 } 20910 20911 private void dumpProto(FileDescriptor fd) { 20912 final ProtoOutputStream proto = new ProtoOutputStream(fd); 20913 20914 synchronized (mPackages) { 20915 final long requiredVerifierPackageToken = 20916 proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE); 20917 proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage); 20918 proto.write( 20919 PackageServiceDumpProto.PackageShortProto.UID, 20920 getPackageUid( 20921 mRequiredVerifierPackage, 20922 MATCH_DEBUG_TRIAGED_MISSING, 20923 UserHandle.USER_SYSTEM)); 20924 proto.end(requiredVerifierPackageToken); 20925 20926 if (mIntentFilterVerifierComponent != null) { 20927 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 20928 final long verifierPackageToken = 20929 proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE); 20930 proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName); 20931 proto.write( 20932 PackageServiceDumpProto.PackageShortProto.UID, 20933 getPackageUid( 20934 verifierPackageName, 20935 MATCH_DEBUG_TRIAGED_MISSING, 20936 UserHandle.USER_SYSTEM)); 20937 proto.end(verifierPackageToken); 20938 } 20939 20940 dumpSharedLibrariesProto(proto); 20941 dumpFeaturesProto(proto); 20942 mSettings.dumpPackagesProto(proto); 20943 mSettings.dumpSharedUsersProto(proto); 20944 dumpMessagesProto(proto); 20945 } 20946 proto.flush(); 20947 } 20948 20949 private void dumpMessagesProto(ProtoOutputStream proto) { 20950 BufferedReader in = null; 20951 String line = null; 20952 try { 20953 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 20954 while ((line = in.readLine()) != null) { 20955 if (line.contains("ignored: updated version")) continue; 20956 proto.write(PackageServiceDumpProto.MESSAGES, line); 20957 } 20958 } catch (IOException ignored) { 20959 } finally { 20960 IoUtils.closeQuietly(in); 20961 } 20962 } 20963 20964 private void dumpFeaturesProto(ProtoOutputStream proto) { 20965 synchronized (mAvailableFeatures) { 20966 final int count = mAvailableFeatures.size(); 20967 for (int i = 0; i < count; i++) { 20968 final FeatureInfo feat = mAvailableFeatures.valueAt(i); 20969 final long featureToken = proto.start(PackageServiceDumpProto.FEATURES); 20970 proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name); 20971 proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version); 20972 proto.end(featureToken); 20973 } 20974 } 20975 } 20976 20977 private void dumpSharedLibrariesProto(ProtoOutputStream proto) { 20978 final int count = mSharedLibraries.size(); 20979 for (int i = 0; i < count; i++) { 20980 final String libName = mSharedLibraries.keyAt(i); 20981 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName); 20982 if (versionedLib == null) { 20983 continue; 20984 } 20985 final int versionCount = versionedLib.size(); 20986 for (int j = 0; j < versionCount; j++) { 20987 final SharedLibraryEntry libEntry = versionedLib.valueAt(j); 20988 final long sharedLibraryToken = 20989 proto.start(PackageServiceDumpProto.SHARED_LIBRARIES); 20990 proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName()); 20991 final boolean isJar = (libEntry.path != null); 20992 proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar); 20993 if (isJar) { 20994 proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path); 20995 } else { 20996 proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk); 20997 } 20998 proto.end(sharedLibraryToken); 20999 } 21000 } 21001 } 21002 21003 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 21004 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 21005 ipw.println(); 21006 ipw.println("Dexopt state:"); 21007 ipw.increaseIndent(); 21008 Collection<PackageParser.Package> packages = null; 21009 if (packageName != null) { 21010 PackageParser.Package targetPackage = mPackages.get(packageName); 21011 if (targetPackage != null) { 21012 packages = Collections.singletonList(targetPackage); 21013 } else { 21014 ipw.println("Unable to find package: " + packageName); 21015 return; 21016 } 21017 } else { 21018 packages = mPackages.values(); 21019 } 21020 21021 for (PackageParser.Package pkg : packages) { 21022 ipw.println("[" + pkg.packageName + "]"); 21023 ipw.increaseIndent(); 21024 mPackageDexOptimizer.dumpDexoptState(ipw, pkg); 21025 ipw.decreaseIndent(); 21026 } 21027 } 21028 21029 private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) { 21030 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 21031 ipw.println(); 21032 ipw.println("Compiler stats:"); 21033 ipw.increaseIndent(); 21034 Collection<PackageParser.Package> packages = null; 21035 if (packageName != null) { 21036 PackageParser.Package targetPackage = mPackages.get(packageName); 21037 if (targetPackage != null) { 21038 packages = Collections.singletonList(targetPackage); 21039 } else { 21040 ipw.println("Unable to find package: " + packageName); 21041 return; 21042 } 21043 } else { 21044 packages = mPackages.values(); 21045 } 21046 21047 for (PackageParser.Package pkg : packages) { 21048 ipw.println("[" + pkg.packageName + "]"); 21049 ipw.increaseIndent(); 21050 21051 CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName); 21052 if (stats == null) { 21053 ipw.println("(No recorded stats)"); 21054 } else { 21055 stats.dump(ipw); 21056 } 21057 ipw.decreaseIndent(); 21058 } 21059 } 21060 21061 private void dumpEnabledOverlaysLPr(PrintWriter pw) { 21062 pw.println("Enabled overlay paths:"); 21063 final int N = mEnabledOverlayPaths.size(); 21064 for (int i = 0; i < N; i++) { 21065 final int userId = mEnabledOverlayPaths.keyAt(i); 21066 pw.println(String.format(" User %d:", userId)); 21067 final ArrayMap<String, ArrayList<String>> userSpecificOverlays = 21068 mEnabledOverlayPaths.valueAt(i); 21069 final int M = userSpecificOverlays.size(); 21070 for (int j = 0; j < M; j++) { 21071 final String targetPackageName = userSpecificOverlays.keyAt(j); 21072 final ArrayList<String> overlayPackagePaths = userSpecificOverlays.valueAt(j); 21073 pw.println(String.format(" %s: %s", targetPackageName, overlayPackagePaths)); 21074 } 21075 } 21076 } 21077 21078 private String dumpDomainString(String packageName) { 21079 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 21080 .getList(); 21081 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 21082 21083 ArraySet<String> result = new ArraySet<>(); 21084 if (iviList.size() > 0) { 21085 for (IntentFilterVerificationInfo ivi : iviList) { 21086 for (String host : ivi.getDomains()) { 21087 result.add(host); 21088 } 21089 } 21090 } 21091 if (filters != null && filters.size() > 0) { 21092 for (IntentFilter filter : filters) { 21093 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 21094 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 21095 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 21096 result.addAll(filter.getHostsList()); 21097 } 21098 } 21099 } 21100 21101 StringBuilder sb = new StringBuilder(result.size() * 16); 21102 for (String domain : result) { 21103 if (sb.length() > 0) sb.append(" "); 21104 sb.append(domain); 21105 } 21106 return sb.toString(); 21107 } 21108 21109 // ------- apps on sdcard specific code ------- 21110 static final boolean DEBUG_SD_INSTALL = false; 21111 21112 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 21113 21114 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 21115 21116 private boolean mMediaMounted = false; 21117 21118 static String getEncryptKey() { 21119 try { 21120 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 21121 SD_ENCRYPTION_KEYSTORE_NAME); 21122 if (sdEncKey == null) { 21123 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 21124 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 21125 if (sdEncKey == null) { 21126 Slog.e(TAG, "Failed to create encryption keys"); 21127 return null; 21128 } 21129 } 21130 return sdEncKey; 21131 } catch (NoSuchAlgorithmException nsae) { 21132 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 21133 return null; 21134 } catch (IOException ioe) { 21135 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 21136 return null; 21137 } 21138 } 21139 21140 /* 21141 * Update media status on PackageManager. 21142 */ 21143 @Override 21144 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 21145 int callingUid = Binder.getCallingUid(); 21146 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 21147 throw new SecurityException("Media status can only be updated by the system"); 21148 } 21149 // reader; this apparently protects mMediaMounted, but should probably 21150 // be a different lock in that case. 21151 synchronized (mPackages) { 21152 Log.i(TAG, "Updating external media status from " 21153 + (mMediaMounted ? "mounted" : "unmounted") + " to " 21154 + (mediaStatus ? "mounted" : "unmounted")); 21155 if (DEBUG_SD_INSTALL) 21156 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 21157 + ", mMediaMounted=" + mMediaMounted); 21158 if (mediaStatus == mMediaMounted) { 21159 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 21160 : 0, -1); 21161 mHandler.sendMessage(msg); 21162 return; 21163 } 21164 mMediaMounted = mediaStatus; 21165 } 21166 // Queue up an async operation since the package installation may take a 21167 // little while. 21168 mHandler.post(new Runnable() { 21169 public void run() { 21170 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 21171 } 21172 }); 21173 } 21174 21175 /** 21176 * Called by StorageManagerService when the initial ASECs to scan are available. 21177 * Should block until all the ASEC containers are finished being scanned. 21178 */ 21179 public void scanAvailableAsecs() { 21180 updateExternalMediaStatusInner(true, false, false); 21181 } 21182 21183 /* 21184 * Collect information of applications on external media, map them against 21185 * existing containers and update information based on current mount status. 21186 * Please note that we always have to report status if reportStatus has been 21187 * set to true especially when unloading packages. 21188 */ 21189 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 21190 boolean externalStorage) { 21191 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 21192 int[] uidArr = EmptyArray.INT; 21193 21194 final String[] list = PackageHelper.getSecureContainerList(); 21195 if (ArrayUtils.isEmpty(list)) { 21196 Log.i(TAG, "No secure containers found"); 21197 } else { 21198 // Process list of secure containers and categorize them 21199 // as active or stale based on their package internal state. 21200 21201 // reader 21202 synchronized (mPackages) { 21203 for (String cid : list) { 21204 // Leave stages untouched for now; installer service owns them 21205 if (PackageInstallerService.isStageName(cid)) continue; 21206 21207 if (DEBUG_SD_INSTALL) 21208 Log.i(TAG, "Processing container " + cid); 21209 String pkgName = getAsecPackageName(cid); 21210 if (pkgName == null) { 21211 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 21212 continue; 21213 } 21214 if (DEBUG_SD_INSTALL) 21215 Log.i(TAG, "Looking for pkg : " + pkgName); 21216 21217 final PackageSetting ps = mSettings.mPackages.get(pkgName); 21218 if (ps == null) { 21219 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 21220 continue; 21221 } 21222 21223 /* 21224 * Skip packages that are not external if we're unmounting 21225 * external storage. 21226 */ 21227 if (externalStorage && !isMounted && !isExternal(ps)) { 21228 continue; 21229 } 21230 21231 final AsecInstallArgs args = new AsecInstallArgs(cid, 21232 getAppDexInstructionSets(ps), ps.isForwardLocked()); 21233 // The package status is changed only if the code path 21234 // matches between settings and the container id. 21235 if (ps.codePathString != null 21236 && ps.codePathString.startsWith(args.getCodePath())) { 21237 if (DEBUG_SD_INSTALL) { 21238 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 21239 + " at code path: " + ps.codePathString); 21240 } 21241 21242 // We do have a valid package installed on sdcard 21243 processCids.put(args, ps.codePathString); 21244 final int uid = ps.appId; 21245 if (uid != -1) { 21246 uidArr = ArrayUtils.appendInt(uidArr, uid); 21247 } 21248 } else { 21249 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 21250 + ps.codePathString); 21251 } 21252 } 21253 } 21254 21255 Arrays.sort(uidArr); 21256 } 21257 21258 // Process packages with valid entries. 21259 if (isMounted) { 21260 if (DEBUG_SD_INSTALL) 21261 Log.i(TAG, "Loading packages"); 21262 loadMediaPackages(processCids, uidArr, externalStorage); 21263 startCleaningPackages(); 21264 mInstallerService.onSecureContainersAvailable(); 21265 } else { 21266 if (DEBUG_SD_INSTALL) 21267 Log.i(TAG, "Unloading packages"); 21268 unloadMediaPackages(processCids, uidArr, reportStatus); 21269 } 21270 } 21271 21272 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21273 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 21274 final int size = infos.size(); 21275 final String[] packageNames = new String[size]; 21276 final int[] packageUids = new int[size]; 21277 for (int i = 0; i < size; i++) { 21278 final ApplicationInfo info = infos.get(i); 21279 packageNames[i] = info.packageName; 21280 packageUids[i] = info.uid; 21281 } 21282 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 21283 finishedReceiver); 21284 } 21285 21286 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21287 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 21288 sendResourcesChangedBroadcast(mediaStatus, replacing, 21289 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 21290 } 21291 21292 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21293 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 21294 int size = pkgList.length; 21295 if (size > 0) { 21296 // Send broadcasts here 21297 Bundle extras = new Bundle(); 21298 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 21299 if (uidArr != null) { 21300 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 21301 } 21302 if (replacing) { 21303 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 21304 } 21305 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 21306 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 21307 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 21308 } 21309 } 21310 21311 /* 21312 * Look at potentially valid container ids from processCids If package 21313 * information doesn't match the one on record or package scanning fails, 21314 * the cid is added to list of removeCids. We currently don't delete stale 21315 * containers. 21316 */ 21317 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 21318 boolean externalStorage) { 21319 ArrayList<String> pkgList = new ArrayList<String>(); 21320 Set<AsecInstallArgs> keys = processCids.keySet(); 21321 21322 for (AsecInstallArgs args : keys) { 21323 String codePath = processCids.get(args); 21324 if (DEBUG_SD_INSTALL) 21325 Log.i(TAG, "Loading container : " + args.cid); 21326 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 21327 try { 21328 // Make sure there are no container errors first. 21329 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 21330 Slog.e(TAG, "Failed to mount cid : " + args.cid 21331 + " when installing from sdcard"); 21332 continue; 21333 } 21334 // Check code path here. 21335 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 21336 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 21337 + " does not match one in settings " + codePath); 21338 continue; 21339 } 21340 // Parse package 21341 int parseFlags = mDefParseFlags; 21342 if (args.isExternalAsec()) { 21343 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 21344 } 21345 if (args.isFwdLocked()) { 21346 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 21347 } 21348 21349 synchronized (mInstallLock) { 21350 PackageParser.Package pkg = null; 21351 try { 21352 // Sadly we don't know the package name yet to freeze it 21353 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 21354 SCAN_IGNORE_FROZEN, 0, null); 21355 } catch (PackageManagerException e) { 21356 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 21357 } 21358 // Scan the package 21359 if (pkg != null) { 21360 /* 21361 * TODO why is the lock being held? doPostInstall is 21362 * called in other places without the lock. This needs 21363 * to be straightened out. 21364 */ 21365 // writer 21366 synchronized (mPackages) { 21367 retCode = PackageManager.INSTALL_SUCCEEDED; 21368 pkgList.add(pkg.packageName); 21369 // Post process args 21370 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 21371 pkg.applicationInfo.uid); 21372 } 21373 } else { 21374 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 21375 } 21376 } 21377 21378 } finally { 21379 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 21380 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 21381 } 21382 } 21383 } 21384 // writer 21385 synchronized (mPackages) { 21386 // If the platform SDK has changed since the last time we booted, 21387 // we need to re-grant app permission to catch any new ones that 21388 // appear. This is really a hack, and means that apps can in some 21389 // cases get permissions that the user didn't initially explicitly 21390 // allow... it would be nice to have some better way to handle 21391 // this situation. 21392 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 21393 : mSettings.getInternalVersion(); 21394 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 21395 : StorageManager.UUID_PRIVATE_INTERNAL; 21396 21397 int updateFlags = UPDATE_PERMISSIONS_ALL; 21398 if (ver.sdkVersion != mSdkVersion) { 21399 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 21400 + mSdkVersion + "; regranting permissions for external"); 21401 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 21402 } 21403 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 21404 21405 // Yay, everything is now upgraded 21406 ver.forceCurrent(); 21407 21408 // can downgrade to reader 21409 // Persist settings 21410 mSettings.writeLPr(); 21411 } 21412 // Send a broadcast to let everyone know we are done processing 21413 if (pkgList.size() > 0) { 21414 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 21415 } 21416 } 21417 21418 /* 21419 * Utility method to unload a list of specified containers 21420 */ 21421 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 21422 // Just unmount all valid containers. 21423 for (AsecInstallArgs arg : cidArgs) { 21424 synchronized (mInstallLock) { 21425 arg.doPostDeleteLI(false); 21426 } 21427 } 21428 } 21429 21430 /* 21431 * Unload packages mounted on external media. This involves deleting package 21432 * data from internal structures, sending broadcasts about disabled packages, 21433 * gc'ing to free up references, unmounting all secure containers 21434 * corresponding to packages on external media, and posting a 21435 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 21436 * that we always have to post this message if status has been requested no 21437 * matter what. 21438 */ 21439 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 21440 final boolean reportStatus) { 21441 if (DEBUG_SD_INSTALL) 21442 Log.i(TAG, "unloading media packages"); 21443 ArrayList<String> pkgList = new ArrayList<String>(); 21444 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 21445 final Set<AsecInstallArgs> keys = processCids.keySet(); 21446 for (AsecInstallArgs args : keys) { 21447 String pkgName = args.getPackageName(); 21448 if (DEBUG_SD_INSTALL) 21449 Log.i(TAG, "Trying to unload pkg : " + pkgName); 21450 // Delete package internally 21451 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 21452 synchronized (mInstallLock) { 21453 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 21454 final boolean res; 21455 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 21456 "unloadMediaPackages")) { 21457 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 21458 null); 21459 } 21460 if (res) { 21461 pkgList.add(pkgName); 21462 } else { 21463 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 21464 failedList.add(args); 21465 } 21466 } 21467 } 21468 21469 // reader 21470 synchronized (mPackages) { 21471 // We didn't update the settings after removing each package; 21472 // write them now for all packages. 21473 mSettings.writeLPr(); 21474 } 21475 21476 // We have to absolutely send UPDATED_MEDIA_STATUS only 21477 // after confirming that all the receivers processed the ordered 21478 // broadcast when packages get disabled, force a gc to clean things up. 21479 // and unload all the containers. 21480 if (pkgList.size() > 0) { 21481 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 21482 new IIntentReceiver.Stub() { 21483 public void performReceive(Intent intent, int resultCode, String data, 21484 Bundle extras, boolean ordered, boolean sticky, 21485 int sendingUser) throws RemoteException { 21486 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 21487 reportStatus ? 1 : 0, 1, keys); 21488 mHandler.sendMessage(msg); 21489 } 21490 }); 21491 } else { 21492 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 21493 keys); 21494 mHandler.sendMessage(msg); 21495 } 21496 } 21497 21498 private void loadPrivatePackages(final VolumeInfo vol) { 21499 mHandler.post(new Runnable() { 21500 @Override 21501 public void run() { 21502 loadPrivatePackagesInner(vol); 21503 } 21504 }); 21505 } 21506 21507 private void loadPrivatePackagesInner(VolumeInfo vol) { 21508 final String volumeUuid = vol.fsUuid; 21509 if (TextUtils.isEmpty(volumeUuid)) { 21510 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 21511 return; 21512 } 21513 21514 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 21515 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 21516 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 21517 21518 final VersionInfo ver; 21519 final List<PackageSetting> packages; 21520 synchronized (mPackages) { 21521 ver = mSettings.findOrCreateVersion(volumeUuid); 21522 packages = mSettings.getVolumePackagesLPr(volumeUuid); 21523 } 21524 21525 for (PackageSetting ps : packages) { 21526 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 21527 synchronized (mInstallLock) { 21528 final PackageParser.Package pkg; 21529 try { 21530 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 21531 loaded.add(pkg.applicationInfo); 21532 21533 } catch (PackageManagerException e) { 21534 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 21535 } 21536 21537 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 21538 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 21539 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 21540 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 21541 } 21542 } 21543 } 21544 21545 // Reconcile app data for all started/unlocked users 21546 final StorageManager sm = mContext.getSystemService(StorageManager.class); 21547 final UserManager um = mContext.getSystemService(UserManager.class); 21548 UserManagerInternal umInternal = getUserManagerInternal(); 21549 for (UserInfo user : um.getUsers()) { 21550 final int flags; 21551 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 21552 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 21553 } else if (umInternal.isUserRunning(user.id)) { 21554 flags = StorageManager.FLAG_STORAGE_DE; 21555 } else { 21556 continue; 21557 } 21558 21559 try { 21560 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 21561 synchronized (mInstallLock) { 21562 reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */); 21563 } 21564 } catch (IllegalStateException e) { 21565 // Device was probably ejected, and we'll process that event momentarily 21566 Slog.w(TAG, "Failed to prepare storage: " + e); 21567 } 21568 } 21569 21570 synchronized (mPackages) { 21571 int updateFlags = UPDATE_PERMISSIONS_ALL; 21572 if (ver.sdkVersion != mSdkVersion) { 21573 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 21574 + mSdkVersion + "; regranting permissions for " + volumeUuid); 21575 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 21576 } 21577 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 21578 21579 // Yay, everything is now upgraded 21580 ver.forceCurrent(); 21581 21582 mSettings.writeLPr(); 21583 } 21584 21585 for (PackageFreezer freezer : freezers) { 21586 freezer.close(); 21587 } 21588 21589 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 21590 sendResourcesChangedBroadcast(true, false, loaded, null); 21591 } 21592 21593 private void unloadPrivatePackages(final VolumeInfo vol) { 21594 mHandler.post(new Runnable() { 21595 @Override 21596 public void run() { 21597 unloadPrivatePackagesInner(vol); 21598 } 21599 }); 21600 } 21601 21602 private void unloadPrivatePackagesInner(VolumeInfo vol) { 21603 final String volumeUuid = vol.fsUuid; 21604 if (TextUtils.isEmpty(volumeUuid)) { 21605 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 21606 return; 21607 } 21608 21609 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 21610 synchronized (mInstallLock) { 21611 synchronized (mPackages) { 21612 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 21613 for (PackageSetting ps : packages) { 21614 if (ps.pkg == null) continue; 21615 21616 final ApplicationInfo info = ps.pkg.applicationInfo; 21617 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 21618 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 21619 21620 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 21621 "unloadPrivatePackagesInner")) { 21622 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 21623 false, null)) { 21624 unloaded.add(info); 21625 } else { 21626 Slog.w(TAG, "Failed to unload " + ps.codePath); 21627 } 21628 } 21629 21630 // Try very hard to release any references to this package 21631 // so we don't risk the system server being killed due to 21632 // open FDs 21633 AttributeCache.instance().removePackage(ps.name); 21634 } 21635 21636 mSettings.writeLPr(); 21637 } 21638 } 21639 21640 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 21641 sendResourcesChangedBroadcast(false, false, unloaded, null); 21642 21643 // Try very hard to release any references to this path so we don't risk 21644 // the system server being killed due to open FDs 21645 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 21646 21647 for (int i = 0; i < 3; i++) { 21648 System.gc(); 21649 System.runFinalization(); 21650 } 21651 } 21652 21653 private void assertPackageKnown(String volumeUuid, String packageName) 21654 throws PackageManagerException { 21655 synchronized (mPackages) { 21656 // Normalize package name to handle renamed packages 21657 packageName = normalizePackageNameLPr(packageName); 21658 21659 final PackageSetting ps = mSettings.mPackages.get(packageName); 21660 if (ps == null) { 21661 throw new PackageManagerException("Package " + packageName + " is unknown"); 21662 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 21663 throw new PackageManagerException( 21664 "Package " + packageName + " found on unknown volume " + volumeUuid 21665 + "; expected volume " + ps.volumeUuid); 21666 } 21667 } 21668 } 21669 21670 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 21671 throws PackageManagerException { 21672 synchronized (mPackages) { 21673 // Normalize package name to handle renamed packages 21674 packageName = normalizePackageNameLPr(packageName); 21675 21676 final PackageSetting ps = mSettings.mPackages.get(packageName); 21677 if (ps == null) { 21678 throw new PackageManagerException("Package " + packageName + " is unknown"); 21679 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 21680 throw new PackageManagerException( 21681 "Package " + packageName + " found on unknown volume " + volumeUuid 21682 + "; expected volume " + ps.volumeUuid); 21683 } else if (!ps.getInstalled(userId)) { 21684 throw new PackageManagerException( 21685 "Package " + packageName + " not installed for user " + userId); 21686 } 21687 } 21688 } 21689 21690 private List<String> collectAbsoluteCodePaths() { 21691 synchronized (mPackages) { 21692 List<String> codePaths = new ArrayList<>(); 21693 final int packageCount = mSettings.mPackages.size(); 21694 for (int i = 0; i < packageCount; i++) { 21695 final PackageSetting ps = mSettings.mPackages.valueAt(i); 21696 codePaths.add(ps.codePath.getAbsolutePath()); 21697 } 21698 return codePaths; 21699 } 21700 } 21701 21702 /** 21703 * Examine all apps present on given mounted volume, and destroy apps that 21704 * aren't expected, either due to uninstallation or reinstallation on 21705 * another volume. 21706 */ 21707 private void reconcileApps(String volumeUuid) { 21708 List<String> absoluteCodePaths = collectAbsoluteCodePaths(); 21709 List<File> filesToDelete = null; 21710 21711 final File[] files = FileUtils.listFilesOrEmpty( 21712 Environment.getDataAppDirectory(volumeUuid)); 21713 for (File file : files) { 21714 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 21715 && !PackageInstallerService.isStageName(file.getName()); 21716 if (!isPackage) { 21717 // Ignore entries which are not packages 21718 continue; 21719 } 21720 21721 String absolutePath = file.getAbsolutePath(); 21722 21723 boolean pathValid = false; 21724 final int absoluteCodePathCount = absoluteCodePaths.size(); 21725 for (int i = 0; i < absoluteCodePathCount; i++) { 21726 String absoluteCodePath = absoluteCodePaths.get(i); 21727 if (absolutePath.startsWith(absoluteCodePath)) { 21728 pathValid = true; 21729 break; 21730 } 21731 } 21732 21733 if (!pathValid) { 21734 if (filesToDelete == null) { 21735 filesToDelete = new ArrayList<>(); 21736 } 21737 filesToDelete.add(file); 21738 } 21739 } 21740 21741 if (filesToDelete != null) { 21742 final int fileToDeleteCount = filesToDelete.size(); 21743 for (int i = 0; i < fileToDeleteCount; i++) { 21744 File fileToDelete = filesToDelete.get(i); 21745 logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete); 21746 synchronized (mInstallLock) { 21747 removeCodePathLI(fileToDelete); 21748 } 21749 } 21750 } 21751 } 21752 21753 /** 21754 * Reconcile all app data for the given user. 21755 * <p> 21756 * Verifies that directories exist and that ownership and labeling is 21757 * correct for all installed apps on all mounted volumes. 21758 */ 21759 void reconcileAppsData(int userId, int flags, boolean migrateAppsData) { 21760 final StorageManager storage = mContext.getSystemService(StorageManager.class); 21761 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 21762 final String volumeUuid = vol.getFsUuid(); 21763 synchronized (mInstallLock) { 21764 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData); 21765 } 21766 } 21767 } 21768 21769 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags, 21770 boolean migrateAppData) { 21771 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */); 21772 } 21773 21774 /** 21775 * Reconcile all app data on given mounted volume. 21776 * <p> 21777 * Destroys app data that isn't expected, either due to uninstallation or 21778 * reinstallation on another volume. 21779 * <p> 21780 * Verifies that directories exist and that ownership and labeling is 21781 * correct for all installed apps. 21782 * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true) 21783 */ 21784 private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags, 21785 boolean migrateAppData, boolean onlyCoreApps) { 21786 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 21787 + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData); 21788 List<String> result = onlyCoreApps ? new ArrayList<>() : null; 21789 21790 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 21791 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 21792 21793 // First look for stale data that doesn't belong, and check if things 21794 // have changed since we did our last restorecon 21795 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 21796 if (StorageManager.isFileEncryptedNativeOrEmulated() 21797 && !StorageManager.isUserKeyUnlocked(userId)) { 21798 throw new RuntimeException( 21799 "Yikes, someone asked us to reconcile CE storage while " + userId 21800 + " was still locked; this would have caused massive data loss!"); 21801 } 21802 21803 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 21804 for (File file : files) { 21805 final String packageName = file.getName(); 21806 try { 21807 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 21808 } catch (PackageManagerException e) { 21809 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 21810 try { 21811 mInstaller.destroyAppData(volumeUuid, packageName, userId, 21812 StorageManager.FLAG_STORAGE_CE, 0); 21813 } catch (InstallerException e2) { 21814 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 21815 } 21816 } 21817 } 21818 } 21819 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 21820 final File[] files = FileUtils.listFilesOrEmpty(deDir); 21821 for (File file : files) { 21822 final String packageName = file.getName(); 21823 try { 21824 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 21825 } catch (PackageManagerException e) { 21826 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 21827 try { 21828 mInstaller.destroyAppData(volumeUuid, packageName, userId, 21829 StorageManager.FLAG_STORAGE_DE, 0); 21830 } catch (InstallerException e2) { 21831 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 21832 } 21833 } 21834 } 21835 } 21836 21837 // Ensure that data directories are ready to roll for all packages 21838 // installed for this volume and user 21839 final List<PackageSetting> packages; 21840 synchronized (mPackages) { 21841 packages = mSettings.getVolumePackagesLPr(volumeUuid); 21842 } 21843 int preparedCount = 0; 21844 for (PackageSetting ps : packages) { 21845 final String packageName = ps.name; 21846 if (ps.pkg == null) { 21847 Slog.w(TAG, "Odd, missing scanned package " + packageName); 21848 // TODO: might be due to legacy ASEC apps; we should circle back 21849 // and reconcile again once they're scanned 21850 continue; 21851 } 21852 // Skip non-core apps if requested 21853 if (onlyCoreApps && !ps.pkg.coreApp) { 21854 result.add(packageName); 21855 continue; 21856 } 21857 21858 if (ps.getInstalled(userId)) { 21859 prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData); 21860 preparedCount++; 21861 } 21862 } 21863 21864 Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages"); 21865 return result; 21866 } 21867 21868 /** 21869 * Prepare app data for the given app just after it was installed or 21870 * upgraded. This method carefully only touches users that it's installed 21871 * for, and it forces a restorecon to handle any seinfo changes. 21872 * <p> 21873 * Verifies that directories exist and that ownership and labeling is 21874 * correct for all installed apps. If there is an ownership mismatch, it 21875 * will try recovering system apps by wiping data; third-party app data is 21876 * left intact. 21877 * <p> 21878 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 21879 */ 21880 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 21881 final PackageSetting ps; 21882 synchronized (mPackages) { 21883 ps = mSettings.mPackages.get(pkg.packageName); 21884 mSettings.writeKernelMappingLPr(ps); 21885 } 21886 21887 final UserManager um = mContext.getSystemService(UserManager.class); 21888 UserManagerInternal umInternal = getUserManagerInternal(); 21889 for (UserInfo user : um.getUsers()) { 21890 final int flags; 21891 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 21892 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 21893 } else if (umInternal.isUserRunning(user.id)) { 21894 flags = StorageManager.FLAG_STORAGE_DE; 21895 } else { 21896 continue; 21897 } 21898 21899 if (ps.getInstalled(user.id)) { 21900 // TODO: when user data is locked, mark that we're still dirty 21901 prepareAppDataLIF(pkg, user.id, flags); 21902 } 21903 } 21904 } 21905 21906 /** 21907 * Prepare app data for the given app. 21908 * <p> 21909 * Verifies that directories exist and that ownership and labeling is 21910 * correct for all installed apps. If there is an ownership mismatch, this 21911 * will try recovering system apps by wiping data; third-party app data is 21912 * left intact. 21913 */ 21914 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 21915 if (pkg == null) { 21916 Slog.wtf(TAG, "Package was null!", new Throwable()); 21917 return; 21918 } 21919 prepareAppDataLeafLIF(pkg, userId, flags); 21920 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 21921 for (int i = 0; i < childCount; i++) { 21922 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 21923 } 21924 } 21925 21926 private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags, 21927 boolean maybeMigrateAppData) { 21928 prepareAppDataLIF(pkg, userId, flags); 21929 21930 if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) { 21931 // We may have just shuffled around app data directories, so 21932 // prepare them one more time 21933 prepareAppDataLIF(pkg, userId, flags); 21934 } 21935 } 21936 21937 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 21938 if (DEBUG_APP_DATA) { 21939 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 21940 + Integer.toHexString(flags)); 21941 } 21942 21943 final String volumeUuid = pkg.volumeUuid; 21944 final String packageName = pkg.packageName; 21945 final ApplicationInfo app = pkg.applicationInfo; 21946 final int appId = UserHandle.getAppId(app.uid); 21947 21948 Preconditions.checkNotNull(app.seInfo); 21949 21950 long ceDataInode = -1; 21951 try { 21952 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 21953 appId, app.seInfo, app.targetSdkVersion); 21954 } catch (InstallerException e) { 21955 if (app.isSystemApp()) { 21956 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 21957 + ", but trying to recover: " + e); 21958 destroyAppDataLeafLIF(pkg, userId, flags); 21959 try { 21960 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 21961 appId, app.seInfo, app.targetSdkVersion); 21962 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 21963 } catch (InstallerException e2) { 21964 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 21965 } 21966 } else { 21967 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 21968 } 21969 } 21970 21971 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) { 21972 // TODO: mark this structure as dirty so we persist it! 21973 synchronized (mPackages) { 21974 final PackageSetting ps = mSettings.mPackages.get(packageName); 21975 if (ps != null) { 21976 ps.setCeDataInode(ceDataInode, userId); 21977 } 21978 } 21979 } 21980 21981 prepareAppDataContentsLeafLIF(pkg, userId, flags); 21982 } 21983 21984 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 21985 if (pkg == null) { 21986 Slog.wtf(TAG, "Package was null!", new Throwable()); 21987 return; 21988 } 21989 prepareAppDataContentsLeafLIF(pkg, userId, flags); 21990 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 21991 for (int i = 0; i < childCount; i++) { 21992 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 21993 } 21994 } 21995 21996 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 21997 final String volumeUuid = pkg.volumeUuid; 21998 final String packageName = pkg.packageName; 21999 final ApplicationInfo app = pkg.applicationInfo; 22000 22001 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 22002 // Create a native library symlink only if we have native libraries 22003 // and if the native libraries are 32 bit libraries. We do not provide 22004 // this symlink for 64 bit libraries. 22005 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 22006 final String nativeLibPath = app.nativeLibraryDir; 22007 try { 22008 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 22009 nativeLibPath, userId); 22010 } catch (InstallerException e) { 22011 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 22012 } 22013 } 22014 } 22015 } 22016 22017 /** 22018 * For system apps on non-FBE devices, this method migrates any existing 22019 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 22020 * requested by the app. 22021 */ 22022 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 22023 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 22024 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 22025 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 22026 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 22027 try { 22028 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 22029 storageTarget); 22030 } catch (InstallerException e) { 22031 logCriticalInfo(Log.WARN, 22032 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 22033 } 22034 return true; 22035 } else { 22036 return false; 22037 } 22038 } 22039 22040 public PackageFreezer freezePackage(String packageName, String killReason) { 22041 return freezePackage(packageName, UserHandle.USER_ALL, killReason); 22042 } 22043 22044 public PackageFreezer freezePackage(String packageName, int userId, String killReason) { 22045 return new PackageFreezer(packageName, userId, killReason); 22046 } 22047 22048 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 22049 String killReason) { 22050 return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason); 22051 } 22052 22053 public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags, 22054 String killReason) { 22055 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 22056 return new PackageFreezer(); 22057 } else { 22058 return freezePackage(packageName, userId, killReason); 22059 } 22060 } 22061 22062 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 22063 String killReason) { 22064 return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason); 22065 } 22066 22067 public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags, 22068 String killReason) { 22069 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 22070 return new PackageFreezer(); 22071 } else { 22072 return freezePackage(packageName, userId, killReason); 22073 } 22074 } 22075 22076 /** 22077 * Class that freezes and kills the given package upon creation, and 22078 * unfreezes it upon closing. This is typically used when doing surgery on 22079 * app code/data to prevent the app from running while you're working. 22080 */ 22081 private class PackageFreezer implements AutoCloseable { 22082 private final String mPackageName; 22083 private final PackageFreezer[] mChildren; 22084 22085 private final boolean mWeFroze; 22086 22087 private final AtomicBoolean mClosed = new AtomicBoolean(); 22088 private final CloseGuard mCloseGuard = CloseGuard.get(); 22089 22090 /** 22091 * Create and return a stub freezer that doesn't actually do anything, 22092 * typically used when someone requested 22093 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 22094 * {@link PackageManager#DELETE_DONT_KILL_APP}. 22095 */ 22096 public PackageFreezer() { 22097 mPackageName = null; 22098 mChildren = null; 22099 mWeFroze = false; 22100 mCloseGuard.open("close"); 22101 } 22102 22103 public PackageFreezer(String packageName, int userId, String killReason) { 22104 synchronized (mPackages) { 22105 mPackageName = packageName; 22106 mWeFroze = mFrozenPackages.add(mPackageName); 22107 22108 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 22109 if (ps != null) { 22110 killApplication(ps.name, ps.appId, userId, killReason); 22111 } 22112 22113 final PackageParser.Package p = mPackages.get(packageName); 22114 if (p != null && p.childPackages != null) { 22115 final int N = p.childPackages.size(); 22116 mChildren = new PackageFreezer[N]; 22117 for (int i = 0; i < N; i++) { 22118 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 22119 userId, killReason); 22120 } 22121 } else { 22122 mChildren = null; 22123 } 22124 } 22125 mCloseGuard.open("close"); 22126 } 22127 22128 @Override 22129 protected void finalize() throws Throwable { 22130 try { 22131 mCloseGuard.warnIfOpen(); 22132 close(); 22133 } finally { 22134 super.finalize(); 22135 } 22136 } 22137 22138 @Override 22139 public void close() { 22140 mCloseGuard.close(); 22141 if (mClosed.compareAndSet(false, true)) { 22142 synchronized (mPackages) { 22143 if (mWeFroze) { 22144 mFrozenPackages.remove(mPackageName); 22145 } 22146 22147 if (mChildren != null) { 22148 for (PackageFreezer freezer : mChildren) { 22149 freezer.close(); 22150 } 22151 } 22152 } 22153 } 22154 } 22155 } 22156 22157 /** 22158 * Verify that given package is currently frozen. 22159 */ 22160 private void checkPackageFrozen(String packageName) { 22161 synchronized (mPackages) { 22162 if (!mFrozenPackages.contains(packageName)) { 22163 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 22164 } 22165 } 22166 } 22167 22168 @Override 22169 public int movePackage(final String packageName, final String volumeUuid) { 22170 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 22171 22172 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 22173 final int moveId = mNextMoveId.getAndIncrement(); 22174 mHandler.post(new Runnable() { 22175 @Override 22176 public void run() { 22177 try { 22178 movePackageInternal(packageName, volumeUuid, moveId, user); 22179 } catch (PackageManagerException e) { 22180 Slog.w(TAG, "Failed to move " + packageName, e); 22181 mMoveCallbacks.notifyStatusChanged(moveId, 22182 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 22183 } 22184 } 22185 }); 22186 return moveId; 22187 } 22188 22189 private void movePackageInternal(final String packageName, final String volumeUuid, 22190 final int moveId, UserHandle user) throws PackageManagerException { 22191 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22192 final PackageManager pm = mContext.getPackageManager(); 22193 22194 final boolean currentAsec; 22195 final String currentVolumeUuid; 22196 final File codeFile; 22197 final String installerPackageName; 22198 final String packageAbiOverride; 22199 final int appId; 22200 final String seinfo; 22201 final String label; 22202 final int targetSdkVersion; 22203 final PackageFreezer freezer; 22204 final int[] installedUserIds; 22205 22206 // reader 22207 synchronized (mPackages) { 22208 final PackageParser.Package pkg = mPackages.get(packageName); 22209 final PackageSetting ps = mSettings.mPackages.get(packageName); 22210 if (pkg == null || ps == null) { 22211 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 22212 } 22213 22214 if (pkg.applicationInfo.isSystemApp()) { 22215 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 22216 "Cannot move system application"); 22217 } 22218 22219 final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid); 22220 final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean( 22221 com.android.internal.R.bool.config_allow3rdPartyAppOnInternal); 22222 if (isInternalStorage && !allow3rdPartyOnInternal) { 22223 throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL, 22224 "3rd party apps are not allowed on internal storage"); 22225 } 22226 22227 if (pkg.applicationInfo.isExternalAsec()) { 22228 currentAsec = true; 22229 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 22230 } else if (pkg.applicationInfo.isForwardLocked()) { 22231 currentAsec = true; 22232 currentVolumeUuid = "forward_locked"; 22233 } else { 22234 currentAsec = false; 22235 currentVolumeUuid = ps.volumeUuid; 22236 22237 final File probe = new File(pkg.codePath); 22238 final File probeOat = new File(probe, "oat"); 22239 if (!probe.isDirectory() || !probeOat.isDirectory()) { 22240 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22241 "Move only supported for modern cluster style installs"); 22242 } 22243 } 22244 22245 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 22246 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22247 "Package already moved to " + volumeUuid); 22248 } 22249 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 22250 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 22251 "Device admin cannot be moved"); 22252 } 22253 22254 if (mFrozenPackages.contains(packageName)) { 22255 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 22256 "Failed to move already frozen package"); 22257 } 22258 22259 codeFile = new File(pkg.codePath); 22260 installerPackageName = ps.installerPackageName; 22261 packageAbiOverride = ps.cpuAbiOverrideString; 22262 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 22263 seinfo = pkg.applicationInfo.seInfo; 22264 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 22265 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 22266 freezer = freezePackage(packageName, "movePackageInternal"); 22267 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 22268 } 22269 22270 final Bundle extras = new Bundle(); 22271 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 22272 extras.putString(Intent.EXTRA_TITLE, label); 22273 mMoveCallbacks.notifyCreated(moveId, extras); 22274 22275 int installFlags; 22276 final boolean moveCompleteApp; 22277 final File measurePath; 22278 22279 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 22280 installFlags = INSTALL_INTERNAL; 22281 moveCompleteApp = !currentAsec; 22282 measurePath = Environment.getDataAppDirectory(volumeUuid); 22283 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 22284 installFlags = INSTALL_EXTERNAL; 22285 moveCompleteApp = false; 22286 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 22287 } else { 22288 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 22289 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 22290 || !volume.isMountedWritable()) { 22291 freezer.close(); 22292 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22293 "Move location not mounted private volume"); 22294 } 22295 22296 Preconditions.checkState(!currentAsec); 22297 22298 installFlags = INSTALL_INTERNAL; 22299 moveCompleteApp = true; 22300 measurePath = Environment.getDataAppDirectory(volumeUuid); 22301 } 22302 22303 final PackageStats stats = new PackageStats(null, -1); 22304 synchronized (mInstaller) { 22305 for (int userId : installedUserIds) { 22306 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 22307 freezer.close(); 22308 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22309 "Failed to measure package size"); 22310 } 22311 } 22312 } 22313 22314 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 22315 + stats.dataSize); 22316 22317 final long startFreeBytes = measurePath.getFreeSpace(); 22318 final long sizeBytes; 22319 if (moveCompleteApp) { 22320 sizeBytes = stats.codeSize + stats.dataSize; 22321 } else { 22322 sizeBytes = stats.codeSize; 22323 } 22324 22325 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 22326 freezer.close(); 22327 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22328 "Not enough free space to move"); 22329 } 22330 22331 mMoveCallbacks.notifyStatusChanged(moveId, 10); 22332 22333 final CountDownLatch installedLatch = new CountDownLatch(1); 22334 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 22335 @Override 22336 public void onUserActionRequired(Intent intent) throws RemoteException { 22337 throw new IllegalStateException(); 22338 } 22339 22340 @Override 22341 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 22342 Bundle extras) throws RemoteException { 22343 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 22344 + PackageManager.installStatusToString(returnCode, msg)); 22345 22346 installedLatch.countDown(); 22347 freezer.close(); 22348 22349 final int status = PackageManager.installStatusToPublicStatus(returnCode); 22350 switch (status) { 22351 case PackageInstaller.STATUS_SUCCESS: 22352 mMoveCallbacks.notifyStatusChanged(moveId, 22353 PackageManager.MOVE_SUCCEEDED); 22354 break; 22355 case PackageInstaller.STATUS_FAILURE_STORAGE: 22356 mMoveCallbacks.notifyStatusChanged(moveId, 22357 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 22358 break; 22359 default: 22360 mMoveCallbacks.notifyStatusChanged(moveId, 22361 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 22362 break; 22363 } 22364 } 22365 }; 22366 22367 final MoveInfo move; 22368 if (moveCompleteApp) { 22369 // Kick off a thread to report progress estimates 22370 new Thread() { 22371 @Override 22372 public void run() { 22373 while (true) { 22374 try { 22375 if (installedLatch.await(1, TimeUnit.SECONDS)) { 22376 break; 22377 } 22378 } catch (InterruptedException ignored) { 22379 } 22380 22381 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 22382 final int progress = 10 + (int) MathUtils.constrain( 22383 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 22384 mMoveCallbacks.notifyStatusChanged(moveId, progress); 22385 } 22386 } 22387 }.start(); 22388 22389 final String dataAppName = codeFile.getName(); 22390 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 22391 dataAppName, appId, seinfo, targetSdkVersion); 22392 } else { 22393 move = null; 22394 } 22395 22396 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 22397 22398 final Message msg = mHandler.obtainMessage(INIT_COPY); 22399 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 22400 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 22401 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 22402 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/, 22403 PackageManager.INSTALL_REASON_UNKNOWN); 22404 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 22405 msg.obj = params; 22406 22407 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 22408 System.identityHashCode(msg.obj)); 22409 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 22410 System.identityHashCode(msg.obj)); 22411 22412 mHandler.sendMessage(msg); 22413 } 22414 22415 @Override 22416 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 22417 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 22418 22419 final int realMoveId = mNextMoveId.getAndIncrement(); 22420 final Bundle extras = new Bundle(); 22421 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 22422 mMoveCallbacks.notifyCreated(realMoveId, extras); 22423 22424 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 22425 @Override 22426 public void onCreated(int moveId, Bundle extras) { 22427 // Ignored 22428 } 22429 22430 @Override 22431 public void onStatusChanged(int moveId, int status, long estMillis) { 22432 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 22433 } 22434 }; 22435 22436 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22437 storage.setPrimaryStorageUuid(volumeUuid, callback); 22438 return realMoveId; 22439 } 22440 22441 @Override 22442 public int getMoveStatus(int moveId) { 22443 mContext.enforceCallingOrSelfPermission( 22444 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22445 return mMoveCallbacks.mLastStatus.get(moveId); 22446 } 22447 22448 @Override 22449 public void registerMoveCallback(IPackageMoveObserver callback) { 22450 mContext.enforceCallingOrSelfPermission( 22451 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22452 mMoveCallbacks.register(callback); 22453 } 22454 22455 @Override 22456 public void unregisterMoveCallback(IPackageMoveObserver callback) { 22457 mContext.enforceCallingOrSelfPermission( 22458 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22459 mMoveCallbacks.unregister(callback); 22460 } 22461 22462 @Override 22463 public boolean setInstallLocation(int loc) { 22464 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 22465 null); 22466 if (getInstallLocation() == loc) { 22467 return true; 22468 } 22469 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 22470 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 22471 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 22472 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 22473 return true; 22474 } 22475 return false; 22476 } 22477 22478 @Override 22479 public int getInstallLocation() { 22480 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 22481 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 22482 PackageHelper.APP_INSTALL_AUTO); 22483 } 22484 22485 /** Called by UserManagerService */ 22486 void cleanUpUser(UserManagerService userManager, int userHandle) { 22487 synchronized (mPackages) { 22488 mDirtyUsers.remove(userHandle); 22489 mUserNeedsBadging.delete(userHandle); 22490 mSettings.removeUserLPw(userHandle); 22491 mPendingBroadcasts.remove(userHandle); 22492 mInstantAppRegistry.onUserRemovedLPw(userHandle); 22493 removeUnusedPackagesLPw(userManager, userHandle); 22494 } 22495 } 22496 22497 /** 22498 * We're removing userHandle and would like to remove any downloaded packages 22499 * that are no longer in use by any other user. 22500 * @param userHandle the user being removed 22501 */ 22502 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 22503 final boolean DEBUG_CLEAN_APKS = false; 22504 int [] users = userManager.getUserIds(); 22505 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 22506 while (psit.hasNext()) { 22507 PackageSetting ps = psit.next(); 22508 if (ps.pkg == null) { 22509 continue; 22510 } 22511 final String packageName = ps.pkg.packageName; 22512 // Skip over if system app 22513 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 22514 continue; 22515 } 22516 if (DEBUG_CLEAN_APKS) { 22517 Slog.i(TAG, "Checking package " + packageName); 22518 } 22519 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 22520 if (keep) { 22521 if (DEBUG_CLEAN_APKS) { 22522 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 22523 } 22524 } else { 22525 for (int i = 0; i < users.length; i++) { 22526 if (users[i] != userHandle && ps.getInstalled(users[i])) { 22527 keep = true; 22528 if (DEBUG_CLEAN_APKS) { 22529 Slog.i(TAG, " Keeping package " + packageName + " for user " 22530 + users[i]); 22531 } 22532 break; 22533 } 22534 } 22535 } 22536 if (!keep) { 22537 if (DEBUG_CLEAN_APKS) { 22538 Slog.i(TAG, " Removing package " + packageName); 22539 } 22540 mHandler.post(new Runnable() { 22541 public void run() { 22542 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 22543 userHandle, 0); 22544 } //end run 22545 }); 22546 } 22547 } 22548 } 22549 22550 /** Called by UserManagerService */ 22551 void createNewUser(int userId, String[] disallowedPackages) { 22552 synchronized (mInstallLock) { 22553 mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages); 22554 } 22555 synchronized (mPackages) { 22556 scheduleWritePackageRestrictionsLocked(userId); 22557 scheduleWritePackageListLocked(userId); 22558 applyFactoryDefaultBrowserLPw(userId); 22559 primeDomainVerificationsLPw(userId); 22560 } 22561 } 22562 22563 void onNewUserCreated(final int userId) { 22564 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 22565 // If permission review for legacy apps is required, we represent 22566 // dagerous permissions for such apps as always granted runtime 22567 // permissions to keep per user flag state whether review is needed. 22568 // Hence, if a new user is added we have to propagate dangerous 22569 // permission grants for these legacy apps. 22570 if (mPermissionReviewRequired) { 22571 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 22572 | UPDATE_PERMISSIONS_REPLACE_ALL); 22573 } 22574 } 22575 22576 @Override 22577 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 22578 mContext.enforceCallingOrSelfPermission( 22579 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 22580 "Only package verification agents can read the verifier device identity"); 22581 22582 synchronized (mPackages) { 22583 return mSettings.getVerifierDeviceIdentityLPw(); 22584 } 22585 } 22586 22587 @Override 22588 public void setPermissionEnforced(String permission, boolean enforced) { 22589 // TODO: Now that we no longer change GID for storage, this should to away. 22590 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 22591 "setPermissionEnforced"); 22592 if (READ_EXTERNAL_STORAGE.equals(permission)) { 22593 synchronized (mPackages) { 22594 if (mSettings.mReadExternalStorageEnforced == null 22595 || mSettings.mReadExternalStorageEnforced != enforced) { 22596 mSettings.mReadExternalStorageEnforced = enforced; 22597 mSettings.writeLPr(); 22598 } 22599 } 22600 // kill any non-foreground processes so we restart them and 22601 // grant/revoke the GID. 22602 final IActivityManager am = ActivityManager.getService(); 22603 if (am != null) { 22604 final long token = Binder.clearCallingIdentity(); 22605 try { 22606 am.killProcessesBelowForeground("setPermissionEnforcement"); 22607 } catch (RemoteException e) { 22608 } finally { 22609 Binder.restoreCallingIdentity(token); 22610 } 22611 } 22612 } else { 22613 throw new IllegalArgumentException("No selective enforcement for " + permission); 22614 } 22615 } 22616 22617 @Override 22618 @Deprecated 22619 public boolean isPermissionEnforced(String permission) { 22620 return true; 22621 } 22622 22623 @Override 22624 public boolean isStorageLow() { 22625 final long token = Binder.clearCallingIdentity(); 22626 try { 22627 final DeviceStorageMonitorInternal 22628 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 22629 if (dsm != null) { 22630 return dsm.isMemoryLow(); 22631 } else { 22632 return false; 22633 } 22634 } finally { 22635 Binder.restoreCallingIdentity(token); 22636 } 22637 } 22638 22639 @Override 22640 public IPackageInstaller getPackageInstaller() { 22641 return mInstallerService; 22642 } 22643 22644 private boolean userNeedsBadging(int userId) { 22645 int index = mUserNeedsBadging.indexOfKey(userId); 22646 if (index < 0) { 22647 final UserInfo userInfo; 22648 final long token = Binder.clearCallingIdentity(); 22649 try { 22650 userInfo = sUserManager.getUserInfo(userId); 22651 } finally { 22652 Binder.restoreCallingIdentity(token); 22653 } 22654 final boolean b; 22655 if (userInfo != null && userInfo.isManagedProfile()) { 22656 b = true; 22657 } else { 22658 b = false; 22659 } 22660 mUserNeedsBadging.put(userId, b); 22661 return b; 22662 } 22663 return mUserNeedsBadging.valueAt(index); 22664 } 22665 22666 @Override 22667 public KeySet getKeySetByAlias(String packageName, String alias) { 22668 if (packageName == null || alias == null) { 22669 return null; 22670 } 22671 synchronized(mPackages) { 22672 final PackageParser.Package pkg = mPackages.get(packageName); 22673 if (pkg == null) { 22674 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22675 throw new IllegalArgumentException("Unknown package: " + packageName); 22676 } 22677 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22678 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 22679 } 22680 } 22681 22682 @Override 22683 public KeySet getSigningKeySet(String packageName) { 22684 if (packageName == null) { 22685 return null; 22686 } 22687 synchronized(mPackages) { 22688 final PackageParser.Package pkg = mPackages.get(packageName); 22689 if (pkg == null) { 22690 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22691 throw new IllegalArgumentException("Unknown package: " + packageName); 22692 } 22693 if (pkg.applicationInfo.uid != Binder.getCallingUid() 22694 && Process.SYSTEM_UID != Binder.getCallingUid()) { 22695 throw new SecurityException("May not access signing KeySet of other apps."); 22696 } 22697 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22698 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 22699 } 22700 } 22701 22702 @Override 22703 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 22704 if (packageName == null || ks == null) { 22705 return false; 22706 } 22707 synchronized(mPackages) { 22708 final PackageParser.Package pkg = mPackages.get(packageName); 22709 if (pkg == null) { 22710 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22711 throw new IllegalArgumentException("Unknown package: " + packageName); 22712 } 22713 IBinder ksh = ks.getToken(); 22714 if (ksh instanceof KeySetHandle) { 22715 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22716 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 22717 } 22718 return false; 22719 } 22720 } 22721 22722 @Override 22723 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 22724 if (packageName == null || ks == null) { 22725 return false; 22726 } 22727 synchronized(mPackages) { 22728 final PackageParser.Package pkg = mPackages.get(packageName); 22729 if (pkg == null) { 22730 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22731 throw new IllegalArgumentException("Unknown package: " + packageName); 22732 } 22733 IBinder ksh = ks.getToken(); 22734 if (ksh instanceof KeySetHandle) { 22735 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22736 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 22737 } 22738 return false; 22739 } 22740 } 22741 22742 private void deletePackageIfUnusedLPr(final String packageName) { 22743 PackageSetting ps = mSettings.mPackages.get(packageName); 22744 if (ps == null) { 22745 return; 22746 } 22747 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 22748 // TODO Implement atomic delete if package is unused 22749 // It is currently possible that the package will be deleted even if it is installed 22750 // after this method returns. 22751 mHandler.post(new Runnable() { 22752 public void run() { 22753 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 22754 0, PackageManager.DELETE_ALL_USERS); 22755 } 22756 }); 22757 } 22758 } 22759 22760 /** 22761 * Check and throw if the given before/after packages would be considered a 22762 * downgrade. 22763 */ 22764 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 22765 throws PackageManagerException { 22766 if (after.versionCode < before.mVersionCode) { 22767 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 22768 "Update version code " + after.versionCode + " is older than current " 22769 + before.mVersionCode); 22770 } else if (after.versionCode == before.mVersionCode) { 22771 if (after.baseRevisionCode < before.baseRevisionCode) { 22772 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 22773 "Update base revision code " + after.baseRevisionCode 22774 + " is older than current " + before.baseRevisionCode); 22775 } 22776 22777 if (!ArrayUtils.isEmpty(after.splitNames)) { 22778 for (int i = 0; i < after.splitNames.length; i++) { 22779 final String splitName = after.splitNames[i]; 22780 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 22781 if (j != -1) { 22782 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 22783 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 22784 "Update split " + splitName + " revision code " 22785 + after.splitRevisionCodes[i] + " is older than current " 22786 + before.splitRevisionCodes[j]); 22787 } 22788 } 22789 } 22790 } 22791 } 22792 } 22793 22794 private static class MoveCallbacks extends Handler { 22795 private static final int MSG_CREATED = 1; 22796 private static final int MSG_STATUS_CHANGED = 2; 22797 22798 private final RemoteCallbackList<IPackageMoveObserver> 22799 mCallbacks = new RemoteCallbackList<>(); 22800 22801 private final SparseIntArray mLastStatus = new SparseIntArray(); 22802 22803 public MoveCallbacks(Looper looper) { 22804 super(looper); 22805 } 22806 22807 public void register(IPackageMoveObserver callback) { 22808 mCallbacks.register(callback); 22809 } 22810 22811 public void unregister(IPackageMoveObserver callback) { 22812 mCallbacks.unregister(callback); 22813 } 22814 22815 @Override 22816 public void handleMessage(Message msg) { 22817 final SomeArgs args = (SomeArgs) msg.obj; 22818 final int n = mCallbacks.beginBroadcast(); 22819 for (int i = 0; i < n; i++) { 22820 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 22821 try { 22822 invokeCallback(callback, msg.what, args); 22823 } catch (RemoteException ignored) { 22824 } 22825 } 22826 mCallbacks.finishBroadcast(); 22827 args.recycle(); 22828 } 22829 22830 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 22831 throws RemoteException { 22832 switch (what) { 22833 case MSG_CREATED: { 22834 callback.onCreated(args.argi1, (Bundle) args.arg2); 22835 break; 22836 } 22837 case MSG_STATUS_CHANGED: { 22838 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 22839 break; 22840 } 22841 } 22842 } 22843 22844 private void notifyCreated(int moveId, Bundle extras) { 22845 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 22846 22847 final SomeArgs args = SomeArgs.obtain(); 22848 args.argi1 = moveId; 22849 args.arg2 = extras; 22850 obtainMessage(MSG_CREATED, args).sendToTarget(); 22851 } 22852 22853 private void notifyStatusChanged(int moveId, int status) { 22854 notifyStatusChanged(moveId, status, -1); 22855 } 22856 22857 private void notifyStatusChanged(int moveId, int status, long estMillis) { 22858 Slog.v(TAG, "Move " + moveId + " status " + status); 22859 22860 final SomeArgs args = SomeArgs.obtain(); 22861 args.argi1 = moveId; 22862 args.argi2 = status; 22863 args.arg3 = estMillis; 22864 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 22865 22866 synchronized (mLastStatus) { 22867 mLastStatus.put(moveId, status); 22868 } 22869 } 22870 } 22871 22872 private final static class OnPermissionChangeListeners extends Handler { 22873 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 22874 22875 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 22876 new RemoteCallbackList<>(); 22877 22878 public OnPermissionChangeListeners(Looper looper) { 22879 super(looper); 22880 } 22881 22882 @Override 22883 public void handleMessage(Message msg) { 22884 switch (msg.what) { 22885 case MSG_ON_PERMISSIONS_CHANGED: { 22886 final int uid = msg.arg1; 22887 handleOnPermissionsChanged(uid); 22888 } break; 22889 } 22890 } 22891 22892 public void addListenerLocked(IOnPermissionsChangeListener listener) { 22893 mPermissionListeners.register(listener); 22894 22895 } 22896 22897 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 22898 mPermissionListeners.unregister(listener); 22899 } 22900 22901 public void onPermissionsChanged(int uid) { 22902 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 22903 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 22904 } 22905 } 22906 22907 private void handleOnPermissionsChanged(int uid) { 22908 final int count = mPermissionListeners.beginBroadcast(); 22909 try { 22910 for (int i = 0; i < count; i++) { 22911 IOnPermissionsChangeListener callback = mPermissionListeners 22912 .getBroadcastItem(i); 22913 try { 22914 callback.onPermissionsChanged(uid); 22915 } catch (RemoteException e) { 22916 Log.e(TAG, "Permission listener is dead", e); 22917 } 22918 } 22919 } finally { 22920 mPermissionListeners.finishBroadcast(); 22921 } 22922 } 22923 } 22924 22925 private class PackageManagerInternalImpl extends PackageManagerInternal { 22926 @Override 22927 public void setLocationPackagesProvider(PackagesProvider provider) { 22928 synchronized (mPackages) { 22929 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 22930 } 22931 } 22932 22933 @Override 22934 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 22935 synchronized (mPackages) { 22936 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 22937 } 22938 } 22939 22940 @Override 22941 public void setSmsAppPackagesProvider(PackagesProvider provider) { 22942 synchronized (mPackages) { 22943 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 22944 } 22945 } 22946 22947 @Override 22948 public void setDialerAppPackagesProvider(PackagesProvider provider) { 22949 synchronized (mPackages) { 22950 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 22951 } 22952 } 22953 22954 @Override 22955 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 22956 synchronized (mPackages) { 22957 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 22958 } 22959 } 22960 22961 @Override 22962 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 22963 synchronized (mPackages) { 22964 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 22965 } 22966 } 22967 22968 @Override 22969 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 22970 synchronized (mPackages) { 22971 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 22972 packageName, userId); 22973 } 22974 } 22975 22976 @Override 22977 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 22978 synchronized (mPackages) { 22979 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 22980 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 22981 packageName, userId); 22982 } 22983 } 22984 22985 @Override 22986 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 22987 synchronized (mPackages) { 22988 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 22989 packageName, userId); 22990 } 22991 } 22992 22993 @Override 22994 public void setKeepUninstalledPackages(final List<String> packageList) { 22995 Preconditions.checkNotNull(packageList); 22996 List<String> removedFromList = null; 22997 synchronized (mPackages) { 22998 if (mKeepUninstalledPackages != null) { 22999 final int packagesCount = mKeepUninstalledPackages.size(); 23000 for (int i = 0; i < packagesCount; i++) { 23001 String oldPackage = mKeepUninstalledPackages.get(i); 23002 if (packageList != null && packageList.contains(oldPackage)) { 23003 continue; 23004 } 23005 if (removedFromList == null) { 23006 removedFromList = new ArrayList<>(); 23007 } 23008 removedFromList.add(oldPackage); 23009 } 23010 } 23011 mKeepUninstalledPackages = new ArrayList<>(packageList); 23012 if (removedFromList != null) { 23013 final int removedCount = removedFromList.size(); 23014 for (int i = 0; i < removedCount; i++) { 23015 deletePackageIfUnusedLPr(removedFromList.get(i)); 23016 } 23017 } 23018 } 23019 } 23020 23021 @Override 23022 public boolean isPermissionsReviewRequired(String packageName, int userId) { 23023 synchronized (mPackages) { 23024 // If we do not support permission review, done. 23025 if (!mPermissionReviewRequired) { 23026 return false; 23027 } 23028 23029 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 23030 if (packageSetting == null) { 23031 return false; 23032 } 23033 23034 // Permission review applies only to apps not supporting the new permission model. 23035 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 23036 return false; 23037 } 23038 23039 // Legacy apps have the permission and get user consent on launch. 23040 PermissionsState permissionsState = packageSetting.getPermissionsState(); 23041 return permissionsState.isPermissionReviewRequired(userId); 23042 } 23043 } 23044 23045 @Override 23046 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 23047 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 23048 } 23049 23050 @Override 23051 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 23052 int userId) { 23053 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 23054 } 23055 23056 @Override 23057 public void setDeviceAndProfileOwnerPackages( 23058 int deviceOwnerUserId, String deviceOwnerPackage, 23059 SparseArray<String> profileOwnerPackages) { 23060 mProtectedPackages.setDeviceAndProfileOwnerPackages( 23061 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages); 23062 } 23063 23064 @Override 23065 public boolean isPackageDataProtected(int userId, String packageName) { 23066 return mProtectedPackages.isPackageDataProtected(userId, packageName); 23067 } 23068 23069 @Override 23070 public boolean isPackageEphemeral(int userId, String packageName) { 23071 synchronized (mPackages) { 23072 final PackageSetting ps = mSettings.mPackages.get(packageName); 23073 return ps != null ? ps.getInstantApp(userId) : false; 23074 } 23075 } 23076 23077 @Override 23078 public boolean wasPackageEverLaunched(String packageName, int userId) { 23079 synchronized (mPackages) { 23080 return mSettings.wasPackageEverLaunchedLPr(packageName, userId); 23081 } 23082 } 23083 23084 @Override 23085 public void grantRuntimePermission(String packageName, String name, int userId, 23086 boolean overridePolicy) { 23087 PackageManagerService.this.grantRuntimePermission(packageName, name, userId, 23088 overridePolicy); 23089 } 23090 23091 @Override 23092 public void revokeRuntimePermission(String packageName, String name, int userId, 23093 boolean overridePolicy) { 23094 PackageManagerService.this.revokeRuntimePermission(packageName, name, userId, 23095 overridePolicy); 23096 } 23097 23098 @Override 23099 public String getNameForUid(int uid) { 23100 return PackageManagerService.this.getNameForUid(uid); 23101 } 23102 23103 @Override 23104 public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj, 23105 Intent origIntent, String resolvedType, String callingPackage, int userId) { 23106 PackageManagerService.this.requestInstantAppResolutionPhaseTwo( 23107 responseObj, origIntent, resolvedType, callingPackage, userId); 23108 } 23109 23110 @Override 23111 public void grantEphemeralAccess(int userId, Intent intent, 23112 int targetAppId, int ephemeralAppId) { 23113 synchronized (mPackages) { 23114 mInstantAppRegistry.grantInstantAccessLPw(userId, intent, 23115 targetAppId, ephemeralAppId); 23116 } 23117 } 23118 23119 @Override 23120 public void pruneInstantApps() { 23121 synchronized (mPackages) { 23122 mInstantAppRegistry.pruneInstantAppsLPw(); 23123 } 23124 } 23125 23126 @Override 23127 public String getSetupWizardPackageName() { 23128 return mSetupWizardPackage; 23129 } 23130 23131 public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) { 23132 if (policy != null) { 23133 mExternalSourcesPolicy = policy; 23134 } 23135 } 23136 23137 @Override 23138 public boolean isPackagePersistent(String packageName) { 23139 synchronized (mPackages) { 23140 PackageParser.Package pkg = mPackages.get(packageName); 23141 return pkg != null 23142 ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM 23143 | ApplicationInfo.FLAG_PERSISTENT)) == 23144 (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT)) 23145 : false; 23146 } 23147 } 23148 23149 @Override 23150 public List<PackageInfo> getOverlayPackages(int userId) { 23151 final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>(); 23152 synchronized (mPackages) { 23153 for (PackageParser.Package p : mPackages.values()) { 23154 if (p.mOverlayTarget != null) { 23155 PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId); 23156 if (pkg != null) { 23157 overlayPackages.add(pkg); 23158 } 23159 } 23160 } 23161 } 23162 return overlayPackages; 23163 } 23164 23165 @Override 23166 public List<String> getTargetPackageNames(int userId) { 23167 List<String> targetPackages = new ArrayList<>(); 23168 synchronized (mPackages) { 23169 for (PackageParser.Package p : mPackages.values()) { 23170 if (p.mOverlayTarget == null) { 23171 targetPackages.add(p.packageName); 23172 } 23173 } 23174 } 23175 return targetPackages; 23176 } 23177 23178 @Override 23179 public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName, 23180 @Nullable List<String> overlayPackageNames) { 23181 synchronized (mPackages) { 23182 if (targetPackageName == null || mPackages.get(targetPackageName) == null) { 23183 Slog.e(TAG, "failed to find package " + targetPackageName); 23184 return false; 23185 } 23186 23187 ArrayList<String> paths = null; 23188 if (overlayPackageNames != null) { 23189 final int N = overlayPackageNames.size(); 23190 paths = new ArrayList<String>(N); 23191 for (int i = 0; i < N; i++) { 23192 final String packageName = overlayPackageNames.get(i); 23193 final PackageParser.Package pkg = mPackages.get(packageName); 23194 if (pkg == null) { 23195 Slog.e(TAG, "failed to find package " + packageName); 23196 return false; 23197 } 23198 paths.add(pkg.baseCodePath); 23199 } 23200 } 23201 23202 ArrayMap<String, ArrayList<String>> userSpecificOverlays = 23203 mEnabledOverlayPaths.get(userId); 23204 if (userSpecificOverlays == null) { 23205 userSpecificOverlays = new ArrayMap<String, ArrayList<String>>(); 23206 mEnabledOverlayPaths.put(userId, userSpecificOverlays); 23207 } 23208 23209 if (paths != null && paths.size() > 0) { 23210 userSpecificOverlays.put(targetPackageName, paths); 23211 } else { 23212 userSpecificOverlays.remove(targetPackageName); 23213 } 23214 return true; 23215 } 23216 } 23217 23218 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 23219 int flags, int userId) { 23220 return resolveIntentInternal( 23221 intent, resolvedType, flags, userId, true /*includeInstantApp*/); 23222 } 23223 } 23224 23225 @Override 23226 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 23227 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 23228 synchronized (mPackages) { 23229 final long identity = Binder.clearCallingIdentity(); 23230 try { 23231 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 23232 packageNames, userId); 23233 } finally { 23234 Binder.restoreCallingIdentity(identity); 23235 } 23236 } 23237 } 23238 23239 @Override 23240 public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) { 23241 enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices"); 23242 synchronized (mPackages) { 23243 final long identity = Binder.clearCallingIdentity(); 23244 try { 23245 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr( 23246 packageNames, userId); 23247 } finally { 23248 Binder.restoreCallingIdentity(identity); 23249 } 23250 } 23251 } 23252 23253 private static void enforceSystemOrPhoneCaller(String tag) { 23254 int callingUid = Binder.getCallingUid(); 23255 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 23256 throw new SecurityException( 23257 "Cannot call " + tag + " from UID " + callingUid); 23258 } 23259 } 23260 23261 boolean isHistoricalPackageUsageAvailable() { 23262 return mPackageUsage.isHistoricalPackageUsageAvailable(); 23263 } 23264 23265 /** 23266 * Return a <b>copy</b> of the collection of packages known to the package manager. 23267 * @return A copy of the values of mPackages. 23268 */ 23269 Collection<PackageParser.Package> getPackages() { 23270 synchronized (mPackages) { 23271 return new ArrayList<>(mPackages.values()); 23272 } 23273 } 23274 23275 /** 23276 * Logs process start information (including base APK hash) to the security log. 23277 * @hide 23278 */ 23279 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 23280 String apkFile, int pid) { 23281 if (!SecurityLog.isLoggingEnabled()) { 23282 return; 23283 } 23284 Bundle data = new Bundle(); 23285 data.putLong("startTimestamp", System.currentTimeMillis()); 23286 data.putString("processName", processName); 23287 data.putInt("uid", uid); 23288 data.putString("seinfo", seinfo); 23289 data.putString("apkFile", apkFile); 23290 data.putInt("pid", pid); 23291 Message msg = mProcessLoggingHandler.obtainMessage( 23292 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 23293 msg.setData(data); 23294 mProcessLoggingHandler.sendMessage(msg); 23295 } 23296 23297 public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) { 23298 return mCompilerStats.getPackageStats(pkgName); 23299 } 23300 23301 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) { 23302 return getOrCreateCompilerPackageStats(pkg.packageName); 23303 } 23304 23305 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) { 23306 return mCompilerStats.getOrCreatePackageStats(pkgName); 23307 } 23308 23309 public void deleteCompilerPackageStats(String pkgName) { 23310 mCompilerStats.deletePackageStats(pkgName); 23311 } 23312 23313 @Override 23314 public int getInstallReason(String packageName, int userId) { 23315 enforceCrossUserPermission(Binder.getCallingUid(), userId, 23316 true /* requireFullPermission */, false /* checkShell */, 23317 "get install reason"); 23318 synchronized (mPackages) { 23319 final PackageSetting ps = mSettings.mPackages.get(packageName); 23320 if (ps != null) { 23321 return ps.getInstallReason(userId); 23322 } 23323 } 23324 return PackageManager.INSTALL_REASON_UNKNOWN; 23325 } 23326 23327 @Override 23328 public boolean canRequestPackageInstalls(String packageName, int userId) { 23329 int callingUid = Binder.getCallingUid(); 23330 int uid = getPackageUid(packageName, 0, userId); 23331 if (callingUid != uid && callingUid != Process.ROOT_UID 23332 && callingUid != Process.SYSTEM_UID) { 23333 throw new SecurityException( 23334 "Caller uid " + callingUid + " does not own package " + packageName); 23335 } 23336 ApplicationInfo info = getApplicationInfo(packageName, 0, userId); 23337 if (info == null) { 23338 return false; 23339 } 23340 if (info.targetSdkVersion < Build.VERSION_CODES.O) { 23341 throw new UnsupportedOperationException( 23342 "Operation only supported on apps targeting Android O or higher"); 23343 } 23344 String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES; 23345 String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission); 23346 if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) { 23347 throw new SecurityException("Need to declare " + appOpPermission + " to call this api"); 23348 } 23349 if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) { 23350 return false; 23351 } 23352 if (mExternalSourcesPolicy != null) { 23353 int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid); 23354 if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) { 23355 return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED; 23356 } 23357 } 23358 return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED; 23359 } 23360} 23361