PackageManagerService.java revision cd824ef3895bd581c9d87d9b010385fd15b41d7e
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.InstantAppInfo; 132import android.content.pm.EphemeralRequest; 133import android.content.pm.EphemeralResolveInfo; 134import android.content.pm.EphemeralResponse; 135import android.content.pm.FallbackCategoryProvider; 136import android.content.pm.FeatureInfo; 137import android.content.pm.IOnPermissionsChangeListener; 138import android.content.pm.IPackageDataObserver; 139import android.content.pm.IPackageDeleteObserver; 140import android.content.pm.IPackageDeleteObserver2; 141import android.content.pm.IPackageInstallObserver2; 142import android.content.pm.IPackageInstaller; 143import android.content.pm.IPackageManager; 144import android.content.pm.IPackageMoveObserver; 145import android.content.pm.IPackageStatsObserver; 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.StorageManagerInternal; 208import android.os.storage.StorageEventListener; 209import android.os.storage.StorageManager; 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.system.ErrnoException; 217import android.system.Os; 218import android.text.TextUtils; 219import android.text.format.DateUtils; 220import android.util.ArrayMap; 221import android.util.ArraySet; 222import android.util.Base64; 223import android.util.DisplayMetrics; 224import android.util.EventLog; 225import android.util.ExceptionUtils; 226import android.util.Log; 227import android.util.LogPrinter; 228import android.util.MathUtils; 229import android.util.PackageUtils; 230import android.util.Pair; 231import android.util.PrintStreamPrinter; 232import android.util.Slog; 233import android.util.SparseArray; 234import android.util.SparseBooleanArray; 235import android.util.SparseIntArray; 236import android.util.Xml; 237import android.util.jar.StrictJarFile; 238import android.view.Display; 239 240import com.android.internal.R; 241import com.android.internal.annotations.GuardedBy; 242import com.android.internal.app.IMediaContainerService; 243import com.android.internal.app.ResolverActivity; 244import com.android.internal.content.NativeLibraryHelper; 245import com.android.internal.content.PackageHelper; 246import com.android.internal.logging.MetricsLogger; 247import com.android.internal.logging.nano.MetricsProto.MetricsEvent; 248import com.android.internal.os.IParcelFileDescriptorFactory; 249import com.android.internal.os.RoSystemProperties; 250import com.android.internal.os.SomeArgs; 251import com.android.internal.os.Zygote; 252import com.android.internal.telephony.CarrierAppUtils; 253import com.android.internal.util.ArrayUtils; 254import com.android.internal.util.ConcurrentUtils; 255import com.android.internal.util.FastPrintWriter; 256import com.android.internal.util.FastXmlSerializer; 257import com.android.internal.util.IndentingPrintWriter; 258import com.android.internal.util.Preconditions; 259import com.android.internal.util.XmlUtils; 260import com.android.server.AttributeCache; 261import com.android.server.BackgroundDexOptJobService; 262import com.android.server.DeviceIdleController; 263import com.android.server.EventLogTags; 264import com.android.server.FgThread; 265import com.android.server.IntentResolver; 266import com.android.server.LocalServices; 267import com.android.server.ServiceThread; 268import com.android.server.SystemConfig; 269import com.android.server.SystemServerInitThreadPool; 270import com.android.server.Watchdog; 271import com.android.server.net.NetworkPolicyManagerInternal; 272import com.android.server.pm.Installer.InstallerException; 273import com.android.server.pm.PermissionsState.PermissionState; 274import com.android.server.pm.Settings.DatabaseVersion; 275import com.android.server.pm.Settings.VersionInfo; 276import com.android.server.pm.dex.DexManager; 277import com.android.server.storage.DeviceStorageMonitorInternal; 278 279import dalvik.system.CloseGuard; 280import dalvik.system.DexFile; 281import dalvik.system.VMRuntime; 282 283import libcore.io.IoUtils; 284import libcore.util.EmptyArray; 285 286import org.xmlpull.v1.XmlPullParser; 287import org.xmlpull.v1.XmlPullParserException; 288import org.xmlpull.v1.XmlSerializer; 289 290import java.io.BufferedOutputStream; 291import java.io.BufferedReader; 292import java.io.ByteArrayInputStream; 293import java.io.ByteArrayOutputStream; 294import java.io.File; 295import java.io.FileDescriptor; 296import java.io.FileInputStream; 297import java.io.FileNotFoundException; 298import java.io.FileOutputStream; 299import java.io.FileReader; 300import java.io.FilenameFilter; 301import java.io.IOException; 302import java.io.PrintWriter; 303import java.nio.charset.StandardCharsets; 304import java.security.DigestInputStream; 305import java.security.MessageDigest; 306import java.security.NoSuchAlgorithmException; 307import java.security.PublicKey; 308import java.security.SecureRandom; 309import java.security.cert.Certificate; 310import java.security.cert.CertificateEncodingException; 311import java.security.cert.CertificateException; 312import java.text.SimpleDateFormat; 313import java.util.ArrayList; 314import java.util.Arrays; 315import java.util.Collection; 316import java.util.Collections; 317import java.util.Comparator; 318import java.util.Date; 319import java.util.HashSet; 320import java.util.HashMap; 321import java.util.Iterator; 322import java.util.List; 323import java.util.Map; 324import java.util.Objects; 325import java.util.Set; 326import java.util.concurrent.CountDownLatch; 327import java.util.concurrent.Future; 328import java.util.concurrent.TimeUnit; 329import java.util.concurrent.atomic.AtomicBoolean; 330import java.util.concurrent.atomic.AtomicInteger; 331 332/** 333 * Keep track of all those APKs everywhere. 334 * <p> 335 * Internally there are two important locks: 336 * <ul> 337 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 338 * and other related state. It is a fine-grained lock that should only be held 339 * momentarily, as it's one of the most contended locks in the system. 340 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 341 * operations typically involve heavy lifting of application data on disk. Since 342 * {@code installd} is single-threaded, and it's operations can often be slow, 343 * this lock should never be acquired while already holding {@link #mPackages}. 344 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 345 * holding {@link #mInstallLock}. 346 * </ul> 347 * Many internal methods rely on the caller to hold the appropriate locks, and 348 * this contract is expressed through method name suffixes: 349 * <ul> 350 * <li>fooLI(): the caller must hold {@link #mInstallLock} 351 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 352 * being modified must be frozen 353 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 354 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 355 * </ul> 356 * <p> 357 * Because this class is very central to the platform's security; please run all 358 * CTS and unit tests whenever making modifications: 359 * 360 * <pre> 361 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 362 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases 363 * </pre> 364 */ 365public class PackageManagerService extends IPackageManager.Stub { 366 static final String TAG = "PackageManager"; 367 static final boolean DEBUG_SETTINGS = false; 368 static final boolean DEBUG_PREFERRED = false; 369 static final boolean DEBUG_UPGRADE = false; 370 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 371 private static final boolean DEBUG_BACKUP = false; 372 private static final boolean DEBUG_INSTALL = false; 373 private static final boolean DEBUG_REMOVE = false; 374 private static final boolean DEBUG_BROADCASTS = false; 375 private static final boolean DEBUG_SHOW_INFO = false; 376 private static final boolean DEBUG_PACKAGE_INFO = false; 377 private static final boolean DEBUG_INTENT_MATCHING = false; 378 private static final boolean DEBUG_PACKAGE_SCANNING = false; 379 private static final boolean DEBUG_VERIFY = false; 380 private static final boolean DEBUG_FILTERS = false; 381 382 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 383 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 384 // user, but by default initialize to this. 385 public static final boolean DEBUG_DEXOPT = false; 386 387 private static final boolean DEBUG_ABI_SELECTION = false; 388 private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE; 389 private static final boolean DEBUG_TRIAGED_MISSING = false; 390 private static final boolean DEBUG_APP_DATA = false; 391 392 /** REMOVE. According to Svet, this was only used to reset permissions during development. */ 393 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 394 395 private static final boolean DISABLE_EPHEMERAL_APPS = false; 396 private static final boolean HIDE_EPHEMERAL_APIS = false; 397 398 private static final boolean ENABLE_QUOTA = 399 SystemProperties.getBoolean("persist.fw.quota", false); 400 401 private static final int RADIO_UID = Process.PHONE_UID; 402 private static final int LOG_UID = Process.LOG_UID; 403 private static final int NFC_UID = Process.NFC_UID; 404 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 405 private static final int SHELL_UID = Process.SHELL_UID; 406 407 // Cap the size of permission trees that 3rd party apps can define 408 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 409 410 // Suffix used during package installation when copying/moving 411 // package apks to install directory. 412 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 413 414 static final int SCAN_NO_DEX = 1<<1; 415 static final int SCAN_FORCE_DEX = 1<<2; 416 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 417 static final int SCAN_NEW_INSTALL = 1<<4; 418 static final int SCAN_UPDATE_TIME = 1<<5; 419 static final int SCAN_BOOTING = 1<<6; 420 static final int SCAN_TRUSTED_OVERLAY = 1<<7; 421 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8; 422 static final int SCAN_REPLACING = 1<<9; 423 static final int SCAN_REQUIRE_KNOWN = 1<<10; 424 static final int SCAN_MOVE = 1<<11; 425 static final int SCAN_INITIAL = 1<<12; 426 static final int SCAN_CHECK_ONLY = 1<<13; 427 static final int SCAN_DONT_KILL_APP = 1<<14; 428 static final int SCAN_IGNORE_FROZEN = 1<<15; 429 static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16; 430 static final int SCAN_AS_INSTANT_APP = 1<<17; 431 static final int SCAN_AS_FULL_APP = 1<<18; 432 /** Should not be with the scan flags */ 433 static final int FLAGS_REMOVE_CHATTY = 1<<31; 434 435 private static final String STATIC_SHARED_LIB_DELIMITER = "_"; 436 437 private static final int[] EMPTY_INT_ARRAY = new int[0]; 438 439 /** 440 * Timeout (in milliseconds) after which the watchdog should declare that 441 * our handler thread is wedged. The usual default for such things is one 442 * minute but we sometimes do very lengthy I/O operations on this thread, 443 * such as installing multi-gigabyte applications, so ours needs to be longer. 444 */ 445 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 446 447 /** 448 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 449 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 450 * settings entry if available, otherwise we use the hardcoded default. If it's been 451 * more than this long since the last fstrim, we force one during the boot sequence. 452 * 453 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 454 * one gets run at the next available charging+idle time. This final mandatory 455 * no-fstrim check kicks in only of the other scheduling criteria is never met. 456 */ 457 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 458 459 /** 460 * Whether verification is enabled by default. 461 */ 462 private static final boolean DEFAULT_VERIFY_ENABLE = true; 463 464 /** 465 * The default maximum time to wait for the verification agent to return in 466 * milliseconds. 467 */ 468 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 469 470 /** 471 * The default response for package verification timeout. 472 * 473 * This can be either PackageManager.VERIFICATION_ALLOW or 474 * PackageManager.VERIFICATION_REJECT. 475 */ 476 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 477 478 static final String PLATFORM_PACKAGE_NAME = "android"; 479 480 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 481 482 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 483 DEFAULT_CONTAINER_PACKAGE, 484 "com.android.defcontainer.DefaultContainerService"); 485 486 private static final String KILL_APP_REASON_GIDS_CHANGED = 487 "permission grant or revoke changed gids"; 488 489 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 490 "permissions revoked"; 491 492 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 493 494 private static final String PACKAGE_SCHEME = "package"; 495 496 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 497 /** 498 * If VENDOR_OVERLAY_THEME_PROPERTY is set, search for runtime resource overlay APKs also in 499 * VENDOR_OVERLAY_DIR/<value of VENDOR_OVERLAY_THEME_PROPERTY> in addition to 500 * VENDOR_OVERLAY_DIR. 501 */ 502 private static final String VENDOR_OVERLAY_THEME_PROPERTY = "ro.boot.vendor.overlay.theme"; 503 /** 504 * Same as VENDOR_OVERLAY_THEME_PROPERTY, except persistent. If set will override whatever 505 * is in VENDOR_OVERLAY_THEME_PROPERTY. 506 */ 507 private static final String VENDOR_OVERLAY_THEME_PERSIST_PROPERTY 508 = "persist.vendor.overlay.theme"; 509 510 /** Permission grant: not grant the permission. */ 511 private static final int GRANT_DENIED = 1; 512 513 /** Permission grant: grant the permission as an install permission. */ 514 private static final int GRANT_INSTALL = 2; 515 516 /** Permission grant: grant the permission as a runtime one. */ 517 private static final int GRANT_RUNTIME = 3; 518 519 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 520 private static final int GRANT_UPGRADE = 4; 521 522 /** Canonical intent used to identify what counts as a "web browser" app */ 523 private static final Intent sBrowserIntent; 524 static { 525 sBrowserIntent = new Intent(); 526 sBrowserIntent.setAction(Intent.ACTION_VIEW); 527 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 528 sBrowserIntent.setData(Uri.parse("http:")); 529 } 530 531 /** 532 * The set of all protected actions [i.e. those actions for which a high priority 533 * intent filter is disallowed]. 534 */ 535 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 536 static { 537 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 538 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 539 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 540 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 541 } 542 543 // Compilation reasons. 544 public static final int REASON_FIRST_BOOT = 0; 545 public static final int REASON_BOOT = 1; 546 public static final int REASON_INSTALL = 2; 547 public static final int REASON_BACKGROUND_DEXOPT = 3; 548 public static final int REASON_AB_OTA = 4; 549 public static final int REASON_NON_SYSTEM_LIBRARY = 5; 550 public static final int REASON_SHARED_APK = 6; 551 public static final int REASON_FORCED_DEXOPT = 7; 552 public static final int REASON_CORE_APP = 8; 553 554 public static final int REASON_LAST = REASON_CORE_APP; 555 556 /** All dangerous permission names in the same order as the events in MetricsEvent */ 557 private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList( 558 Manifest.permission.READ_CALENDAR, 559 Manifest.permission.WRITE_CALENDAR, 560 Manifest.permission.CAMERA, 561 Manifest.permission.READ_CONTACTS, 562 Manifest.permission.WRITE_CONTACTS, 563 Manifest.permission.GET_ACCOUNTS, 564 Manifest.permission.ACCESS_FINE_LOCATION, 565 Manifest.permission.ACCESS_COARSE_LOCATION, 566 Manifest.permission.RECORD_AUDIO, 567 Manifest.permission.READ_PHONE_STATE, 568 Manifest.permission.CALL_PHONE, 569 Manifest.permission.READ_CALL_LOG, 570 Manifest.permission.WRITE_CALL_LOG, 571 Manifest.permission.ADD_VOICEMAIL, 572 Manifest.permission.USE_SIP, 573 Manifest.permission.PROCESS_OUTGOING_CALLS, 574 Manifest.permission.READ_CELL_BROADCASTS, 575 Manifest.permission.BODY_SENSORS, 576 Manifest.permission.SEND_SMS, 577 Manifest.permission.RECEIVE_SMS, 578 Manifest.permission.READ_SMS, 579 Manifest.permission.RECEIVE_WAP_PUSH, 580 Manifest.permission.RECEIVE_MMS, 581 Manifest.permission.READ_EXTERNAL_STORAGE, 582 Manifest.permission.WRITE_EXTERNAL_STORAGE, 583 Manifest.permission.READ_PHONE_NUMBER); 584 585 586 /** 587 * Version number for the package parser cache. Increment this whenever the format or 588 * extent of cached data changes. See {@code PackageParser#setCacheDir}. 589 */ 590 private static final String PACKAGE_PARSER_CACHE_VERSION = "1"; 591 592 /** 593 * Whether the package parser cache is enabled. 594 */ 595 private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true; 596 597 final ServiceThread mHandlerThread; 598 599 final PackageHandler mHandler; 600 601 private final ProcessLoggingHandler mProcessLoggingHandler; 602 603 /** 604 * Messages for {@link #mHandler} that need to wait for system ready before 605 * being dispatched. 606 */ 607 private ArrayList<Message> mPostSystemReadyMessages; 608 609 final int mSdkVersion = Build.VERSION.SDK_INT; 610 611 final Context mContext; 612 final boolean mFactoryTest; 613 final boolean mOnlyCore; 614 final DisplayMetrics mMetrics; 615 final int mDefParseFlags; 616 final String[] mSeparateProcesses; 617 final boolean mIsUpgrade; 618 final boolean mIsPreNUpgrade; 619 final boolean mIsPreNMR1Upgrade; 620 621 @GuardedBy("mPackages") 622 private boolean mDexOptDialogShown; 623 624 /** The location for ASEC container files on internal storage. */ 625 final String mAsecInternalPath; 626 627 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 628 // LOCK HELD. Can be called with mInstallLock held. 629 @GuardedBy("mInstallLock") 630 final Installer mInstaller; 631 632 /** Directory where installed third-party apps stored */ 633 final File mAppInstallDir; 634 635 /** 636 * Directory to which applications installed internally have their 637 * 32 bit native libraries copied. 638 */ 639 private File mAppLib32InstallDir; 640 641 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 642 // apps. 643 final File mDrmAppPrivateInstallDir; 644 645 // ---------------------------------------------------------------- 646 647 // Lock for state used when installing and doing other long running 648 // operations. Methods that must be called with this lock held have 649 // the suffix "LI". 650 final Object mInstallLock = new Object(); 651 652 // ---------------------------------------------------------------- 653 654 // Keys are String (package name), values are Package. This also serves 655 // as the lock for the global state. Methods that must be called with 656 // this lock held have the prefix "LP". 657 @GuardedBy("mPackages") 658 final ArrayMap<String, PackageParser.Package> mPackages = 659 new ArrayMap<String, PackageParser.Package>(); 660 661 final ArrayMap<String, Set<String>> mKnownCodebase = 662 new ArrayMap<String, Set<String>>(); 663 664 // Tracks available target package names -> overlay package paths. 665 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 666 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 667 668 /** 669 * Tracks new system packages [received in an OTA] that we expect to 670 * find updated user-installed versions. Keys are package name, values 671 * are package location. 672 */ 673 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 674 /** 675 * Tracks high priority intent filters for protected actions. During boot, certain 676 * filter actions are protected and should never be allowed to have a high priority 677 * intent filter for them. However, there is one, and only one exception -- the 678 * setup wizard. It must be able to define a high priority intent filter for these 679 * actions to ensure there are no escapes from the wizard. We need to delay processing 680 * of these during boot as we need to look at all of the system packages in order 681 * to know which component is the setup wizard. 682 */ 683 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 684 /** 685 * Whether or not processing protected filters should be deferred. 686 */ 687 private boolean mDeferProtectedFilters = true; 688 689 /** 690 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 691 */ 692 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 693 /** 694 * Whether or not system app permissions should be promoted from install to runtime. 695 */ 696 boolean mPromoteSystemApps; 697 698 @GuardedBy("mPackages") 699 final Settings mSettings; 700 701 /** 702 * Set of package names that are currently "frozen", which means active 703 * surgery is being done on the code/data for that package. The platform 704 * will refuse to launch frozen packages to avoid race conditions. 705 * 706 * @see PackageFreezer 707 */ 708 @GuardedBy("mPackages") 709 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 710 711 final ProtectedPackages mProtectedPackages; 712 713 boolean mFirstBoot; 714 715 PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy; 716 717 // System configuration read by SystemConfig. 718 final int[] mGlobalGids; 719 final SparseArray<ArraySet<String>> mSystemPermissions; 720 @GuardedBy("mAvailableFeatures") 721 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 722 723 // If mac_permissions.xml was found for seinfo labeling. 724 boolean mFoundPolicyFile; 725 726 private final InstantAppRegistry mInstantAppRegistry; 727 728 @GuardedBy("mPackages") 729 int mChangedPackagesSequenceNumber; 730 /** 731 * List of changed [installed, removed or updated] packages. 732 * mapping from user id -> sequence number -> package name 733 */ 734 @GuardedBy("mPackages") 735 final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>(); 736 /** 737 * The sequence number of the last change to a package. 738 * mapping from user id -> package name -> sequence number 739 */ 740 @GuardedBy("mPackages") 741 final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>(); 742 743 public static final class SharedLibraryEntry { 744 public final String path; 745 public final String apk; 746 public final SharedLibraryInfo info; 747 748 SharedLibraryEntry(String _path, String _apk, String name, int version, int type, 749 String declaringPackageName, int declaringPackageVersionCode) { 750 path = _path; 751 apk = _apk; 752 info = new SharedLibraryInfo(name, version, type, new VersionedPackage( 753 declaringPackageName, declaringPackageVersionCode), null); 754 } 755 } 756 757 // Currently known shared libraries. 758 final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>(); 759 final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage = 760 new ArrayMap<>(); 761 762 // All available activities, for your resolving pleasure. 763 final ActivityIntentResolver mActivities = 764 new ActivityIntentResolver(); 765 766 // All available receivers, for your resolving pleasure. 767 final ActivityIntentResolver mReceivers = 768 new ActivityIntentResolver(); 769 770 // All available services, for your resolving pleasure. 771 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 772 773 // All available providers, for your resolving pleasure. 774 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 775 776 // Mapping from provider base names (first directory in content URI codePath) 777 // to the provider information. 778 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 779 new ArrayMap<String, PackageParser.Provider>(); 780 781 // Mapping from instrumentation class names to info about them. 782 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 783 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 784 785 // Mapping from permission names to info about them. 786 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 787 new ArrayMap<String, PackageParser.PermissionGroup>(); 788 789 // Packages whose data we have transfered into another package, thus 790 // should no longer exist. 791 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 792 793 // Broadcast actions that are only available to the system. 794 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 795 796 /** List of packages waiting for verification. */ 797 final SparseArray<PackageVerificationState> mPendingVerification 798 = new SparseArray<PackageVerificationState>(); 799 800 /** Set of packages associated with each app op permission. */ 801 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 802 803 final PackageInstallerService mInstallerService; 804 805 private final PackageDexOptimizer mPackageDexOptimizer; 806 // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package 807 // is used by other apps). 808 private final DexManager mDexManager; 809 810 private AtomicInteger mNextMoveId = new AtomicInteger(); 811 private final MoveCallbacks mMoveCallbacks; 812 813 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 814 815 // Cache of users who need badging. 816 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 817 818 /** Token for keys in mPendingVerification. */ 819 private int mPendingVerificationToken = 0; 820 821 volatile boolean mSystemReady; 822 volatile boolean mSafeMode; 823 volatile boolean mHasSystemUidErrors; 824 825 ApplicationInfo mAndroidApplication; 826 final ActivityInfo mResolveActivity = new ActivityInfo(); 827 final ResolveInfo mResolveInfo = new ResolveInfo(); 828 ComponentName mResolveComponentName; 829 PackageParser.Package mPlatformPackage; 830 ComponentName mCustomResolverComponentName; 831 832 boolean mResolverReplaced = false; 833 834 private final @Nullable ComponentName mIntentFilterVerifierComponent; 835 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 836 837 private int mIntentFilterVerificationToken = 0; 838 839 /** The service connection to the ephemeral resolver */ 840 final EphemeralResolverConnection mEphemeralResolverConnection; 841 842 /** Component used to install ephemeral applications */ 843 ComponentName mEphemeralInstallerComponent; 844 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 845 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 846 847 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 848 = new SparseArray<IntentFilterVerificationState>(); 849 850 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy; 851 852 // List of packages names to keep cached, even if they are uninstalled for all users 853 private List<String> mKeepUninstalledPackages; 854 855 private UserManagerInternal mUserManagerInternal; 856 857 private DeviceIdleController.LocalService mDeviceIdleController; 858 859 private File mCacheDir; 860 861 private ArraySet<String> mPrivappPermissionsViolations; 862 863 private Future<?> mPrepareAppDataFuture; 864 865 private static class IFVerificationParams { 866 PackageParser.Package pkg; 867 boolean replacing; 868 int userId; 869 int verifierUid; 870 871 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 872 int _userId, int _verifierUid) { 873 pkg = _pkg; 874 replacing = _replacing; 875 userId = _userId; 876 replacing = _replacing; 877 verifierUid = _verifierUid; 878 } 879 } 880 881 private interface IntentFilterVerifier<T extends IntentFilter> { 882 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 883 T filter, String packageName); 884 void startVerifications(int userId); 885 void receiveVerificationResponse(int verificationId); 886 } 887 888 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 889 private Context mContext; 890 private ComponentName mIntentFilterVerifierComponent; 891 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 892 893 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 894 mContext = context; 895 mIntentFilterVerifierComponent = verifierComponent; 896 } 897 898 private String getDefaultScheme() { 899 return IntentFilter.SCHEME_HTTPS; 900 } 901 902 @Override 903 public void startVerifications(int userId) { 904 // Launch verifications requests 905 int count = mCurrentIntentFilterVerifications.size(); 906 for (int n=0; n<count; n++) { 907 int verificationId = mCurrentIntentFilterVerifications.get(n); 908 final IntentFilterVerificationState ivs = 909 mIntentFilterVerificationStates.get(verificationId); 910 911 String packageName = ivs.getPackageName(); 912 913 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 914 final int filterCount = filters.size(); 915 ArraySet<String> domainsSet = new ArraySet<>(); 916 for (int m=0; m<filterCount; m++) { 917 PackageParser.ActivityIntentInfo filter = filters.get(m); 918 domainsSet.addAll(filter.getHostsList()); 919 } 920 synchronized (mPackages) { 921 if (mSettings.createIntentFilterVerificationIfNeededLPw( 922 packageName, domainsSet) != null) { 923 scheduleWriteSettingsLocked(); 924 } 925 } 926 sendVerificationRequest(userId, verificationId, ivs); 927 } 928 mCurrentIntentFilterVerifications.clear(); 929 } 930 931 private void sendVerificationRequest(int userId, int verificationId, 932 IntentFilterVerificationState ivs) { 933 934 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 935 verificationIntent.putExtra( 936 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 937 verificationId); 938 verificationIntent.putExtra( 939 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 940 getDefaultScheme()); 941 verificationIntent.putExtra( 942 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 943 ivs.getHostsString()); 944 verificationIntent.putExtra( 945 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 946 ivs.getPackageName()); 947 verificationIntent.setComponent(mIntentFilterVerifierComponent); 948 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 949 950 UserHandle user = new UserHandle(userId); 951 mContext.sendBroadcastAsUser(verificationIntent, user); 952 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 953 "Sending IntentFilter verification broadcast"); 954 } 955 956 public void receiveVerificationResponse(int verificationId) { 957 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 958 959 final boolean verified = ivs.isVerified(); 960 961 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 962 final int count = filters.size(); 963 if (DEBUG_DOMAIN_VERIFICATION) { 964 Slog.i(TAG, "Received verification response " + verificationId 965 + " for " + count + " filters, verified=" + verified); 966 } 967 for (int n=0; n<count; n++) { 968 PackageParser.ActivityIntentInfo filter = filters.get(n); 969 filter.setVerified(verified); 970 971 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 972 + " verified with result:" + verified + " and hosts:" 973 + ivs.getHostsString()); 974 } 975 976 mIntentFilterVerificationStates.remove(verificationId); 977 978 final String packageName = ivs.getPackageName(); 979 IntentFilterVerificationInfo ivi = null; 980 981 synchronized (mPackages) { 982 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 983 } 984 if (ivi == null) { 985 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 986 + verificationId + " packageName:" + packageName); 987 return; 988 } 989 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 990 "Updating IntentFilterVerificationInfo for package " + packageName 991 +" verificationId:" + verificationId); 992 993 synchronized (mPackages) { 994 if (verified) { 995 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 996 } else { 997 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 998 } 999 scheduleWriteSettingsLocked(); 1000 1001 final int userId = ivs.getUserId(); 1002 if (userId != UserHandle.USER_ALL) { 1003 final int userStatus = 1004 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 1005 1006 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 1007 boolean needUpdate = false; 1008 1009 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 1010 // already been set by the User thru the Disambiguation dialog 1011 switch (userStatus) { 1012 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 1013 if (verified) { 1014 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 1015 } else { 1016 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 1017 } 1018 needUpdate = true; 1019 break; 1020 1021 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 1022 if (verified) { 1023 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 1024 needUpdate = true; 1025 } 1026 break; 1027 1028 default: 1029 // Nothing to do 1030 } 1031 1032 if (needUpdate) { 1033 mSettings.updateIntentFilterVerificationStatusLPw( 1034 packageName, updatedStatus, userId); 1035 scheduleWritePackageRestrictionsLocked(userId); 1036 } 1037 } 1038 } 1039 } 1040 1041 @Override 1042 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 1043 ActivityIntentInfo filter, String packageName) { 1044 if (!hasValidDomains(filter)) { 1045 return false; 1046 } 1047 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 1048 if (ivs == null) { 1049 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 1050 packageName); 1051 } 1052 if (DEBUG_DOMAIN_VERIFICATION) { 1053 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 1054 } 1055 ivs.addFilter(filter); 1056 return true; 1057 } 1058 1059 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 1060 int userId, int verificationId, String packageName) { 1061 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 1062 verifierUid, userId, packageName); 1063 ivs.setPendingState(); 1064 synchronized (mPackages) { 1065 mIntentFilterVerificationStates.append(verificationId, ivs); 1066 mCurrentIntentFilterVerifications.add(verificationId); 1067 } 1068 return ivs; 1069 } 1070 } 1071 1072 private static boolean hasValidDomains(ActivityIntentInfo filter) { 1073 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 1074 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 1075 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 1076 } 1077 1078 // Set of pending broadcasts for aggregating enable/disable of components. 1079 static class PendingPackageBroadcasts { 1080 // for each user id, a map of <package name -> components within that package> 1081 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 1082 1083 public PendingPackageBroadcasts() { 1084 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 1085 } 1086 1087 public ArrayList<String> get(int userId, String packageName) { 1088 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1089 return packages.get(packageName); 1090 } 1091 1092 public void put(int userId, String packageName, ArrayList<String> components) { 1093 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1094 packages.put(packageName, components); 1095 } 1096 1097 public void remove(int userId, String packageName) { 1098 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 1099 if (packages != null) { 1100 packages.remove(packageName); 1101 } 1102 } 1103 1104 public void remove(int userId) { 1105 mUidMap.remove(userId); 1106 } 1107 1108 public int userIdCount() { 1109 return mUidMap.size(); 1110 } 1111 1112 public int userIdAt(int n) { 1113 return mUidMap.keyAt(n); 1114 } 1115 1116 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 1117 return mUidMap.get(userId); 1118 } 1119 1120 public int size() { 1121 // total number of pending broadcast entries across all userIds 1122 int num = 0; 1123 for (int i = 0; i< mUidMap.size(); i++) { 1124 num += mUidMap.valueAt(i).size(); 1125 } 1126 return num; 1127 } 1128 1129 public void clear() { 1130 mUidMap.clear(); 1131 } 1132 1133 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1134 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1135 if (map == null) { 1136 map = new ArrayMap<String, ArrayList<String>>(); 1137 mUidMap.put(userId, map); 1138 } 1139 return map; 1140 } 1141 } 1142 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1143 1144 // Service Connection to remote media container service to copy 1145 // package uri's from external media onto secure containers 1146 // or internal storage. 1147 private IMediaContainerService mContainerService = null; 1148 1149 static final int SEND_PENDING_BROADCAST = 1; 1150 static final int MCS_BOUND = 3; 1151 static final int END_COPY = 4; 1152 static final int INIT_COPY = 5; 1153 static final int MCS_UNBIND = 6; 1154 static final int START_CLEANING_PACKAGE = 7; 1155 static final int FIND_INSTALL_LOC = 8; 1156 static final int POST_INSTALL = 9; 1157 static final int MCS_RECONNECT = 10; 1158 static final int MCS_GIVE_UP = 11; 1159 static final int UPDATED_MEDIA_STATUS = 12; 1160 static final int WRITE_SETTINGS = 13; 1161 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1162 static final int PACKAGE_VERIFIED = 15; 1163 static final int CHECK_PENDING_VERIFICATION = 16; 1164 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1165 static final int INTENT_FILTER_VERIFIED = 18; 1166 static final int WRITE_PACKAGE_LIST = 19; 1167 static final int EPHEMERAL_RESOLUTION_PHASE_TWO = 20; 1168 1169 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1170 1171 // Delay time in millisecs 1172 static final int BROADCAST_DELAY = 10 * 1000; 1173 1174 static UserManagerService sUserManager; 1175 1176 // Stores a list of users whose package restrictions file needs to be updated 1177 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1178 1179 final private DefaultContainerConnection mDefContainerConn = 1180 new DefaultContainerConnection(); 1181 class DefaultContainerConnection implements ServiceConnection { 1182 public void onServiceConnected(ComponentName name, IBinder service) { 1183 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1184 final IMediaContainerService imcs = IMediaContainerService.Stub 1185 .asInterface(Binder.allowBlocking(service)); 1186 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1187 } 1188 1189 public void onServiceDisconnected(ComponentName name) { 1190 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1191 } 1192 } 1193 1194 // Recordkeeping of restore-after-install operations that are currently in flight 1195 // between the Package Manager and the Backup Manager 1196 static class PostInstallData { 1197 public InstallArgs args; 1198 public PackageInstalledInfo res; 1199 1200 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1201 args = _a; 1202 res = _r; 1203 } 1204 } 1205 1206 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1207 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1208 1209 // XML tags for backup/restore of various bits of state 1210 private static final String TAG_PREFERRED_BACKUP = "pa"; 1211 private static final String TAG_DEFAULT_APPS = "da"; 1212 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1213 1214 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1215 private static final String TAG_ALL_GRANTS = "rt-grants"; 1216 private static final String TAG_GRANT = "grant"; 1217 private static final String ATTR_PACKAGE_NAME = "pkg"; 1218 1219 private static final String TAG_PERMISSION = "perm"; 1220 private static final String ATTR_PERMISSION_NAME = "name"; 1221 private static final String ATTR_IS_GRANTED = "g"; 1222 private static final String ATTR_USER_SET = "set"; 1223 private static final String ATTR_USER_FIXED = "fixed"; 1224 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1225 1226 // System/policy permission grants are not backed up 1227 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1228 FLAG_PERMISSION_POLICY_FIXED 1229 | FLAG_PERMISSION_SYSTEM_FIXED 1230 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1231 1232 // And we back up these user-adjusted states 1233 private static final int USER_RUNTIME_GRANT_MASK = 1234 FLAG_PERMISSION_USER_SET 1235 | FLAG_PERMISSION_USER_FIXED 1236 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1237 1238 final @Nullable String mRequiredVerifierPackage; 1239 final @NonNull String mRequiredInstallerPackage; 1240 final @NonNull String mRequiredUninstallerPackage; 1241 final @Nullable String mSetupWizardPackage; 1242 final @Nullable String mStorageManagerPackage; 1243 final @NonNull String mServicesSystemSharedLibraryPackageName; 1244 final @NonNull String mSharedSystemSharedLibraryPackageName; 1245 1246 final boolean mPermissionReviewRequired; 1247 1248 private final PackageUsage mPackageUsage = new PackageUsage(); 1249 private final CompilerStats mCompilerStats = new CompilerStats(); 1250 1251 class PackageHandler extends Handler { 1252 private boolean mBound = false; 1253 final ArrayList<HandlerParams> mPendingInstalls = 1254 new ArrayList<HandlerParams>(); 1255 1256 private boolean connectToService() { 1257 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1258 " DefaultContainerService"); 1259 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1260 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1261 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1262 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1263 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1264 mBound = true; 1265 return true; 1266 } 1267 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1268 return false; 1269 } 1270 1271 private void disconnectService() { 1272 mContainerService = null; 1273 mBound = false; 1274 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1275 mContext.unbindService(mDefContainerConn); 1276 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1277 } 1278 1279 PackageHandler(Looper looper) { 1280 super(looper); 1281 } 1282 1283 public void handleMessage(Message msg) { 1284 try { 1285 doHandleMessage(msg); 1286 } finally { 1287 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1288 } 1289 } 1290 1291 void doHandleMessage(Message msg) { 1292 switch (msg.what) { 1293 case INIT_COPY: { 1294 HandlerParams params = (HandlerParams) msg.obj; 1295 int idx = mPendingInstalls.size(); 1296 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1297 // If a bind was already initiated we dont really 1298 // need to do anything. The pending install 1299 // will be processed later on. 1300 if (!mBound) { 1301 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1302 System.identityHashCode(mHandler)); 1303 // If this is the only one pending we might 1304 // have to bind to the service again. 1305 if (!connectToService()) { 1306 Slog.e(TAG, "Failed to bind to media container service"); 1307 params.serviceError(); 1308 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1309 System.identityHashCode(mHandler)); 1310 if (params.traceMethod != null) { 1311 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1312 params.traceCookie); 1313 } 1314 return; 1315 } else { 1316 // Once we bind to the service, the first 1317 // pending request will be processed. 1318 mPendingInstalls.add(idx, params); 1319 } 1320 } else { 1321 mPendingInstalls.add(idx, params); 1322 // Already bound to the service. Just make 1323 // sure we trigger off processing the first request. 1324 if (idx == 0) { 1325 mHandler.sendEmptyMessage(MCS_BOUND); 1326 } 1327 } 1328 break; 1329 } 1330 case MCS_BOUND: { 1331 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1332 if (msg.obj != null) { 1333 mContainerService = (IMediaContainerService) msg.obj; 1334 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1335 System.identityHashCode(mHandler)); 1336 } 1337 if (mContainerService == null) { 1338 if (!mBound) { 1339 // Something seriously wrong since we are not bound and we are not 1340 // waiting for connection. Bail out. 1341 Slog.e(TAG, "Cannot bind to media container service"); 1342 for (HandlerParams params : mPendingInstalls) { 1343 // Indicate service bind error 1344 params.serviceError(); 1345 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1346 System.identityHashCode(params)); 1347 if (params.traceMethod != null) { 1348 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1349 params.traceMethod, params.traceCookie); 1350 } 1351 return; 1352 } 1353 mPendingInstalls.clear(); 1354 } else { 1355 Slog.w(TAG, "Waiting to connect to media container service"); 1356 } 1357 } else if (mPendingInstalls.size() > 0) { 1358 HandlerParams params = mPendingInstalls.get(0); 1359 if (params != null) { 1360 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1361 System.identityHashCode(params)); 1362 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1363 if (params.startCopy()) { 1364 // We are done... look for more work or to 1365 // go idle. 1366 if (DEBUG_SD_INSTALL) Log.i(TAG, 1367 "Checking for more work or unbind..."); 1368 // Delete pending install 1369 if (mPendingInstalls.size() > 0) { 1370 mPendingInstalls.remove(0); 1371 } 1372 if (mPendingInstalls.size() == 0) { 1373 if (mBound) { 1374 if (DEBUG_SD_INSTALL) Log.i(TAG, 1375 "Posting delayed MCS_UNBIND"); 1376 removeMessages(MCS_UNBIND); 1377 Message ubmsg = obtainMessage(MCS_UNBIND); 1378 // Unbind after a little delay, to avoid 1379 // continual thrashing. 1380 sendMessageDelayed(ubmsg, 10000); 1381 } 1382 } else { 1383 // There are more pending requests in queue. 1384 // Just post MCS_BOUND message to trigger processing 1385 // of next pending install. 1386 if (DEBUG_SD_INSTALL) Log.i(TAG, 1387 "Posting MCS_BOUND for next work"); 1388 mHandler.sendEmptyMessage(MCS_BOUND); 1389 } 1390 } 1391 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1392 } 1393 } else { 1394 // Should never happen ideally. 1395 Slog.w(TAG, "Empty queue"); 1396 } 1397 break; 1398 } 1399 case MCS_RECONNECT: { 1400 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1401 if (mPendingInstalls.size() > 0) { 1402 if (mBound) { 1403 disconnectService(); 1404 } 1405 if (!connectToService()) { 1406 Slog.e(TAG, "Failed to bind to media container service"); 1407 for (HandlerParams params : mPendingInstalls) { 1408 // Indicate service bind error 1409 params.serviceError(); 1410 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1411 System.identityHashCode(params)); 1412 } 1413 mPendingInstalls.clear(); 1414 } 1415 } 1416 break; 1417 } 1418 case MCS_UNBIND: { 1419 // If there is no actual work left, then time to unbind. 1420 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1421 1422 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1423 if (mBound) { 1424 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1425 1426 disconnectService(); 1427 } 1428 } else if (mPendingInstalls.size() > 0) { 1429 // There are more pending requests in queue. 1430 // Just post MCS_BOUND message to trigger processing 1431 // of next pending install. 1432 mHandler.sendEmptyMessage(MCS_BOUND); 1433 } 1434 1435 break; 1436 } 1437 case MCS_GIVE_UP: { 1438 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1439 HandlerParams params = mPendingInstalls.remove(0); 1440 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1441 System.identityHashCode(params)); 1442 break; 1443 } 1444 case SEND_PENDING_BROADCAST: { 1445 String packages[]; 1446 ArrayList<String> components[]; 1447 int size = 0; 1448 int uids[]; 1449 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1450 synchronized (mPackages) { 1451 if (mPendingBroadcasts == null) { 1452 return; 1453 } 1454 size = mPendingBroadcasts.size(); 1455 if (size <= 0) { 1456 // Nothing to be done. Just return 1457 return; 1458 } 1459 packages = new String[size]; 1460 components = new ArrayList[size]; 1461 uids = new int[size]; 1462 int i = 0; // filling out the above arrays 1463 1464 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1465 int packageUserId = mPendingBroadcasts.userIdAt(n); 1466 Iterator<Map.Entry<String, ArrayList<String>>> it 1467 = mPendingBroadcasts.packagesForUserId(packageUserId) 1468 .entrySet().iterator(); 1469 while (it.hasNext() && i < size) { 1470 Map.Entry<String, ArrayList<String>> ent = it.next(); 1471 packages[i] = ent.getKey(); 1472 components[i] = ent.getValue(); 1473 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1474 uids[i] = (ps != null) 1475 ? UserHandle.getUid(packageUserId, ps.appId) 1476 : -1; 1477 i++; 1478 } 1479 } 1480 size = i; 1481 mPendingBroadcasts.clear(); 1482 } 1483 // Send broadcasts 1484 for (int i = 0; i < size; i++) { 1485 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1486 } 1487 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1488 break; 1489 } 1490 case START_CLEANING_PACKAGE: { 1491 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1492 final String packageName = (String)msg.obj; 1493 final int userId = msg.arg1; 1494 final boolean andCode = msg.arg2 != 0; 1495 synchronized (mPackages) { 1496 if (userId == UserHandle.USER_ALL) { 1497 int[] users = sUserManager.getUserIds(); 1498 for (int user : users) { 1499 mSettings.addPackageToCleanLPw( 1500 new PackageCleanItem(user, packageName, andCode)); 1501 } 1502 } else { 1503 mSettings.addPackageToCleanLPw( 1504 new PackageCleanItem(userId, packageName, andCode)); 1505 } 1506 } 1507 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1508 startCleaningPackages(); 1509 } break; 1510 case POST_INSTALL: { 1511 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1512 1513 PostInstallData data = mRunningInstalls.get(msg.arg1); 1514 final boolean didRestore = (msg.arg2 != 0); 1515 mRunningInstalls.delete(msg.arg1); 1516 1517 if (data != null) { 1518 InstallArgs args = data.args; 1519 PackageInstalledInfo parentRes = data.res; 1520 1521 final boolean grantPermissions = (args.installFlags 1522 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1523 final boolean killApp = (args.installFlags 1524 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1525 final String[] grantedPermissions = args.installGrantPermissions; 1526 1527 // Handle the parent package 1528 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1529 grantedPermissions, didRestore, args.installerPackageName, 1530 args.observer); 1531 1532 // Handle the child packages 1533 final int childCount = (parentRes.addedChildPackages != null) 1534 ? parentRes.addedChildPackages.size() : 0; 1535 for (int i = 0; i < childCount; i++) { 1536 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1537 handlePackagePostInstall(childRes, grantPermissions, killApp, 1538 grantedPermissions, false, args.installerPackageName, 1539 args.observer); 1540 } 1541 1542 // Log tracing if needed 1543 if (args.traceMethod != null) { 1544 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1545 args.traceCookie); 1546 } 1547 } else { 1548 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1549 } 1550 1551 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1552 } break; 1553 case UPDATED_MEDIA_STATUS: { 1554 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1555 boolean reportStatus = msg.arg1 == 1; 1556 boolean doGc = msg.arg2 == 1; 1557 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1558 if (doGc) { 1559 // Force a gc to clear up stale containers. 1560 Runtime.getRuntime().gc(); 1561 } 1562 if (msg.obj != null) { 1563 @SuppressWarnings("unchecked") 1564 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1565 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1566 // Unload containers 1567 unloadAllContainers(args); 1568 } 1569 if (reportStatus) { 1570 try { 1571 if (DEBUG_SD_INSTALL) Log.i(TAG, 1572 "Invoking StorageManagerService call back"); 1573 PackageHelper.getStorageManager().finishMediaUpdate(); 1574 } catch (RemoteException e) { 1575 Log.e(TAG, "StorageManagerService not running?"); 1576 } 1577 } 1578 } break; 1579 case WRITE_SETTINGS: { 1580 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1581 synchronized (mPackages) { 1582 removeMessages(WRITE_SETTINGS); 1583 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1584 mSettings.writeLPr(); 1585 mDirtyUsers.clear(); 1586 } 1587 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1588 } break; 1589 case WRITE_PACKAGE_RESTRICTIONS: { 1590 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1591 synchronized (mPackages) { 1592 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1593 for (int userId : mDirtyUsers) { 1594 mSettings.writePackageRestrictionsLPr(userId); 1595 } 1596 mDirtyUsers.clear(); 1597 } 1598 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1599 } break; 1600 case WRITE_PACKAGE_LIST: { 1601 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1602 synchronized (mPackages) { 1603 removeMessages(WRITE_PACKAGE_LIST); 1604 mSettings.writePackageListLPr(msg.arg1); 1605 } 1606 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1607 } break; 1608 case CHECK_PENDING_VERIFICATION: { 1609 final int verificationId = msg.arg1; 1610 final PackageVerificationState state = mPendingVerification.get(verificationId); 1611 1612 if ((state != null) && !state.timeoutExtended()) { 1613 final InstallArgs args = state.getInstallArgs(); 1614 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1615 1616 Slog.i(TAG, "Verification timed out for " + originUri); 1617 mPendingVerification.remove(verificationId); 1618 1619 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1620 1621 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1622 Slog.i(TAG, "Continuing with installation of " + originUri); 1623 state.setVerifierResponse(Binder.getCallingUid(), 1624 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1625 broadcastPackageVerified(verificationId, originUri, 1626 PackageManager.VERIFICATION_ALLOW, 1627 state.getInstallArgs().getUser()); 1628 try { 1629 ret = args.copyApk(mContainerService, true); 1630 } catch (RemoteException e) { 1631 Slog.e(TAG, "Could not contact the ContainerService"); 1632 } 1633 } else { 1634 broadcastPackageVerified(verificationId, originUri, 1635 PackageManager.VERIFICATION_REJECT, 1636 state.getInstallArgs().getUser()); 1637 } 1638 1639 Trace.asyncTraceEnd( 1640 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1641 1642 processPendingInstall(args, ret); 1643 mHandler.sendEmptyMessage(MCS_UNBIND); 1644 } 1645 break; 1646 } 1647 case PACKAGE_VERIFIED: { 1648 final int verificationId = msg.arg1; 1649 1650 final PackageVerificationState state = mPendingVerification.get(verificationId); 1651 if (state == null) { 1652 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1653 break; 1654 } 1655 1656 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1657 1658 state.setVerifierResponse(response.callerUid, response.code); 1659 1660 if (state.isVerificationComplete()) { 1661 mPendingVerification.remove(verificationId); 1662 1663 final InstallArgs args = state.getInstallArgs(); 1664 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1665 1666 int ret; 1667 if (state.isInstallAllowed()) { 1668 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1669 broadcastPackageVerified(verificationId, originUri, 1670 response.code, state.getInstallArgs().getUser()); 1671 try { 1672 ret = args.copyApk(mContainerService, true); 1673 } catch (RemoteException e) { 1674 Slog.e(TAG, "Could not contact the ContainerService"); 1675 } 1676 } else { 1677 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1678 } 1679 1680 Trace.asyncTraceEnd( 1681 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1682 1683 processPendingInstall(args, ret); 1684 mHandler.sendEmptyMessage(MCS_UNBIND); 1685 } 1686 1687 break; 1688 } 1689 case START_INTENT_FILTER_VERIFICATIONS: { 1690 IFVerificationParams params = (IFVerificationParams) msg.obj; 1691 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1692 params.replacing, params.pkg); 1693 break; 1694 } 1695 case INTENT_FILTER_VERIFIED: { 1696 final int verificationId = msg.arg1; 1697 1698 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1699 verificationId); 1700 if (state == null) { 1701 Slog.w(TAG, "Invalid IntentFilter verification token " 1702 + verificationId + " received"); 1703 break; 1704 } 1705 1706 final int userId = state.getUserId(); 1707 1708 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1709 "Processing IntentFilter verification with token:" 1710 + verificationId + " and userId:" + userId); 1711 1712 final IntentFilterVerificationResponse response = 1713 (IntentFilterVerificationResponse) msg.obj; 1714 1715 state.setVerifierResponse(response.callerUid, response.code); 1716 1717 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1718 "IntentFilter verification with token:" + verificationId 1719 + " and userId:" + userId 1720 + " is settings verifier response with response code:" 1721 + response.code); 1722 1723 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1724 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1725 + response.getFailedDomainsString()); 1726 } 1727 1728 if (state.isVerificationComplete()) { 1729 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1730 } else { 1731 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1732 "IntentFilter verification with token:" + verificationId 1733 + " was not said to be complete"); 1734 } 1735 1736 break; 1737 } 1738 case EPHEMERAL_RESOLUTION_PHASE_TWO: { 1739 EphemeralResolver.doEphemeralResolutionPhaseTwo(mContext, 1740 mEphemeralResolverConnection, 1741 (EphemeralRequest) msg.obj, 1742 mEphemeralInstallerActivity, 1743 mHandler); 1744 } 1745 } 1746 } 1747 } 1748 1749 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1750 boolean killApp, String[] grantedPermissions, 1751 boolean launchedForRestore, String installerPackage, 1752 IPackageInstallObserver2 installObserver) { 1753 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1754 // Send the removed broadcasts 1755 if (res.removedInfo != null) { 1756 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1757 } 1758 1759 // Now that we successfully installed the package, grant runtime 1760 // permissions if requested before broadcasting the install. Also 1761 // for legacy apps in permission review mode we clear the permission 1762 // review flag which is used to emulate runtime permissions for 1763 // legacy apps. 1764 if (grantPermissions) { 1765 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1766 } 1767 1768 final boolean update = res.removedInfo != null 1769 && res.removedInfo.removedPackage != null; 1770 1771 // If this is the first time we have child packages for a disabled privileged 1772 // app that had no children, we grant requested runtime permissions to the new 1773 // children if the parent on the system image had them already granted. 1774 if (res.pkg.parentPackage != null) { 1775 synchronized (mPackages) { 1776 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1777 } 1778 } 1779 1780 synchronized (mPackages) { 1781 mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers); 1782 } 1783 1784 final String packageName = res.pkg.applicationInfo.packageName; 1785 1786 // Determine the set of users who are adding this package for 1787 // the first time vs. those who are seeing an update. 1788 int[] firstUsers = EMPTY_INT_ARRAY; 1789 int[] updateUsers = EMPTY_INT_ARRAY; 1790 final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0; 1791 final PackageSetting ps = (PackageSetting) res.pkg.mExtras; 1792 for (int newUser : res.newUsers) { 1793 if (ps.getInstantApp(newUser)) { 1794 continue; 1795 } 1796 if (allNewUsers) { 1797 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1798 continue; 1799 } 1800 boolean isNew = true; 1801 for (int origUser : res.origUsers) { 1802 if (origUser == newUser) { 1803 isNew = false; 1804 break; 1805 } 1806 } 1807 if (isNew) { 1808 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1809 } else { 1810 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1811 } 1812 } 1813 1814 // Send installed broadcasts if the package is not a static shared lib. 1815 if (res.pkg.staticSharedLibName == null) { 1816 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1817 1818 // Send added for users that see the package for the first time 1819 // sendPackageAddedForNewUsers also deals with system apps 1820 int appId = UserHandle.getAppId(res.uid); 1821 boolean isSystem = res.pkg.applicationInfo.isSystemApp(); 1822 sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers); 1823 1824 // Send added for users that don't see the package for the first time 1825 Bundle extras = new Bundle(1); 1826 extras.putInt(Intent.EXTRA_UID, res.uid); 1827 if (update) { 1828 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1829 } 1830 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1831 extras, 0 /*flags*/, null /*targetPackage*/, 1832 null /*finishedReceiver*/, updateUsers); 1833 1834 // Send replaced for users that don't see the package for the first time 1835 if (update) { 1836 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1837 packageName, extras, 0 /*flags*/, 1838 null /*targetPackage*/, null /*finishedReceiver*/, 1839 updateUsers); 1840 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1841 null /*package*/, null /*extras*/, 0 /*flags*/, 1842 packageName /*targetPackage*/, 1843 null /*finishedReceiver*/, updateUsers); 1844 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 1845 // First-install and we did a restore, so we're responsible for the 1846 // first-launch broadcast. 1847 if (DEBUG_BACKUP) { 1848 Slog.i(TAG, "Post-restore of " + packageName 1849 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers)); 1850 } 1851 sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers); 1852 } 1853 1854 // Send broadcast package appeared if forward locked/external for all users 1855 // treat asec-hosted packages like removable media on upgrade 1856 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1857 if (DEBUG_INSTALL) { 1858 Slog.i(TAG, "upgrading pkg " + res.pkg 1859 + " is ASEC-hosted -> AVAILABLE"); 1860 } 1861 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1862 ArrayList<String> pkgList = new ArrayList<>(1); 1863 pkgList.add(packageName); 1864 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1865 } 1866 } 1867 1868 // Work that needs to happen on first install within each user 1869 if (firstUsers != null && firstUsers.length > 0) { 1870 synchronized (mPackages) { 1871 for (int userId : firstUsers) { 1872 // If this app is a browser and it's newly-installed for some 1873 // users, clear any default-browser state in those users. The 1874 // app's nature doesn't depend on the user, so we can just check 1875 // its browser nature in any user and generalize. 1876 if (packageIsBrowser(packageName, userId)) { 1877 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1878 } 1879 1880 // We may also need to apply pending (restored) runtime 1881 // permission grants within these users. 1882 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1883 } 1884 } 1885 } 1886 1887 // Log current value of "unknown sources" setting 1888 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1889 getUnknownSourcesSettings()); 1890 1891 // Force a gc to clear up things 1892 Runtime.getRuntime().gc(); 1893 1894 // Remove the replaced package's older resources safely now 1895 // We delete after a gc for applications on sdcard. 1896 if (res.removedInfo != null && res.removedInfo.args != null) { 1897 synchronized (mInstallLock) { 1898 res.removedInfo.args.doPostDeleteLI(true); 1899 } 1900 } 1901 1902 // Notify DexManager that the package was installed for new users. 1903 // The updated users should already be indexed and the package code paths 1904 // should not change. 1905 // Don't notify the manager for ephemeral apps as they are not expected to 1906 // survive long enough to benefit of background optimizations. 1907 for (int userId : firstUsers) { 1908 PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId); 1909 mDexManager.notifyPackageInstalled(info, userId); 1910 } 1911 } 1912 1913 // If someone is watching installs - notify them 1914 if (installObserver != null) { 1915 try { 1916 Bundle extras = extrasForInstallResult(res); 1917 installObserver.onPackageInstalled(res.name, res.returnCode, 1918 res.returnMsg, extras); 1919 } catch (RemoteException e) { 1920 Slog.i(TAG, "Observer no longer exists."); 1921 } 1922 } 1923 } 1924 1925 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1926 PackageParser.Package pkg) { 1927 if (pkg.parentPackage == null) { 1928 return; 1929 } 1930 if (pkg.requestedPermissions == null) { 1931 return; 1932 } 1933 final PackageSetting disabledSysParentPs = mSettings 1934 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1935 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1936 || !disabledSysParentPs.isPrivileged() 1937 || (disabledSysParentPs.childPackageNames != null 1938 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1939 return; 1940 } 1941 final int[] allUserIds = sUserManager.getUserIds(); 1942 final int permCount = pkg.requestedPermissions.size(); 1943 for (int i = 0; i < permCount; i++) { 1944 String permission = pkg.requestedPermissions.get(i); 1945 BasePermission bp = mSettings.mPermissions.get(permission); 1946 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1947 continue; 1948 } 1949 for (int userId : allUserIds) { 1950 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1951 permission, userId)) { 1952 grantRuntimePermission(pkg.packageName, permission, userId); 1953 } 1954 } 1955 } 1956 } 1957 1958 private StorageEventListener mStorageListener = new StorageEventListener() { 1959 @Override 1960 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1961 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1962 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1963 final String volumeUuid = vol.getFsUuid(); 1964 1965 // Clean up any users or apps that were removed or recreated 1966 // while this volume was missing 1967 sUserManager.reconcileUsers(volumeUuid); 1968 reconcileApps(volumeUuid); 1969 1970 // Clean up any install sessions that expired or were 1971 // cancelled while this volume was missing 1972 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1973 1974 loadPrivatePackages(vol); 1975 1976 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1977 unloadPrivatePackages(vol); 1978 } 1979 } 1980 1981 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1982 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1983 updateExternalMediaStatus(true, false); 1984 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1985 updateExternalMediaStatus(false, false); 1986 } 1987 } 1988 } 1989 1990 @Override 1991 public void onVolumeForgotten(String fsUuid) { 1992 if (TextUtils.isEmpty(fsUuid)) { 1993 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1994 return; 1995 } 1996 1997 // Remove any apps installed on the forgotten volume 1998 synchronized (mPackages) { 1999 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 2000 for (PackageSetting ps : packages) { 2001 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 2002 deletePackageVersioned(new VersionedPackage(ps.name, 2003 PackageManager.VERSION_CODE_HIGHEST), 2004 new LegacyPackageDeleteObserver(null).getBinder(), 2005 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 2006 // Try very hard to release any references to this package 2007 // so we don't risk the system server being killed due to 2008 // open FDs 2009 AttributeCache.instance().removePackage(ps.name); 2010 } 2011 2012 mSettings.onVolumeForgotten(fsUuid); 2013 mSettings.writeLPr(); 2014 } 2015 } 2016 }; 2017 2018 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 2019 String[] grantedPermissions) { 2020 for (int userId : userIds) { 2021 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 2022 } 2023 } 2024 2025 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 2026 String[] grantedPermissions) { 2027 SettingBase sb = (SettingBase) pkg.mExtras; 2028 if (sb == null) { 2029 return; 2030 } 2031 2032 PermissionsState permissionsState = sb.getPermissionsState(); 2033 2034 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 2035 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 2036 2037 final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 2038 >= Build.VERSION_CODES.M; 2039 2040 for (String permission : pkg.requestedPermissions) { 2041 final BasePermission bp; 2042 synchronized (mPackages) { 2043 bp = mSettings.mPermissions.get(permission); 2044 } 2045 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 2046 && (grantedPermissions == null 2047 || ArrayUtils.contains(grantedPermissions, permission))) { 2048 final int flags = permissionsState.getPermissionFlags(permission, userId); 2049 if (supportsRuntimePermissions) { 2050 // Installer cannot change immutable permissions. 2051 if ((flags & immutableFlags) == 0) { 2052 grantRuntimePermission(pkg.packageName, permission, userId); 2053 } 2054 } else if (mPermissionReviewRequired) { 2055 // In permission review mode we clear the review flag when we 2056 // are asked to install the app with all permissions granted. 2057 if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 2058 updatePermissionFlags(permission, pkg.packageName, 2059 PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId); 2060 } 2061 } 2062 } 2063 } 2064 } 2065 2066 Bundle extrasForInstallResult(PackageInstalledInfo res) { 2067 Bundle extras = null; 2068 switch (res.returnCode) { 2069 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 2070 extras = new Bundle(); 2071 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 2072 res.origPermission); 2073 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 2074 res.origPackage); 2075 break; 2076 } 2077 case PackageManager.INSTALL_SUCCEEDED: { 2078 extras = new Bundle(); 2079 extras.putBoolean(Intent.EXTRA_REPLACING, 2080 res.removedInfo != null && res.removedInfo.removedPackage != null); 2081 break; 2082 } 2083 } 2084 return extras; 2085 } 2086 2087 void scheduleWriteSettingsLocked() { 2088 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2089 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2090 } 2091 } 2092 2093 void scheduleWritePackageListLocked(int userId) { 2094 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) { 2095 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST); 2096 msg.arg1 = userId; 2097 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY); 2098 } 2099 } 2100 2101 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2102 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2103 scheduleWritePackageRestrictionsLocked(userId); 2104 } 2105 2106 void scheduleWritePackageRestrictionsLocked(int userId) { 2107 final int[] userIds = (userId == UserHandle.USER_ALL) 2108 ? sUserManager.getUserIds() : new int[]{userId}; 2109 for (int nextUserId : userIds) { 2110 if (!sUserManager.exists(nextUserId)) return; 2111 mDirtyUsers.add(nextUserId); 2112 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2113 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2114 } 2115 } 2116 } 2117 2118 public static PackageManagerService main(Context context, Installer installer, 2119 boolean factoryTest, boolean onlyCore) { 2120 // Self-check for initial settings. 2121 PackageManagerServiceCompilerMapping.checkProperties(); 2122 2123 PackageManagerService m = new PackageManagerService(context, installer, 2124 factoryTest, onlyCore); 2125 m.enableSystemUserPackages(); 2126 ServiceManager.addService("package", m); 2127 return m; 2128 } 2129 2130 private void enableSystemUserPackages() { 2131 if (!UserManager.isSplitSystemUser()) { 2132 return; 2133 } 2134 // For system user, enable apps based on the following conditions: 2135 // - app is whitelisted or belong to one of these groups: 2136 // -- system app which has no launcher icons 2137 // -- system app which has INTERACT_ACROSS_USERS permission 2138 // -- system IME app 2139 // - app is not in the blacklist 2140 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2141 Set<String> enableApps = new ArraySet<>(); 2142 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2143 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2144 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2145 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2146 enableApps.addAll(wlApps); 2147 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2148 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2149 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2150 enableApps.removeAll(blApps); 2151 Log.i(TAG, "Applications installed for system user: " + enableApps); 2152 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2153 UserHandle.SYSTEM); 2154 final int allAppsSize = allAps.size(); 2155 synchronized (mPackages) { 2156 for (int i = 0; i < allAppsSize; i++) { 2157 String pName = allAps.get(i); 2158 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2159 // Should not happen, but we shouldn't be failing if it does 2160 if (pkgSetting == null) { 2161 continue; 2162 } 2163 boolean install = enableApps.contains(pName); 2164 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2165 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2166 + " for system user"); 2167 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2168 } 2169 } 2170 scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM); 2171 } 2172 } 2173 2174 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2175 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2176 Context.DISPLAY_SERVICE); 2177 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2178 } 2179 2180 /** 2181 * Requests that files preopted on a secondary system partition be copied to the data partition 2182 * if possible. Note that the actual copying of the files is accomplished by init for security 2183 * reasons. This simply requests that the copy takes place and awaits confirmation of its 2184 * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy. 2185 */ 2186 private static void requestCopyPreoptedFiles() { 2187 final int WAIT_TIME_MS = 100; 2188 final String CP_PREOPT_PROPERTY = "sys.cppreopt"; 2189 if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) { 2190 SystemProperties.set(CP_PREOPT_PROPERTY, "requested"); 2191 // We will wait for up to 100 seconds. 2192 final long timeStart = SystemClock.uptimeMillis(); 2193 final long timeEnd = timeStart + 100 * 1000; 2194 long timeNow = timeStart; 2195 while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) { 2196 try { 2197 Thread.sleep(WAIT_TIME_MS); 2198 } catch (InterruptedException e) { 2199 // Do nothing 2200 } 2201 timeNow = SystemClock.uptimeMillis(); 2202 if (timeNow > timeEnd) { 2203 SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out"); 2204 Slog.wtf(TAG, "cppreopt did not finish!"); 2205 break; 2206 } 2207 } 2208 2209 Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms"); 2210 } 2211 } 2212 2213 public PackageManagerService(Context context, Installer installer, 2214 boolean factoryTest, boolean onlyCore) { 2215 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager"); 2216 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2217 SystemClock.uptimeMillis()); 2218 2219 if (mSdkVersion <= 0) { 2220 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2221 } 2222 2223 mContext = context; 2224 2225 mPermissionReviewRequired = context.getResources().getBoolean( 2226 R.bool.config_permissionReviewRequired); 2227 2228 mFactoryTest = factoryTest; 2229 mOnlyCore = onlyCore; 2230 mMetrics = new DisplayMetrics(); 2231 mSettings = new Settings(mPackages); 2232 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2233 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2234 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2235 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2236 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2237 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2238 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2239 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2240 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2241 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2242 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2243 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2244 2245 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2246 if (separateProcesses != null && separateProcesses.length() > 0) { 2247 if ("*".equals(separateProcesses)) { 2248 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2249 mSeparateProcesses = null; 2250 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2251 } else { 2252 mDefParseFlags = 0; 2253 mSeparateProcesses = separateProcesses.split(","); 2254 Slog.w(TAG, "Running with debug.separate_processes: " 2255 + separateProcesses); 2256 } 2257 } else { 2258 mDefParseFlags = 0; 2259 mSeparateProcesses = null; 2260 } 2261 2262 mInstaller = installer; 2263 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2264 "*dexopt*"); 2265 mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock); 2266 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2267 2268 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2269 FgThread.get().getLooper()); 2270 2271 getDefaultDisplayMetrics(context, mMetrics); 2272 2273 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config"); 2274 SystemConfig systemConfig = SystemConfig.getInstance(); 2275 mGlobalGids = systemConfig.getGlobalGids(); 2276 mSystemPermissions = systemConfig.getSystemPermissions(); 2277 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2278 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2279 2280 mProtectedPackages = new ProtectedPackages(mContext); 2281 2282 synchronized (mInstallLock) { 2283 // writer 2284 synchronized (mPackages) { 2285 mHandlerThread = new ServiceThread(TAG, 2286 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2287 mHandlerThread.start(); 2288 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2289 mProcessLoggingHandler = new ProcessLoggingHandler(); 2290 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2291 2292 mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this); 2293 mInstantAppRegistry = new InstantAppRegistry(this); 2294 2295 File dataDir = Environment.getDataDirectory(); 2296 mAppInstallDir = new File(dataDir, "app"); 2297 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2298 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2299 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2300 sUserManager = new UserManagerService(context, this, 2301 new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages); 2302 2303 // Propagate permission configuration in to package manager. 2304 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2305 = systemConfig.getPermissions(); 2306 for (int i=0; i<permConfig.size(); i++) { 2307 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2308 BasePermission bp = mSettings.mPermissions.get(perm.name); 2309 if (bp == null) { 2310 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2311 mSettings.mPermissions.put(perm.name, bp); 2312 } 2313 if (perm.gids != null) { 2314 bp.setGids(perm.gids, perm.perUser); 2315 } 2316 } 2317 2318 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2319 final int builtInLibCount = libConfig.size(); 2320 for (int i = 0; i < builtInLibCount; i++) { 2321 String name = libConfig.keyAt(i); 2322 String path = libConfig.valueAt(i); 2323 addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED, 2324 SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0); 2325 } 2326 2327 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2328 2329 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings"); 2330 mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false)); 2331 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2332 2333 // Clean up orphaned packages for which the code path doesn't exist 2334 // and they are an update to a system app - caused by bug/32321269 2335 final int packageSettingCount = mSettings.mPackages.size(); 2336 for (int i = packageSettingCount - 1; i >= 0; i--) { 2337 PackageSetting ps = mSettings.mPackages.valueAt(i); 2338 if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists()) 2339 && mSettings.getDisabledSystemPkgLPr(ps.name) != null) { 2340 mSettings.mPackages.removeAt(i); 2341 mSettings.enableSystemPackageLPw(ps.name); 2342 } 2343 } 2344 2345 if (mFirstBoot) { 2346 requestCopyPreoptedFiles(); 2347 } 2348 2349 String customResolverActivity = Resources.getSystem().getString( 2350 R.string.config_customResolverActivity); 2351 if (TextUtils.isEmpty(customResolverActivity)) { 2352 customResolverActivity = null; 2353 } else { 2354 mCustomResolverComponentName = ComponentName.unflattenFromString( 2355 customResolverActivity); 2356 } 2357 2358 long startTime = SystemClock.uptimeMillis(); 2359 2360 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2361 startTime); 2362 2363 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2364 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2365 2366 if (bootClassPath == null) { 2367 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2368 } 2369 2370 if (systemServerClassPath == null) { 2371 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2372 } 2373 2374 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2375 final String[] dexCodeInstructionSets = 2376 getDexCodeInstructionSets( 2377 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2378 2379 /** 2380 * Ensure all external libraries have had dexopt run on them. 2381 */ 2382 if (mSharedLibraries.size() > 0) { 2383 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 2384 // NOTE: For now, we're compiling these system "shared libraries" 2385 // (and framework jars) into all available architectures. It's possible 2386 // to compile them only when we come across an app that uses them (there's 2387 // already logic for that in scanPackageLI) but that adds some complexity. 2388 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2389 final int libCount = mSharedLibraries.size(); 2390 for (int i = 0; i < libCount; i++) { 2391 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 2392 final int versionCount = versionedLib.size(); 2393 for (int j = 0; j < versionCount; j++) { 2394 SharedLibraryEntry libEntry = versionedLib.valueAt(j); 2395 final String libPath = libEntry.path != null 2396 ? libEntry.path : libEntry.apk; 2397 if (libPath == null) { 2398 continue; 2399 } 2400 try { 2401 // Shared libraries do not have profiles so we perform a full 2402 // AOT compilation (if needed). 2403 int dexoptNeeded = DexFile.getDexOptNeeded( 2404 libPath, dexCodeInstructionSet, 2405 getCompilerFilterForReason(REASON_SHARED_APK), 2406 false /* newProfile */); 2407 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2408 mInstaller.dexopt(libPath, Process.SYSTEM_UID, "*", 2409 dexCodeInstructionSet, dexoptNeeded, null, 2410 DEXOPT_PUBLIC, 2411 getCompilerFilterForReason(REASON_SHARED_APK), 2412 StorageManager.UUID_PRIVATE_INTERNAL, 2413 PackageDexOptimizer.SKIP_SHARED_LIBRARY_CHECK); 2414 } 2415 } catch (FileNotFoundException e) { 2416 Slog.w(TAG, "Library not found: " + libPath); 2417 } catch (IOException | InstallerException e) { 2418 Slog.w(TAG, "Cannot dexopt " + libPath + "; is it an APK or JAR? " 2419 + e.getMessage()); 2420 } 2421 } 2422 } 2423 } 2424 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2425 } 2426 2427 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2428 2429 final VersionInfo ver = mSettings.getInternalVersion(); 2430 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2431 2432 // when upgrading from pre-M, promote system app permissions from install to runtime 2433 mPromoteSystemApps = 2434 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2435 2436 // When upgrading from pre-N, we need to handle package extraction like first boot, 2437 // as there is no profiling data available. 2438 mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N; 2439 2440 mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1; 2441 2442 // save off the names of pre-existing system packages prior to scanning; we don't 2443 // want to automatically grant runtime permissions for new system apps 2444 if (mPromoteSystemApps) { 2445 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2446 while (pkgSettingIter.hasNext()) { 2447 PackageSetting ps = pkgSettingIter.next(); 2448 if (isSystemApp(ps)) { 2449 mExistingSystemPackages.add(ps.name); 2450 } 2451 } 2452 } 2453 2454 mCacheDir = preparePackageParserCache(mIsUpgrade); 2455 2456 // Set flag to monitor and not change apk file paths when 2457 // scanning install directories. 2458 int scanFlags = SCAN_BOOTING | SCAN_INITIAL; 2459 2460 if (mIsUpgrade || mFirstBoot) { 2461 scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE; 2462 } 2463 2464 // Collect vendor overlay packages. (Do this before scanning any apps.) 2465 // For security and version matching reason, only consider 2466 // overlay packages if they reside in the right directory. 2467 String overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PERSIST_PROPERTY); 2468 if (overlayThemeDir.isEmpty()) { 2469 overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PROPERTY); 2470 } 2471 if (!overlayThemeDir.isEmpty()) { 2472 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR, overlayThemeDir), mDefParseFlags 2473 | PackageParser.PARSE_IS_SYSTEM 2474 | PackageParser.PARSE_IS_SYSTEM_DIR 2475 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2476 } 2477 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags 2478 | PackageParser.PARSE_IS_SYSTEM 2479 | PackageParser.PARSE_IS_SYSTEM_DIR 2480 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2481 2482 // Find base frameworks (resource packages without code). 2483 scanDirTracedLI(frameworkDir, mDefParseFlags 2484 | PackageParser.PARSE_IS_SYSTEM 2485 | PackageParser.PARSE_IS_SYSTEM_DIR 2486 | PackageParser.PARSE_IS_PRIVILEGED, 2487 scanFlags | SCAN_NO_DEX, 0); 2488 2489 // Collected privileged system packages. 2490 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2491 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2492 | PackageParser.PARSE_IS_SYSTEM 2493 | PackageParser.PARSE_IS_SYSTEM_DIR 2494 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2495 2496 // Collect ordinary system packages. 2497 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2498 scanDirTracedLI(systemAppDir, mDefParseFlags 2499 | PackageParser.PARSE_IS_SYSTEM 2500 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2501 2502 // Collect all vendor packages. 2503 File vendorAppDir = new File("/vendor/app"); 2504 try { 2505 vendorAppDir = vendorAppDir.getCanonicalFile(); 2506 } catch (IOException e) { 2507 // failed to look up canonical path, continue with original one 2508 } 2509 scanDirTracedLI(vendorAppDir, mDefParseFlags 2510 | PackageParser.PARSE_IS_SYSTEM 2511 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2512 2513 // Collect all OEM packages. 2514 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2515 scanDirTracedLI(oemAppDir, mDefParseFlags 2516 | PackageParser.PARSE_IS_SYSTEM 2517 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2518 2519 // Prune any system packages that no longer exist. 2520 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2521 if (!mOnlyCore) { 2522 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2523 while (psit.hasNext()) { 2524 PackageSetting ps = psit.next(); 2525 2526 /* 2527 * If this is not a system app, it can't be a 2528 * disable system app. 2529 */ 2530 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2531 continue; 2532 } 2533 2534 /* 2535 * If the package is scanned, it's not erased. 2536 */ 2537 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2538 if (scannedPkg != null) { 2539 /* 2540 * If the system app is both scanned and in the 2541 * disabled packages list, then it must have been 2542 * added via OTA. Remove it from the currently 2543 * scanned package so the previously user-installed 2544 * application can be scanned. 2545 */ 2546 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2547 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2548 + ps.name + "; removing system app. Last known codePath=" 2549 + ps.codePathString + ", installStatus=" + ps.installStatus 2550 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2551 + scannedPkg.mVersionCode); 2552 removePackageLI(scannedPkg, true); 2553 mExpectingBetter.put(ps.name, ps.codePath); 2554 } 2555 2556 continue; 2557 } 2558 2559 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2560 psit.remove(); 2561 logCriticalInfo(Log.WARN, "System package " + ps.name 2562 + " no longer exists; it's data will be wiped"); 2563 // Actual deletion of code and data will be handled by later 2564 // reconciliation step 2565 } else { 2566 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2567 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2568 possiblyDeletedUpdatedSystemApps.add(ps.name); 2569 } 2570 } 2571 } 2572 } 2573 2574 //look for any incomplete package installations 2575 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2576 for (int i = 0; i < deletePkgsList.size(); i++) { 2577 // Actual deletion of code and data will be handled by later 2578 // reconciliation step 2579 final String packageName = deletePkgsList.get(i).name; 2580 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2581 synchronized (mPackages) { 2582 mSettings.removePackageLPw(packageName); 2583 } 2584 } 2585 2586 //delete tmp files 2587 deleteTempPackageFiles(); 2588 2589 // Remove any shared userIDs that have no associated packages 2590 mSettings.pruneSharedUsersLPw(); 2591 2592 if (!mOnlyCore) { 2593 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2594 SystemClock.uptimeMillis()); 2595 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2596 2597 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2598 | PackageParser.PARSE_FORWARD_LOCK, 2599 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2600 2601 /** 2602 * Remove disable package settings for any updated system 2603 * apps that were removed via an OTA. If they're not a 2604 * previously-updated app, remove them completely. 2605 * Otherwise, just revoke their system-level permissions. 2606 */ 2607 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2608 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2609 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2610 2611 String msg; 2612 if (deletedPkg == null) { 2613 msg = "Updated system package " + deletedAppName 2614 + " no longer exists; it's data will be wiped"; 2615 // Actual deletion of code and data will be handled by later 2616 // reconciliation step 2617 } else { 2618 msg = "Updated system app + " + deletedAppName 2619 + " no longer present; removing system privileges for " 2620 + deletedAppName; 2621 2622 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2623 2624 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2625 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2626 } 2627 logCriticalInfo(Log.WARN, msg); 2628 } 2629 2630 /** 2631 * Make sure all system apps that we expected to appear on 2632 * the userdata partition actually showed up. If they never 2633 * appeared, crawl back and revive the system version. 2634 */ 2635 for (int i = 0; i < mExpectingBetter.size(); i++) { 2636 final String packageName = mExpectingBetter.keyAt(i); 2637 if (!mPackages.containsKey(packageName)) { 2638 final File scanFile = mExpectingBetter.valueAt(i); 2639 2640 logCriticalInfo(Log.WARN, "Expected better " + packageName 2641 + " but never showed up; reverting to system"); 2642 2643 int reparseFlags = mDefParseFlags; 2644 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2645 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2646 | PackageParser.PARSE_IS_SYSTEM_DIR 2647 | PackageParser.PARSE_IS_PRIVILEGED; 2648 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2649 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2650 | PackageParser.PARSE_IS_SYSTEM_DIR; 2651 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2652 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2653 | PackageParser.PARSE_IS_SYSTEM_DIR; 2654 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2655 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2656 | PackageParser.PARSE_IS_SYSTEM_DIR; 2657 } else { 2658 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2659 continue; 2660 } 2661 2662 mSettings.enableSystemPackageLPw(packageName); 2663 2664 try { 2665 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2666 } catch (PackageManagerException e) { 2667 Slog.e(TAG, "Failed to parse original system package: " 2668 + e.getMessage()); 2669 } 2670 } 2671 } 2672 } 2673 mExpectingBetter.clear(); 2674 2675 // Resolve the storage manager. 2676 mStorageManagerPackage = getStorageManagerPackageName(); 2677 2678 // Resolve protected action filters. Only the setup wizard is allowed to 2679 // have a high priority filter for these actions. 2680 mSetupWizardPackage = getSetupWizardPackageName(); 2681 if (mProtectedFilters.size() > 0) { 2682 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2683 Slog.i(TAG, "No setup wizard;" 2684 + " All protected intents capped to priority 0"); 2685 } 2686 for (ActivityIntentInfo filter : mProtectedFilters) { 2687 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2688 if (DEBUG_FILTERS) { 2689 Slog.i(TAG, "Found setup wizard;" 2690 + " allow priority " + filter.getPriority() + ";" 2691 + " package: " + filter.activity.info.packageName 2692 + " activity: " + filter.activity.className 2693 + " priority: " + filter.getPriority()); 2694 } 2695 // skip setup wizard; allow it to keep the high priority filter 2696 continue; 2697 } 2698 Slog.w(TAG, "Protected action; cap priority to 0;" 2699 + " package: " + filter.activity.info.packageName 2700 + " activity: " + filter.activity.className 2701 + " origPrio: " + filter.getPriority()); 2702 filter.setPriority(0); 2703 } 2704 } 2705 mDeferProtectedFilters = false; 2706 mProtectedFilters.clear(); 2707 2708 // Now that we know all of the shared libraries, update all clients to have 2709 // the correct library paths. 2710 updateAllSharedLibrariesLPw(null); 2711 2712 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2713 // NOTE: We ignore potential failures here during a system scan (like 2714 // the rest of the commands above) because there's precious little we 2715 // can do about it. A settings error is reported, though. 2716 adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/); 2717 } 2718 2719 // Now that we know all the packages we are keeping, 2720 // read and update their last usage times. 2721 mPackageUsage.read(mPackages); 2722 mCompilerStats.read(); 2723 2724 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2725 SystemClock.uptimeMillis()); 2726 Slog.i(TAG, "Time to scan packages: " 2727 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2728 + " seconds"); 2729 2730 // If the platform SDK has changed since the last time we booted, 2731 // we need to re-grant app permission to catch any new ones that 2732 // appear. This is really a hack, and means that apps can in some 2733 // cases get permissions that the user didn't initially explicitly 2734 // allow... it would be nice to have some better way to handle 2735 // this situation. 2736 int updateFlags = UPDATE_PERMISSIONS_ALL; 2737 if (ver.sdkVersion != mSdkVersion) { 2738 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2739 + mSdkVersion + "; regranting permissions for internal storage"); 2740 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2741 } 2742 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2743 ver.sdkVersion = mSdkVersion; 2744 2745 // If this is the first boot or an update from pre-M, and it is a normal 2746 // boot, then we need to initialize the default preferred apps across 2747 // all defined users. 2748 if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) { 2749 for (UserInfo user : sUserManager.getUsers(true)) { 2750 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2751 applyFactoryDefaultBrowserLPw(user.id); 2752 primeDomainVerificationsLPw(user.id); 2753 } 2754 } 2755 2756 // Prepare storage for system user really early during boot, 2757 // since core system apps like SettingsProvider and SystemUI 2758 // can't wait for user to start 2759 final int storageFlags; 2760 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2761 storageFlags = StorageManager.FLAG_STORAGE_DE; 2762 } else { 2763 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2764 } 2765 List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, 2766 UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */, 2767 true /* onlyCoreApps */); 2768 mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> { 2769 if (deferPackages == null || deferPackages.isEmpty()) { 2770 return; 2771 } 2772 int count = 0; 2773 for (String pkgName : deferPackages) { 2774 PackageParser.Package pkg = null; 2775 synchronized (mPackages) { 2776 PackageSetting ps = mSettings.getPackageLPr(pkgName); 2777 if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) { 2778 pkg = ps.pkg; 2779 } 2780 } 2781 if (pkg != null) { 2782 synchronized (mInstallLock) { 2783 prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags, 2784 true /* maybeMigrateAppData */); 2785 } 2786 count++; 2787 } 2788 } 2789 Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages"); 2790 }, "prepareAppData"); 2791 2792 // If this is first boot after an OTA, and a normal boot, then 2793 // we need to clear code cache directories. 2794 // Note that we do *not* clear the application profiles. These remain valid 2795 // across OTAs and are used to drive profile verification (post OTA) and 2796 // profile compilation (without waiting to collect a fresh set of profiles). 2797 if (mIsUpgrade && !onlyCore) { 2798 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2799 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2800 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2801 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2802 // No apps are running this early, so no need to freeze 2803 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2804 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2805 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2806 } 2807 } 2808 ver.fingerprint = Build.FINGERPRINT; 2809 } 2810 2811 checkDefaultBrowser(); 2812 2813 // clear only after permissions and other defaults have been updated 2814 mExistingSystemPackages.clear(); 2815 mPromoteSystemApps = false; 2816 2817 // All the changes are done during package scanning. 2818 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2819 2820 // can downgrade to reader 2821 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings"); 2822 mSettings.writeLPr(); 2823 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2824 2825 // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty 2826 // early on (before the package manager declares itself as early) because other 2827 // components in the system server might ask for package contexts for these apps. 2828 // 2829 // Note that "onlyCore" in this context means the system is encrypted or encrypting 2830 // (i.e, that the data partition is unavailable). 2831 if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) { 2832 long start = System.nanoTime(); 2833 List<PackageParser.Package> coreApps = new ArrayList<>(); 2834 for (PackageParser.Package pkg : mPackages.values()) { 2835 if (pkg.coreApp) { 2836 coreApps.add(pkg); 2837 } 2838 } 2839 2840 int[] stats = performDexOptUpgrade(coreApps, false, 2841 getCompilerFilterForReason(REASON_CORE_APP)); 2842 2843 final int elapsedTimeSeconds = 2844 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start); 2845 MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds); 2846 2847 if (DEBUG_DEXOPT) { 2848 Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" + 2849 stats[0] + ", " + stats[1] + ", " + stats[2] + ")"); 2850 } 2851 2852 2853 // TODO: Should we log these stats to tron too ? 2854 // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]); 2855 // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]); 2856 // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]); 2857 // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size()); 2858 } 2859 2860 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2861 SystemClock.uptimeMillis()); 2862 2863 if (!mOnlyCore) { 2864 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2865 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2866 mRequiredUninstallerPackage = getRequiredUninstallerLPr(); 2867 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2868 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2869 mIntentFilterVerifierComponent); 2870 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2871 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES, 2872 SharedLibraryInfo.VERSION_UNDEFINED); 2873 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2874 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED, 2875 SharedLibraryInfo.VERSION_UNDEFINED); 2876 } else { 2877 mRequiredVerifierPackage = null; 2878 mRequiredInstallerPackage = null; 2879 mRequiredUninstallerPackage = null; 2880 mIntentFilterVerifierComponent = null; 2881 mIntentFilterVerifier = null; 2882 mServicesSystemSharedLibraryPackageName = null; 2883 mSharedSystemSharedLibraryPackageName = null; 2884 } 2885 2886 mInstallerService = new PackageInstallerService(context, this); 2887 2888 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2889 if (ephemeralResolverComponent != null) { 2890 if (DEBUG_EPHEMERAL) { 2891 Slog.i(TAG, "Ephemeral resolver: " + ephemeralResolverComponent); 2892 } 2893 mEphemeralResolverConnection = 2894 new EphemeralResolverConnection(mContext, ephemeralResolverComponent); 2895 } else { 2896 mEphemeralResolverConnection = null; 2897 } 2898 mEphemeralInstallerComponent = getEphemeralInstallerLPr(); 2899 if (mEphemeralInstallerComponent != null) { 2900 if (DEBUG_EPHEMERAL) { 2901 Slog.i(TAG, "Ephemeral installer: " + mEphemeralInstallerComponent); 2902 } 2903 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2904 } 2905 2906 // Read and update the usage of dex files. 2907 // Do this at the end of PM init so that all the packages have their 2908 // data directory reconciled. 2909 // At this point we know the code paths of the packages, so we can validate 2910 // the disk file and build the internal cache. 2911 // The usage file is expected to be small so loading and verifying it 2912 // should take a fairly small time compare to the other activities (e.g. package 2913 // scanning). 2914 final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>(); 2915 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 2916 for (int userId : currentUserIds) { 2917 userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList()); 2918 } 2919 mDexManager.load(userPackages); 2920 } // synchronized (mPackages) 2921 } // synchronized (mInstallLock) 2922 2923 // Now after opening every single application zip, make sure they 2924 // are all flushed. Not really needed, but keeps things nice and 2925 // tidy. 2926 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC"); 2927 Runtime.getRuntime().gc(); 2928 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2929 2930 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks"); 2931 FallbackCategoryProvider.loadFallbacks(); 2932 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2933 2934 // The initial scanning above does many calls into installd while 2935 // holding the mPackages lock, but we're mostly interested in yelling 2936 // once we have a booted system. 2937 mInstaller.setWarnIfHeld(mPackages); 2938 2939 // Expose private service for system components to use. 2940 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2941 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2942 } 2943 2944 private static File preparePackageParserCache(boolean isUpgrade) { 2945 if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) { 2946 return null; 2947 } 2948 2949 // Disable package parsing on eng builds to allow for faster incremental development. 2950 if ("eng".equals(Build.TYPE)) { 2951 return null; 2952 } 2953 2954 if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) { 2955 Slog.i(TAG, "Disabling package parser cache due to system property."); 2956 return null; 2957 } 2958 2959 // The base directory for the package parser cache lives under /data/system/. 2960 final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(), 2961 "package_cache"); 2962 if (cacheBaseDir == null) { 2963 return null; 2964 } 2965 2966 // If this is a system upgrade scenario, delete the contents of the package cache dir. 2967 // This also serves to "GC" unused entries when the package cache version changes (which 2968 // can only happen during upgrades). 2969 if (isUpgrade) { 2970 FileUtils.deleteContents(cacheBaseDir); 2971 } 2972 2973 2974 // Return the versioned package cache directory. This is something like 2975 // "/data/system/package_cache/1" 2976 File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION); 2977 2978 // The following is a workaround to aid development on non-numbered userdebug 2979 // builds or cases where "adb sync" is used on userdebug builds. If we detect that 2980 // the system partition is newer. 2981 // 2982 // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build 2983 // that starts with "eng." to signify that this is an engineering build and not 2984 // destined for release. 2985 if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) { 2986 Slog.w(TAG, "Wiping cache directory because the system partition changed."); 2987 2988 // Heuristic: If the /system directory has been modified recently due to an "adb sync" 2989 // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable 2990 // in general and should not be used for production changes. In this specific case, 2991 // we know that they will work. 2992 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2993 if (cacheDir.lastModified() < frameworkDir.lastModified()) { 2994 FileUtils.deleteContents(cacheBaseDir); 2995 cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION); 2996 } 2997 } 2998 2999 return cacheDir; 3000 } 3001 3002 @Override 3003 public boolean isFirstBoot() { 3004 return mFirstBoot; 3005 } 3006 3007 @Override 3008 public boolean isOnlyCoreApps() { 3009 return mOnlyCore; 3010 } 3011 3012 @Override 3013 public boolean isUpgrade() { 3014 return mIsUpgrade; 3015 } 3016 3017 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 3018 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 3019 3020 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 3021 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3022 UserHandle.USER_SYSTEM); 3023 if (matches.size() == 1) { 3024 return matches.get(0).getComponentInfo().packageName; 3025 } else if (matches.size() == 0) { 3026 Log.e(TAG, "There should probably be a verifier, but, none were found"); 3027 return null; 3028 } 3029 throw new RuntimeException("There must be exactly one verifier; found " + matches); 3030 } 3031 3032 private @NonNull String getRequiredSharedLibraryLPr(String name, int version) { 3033 synchronized (mPackages) { 3034 SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version); 3035 if (libraryEntry == null) { 3036 throw new IllegalStateException("Missing required shared library:" + name); 3037 } 3038 return libraryEntry.apk; 3039 } 3040 } 3041 3042 private @NonNull String getRequiredInstallerLPr() { 3043 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 3044 intent.addCategory(Intent.CATEGORY_DEFAULT); 3045 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 3046 3047 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3048 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3049 UserHandle.USER_SYSTEM); 3050 if (matches.size() == 1) { 3051 ResolveInfo resolveInfo = matches.get(0); 3052 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 3053 throw new RuntimeException("The installer must be a privileged app"); 3054 } 3055 return matches.get(0).getComponentInfo().packageName; 3056 } else { 3057 throw new RuntimeException("There must be exactly one installer; found " + matches); 3058 } 3059 } 3060 3061 private @NonNull String getRequiredUninstallerLPr() { 3062 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 3063 intent.addCategory(Intent.CATEGORY_DEFAULT); 3064 intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null)); 3065 3066 final ResolveInfo resolveInfo = resolveIntent(intent, null, 3067 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3068 UserHandle.USER_SYSTEM); 3069 if (resolveInfo == null || 3070 mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) { 3071 throw new RuntimeException("There must be exactly one uninstaller; found " 3072 + resolveInfo); 3073 } 3074 return resolveInfo.getComponentInfo().packageName; 3075 } 3076 3077 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 3078 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 3079 3080 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 3081 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3082 UserHandle.USER_SYSTEM); 3083 ResolveInfo best = null; 3084 final int N = matches.size(); 3085 for (int i = 0; i < N; i++) { 3086 final ResolveInfo cur = matches.get(i); 3087 final String packageName = cur.getComponentInfo().packageName; 3088 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 3089 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 3090 continue; 3091 } 3092 3093 if (best == null || cur.priority > best.priority) { 3094 best = cur; 3095 } 3096 } 3097 3098 if (best != null) { 3099 return best.getComponentInfo().getComponentName(); 3100 } else { 3101 throw new RuntimeException("There must be at least one intent filter verifier"); 3102 } 3103 } 3104 3105 private @Nullable ComponentName getEphemeralResolverLPr() { 3106 final String[] packageArray = 3107 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 3108 if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) { 3109 if (DEBUG_EPHEMERAL) { 3110 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 3111 } 3112 return null; 3113 } 3114 3115 final int resolveFlags = 3116 MATCH_DIRECT_BOOT_AWARE 3117 | MATCH_DIRECT_BOOT_UNAWARE 3118 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3119 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 3120 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 3121 resolveFlags, UserHandle.USER_SYSTEM); 3122 3123 final int N = resolvers.size(); 3124 if (N == 0) { 3125 if (DEBUG_EPHEMERAL) { 3126 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 3127 } 3128 return null; 3129 } 3130 3131 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 3132 for (int i = 0; i < N; i++) { 3133 final ResolveInfo info = resolvers.get(i); 3134 3135 if (info.serviceInfo == null) { 3136 continue; 3137 } 3138 3139 final String packageName = info.serviceInfo.packageName; 3140 if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) { 3141 if (DEBUG_EPHEMERAL) { 3142 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 3143 + " pkg: " + packageName + ", info:" + info); 3144 } 3145 continue; 3146 } 3147 3148 if (DEBUG_EPHEMERAL) { 3149 Slog.v(TAG, "Ephemeral resolver found;" 3150 + " pkg: " + packageName + ", info:" + info); 3151 } 3152 return new ComponentName(packageName, info.serviceInfo.name); 3153 } 3154 if (DEBUG_EPHEMERAL) { 3155 Slog.v(TAG, "Ephemeral resolver NOT found"); 3156 } 3157 return null; 3158 } 3159 3160 private @Nullable ComponentName getEphemeralInstallerLPr() { 3161 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 3162 intent.addCategory(Intent.CATEGORY_DEFAULT); 3163 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 3164 3165 final int resolveFlags = 3166 MATCH_DIRECT_BOOT_AWARE 3167 | MATCH_DIRECT_BOOT_UNAWARE 3168 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3169 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3170 resolveFlags, UserHandle.USER_SYSTEM); 3171 Iterator<ResolveInfo> iter = matches.iterator(); 3172 while (iter.hasNext()) { 3173 final ResolveInfo rInfo = iter.next(); 3174 final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName); 3175 if (ps != null) { 3176 final PermissionsState permissionsState = ps.getPermissionsState(); 3177 if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) { 3178 continue; 3179 } 3180 } 3181 iter.remove(); 3182 } 3183 if (matches.size() == 0) { 3184 return null; 3185 } else if (matches.size() == 1) { 3186 return matches.get(0).getComponentInfo().getComponentName(); 3187 } else { 3188 throw new RuntimeException( 3189 "There must be at most one ephemeral installer; found " + matches); 3190 } 3191 } 3192 3193 private void primeDomainVerificationsLPw(int userId) { 3194 if (DEBUG_DOMAIN_VERIFICATION) { 3195 Slog.d(TAG, "Priming domain verifications in user " + userId); 3196 } 3197 3198 SystemConfig systemConfig = SystemConfig.getInstance(); 3199 ArraySet<String> packages = systemConfig.getLinkedApps(); 3200 3201 for (String packageName : packages) { 3202 PackageParser.Package pkg = mPackages.get(packageName); 3203 if (pkg != null) { 3204 if (!pkg.isSystemApp()) { 3205 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 3206 continue; 3207 } 3208 3209 ArraySet<String> domains = null; 3210 for (PackageParser.Activity a : pkg.activities) { 3211 for (ActivityIntentInfo filter : a.intents) { 3212 if (hasValidDomains(filter)) { 3213 if (domains == null) { 3214 domains = new ArraySet<String>(); 3215 } 3216 domains.addAll(filter.getHostsList()); 3217 } 3218 } 3219 } 3220 3221 if (domains != null && domains.size() > 0) { 3222 if (DEBUG_DOMAIN_VERIFICATION) { 3223 Slog.v(TAG, " + " + packageName); 3224 } 3225 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 3226 // state w.r.t. the formal app-linkage "no verification attempted" state; 3227 // and then 'always' in the per-user state actually used for intent resolution. 3228 final IntentFilterVerificationInfo ivi; 3229 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains); 3230 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 3231 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 3232 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 3233 } else { 3234 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 3235 + "' does not handle web links"); 3236 } 3237 } else { 3238 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 3239 } 3240 } 3241 3242 scheduleWritePackageRestrictionsLocked(userId); 3243 scheduleWriteSettingsLocked(); 3244 } 3245 3246 private void applyFactoryDefaultBrowserLPw(int userId) { 3247 // The default browser app's package name is stored in a string resource, 3248 // with a product-specific overlay used for vendor customization. 3249 String browserPkg = mContext.getResources().getString( 3250 com.android.internal.R.string.default_browser); 3251 if (!TextUtils.isEmpty(browserPkg)) { 3252 // non-empty string => required to be a known package 3253 PackageSetting ps = mSettings.mPackages.get(browserPkg); 3254 if (ps == null) { 3255 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 3256 browserPkg = null; 3257 } else { 3258 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3259 } 3260 } 3261 3262 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3263 // default. If there's more than one, just leave everything alone. 3264 if (browserPkg == null) { 3265 calculateDefaultBrowserLPw(userId); 3266 } 3267 } 3268 3269 private void calculateDefaultBrowserLPw(int userId) { 3270 List<String> allBrowsers = resolveAllBrowserApps(userId); 3271 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3272 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3273 } 3274 3275 private List<String> resolveAllBrowserApps(int userId) { 3276 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3277 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3278 PackageManager.MATCH_ALL, userId); 3279 3280 final int count = list.size(); 3281 List<String> result = new ArrayList<String>(count); 3282 for (int i=0; i<count; i++) { 3283 ResolveInfo info = list.get(i); 3284 if (info.activityInfo == null 3285 || !info.handleAllWebDataURI 3286 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3287 || result.contains(info.activityInfo.packageName)) { 3288 continue; 3289 } 3290 result.add(info.activityInfo.packageName); 3291 } 3292 3293 return result; 3294 } 3295 3296 private boolean packageIsBrowser(String packageName, int userId) { 3297 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3298 PackageManager.MATCH_ALL, userId); 3299 final int N = list.size(); 3300 for (int i = 0; i < N; i++) { 3301 ResolveInfo info = list.get(i); 3302 if (packageName.equals(info.activityInfo.packageName)) { 3303 return true; 3304 } 3305 } 3306 return false; 3307 } 3308 3309 private void checkDefaultBrowser() { 3310 final int myUserId = UserHandle.myUserId(); 3311 final String packageName = getDefaultBrowserPackageName(myUserId); 3312 if (packageName != null) { 3313 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3314 if (info == null) { 3315 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3316 synchronized (mPackages) { 3317 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3318 } 3319 } 3320 } 3321 } 3322 3323 @Override 3324 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3325 throws RemoteException { 3326 try { 3327 return super.onTransact(code, data, reply, flags); 3328 } catch (RuntimeException e) { 3329 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3330 Slog.wtf(TAG, "Package Manager Crash", e); 3331 } 3332 throw e; 3333 } 3334 } 3335 3336 static int[] appendInts(int[] cur, int[] add) { 3337 if (add == null) return cur; 3338 if (cur == null) return add; 3339 final int N = add.length; 3340 for (int i=0; i<N; i++) { 3341 cur = appendInt(cur, add[i]); 3342 } 3343 return cur; 3344 } 3345 3346 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3347 if (!sUserManager.exists(userId)) return null; 3348 if (ps == null) { 3349 return null; 3350 } 3351 final PackageParser.Package p = ps.pkg; 3352 if (p == null) { 3353 return null; 3354 } 3355 // Filter out ephemeral app metadata: 3356 // * The system/shell/root can see metadata for any app 3357 // * An installed app can see metadata for 1) other installed apps 3358 // and 2) ephemeral apps that have explicitly interacted with it 3359 // * Ephemeral apps can only see their own metadata 3360 // * Holding a signature permission allows seeing instant apps 3361 final int callingAppId = UserHandle.getAppId(Binder.getCallingUid()); 3362 if (callingAppId != Process.SYSTEM_UID 3363 && callingAppId != Process.SHELL_UID 3364 && callingAppId != Process.ROOT_UID 3365 && checkUidPermission(Manifest.permission.ACCESS_INSTANT_APPS, 3366 Binder.getCallingUid()) != PackageManager.PERMISSION_GRANTED) { 3367 final String instantAppPackageName = getInstantAppPackageName(Binder.getCallingUid()); 3368 if (instantAppPackageName != null) { 3369 // ephemeral apps can only get information on themselves 3370 if (!instantAppPackageName.equals(p.packageName)) { 3371 return null; 3372 } 3373 } else { 3374 if (ps.getInstantApp(userId)) { 3375 // only get access to the ephemeral app if we've been granted access 3376 if (!mInstantAppRegistry.isInstantAccessGranted( 3377 userId, callingAppId, ps.appId)) { 3378 return null; 3379 } 3380 } 3381 } 3382 } 3383 3384 final PermissionsState permissionsState = ps.getPermissionsState(); 3385 3386 // Compute GIDs only if requested 3387 final int[] gids = (flags & PackageManager.GET_GIDS) == 0 3388 ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId); 3389 // Compute granted permissions only if package has requested permissions 3390 final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions) 3391 ? Collections.<String>emptySet() : permissionsState.getPermissions(userId); 3392 final PackageUserState state = ps.readUserState(userId); 3393 3394 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0 3395 && ps.isSystem()) { 3396 flags |= MATCH_ANY_USER; 3397 } 3398 3399 PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags, 3400 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3401 3402 if (packageInfo == null) { 3403 return null; 3404 } 3405 3406 packageInfo.packageName = packageInfo.applicationInfo.packageName = 3407 resolveExternalPackageNameLPr(p); 3408 3409 return packageInfo; 3410 } 3411 3412 @Override 3413 public void checkPackageStartable(String packageName, int userId) { 3414 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3415 3416 synchronized (mPackages) { 3417 final PackageSetting ps = mSettings.mPackages.get(packageName); 3418 if (ps == null) { 3419 throw new SecurityException("Package " + packageName + " was not found!"); 3420 } 3421 3422 if (!ps.getInstalled(userId)) { 3423 throw new SecurityException( 3424 "Package " + packageName + " was not installed for user " + userId + "!"); 3425 } 3426 3427 if (mSafeMode && !ps.isSystem()) { 3428 throw new SecurityException("Package " + packageName + " not a system app!"); 3429 } 3430 3431 if (mFrozenPackages.contains(packageName)) { 3432 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3433 } 3434 3435 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3436 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3437 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3438 } 3439 } 3440 } 3441 3442 @Override 3443 public boolean isPackageAvailable(String packageName, int userId) { 3444 if (!sUserManager.exists(userId)) return false; 3445 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3446 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3447 synchronized (mPackages) { 3448 PackageParser.Package p = mPackages.get(packageName); 3449 if (p != null) { 3450 final PackageSetting ps = (PackageSetting) p.mExtras; 3451 if (ps != null) { 3452 final PackageUserState state = ps.readUserState(userId); 3453 if (state != null) { 3454 return PackageParser.isAvailable(state); 3455 } 3456 } 3457 } 3458 } 3459 return false; 3460 } 3461 3462 @Override 3463 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3464 return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST, 3465 flags, userId); 3466 } 3467 3468 @Override 3469 public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage, 3470 int flags, int userId) { 3471 return getPackageInfoInternal(versionedPackage.getPackageName(), 3472 // TODO: We will change version code to long, so in the new API it is long 3473 (int) versionedPackage.getVersionCode(), flags, userId); 3474 } 3475 3476 private PackageInfo getPackageInfoInternal(String packageName, int versionCode, 3477 int flags, int userId) { 3478 if (!sUserManager.exists(userId)) return null; 3479 flags = updateFlagsForPackage(flags, userId, packageName); 3480 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3481 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3482 3483 // reader 3484 synchronized (mPackages) { 3485 // Normalize package name to handle renamed packages and static libs 3486 packageName = resolveInternalPackageNameLPr(packageName, versionCode); 3487 3488 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3489 if (matchFactoryOnly) { 3490 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3491 if (ps != null) { 3492 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 3493 return null; 3494 } 3495 return generatePackageInfo(ps, flags, userId); 3496 } 3497 } 3498 3499 PackageParser.Package p = mPackages.get(packageName); 3500 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3501 return null; 3502 } 3503 if (DEBUG_PACKAGE_INFO) 3504 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3505 if (p != null) { 3506 if (filterSharedLibPackageLPr((PackageSetting) p.mExtras, 3507 Binder.getCallingUid(), userId)) { 3508 return null; 3509 } 3510 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3511 } 3512 if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) { 3513 final PackageSetting ps = mSettings.mPackages.get(packageName); 3514 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 3515 return null; 3516 } 3517 return generatePackageInfo(ps, flags, userId); 3518 } 3519 } 3520 return null; 3521 } 3522 3523 3524 private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId) { 3525 // System/shell/root get to see all static libs 3526 final int appId = UserHandle.getAppId(uid); 3527 if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID 3528 || appId == Process.ROOT_UID) { 3529 return false; 3530 } 3531 3532 // No package means no static lib as it is always on internal storage 3533 if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) { 3534 return false; 3535 } 3536 3537 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName, 3538 ps.pkg.staticSharedLibVersion); 3539 if (libEntry == null) { 3540 return false; 3541 } 3542 3543 final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid)); 3544 final String[] uidPackageNames = getPackagesForUid(resolvedUid); 3545 if (uidPackageNames == null) { 3546 return true; 3547 } 3548 3549 for (String uidPackageName : uidPackageNames) { 3550 if (ps.name.equals(uidPackageName)) { 3551 return false; 3552 } 3553 PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName); 3554 if (uidPs != null) { 3555 final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries, 3556 libEntry.info.getName()); 3557 if (index < 0) { 3558 continue; 3559 } 3560 if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) { 3561 return false; 3562 } 3563 } 3564 } 3565 return true; 3566 } 3567 3568 @Override 3569 public String[] currentToCanonicalPackageNames(String[] names) { 3570 String[] out = new String[names.length]; 3571 // reader 3572 synchronized (mPackages) { 3573 for (int i=names.length-1; i>=0; i--) { 3574 PackageSetting ps = mSettings.mPackages.get(names[i]); 3575 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3576 } 3577 } 3578 return out; 3579 } 3580 3581 @Override 3582 public String[] canonicalToCurrentPackageNames(String[] names) { 3583 String[] out = new String[names.length]; 3584 // reader 3585 synchronized (mPackages) { 3586 for (int i=names.length-1; i>=0; i--) { 3587 String cur = mSettings.getRenamedPackageLPr(names[i]); 3588 out[i] = cur != null ? cur : names[i]; 3589 } 3590 } 3591 return out; 3592 } 3593 3594 @Override 3595 public int getPackageUid(String packageName, int flags, int userId) { 3596 if (!sUserManager.exists(userId)) return -1; 3597 flags = updateFlagsForPackage(flags, userId, packageName); 3598 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3599 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3600 3601 // reader 3602 synchronized (mPackages) { 3603 final PackageParser.Package p = mPackages.get(packageName); 3604 if (p != null && p.isMatch(flags)) { 3605 return UserHandle.getUid(userId, p.applicationInfo.uid); 3606 } 3607 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3608 final PackageSetting ps = mSettings.mPackages.get(packageName); 3609 if (ps != null && ps.isMatch(flags)) { 3610 return UserHandle.getUid(userId, ps.appId); 3611 } 3612 } 3613 } 3614 3615 return -1; 3616 } 3617 3618 @Override 3619 public int[] getPackageGids(String packageName, int flags, int userId) { 3620 if (!sUserManager.exists(userId)) return null; 3621 flags = updateFlagsForPackage(flags, userId, packageName); 3622 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3623 false /* requireFullPermission */, false /* checkShell */, 3624 "getPackageGids"); 3625 3626 // reader 3627 synchronized (mPackages) { 3628 final PackageParser.Package p = mPackages.get(packageName); 3629 if (p != null && p.isMatch(flags)) { 3630 PackageSetting ps = (PackageSetting) p.mExtras; 3631 // TODO: Shouldn't this be checking for package installed state for userId and 3632 // return null? 3633 return ps.getPermissionsState().computeGids(userId); 3634 } 3635 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3636 final PackageSetting ps = mSettings.mPackages.get(packageName); 3637 if (ps != null && ps.isMatch(flags)) { 3638 return ps.getPermissionsState().computeGids(userId); 3639 } 3640 } 3641 } 3642 3643 return null; 3644 } 3645 3646 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3647 if (bp.perm != null) { 3648 return PackageParser.generatePermissionInfo(bp.perm, flags); 3649 } 3650 PermissionInfo pi = new PermissionInfo(); 3651 pi.name = bp.name; 3652 pi.packageName = bp.sourcePackage; 3653 pi.nonLocalizedLabel = bp.name; 3654 pi.protectionLevel = bp.protectionLevel; 3655 return pi; 3656 } 3657 3658 @Override 3659 public PermissionInfo getPermissionInfo(String name, int flags) { 3660 // reader 3661 synchronized (mPackages) { 3662 final BasePermission p = mSettings.mPermissions.get(name); 3663 if (p != null) { 3664 return generatePermissionInfo(p, flags); 3665 } 3666 return null; 3667 } 3668 } 3669 3670 @Override 3671 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3672 int flags) { 3673 // reader 3674 synchronized (mPackages) { 3675 if (group != null && !mPermissionGroups.containsKey(group)) { 3676 // This is thrown as NameNotFoundException 3677 return null; 3678 } 3679 3680 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3681 for (BasePermission p : mSettings.mPermissions.values()) { 3682 if (group == null) { 3683 if (p.perm == null || p.perm.info.group == null) { 3684 out.add(generatePermissionInfo(p, flags)); 3685 } 3686 } else { 3687 if (p.perm != null && group.equals(p.perm.info.group)) { 3688 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3689 } 3690 } 3691 } 3692 return new ParceledListSlice<>(out); 3693 } 3694 } 3695 3696 @Override 3697 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3698 // reader 3699 synchronized (mPackages) { 3700 return PackageParser.generatePermissionGroupInfo( 3701 mPermissionGroups.get(name), flags); 3702 } 3703 } 3704 3705 @Override 3706 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3707 // reader 3708 synchronized (mPackages) { 3709 final int N = mPermissionGroups.size(); 3710 ArrayList<PermissionGroupInfo> out 3711 = new ArrayList<PermissionGroupInfo>(N); 3712 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3713 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3714 } 3715 return new ParceledListSlice<>(out); 3716 } 3717 } 3718 3719 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3720 int uid, int userId) { 3721 if (!sUserManager.exists(userId)) return null; 3722 PackageSetting ps = mSettings.mPackages.get(packageName); 3723 if (ps != null) { 3724 if (filterSharedLibPackageLPr(ps, uid, userId)) { 3725 return null; 3726 } 3727 if (ps.pkg == null) { 3728 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3729 if (pInfo != null) { 3730 return pInfo.applicationInfo; 3731 } 3732 return null; 3733 } 3734 ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 3735 ps.readUserState(userId), userId); 3736 if (ai != null) { 3737 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 3738 } 3739 return ai; 3740 } 3741 return null; 3742 } 3743 3744 @Override 3745 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3746 if (!sUserManager.exists(userId)) return null; 3747 flags = updateFlagsForApplication(flags, userId, packageName); 3748 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3749 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3750 3751 // writer 3752 synchronized (mPackages) { 3753 // Normalize package name to handle renamed packages and static libs 3754 packageName = resolveInternalPackageNameLPr(packageName, 3755 PackageManager.VERSION_CODE_HIGHEST); 3756 3757 PackageParser.Package p = mPackages.get(packageName); 3758 if (DEBUG_PACKAGE_INFO) Log.v( 3759 TAG, "getApplicationInfo " + packageName 3760 + ": " + p); 3761 if (p != null) { 3762 PackageSetting ps = mSettings.mPackages.get(packageName); 3763 if (ps == null) return null; 3764 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 3765 return null; 3766 } 3767 // Note: isEnabledLP() does not apply here - always return info 3768 ApplicationInfo ai = PackageParser.generateApplicationInfo( 3769 p, flags, ps.readUserState(userId), userId); 3770 if (ai != null) { 3771 ai.packageName = resolveExternalPackageNameLPr(p); 3772 } 3773 return ai; 3774 } 3775 if ("android".equals(packageName)||"system".equals(packageName)) { 3776 return mAndroidApplication; 3777 } 3778 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3779 // Already generates the external package name 3780 return generateApplicationInfoFromSettingsLPw(packageName, 3781 Binder.getCallingUid(), flags, userId); 3782 } 3783 } 3784 return null; 3785 } 3786 3787 private String normalizePackageNameLPr(String packageName) { 3788 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 3789 return normalizedPackageName != null ? normalizedPackageName : packageName; 3790 } 3791 3792 @Override 3793 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3794 final IPackageDataObserver observer) { 3795 mContext.enforceCallingOrSelfPermission( 3796 android.Manifest.permission.CLEAR_APP_CACHE, null); 3797 // Queue up an async operation since clearing cache may take a little while. 3798 mHandler.post(new Runnable() { 3799 public void run() { 3800 mHandler.removeCallbacks(this); 3801 boolean success = true; 3802 synchronized (mInstallLock) { 3803 try { 3804 mInstaller.freeCache(volumeUuid, freeStorageSize, 0); 3805 } catch (InstallerException e) { 3806 Slog.w(TAG, "Couldn't clear application caches: " + e); 3807 success = false; 3808 } 3809 } 3810 if (observer != null) { 3811 try { 3812 observer.onRemoveCompleted(null, success); 3813 } catch (RemoteException e) { 3814 Slog.w(TAG, "RemoveException when invoking call back"); 3815 } 3816 } 3817 } 3818 }); 3819 } 3820 3821 @Override 3822 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3823 final IntentSender pi) { 3824 mContext.enforceCallingOrSelfPermission( 3825 android.Manifest.permission.CLEAR_APP_CACHE, null); 3826 // Queue up an async operation since clearing cache may take a little while. 3827 mHandler.post(new Runnable() { 3828 public void run() { 3829 mHandler.removeCallbacks(this); 3830 boolean success = true; 3831 synchronized (mInstallLock) { 3832 try { 3833 mInstaller.freeCache(volumeUuid, freeStorageSize, 0); 3834 } catch (InstallerException e) { 3835 Slog.w(TAG, "Couldn't clear application caches: " + e); 3836 success = false; 3837 } 3838 } 3839 if(pi != null) { 3840 try { 3841 // Callback via pending intent 3842 int code = success ? 1 : 0; 3843 pi.sendIntent(null, code, null, 3844 null, null); 3845 } catch (SendIntentException e1) { 3846 Slog.i(TAG, "Failed to send pending intent"); 3847 } 3848 } 3849 } 3850 }); 3851 } 3852 3853 public void freeStorage(String volumeUuid, long freeStorageSize, int storageFlags) 3854 throws IOException { 3855 synchronized (mInstallLock) { 3856 try { 3857 mInstaller.freeCache(volumeUuid, freeStorageSize, 0); 3858 } catch (InstallerException e) { 3859 throw new IOException("Failed to free enough space", e); 3860 } 3861 } 3862 } 3863 3864 /** 3865 * Update given flags based on encryption status of current user. 3866 */ 3867 private int updateFlags(int flags, int userId) { 3868 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3869 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3870 // Caller expressed an explicit opinion about what encryption 3871 // aware/unaware components they want to see, so fall through and 3872 // give them what they want 3873 } else { 3874 // Caller expressed no opinion, so match based on user state 3875 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 3876 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3877 } else { 3878 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3879 } 3880 } 3881 return flags; 3882 } 3883 3884 private UserManagerInternal getUserManagerInternal() { 3885 if (mUserManagerInternal == null) { 3886 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 3887 } 3888 return mUserManagerInternal; 3889 } 3890 3891 private DeviceIdleController.LocalService getDeviceIdleController() { 3892 if (mDeviceIdleController == null) { 3893 mDeviceIdleController = 3894 LocalServices.getService(DeviceIdleController.LocalService.class); 3895 } 3896 return mDeviceIdleController; 3897 } 3898 3899 /** 3900 * Update given flags when being used to request {@link PackageInfo}. 3901 */ 3902 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3903 final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM; 3904 boolean triaged = true; 3905 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3906 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3907 // Caller is asking for component details, so they'd better be 3908 // asking for specific encryption matching behavior, or be triaged 3909 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3910 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3911 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3912 triaged = false; 3913 } 3914 } 3915 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3916 | PackageManager.MATCH_SYSTEM_ONLY 3917 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3918 triaged = false; 3919 } 3920 if ((flags & PackageManager.MATCH_ANY_USER) != 0) { 3921 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 3922 "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at " 3923 + Debug.getCallers(5)); 3924 } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser 3925 && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) { 3926 // If the caller wants all packages and has a restricted profile associated with it, 3927 // then match all users. This is to make sure that launchers that need to access work 3928 // profile apps don't start breaking. TODO: Remove this hack when launchers stop using 3929 // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380 3930 flags |= PackageManager.MATCH_ANY_USER; 3931 } 3932 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3933 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3934 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3935 } 3936 return updateFlags(flags, userId); 3937 } 3938 3939 /** 3940 * Update given flags when being used to request {@link ApplicationInfo}. 3941 */ 3942 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3943 return updateFlagsForPackage(flags, userId, cookie); 3944 } 3945 3946 /** 3947 * Update given flags when being used to request {@link ComponentInfo}. 3948 */ 3949 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3950 if (cookie instanceof Intent) { 3951 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3952 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3953 } 3954 } 3955 3956 boolean triaged = true; 3957 // Caller is asking for component details, so they'd better be 3958 // asking for specific encryption matching behavior, or be triaged 3959 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3960 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3961 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3962 triaged = false; 3963 } 3964 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3965 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3966 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3967 } 3968 3969 return updateFlags(flags, userId); 3970 } 3971 3972 /** 3973 * Update given intent when being used to request {@link ResolveInfo}. 3974 */ 3975 private Intent updateIntentForResolve(Intent intent) { 3976 if (intent.getSelector() != null) { 3977 intent = intent.getSelector(); 3978 } 3979 if (DEBUG_PREFERRED) { 3980 intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3981 } 3982 return intent; 3983 } 3984 3985 /** 3986 * Update given flags when being used to request {@link ResolveInfo}. 3987 */ 3988 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3989 // Safe mode means we shouldn't match any third-party components 3990 if (mSafeMode) { 3991 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3992 } 3993 final int callingUid = Binder.getCallingUid(); 3994 if (getInstantAppPackageName(callingUid) != null) { 3995 // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components 3996 flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY; 3997 flags |= PackageManager.MATCH_INSTANT; 3998 } else { 3999 // Otherwise, prevent leaking ephemeral components 4000 flags &= ~PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY; 4001 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4002 // Unless called from the system process 4003 flags &= ~PackageManager.MATCH_INSTANT; 4004 } 4005 } 4006 return updateFlagsForComponent(flags, userId, cookie); 4007 } 4008 4009 @Override 4010 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 4011 if (!sUserManager.exists(userId)) return null; 4012 flags = updateFlagsForComponent(flags, userId, component); 4013 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4014 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 4015 synchronized (mPackages) { 4016 PackageParser.Activity a = mActivities.mActivities.get(component); 4017 4018 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 4019 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 4020 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4021 if (ps == null) return null; 4022 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 4023 userId); 4024 } 4025 if (mResolveComponentName.equals(component)) { 4026 return PackageParser.generateActivityInfo(mResolveActivity, flags, 4027 new PackageUserState(), userId); 4028 } 4029 } 4030 return null; 4031 } 4032 4033 @Override 4034 public boolean activitySupportsIntent(ComponentName component, Intent intent, 4035 String resolvedType) { 4036 synchronized (mPackages) { 4037 if (component.equals(mResolveComponentName)) { 4038 // The resolver supports EVERYTHING! 4039 return true; 4040 } 4041 PackageParser.Activity a = mActivities.mActivities.get(component); 4042 if (a == null) { 4043 return false; 4044 } 4045 for (int i=0; i<a.intents.size(); i++) { 4046 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 4047 intent.getData(), intent.getCategories(), TAG) >= 0) { 4048 return true; 4049 } 4050 } 4051 return false; 4052 } 4053 } 4054 4055 @Override 4056 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 4057 if (!sUserManager.exists(userId)) return null; 4058 flags = updateFlagsForComponent(flags, userId, component); 4059 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4060 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 4061 synchronized (mPackages) { 4062 PackageParser.Activity a = mReceivers.mActivities.get(component); 4063 if (DEBUG_PACKAGE_INFO) Log.v( 4064 TAG, "getReceiverInfo " + component + ": " + a); 4065 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 4066 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4067 if (ps == null) return null; 4068 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 4069 userId); 4070 } 4071 } 4072 return null; 4073 } 4074 4075 @Override 4076 public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(int flags, int userId) { 4077 if (!sUserManager.exists(userId)) return null; 4078 Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0"); 4079 4080 flags = updateFlagsForPackage(flags, userId, null); 4081 4082 final boolean canSeeStaticLibraries = 4083 mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES) 4084 == PERMISSION_GRANTED 4085 || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES) 4086 == PERMISSION_GRANTED 4087 || mContext.checkCallingOrSelfPermission(REQUEST_INSTALL_PACKAGES) 4088 == PERMISSION_GRANTED 4089 || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES) 4090 == PERMISSION_GRANTED; 4091 4092 synchronized (mPackages) { 4093 List<SharedLibraryInfo> result = null; 4094 4095 final int libCount = mSharedLibraries.size(); 4096 for (int i = 0; i < libCount; i++) { 4097 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 4098 if (versionedLib == null) { 4099 continue; 4100 } 4101 4102 final int versionCount = versionedLib.size(); 4103 for (int j = 0; j < versionCount; j++) { 4104 SharedLibraryInfo libInfo = versionedLib.valueAt(j).info; 4105 if (!canSeeStaticLibraries && libInfo.isStatic()) { 4106 break; 4107 } 4108 final long identity = Binder.clearCallingIdentity(); 4109 try { 4110 // TODO: We will change version code to long, so in the new API it is long 4111 PackageInfo packageInfo = getPackageInfoVersioned( 4112 libInfo.getDeclaringPackage(), flags, userId); 4113 if (packageInfo == null) { 4114 continue; 4115 } 4116 } finally { 4117 Binder.restoreCallingIdentity(identity); 4118 } 4119 4120 SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(), 4121 libInfo.getVersion(), libInfo.getType(), libInfo.getDeclaringPackage(), 4122 getPackagesUsingSharedLibraryLPr(libInfo, flags, userId)); 4123 4124 if (result == null) { 4125 result = new ArrayList<>(); 4126 } 4127 result.add(resLibInfo); 4128 } 4129 } 4130 4131 return result != null ? new ParceledListSlice<>(result) : null; 4132 } 4133 } 4134 4135 private List<VersionedPackage> getPackagesUsingSharedLibraryLPr( 4136 SharedLibraryInfo libInfo, int flags, int userId) { 4137 List<VersionedPackage> versionedPackages = null; 4138 final int packageCount = mSettings.mPackages.size(); 4139 for (int i = 0; i < packageCount; i++) { 4140 PackageSetting ps = mSettings.mPackages.valueAt(i); 4141 4142 if (ps == null) { 4143 continue; 4144 } 4145 4146 if (!ps.getUserState().get(userId).isAvailable(flags)) { 4147 continue; 4148 } 4149 4150 final String libName = libInfo.getName(); 4151 if (libInfo.isStatic()) { 4152 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 4153 if (libIdx < 0) { 4154 continue; 4155 } 4156 if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) { 4157 continue; 4158 } 4159 if (versionedPackages == null) { 4160 versionedPackages = new ArrayList<>(); 4161 } 4162 // If the dependent is a static shared lib, use the public package name 4163 String dependentPackageName = ps.name; 4164 if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) { 4165 dependentPackageName = ps.pkg.manifestPackageName; 4166 } 4167 versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode)); 4168 } else if (ps.pkg != null) { 4169 if (ArrayUtils.contains(ps.pkg.usesLibraries, libName) 4170 || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) { 4171 if (versionedPackages == null) { 4172 versionedPackages = new ArrayList<>(); 4173 } 4174 versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode)); 4175 } 4176 } 4177 } 4178 4179 return versionedPackages; 4180 } 4181 4182 @Override 4183 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 4184 if (!sUserManager.exists(userId)) return null; 4185 flags = updateFlagsForComponent(flags, userId, component); 4186 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4187 false /* requireFullPermission */, false /* checkShell */, "get service info"); 4188 synchronized (mPackages) { 4189 PackageParser.Service s = mServices.mServices.get(component); 4190 if (DEBUG_PACKAGE_INFO) Log.v( 4191 TAG, "getServiceInfo " + component + ": " + s); 4192 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 4193 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4194 if (ps == null) return null; 4195 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 4196 userId); 4197 } 4198 } 4199 return null; 4200 } 4201 4202 @Override 4203 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 4204 if (!sUserManager.exists(userId)) return null; 4205 flags = updateFlagsForComponent(flags, userId, component); 4206 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4207 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 4208 synchronized (mPackages) { 4209 PackageParser.Provider p = mProviders.mProviders.get(component); 4210 if (DEBUG_PACKAGE_INFO) Log.v( 4211 TAG, "getProviderInfo " + component + ": " + p); 4212 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 4213 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4214 if (ps == null) return null; 4215 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 4216 userId); 4217 } 4218 } 4219 return null; 4220 } 4221 4222 @Override 4223 public String[] getSystemSharedLibraryNames() { 4224 synchronized (mPackages) { 4225 Set<String> libs = null; 4226 final int libCount = mSharedLibraries.size(); 4227 for (int i = 0; i < libCount; i++) { 4228 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 4229 if (versionedLib == null) { 4230 continue; 4231 } 4232 final int versionCount = versionedLib.size(); 4233 for (int j = 0; j < versionCount; j++) { 4234 SharedLibraryEntry libEntry = versionedLib.valueAt(j); 4235 if (!libEntry.info.isStatic()) { 4236 if (libs == null) { 4237 libs = new ArraySet<>(); 4238 } 4239 libs.add(libEntry.info.getName()); 4240 break; 4241 } 4242 PackageSetting ps = mSettings.getPackageLPr(libEntry.apk); 4243 if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(), 4244 UserHandle.getUserId(Binder.getCallingUid()))) { 4245 if (libs == null) { 4246 libs = new ArraySet<>(); 4247 } 4248 libs.add(libEntry.info.getName()); 4249 break; 4250 } 4251 } 4252 } 4253 4254 if (libs != null) { 4255 String[] libsArray = new String[libs.size()]; 4256 libs.toArray(libsArray); 4257 return libsArray; 4258 } 4259 4260 return null; 4261 } 4262 } 4263 4264 @Override 4265 public @NonNull String getServicesSystemSharedLibraryPackageName() { 4266 synchronized (mPackages) { 4267 return mServicesSystemSharedLibraryPackageName; 4268 } 4269 } 4270 4271 @Override 4272 public @NonNull String getSharedSystemSharedLibraryPackageName() { 4273 synchronized (mPackages) { 4274 return mSharedSystemSharedLibraryPackageName; 4275 } 4276 } 4277 4278 private void updateSequenceNumberLP(String packageName, int[] userList) { 4279 for (int i = userList.length - 1; i >= 0; --i) { 4280 final int userId = userList[i]; 4281 SparseArray<String> changedPackages = mChangedPackages.get(userId); 4282 if (changedPackages == null) { 4283 changedPackages = new SparseArray<>(); 4284 mChangedPackages.put(userId, changedPackages); 4285 } 4286 Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId); 4287 if (sequenceNumbers == null) { 4288 sequenceNumbers = new HashMap<>(); 4289 mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers); 4290 } 4291 final Integer sequenceNumber = sequenceNumbers.get(packageName); 4292 if (sequenceNumber != null) { 4293 changedPackages.remove(sequenceNumber); 4294 } 4295 changedPackages.put(mChangedPackagesSequenceNumber, packageName); 4296 sequenceNumbers.put(packageName, mChangedPackagesSequenceNumber); 4297 } 4298 mChangedPackagesSequenceNumber++; 4299 } 4300 4301 @Override 4302 public ChangedPackages getChangedPackages(int sequenceNumber, int userId) { 4303 synchronized (mPackages) { 4304 if (sequenceNumber >= mChangedPackagesSequenceNumber) { 4305 return null; 4306 } 4307 final SparseArray<String> changedPackages = mChangedPackages.get(userId); 4308 if (changedPackages == null) { 4309 return null; 4310 } 4311 final List<String> packageNames = 4312 new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber); 4313 for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) { 4314 final String packageName = changedPackages.get(i); 4315 if (packageName != null) { 4316 packageNames.add(packageName); 4317 } 4318 } 4319 return packageNames.isEmpty() 4320 ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames); 4321 } 4322 } 4323 4324 @Override 4325 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 4326 ArrayList<FeatureInfo> res; 4327 synchronized (mAvailableFeatures) { 4328 res = new ArrayList<>(mAvailableFeatures.size() + 1); 4329 res.addAll(mAvailableFeatures.values()); 4330 } 4331 final FeatureInfo fi = new FeatureInfo(); 4332 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 4333 FeatureInfo.GL_ES_VERSION_UNDEFINED); 4334 res.add(fi); 4335 4336 return new ParceledListSlice<>(res); 4337 } 4338 4339 @Override 4340 public boolean hasSystemFeature(String name, int version) { 4341 synchronized (mAvailableFeatures) { 4342 final FeatureInfo feat = mAvailableFeatures.get(name); 4343 if (feat == null) { 4344 return false; 4345 } else { 4346 return feat.version >= version; 4347 } 4348 } 4349 } 4350 4351 @Override 4352 public int checkPermission(String permName, String pkgName, int userId) { 4353 if (!sUserManager.exists(userId)) { 4354 return PackageManager.PERMISSION_DENIED; 4355 } 4356 4357 synchronized (mPackages) { 4358 final PackageParser.Package p = mPackages.get(pkgName); 4359 if (p != null && p.mExtras != null) { 4360 final PackageSetting ps = (PackageSetting) p.mExtras; 4361 final PermissionsState permissionsState = ps.getPermissionsState(); 4362 if (permissionsState.hasPermission(permName, userId)) { 4363 return PackageManager.PERMISSION_GRANTED; 4364 } 4365 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 4366 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 4367 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 4368 return PackageManager.PERMISSION_GRANTED; 4369 } 4370 } 4371 } 4372 4373 return PackageManager.PERMISSION_DENIED; 4374 } 4375 4376 @Override 4377 public int checkUidPermission(String permName, int uid) { 4378 final int userId = UserHandle.getUserId(uid); 4379 4380 if (!sUserManager.exists(userId)) { 4381 return PackageManager.PERMISSION_DENIED; 4382 } 4383 4384 synchronized (mPackages) { 4385 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4386 if (obj != null) { 4387 final SettingBase ps = (SettingBase) obj; 4388 final PermissionsState permissionsState = ps.getPermissionsState(); 4389 if (permissionsState.hasPermission(permName, userId)) { 4390 return PackageManager.PERMISSION_GRANTED; 4391 } 4392 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 4393 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 4394 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 4395 return PackageManager.PERMISSION_GRANTED; 4396 } 4397 } else { 4398 ArraySet<String> perms = mSystemPermissions.get(uid); 4399 if (perms != null) { 4400 if (perms.contains(permName)) { 4401 return PackageManager.PERMISSION_GRANTED; 4402 } 4403 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 4404 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 4405 return PackageManager.PERMISSION_GRANTED; 4406 } 4407 } 4408 } 4409 } 4410 4411 return PackageManager.PERMISSION_DENIED; 4412 } 4413 4414 @Override 4415 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 4416 if (UserHandle.getCallingUserId() != userId) { 4417 mContext.enforceCallingPermission( 4418 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4419 "isPermissionRevokedByPolicy for user " + userId); 4420 } 4421 4422 if (checkPermission(permission, packageName, userId) 4423 == PackageManager.PERMISSION_GRANTED) { 4424 return false; 4425 } 4426 4427 final long identity = Binder.clearCallingIdentity(); 4428 try { 4429 final int flags = getPermissionFlags(permission, packageName, userId); 4430 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 4431 } finally { 4432 Binder.restoreCallingIdentity(identity); 4433 } 4434 } 4435 4436 @Override 4437 public String getPermissionControllerPackageName() { 4438 synchronized (mPackages) { 4439 return mRequiredInstallerPackage; 4440 } 4441 } 4442 4443 /** 4444 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 4445 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 4446 * @param checkShell whether to prevent shell from access if there's a debugging restriction 4447 * @param message the message to log on security exception 4448 */ 4449 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 4450 boolean checkShell, String message) { 4451 if (userId < 0) { 4452 throw new IllegalArgumentException("Invalid userId " + userId); 4453 } 4454 if (checkShell) { 4455 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 4456 } 4457 if (userId == UserHandle.getUserId(callingUid)) return; 4458 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4459 if (requireFullPermission) { 4460 mContext.enforceCallingOrSelfPermission( 4461 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 4462 } else { 4463 try { 4464 mContext.enforceCallingOrSelfPermission( 4465 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 4466 } catch (SecurityException se) { 4467 mContext.enforceCallingOrSelfPermission( 4468 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 4469 } 4470 } 4471 } 4472 } 4473 4474 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 4475 if (callingUid == Process.SHELL_UID) { 4476 if (userHandle >= 0 4477 && sUserManager.hasUserRestriction(restriction, userHandle)) { 4478 throw new SecurityException("Shell does not have permission to access user " 4479 + userHandle); 4480 } else if (userHandle < 0) { 4481 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 4482 + Debug.getCallers(3)); 4483 } 4484 } 4485 } 4486 4487 private BasePermission findPermissionTreeLP(String permName) { 4488 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 4489 if (permName.startsWith(bp.name) && 4490 permName.length() > bp.name.length() && 4491 permName.charAt(bp.name.length()) == '.') { 4492 return bp; 4493 } 4494 } 4495 return null; 4496 } 4497 4498 private BasePermission checkPermissionTreeLP(String permName) { 4499 if (permName != null) { 4500 BasePermission bp = findPermissionTreeLP(permName); 4501 if (bp != null) { 4502 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 4503 return bp; 4504 } 4505 throw new SecurityException("Calling uid " 4506 + Binder.getCallingUid() 4507 + " is not allowed to add to permission tree " 4508 + bp.name + " owned by uid " + bp.uid); 4509 } 4510 } 4511 throw new SecurityException("No permission tree found for " + permName); 4512 } 4513 4514 static boolean compareStrings(CharSequence s1, CharSequence s2) { 4515 if (s1 == null) { 4516 return s2 == null; 4517 } 4518 if (s2 == null) { 4519 return false; 4520 } 4521 if (s1.getClass() != s2.getClass()) { 4522 return false; 4523 } 4524 return s1.equals(s2); 4525 } 4526 4527 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 4528 if (pi1.icon != pi2.icon) return false; 4529 if (pi1.logo != pi2.logo) return false; 4530 if (pi1.protectionLevel != pi2.protectionLevel) return false; 4531 if (!compareStrings(pi1.name, pi2.name)) return false; 4532 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 4533 // We'll take care of setting this one. 4534 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 4535 // These are not currently stored in settings. 4536 //if (!compareStrings(pi1.group, pi2.group)) return false; 4537 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 4538 //if (pi1.labelRes != pi2.labelRes) return false; 4539 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 4540 return true; 4541 } 4542 4543 int permissionInfoFootprint(PermissionInfo info) { 4544 int size = info.name.length(); 4545 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 4546 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 4547 return size; 4548 } 4549 4550 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 4551 int size = 0; 4552 for (BasePermission perm : mSettings.mPermissions.values()) { 4553 if (perm.uid == tree.uid) { 4554 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 4555 } 4556 } 4557 return size; 4558 } 4559 4560 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 4561 // We calculate the max size of permissions defined by this uid and throw 4562 // if that plus the size of 'info' would exceed our stated maximum. 4563 if (tree.uid != Process.SYSTEM_UID) { 4564 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 4565 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 4566 throw new SecurityException("Permission tree size cap exceeded"); 4567 } 4568 } 4569 } 4570 4571 boolean addPermissionLocked(PermissionInfo info, boolean async) { 4572 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 4573 throw new SecurityException("Label must be specified in permission"); 4574 } 4575 BasePermission tree = checkPermissionTreeLP(info.name); 4576 BasePermission bp = mSettings.mPermissions.get(info.name); 4577 boolean added = bp == null; 4578 boolean changed = true; 4579 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 4580 if (added) { 4581 enforcePermissionCapLocked(info, tree); 4582 bp = new BasePermission(info.name, tree.sourcePackage, 4583 BasePermission.TYPE_DYNAMIC); 4584 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 4585 throw new SecurityException( 4586 "Not allowed to modify non-dynamic permission " 4587 + info.name); 4588 } else { 4589 if (bp.protectionLevel == fixedLevel 4590 && bp.perm.owner.equals(tree.perm.owner) 4591 && bp.uid == tree.uid 4592 && comparePermissionInfos(bp.perm.info, info)) { 4593 changed = false; 4594 } 4595 } 4596 bp.protectionLevel = fixedLevel; 4597 info = new PermissionInfo(info); 4598 info.protectionLevel = fixedLevel; 4599 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 4600 bp.perm.info.packageName = tree.perm.info.packageName; 4601 bp.uid = tree.uid; 4602 if (added) { 4603 mSettings.mPermissions.put(info.name, bp); 4604 } 4605 if (changed) { 4606 if (!async) { 4607 mSettings.writeLPr(); 4608 } else { 4609 scheduleWriteSettingsLocked(); 4610 } 4611 } 4612 return added; 4613 } 4614 4615 @Override 4616 public boolean addPermission(PermissionInfo info) { 4617 synchronized (mPackages) { 4618 return addPermissionLocked(info, false); 4619 } 4620 } 4621 4622 @Override 4623 public boolean addPermissionAsync(PermissionInfo info) { 4624 synchronized (mPackages) { 4625 return addPermissionLocked(info, true); 4626 } 4627 } 4628 4629 @Override 4630 public void removePermission(String name) { 4631 synchronized (mPackages) { 4632 checkPermissionTreeLP(name); 4633 BasePermission bp = mSettings.mPermissions.get(name); 4634 if (bp != null) { 4635 if (bp.type != BasePermission.TYPE_DYNAMIC) { 4636 throw new SecurityException( 4637 "Not allowed to modify non-dynamic permission " 4638 + name); 4639 } 4640 mSettings.mPermissions.remove(name); 4641 mSettings.writeLPr(); 4642 } 4643 } 4644 } 4645 4646 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 4647 BasePermission bp) { 4648 int index = pkg.requestedPermissions.indexOf(bp.name); 4649 if (index == -1) { 4650 throw new SecurityException("Package " + pkg.packageName 4651 + " has not requested permission " + bp.name); 4652 } 4653 if (!bp.isRuntime() && !bp.isDevelopment()) { 4654 throw new SecurityException("Permission " + bp.name 4655 + " is not a changeable permission type"); 4656 } 4657 } 4658 4659 @Override 4660 public void grantRuntimePermission(String packageName, String name, final int userId) { 4661 grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */); 4662 } 4663 4664 private void grantRuntimePermission(String packageName, String name, final int userId, 4665 boolean overridePolicy) { 4666 if (!sUserManager.exists(userId)) { 4667 Log.e(TAG, "No such user:" + userId); 4668 return; 4669 } 4670 4671 mContext.enforceCallingOrSelfPermission( 4672 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 4673 "grantRuntimePermission"); 4674 4675 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4676 true /* requireFullPermission */, true /* checkShell */, 4677 "grantRuntimePermission"); 4678 4679 final int uid; 4680 final SettingBase sb; 4681 4682 synchronized (mPackages) { 4683 final PackageParser.Package pkg = mPackages.get(packageName); 4684 if (pkg == null) { 4685 throw new IllegalArgumentException("Unknown package: " + packageName); 4686 } 4687 4688 final BasePermission bp = mSettings.mPermissions.get(name); 4689 if (bp == null) { 4690 throw new IllegalArgumentException("Unknown permission: " + name); 4691 } 4692 4693 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4694 4695 // If a permission review is required for legacy apps we represent 4696 // their permissions as always granted runtime ones since we need 4697 // to keep the review required permission flag per user while an 4698 // install permission's state is shared across all users. 4699 if (mPermissionReviewRequired 4700 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4701 && bp.isRuntime()) { 4702 return; 4703 } 4704 4705 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 4706 sb = (SettingBase) pkg.mExtras; 4707 if (sb == null) { 4708 throw new IllegalArgumentException("Unknown package: " + packageName); 4709 } 4710 4711 final PermissionsState permissionsState = sb.getPermissionsState(); 4712 4713 final int flags = permissionsState.getPermissionFlags(name, userId); 4714 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4715 throw new SecurityException("Cannot grant system fixed permission " 4716 + name + " for package " + packageName); 4717 } 4718 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) { 4719 throw new SecurityException("Cannot grant policy fixed permission " 4720 + name + " for package " + packageName); 4721 } 4722 4723 if (bp.isDevelopment()) { 4724 // Development permissions must be handled specially, since they are not 4725 // normal runtime permissions. For now they apply to all users. 4726 if (permissionsState.grantInstallPermission(bp) != 4727 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4728 scheduleWriteSettingsLocked(); 4729 } 4730 return; 4731 } 4732 4733 final PackageSetting ps = mSettings.mPackages.get(packageName); 4734 if (ps.getInstantApp(userId) && !bp.isInstant()) { 4735 throw new SecurityException("Cannot grant non-ephemeral permission" 4736 + name + " for package " + packageName); 4737 } 4738 4739 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4740 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4741 return; 4742 } 4743 4744 final int result = permissionsState.grantRuntimePermission(bp, userId); 4745 switch (result) { 4746 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4747 return; 4748 } 4749 4750 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4751 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4752 mHandler.post(new Runnable() { 4753 @Override 4754 public void run() { 4755 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4756 } 4757 }); 4758 } 4759 break; 4760 } 4761 4762 if (bp.isRuntime()) { 4763 logPermissionGranted(mContext, name, packageName); 4764 } 4765 4766 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4767 4768 // Not critical if that is lost - app has to request again. 4769 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4770 } 4771 4772 // Only need to do this if user is initialized. Otherwise it's a new user 4773 // and there are no processes running as the user yet and there's no need 4774 // to make an expensive call to remount processes for the changed permissions. 4775 if (READ_EXTERNAL_STORAGE.equals(name) 4776 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4777 final long token = Binder.clearCallingIdentity(); 4778 try { 4779 if (sUserManager.isInitialized(userId)) { 4780 StorageManagerInternal storageManagerInternal = LocalServices.getService( 4781 StorageManagerInternal.class); 4782 storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName); 4783 } 4784 } finally { 4785 Binder.restoreCallingIdentity(token); 4786 } 4787 } 4788 } 4789 4790 @Override 4791 public void revokeRuntimePermission(String packageName, String name, int userId) { 4792 revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */); 4793 } 4794 4795 private void revokeRuntimePermission(String packageName, String name, int userId, 4796 boolean overridePolicy) { 4797 if (!sUserManager.exists(userId)) { 4798 Log.e(TAG, "No such user:" + userId); 4799 return; 4800 } 4801 4802 mContext.enforceCallingOrSelfPermission( 4803 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4804 "revokeRuntimePermission"); 4805 4806 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4807 true /* requireFullPermission */, true /* checkShell */, 4808 "revokeRuntimePermission"); 4809 4810 final int appId; 4811 4812 synchronized (mPackages) { 4813 final PackageParser.Package pkg = mPackages.get(packageName); 4814 if (pkg == null) { 4815 throw new IllegalArgumentException("Unknown package: " + packageName); 4816 } 4817 4818 final BasePermission bp = mSettings.mPermissions.get(name); 4819 if (bp == null) { 4820 throw new IllegalArgumentException("Unknown permission: " + name); 4821 } 4822 4823 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4824 4825 // If a permission review is required for legacy apps we represent 4826 // their permissions as always granted runtime ones since we need 4827 // to keep the review required permission flag per user while an 4828 // install permission's state is shared across all users. 4829 if (mPermissionReviewRequired 4830 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4831 && bp.isRuntime()) { 4832 return; 4833 } 4834 4835 SettingBase sb = (SettingBase) pkg.mExtras; 4836 if (sb == null) { 4837 throw new IllegalArgumentException("Unknown package: " + packageName); 4838 } 4839 4840 final PermissionsState permissionsState = sb.getPermissionsState(); 4841 4842 final int flags = permissionsState.getPermissionFlags(name, userId); 4843 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4844 throw new SecurityException("Cannot revoke system fixed permission " 4845 + name + " for package " + packageName); 4846 } 4847 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) { 4848 throw new SecurityException("Cannot revoke policy fixed permission " 4849 + name + " for package " + packageName); 4850 } 4851 4852 if (bp.isDevelopment()) { 4853 // Development permissions must be handled specially, since they are not 4854 // normal runtime permissions. For now they apply to all users. 4855 if (permissionsState.revokeInstallPermission(bp) != 4856 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4857 scheduleWriteSettingsLocked(); 4858 } 4859 return; 4860 } 4861 4862 if (permissionsState.revokeRuntimePermission(bp, userId) == 4863 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4864 return; 4865 } 4866 4867 if (bp.isRuntime()) { 4868 logPermissionRevoked(mContext, name, packageName); 4869 } 4870 4871 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4872 4873 // Critical, after this call app should never have the permission. 4874 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4875 4876 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4877 } 4878 4879 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4880 } 4881 4882 /** 4883 * Get the first event id for the permission. 4884 * 4885 * <p>There are four events for each permission: <ul> 4886 * <li>Request permission: first id + 0</li> 4887 * <li>Grant permission: first id + 1</li> 4888 * <li>Request for permission denied: first id + 2</li> 4889 * <li>Revoke permission: first id + 3</li> 4890 * </ul></p> 4891 * 4892 * @param name name of the permission 4893 * 4894 * @return The first event id for the permission 4895 */ 4896 private static int getBaseEventId(@NonNull String name) { 4897 int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name); 4898 4899 if (eventIdIndex == -1) { 4900 if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE 4901 || "user".equals(Build.TYPE)) { 4902 Log.i(TAG, "Unknown permission " + name); 4903 4904 return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN; 4905 } else { 4906 // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated. 4907 // 4908 // Also update 4909 // - EventLogger#ALL_DANGEROUS_PERMISSIONS 4910 // - metrics_constants.proto 4911 throw new IllegalStateException("Unknown permission " + name); 4912 } 4913 } 4914 4915 return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4; 4916 } 4917 4918 /** 4919 * Log that a permission was revoked. 4920 * 4921 * @param context Context of the caller 4922 * @param name name of the permission 4923 * @param packageName package permission if for 4924 */ 4925 private static void logPermissionRevoked(@NonNull Context context, @NonNull String name, 4926 @NonNull String packageName) { 4927 MetricsLogger.action(context, getBaseEventId(name) + 3, packageName); 4928 } 4929 4930 /** 4931 * Log that a permission request was granted. 4932 * 4933 * @param context Context of the caller 4934 * @param name name of the permission 4935 * @param packageName package permission if for 4936 */ 4937 private static void logPermissionGranted(@NonNull Context context, @NonNull String name, 4938 @NonNull String packageName) { 4939 MetricsLogger.action(context, getBaseEventId(name) + 1, packageName); 4940 } 4941 4942 @Override 4943 public void resetRuntimePermissions() { 4944 mContext.enforceCallingOrSelfPermission( 4945 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4946 "revokeRuntimePermission"); 4947 4948 int callingUid = Binder.getCallingUid(); 4949 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4950 mContext.enforceCallingOrSelfPermission( 4951 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4952 "resetRuntimePermissions"); 4953 } 4954 4955 synchronized (mPackages) { 4956 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4957 for (int userId : UserManagerService.getInstance().getUserIds()) { 4958 final int packageCount = mPackages.size(); 4959 for (int i = 0; i < packageCount; i++) { 4960 PackageParser.Package pkg = mPackages.valueAt(i); 4961 if (!(pkg.mExtras instanceof PackageSetting)) { 4962 continue; 4963 } 4964 PackageSetting ps = (PackageSetting) pkg.mExtras; 4965 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4966 } 4967 } 4968 } 4969 } 4970 4971 @Override 4972 public int getPermissionFlags(String name, String packageName, int userId) { 4973 if (!sUserManager.exists(userId)) { 4974 return 0; 4975 } 4976 4977 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4978 4979 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4980 true /* requireFullPermission */, false /* checkShell */, 4981 "getPermissionFlags"); 4982 4983 synchronized (mPackages) { 4984 final PackageParser.Package pkg = mPackages.get(packageName); 4985 if (pkg == null) { 4986 return 0; 4987 } 4988 4989 final BasePermission bp = mSettings.mPermissions.get(name); 4990 if (bp == null) { 4991 return 0; 4992 } 4993 4994 SettingBase sb = (SettingBase) pkg.mExtras; 4995 if (sb == null) { 4996 return 0; 4997 } 4998 4999 PermissionsState permissionsState = sb.getPermissionsState(); 5000 return permissionsState.getPermissionFlags(name, userId); 5001 } 5002 } 5003 5004 @Override 5005 public void updatePermissionFlags(String name, String packageName, int flagMask, 5006 int flagValues, int userId) { 5007 if (!sUserManager.exists(userId)) { 5008 return; 5009 } 5010 5011 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 5012 5013 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5014 true /* requireFullPermission */, true /* checkShell */, 5015 "updatePermissionFlags"); 5016 5017 // Only the system can change these flags and nothing else. 5018 if (getCallingUid() != Process.SYSTEM_UID) { 5019 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5020 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5021 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 5022 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 5023 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 5024 } 5025 5026 synchronized (mPackages) { 5027 final PackageParser.Package pkg = mPackages.get(packageName); 5028 if (pkg == null) { 5029 throw new IllegalArgumentException("Unknown package: " + packageName); 5030 } 5031 5032 final BasePermission bp = mSettings.mPermissions.get(name); 5033 if (bp == null) { 5034 throw new IllegalArgumentException("Unknown permission: " + name); 5035 } 5036 5037 SettingBase sb = (SettingBase) pkg.mExtras; 5038 if (sb == null) { 5039 throw new IllegalArgumentException("Unknown package: " + packageName); 5040 } 5041 5042 PermissionsState permissionsState = sb.getPermissionsState(); 5043 5044 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 5045 5046 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 5047 // Install and runtime permissions are stored in different places, 5048 // so figure out what permission changed and persist the change. 5049 if (permissionsState.getInstallPermissionState(name) != null) { 5050 scheduleWriteSettingsLocked(); 5051 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 5052 || hadState) { 5053 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 5054 } 5055 } 5056 } 5057 } 5058 5059 /** 5060 * Update the permission flags for all packages and runtime permissions of a user in order 5061 * to allow device or profile owner to remove POLICY_FIXED. 5062 */ 5063 @Override 5064 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 5065 if (!sUserManager.exists(userId)) { 5066 return; 5067 } 5068 5069 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 5070 5071 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5072 true /* requireFullPermission */, true /* checkShell */, 5073 "updatePermissionFlagsForAllApps"); 5074 5075 // Only the system can change system fixed flags. 5076 if (getCallingUid() != Process.SYSTEM_UID) { 5077 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5078 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5079 } 5080 5081 synchronized (mPackages) { 5082 boolean changed = false; 5083 final int packageCount = mPackages.size(); 5084 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 5085 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 5086 SettingBase sb = (SettingBase) pkg.mExtras; 5087 if (sb == null) { 5088 continue; 5089 } 5090 PermissionsState permissionsState = sb.getPermissionsState(); 5091 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 5092 userId, flagMask, flagValues); 5093 } 5094 if (changed) { 5095 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 5096 } 5097 } 5098 } 5099 5100 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 5101 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 5102 != PackageManager.PERMISSION_GRANTED 5103 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 5104 != PackageManager.PERMISSION_GRANTED) { 5105 throw new SecurityException(message + " requires " 5106 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 5107 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 5108 } 5109 } 5110 5111 @Override 5112 public boolean shouldShowRequestPermissionRationale(String permissionName, 5113 String packageName, int userId) { 5114 if (UserHandle.getCallingUserId() != userId) { 5115 mContext.enforceCallingPermission( 5116 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5117 "canShowRequestPermissionRationale for user " + userId); 5118 } 5119 5120 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 5121 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 5122 return false; 5123 } 5124 5125 if (checkPermission(permissionName, packageName, userId) 5126 == PackageManager.PERMISSION_GRANTED) { 5127 return false; 5128 } 5129 5130 final int flags; 5131 5132 final long identity = Binder.clearCallingIdentity(); 5133 try { 5134 flags = getPermissionFlags(permissionName, 5135 packageName, userId); 5136 } finally { 5137 Binder.restoreCallingIdentity(identity); 5138 } 5139 5140 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 5141 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 5142 | PackageManager.FLAG_PERMISSION_USER_FIXED; 5143 5144 if ((flags & fixedFlags) != 0) { 5145 return false; 5146 } 5147 5148 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 5149 } 5150 5151 @Override 5152 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 5153 mContext.enforceCallingOrSelfPermission( 5154 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 5155 "addOnPermissionsChangeListener"); 5156 5157 synchronized (mPackages) { 5158 mOnPermissionChangeListeners.addListenerLocked(listener); 5159 } 5160 } 5161 5162 @Override 5163 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 5164 synchronized (mPackages) { 5165 mOnPermissionChangeListeners.removeListenerLocked(listener); 5166 } 5167 } 5168 5169 @Override 5170 public boolean isProtectedBroadcast(String actionName) { 5171 synchronized (mPackages) { 5172 if (mProtectedBroadcasts.contains(actionName)) { 5173 return true; 5174 } else if (actionName != null) { 5175 // TODO: remove these terrible hacks 5176 if (actionName.startsWith("android.net.netmon.lingerExpired") 5177 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 5178 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 5179 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 5180 return true; 5181 } 5182 } 5183 } 5184 return false; 5185 } 5186 5187 @Override 5188 public int checkSignatures(String pkg1, String pkg2) { 5189 synchronized (mPackages) { 5190 final PackageParser.Package p1 = mPackages.get(pkg1); 5191 final PackageParser.Package p2 = mPackages.get(pkg2); 5192 if (p1 == null || p1.mExtras == null 5193 || p2 == null || p2.mExtras == null) { 5194 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5195 } 5196 return compareSignatures(p1.mSignatures, p2.mSignatures); 5197 } 5198 } 5199 5200 @Override 5201 public int checkUidSignatures(int uid1, int uid2) { 5202 // Map to base uids. 5203 uid1 = UserHandle.getAppId(uid1); 5204 uid2 = UserHandle.getAppId(uid2); 5205 // reader 5206 synchronized (mPackages) { 5207 Signature[] s1; 5208 Signature[] s2; 5209 Object obj = mSettings.getUserIdLPr(uid1); 5210 if (obj != null) { 5211 if (obj instanceof SharedUserSetting) { 5212 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 5213 } else if (obj instanceof PackageSetting) { 5214 s1 = ((PackageSetting)obj).signatures.mSignatures; 5215 } else { 5216 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5217 } 5218 } else { 5219 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5220 } 5221 obj = mSettings.getUserIdLPr(uid2); 5222 if (obj != null) { 5223 if (obj instanceof SharedUserSetting) { 5224 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 5225 } else if (obj instanceof PackageSetting) { 5226 s2 = ((PackageSetting)obj).signatures.mSignatures; 5227 } else { 5228 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5229 } 5230 } else { 5231 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5232 } 5233 return compareSignatures(s1, s2); 5234 } 5235 } 5236 5237 /** 5238 * This method should typically only be used when granting or revoking 5239 * permissions, since the app may immediately restart after this call. 5240 * <p> 5241 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 5242 * guard your work against the app being relaunched. 5243 */ 5244 private void killUid(int appId, int userId, String reason) { 5245 final long identity = Binder.clearCallingIdentity(); 5246 try { 5247 IActivityManager am = ActivityManager.getService(); 5248 if (am != null) { 5249 try { 5250 am.killUid(appId, userId, reason); 5251 } catch (RemoteException e) { 5252 /* ignore - same process */ 5253 } 5254 } 5255 } finally { 5256 Binder.restoreCallingIdentity(identity); 5257 } 5258 } 5259 5260 /** 5261 * Compares two sets of signatures. Returns: 5262 * <br /> 5263 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 5264 * <br /> 5265 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 5266 * <br /> 5267 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 5268 * <br /> 5269 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 5270 * <br /> 5271 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 5272 */ 5273 static int compareSignatures(Signature[] s1, Signature[] s2) { 5274 if (s1 == null) { 5275 return s2 == null 5276 ? PackageManager.SIGNATURE_NEITHER_SIGNED 5277 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 5278 } 5279 5280 if (s2 == null) { 5281 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 5282 } 5283 5284 if (s1.length != s2.length) { 5285 return PackageManager.SIGNATURE_NO_MATCH; 5286 } 5287 5288 // Since both signature sets are of size 1, we can compare without HashSets. 5289 if (s1.length == 1) { 5290 return s1[0].equals(s2[0]) ? 5291 PackageManager.SIGNATURE_MATCH : 5292 PackageManager.SIGNATURE_NO_MATCH; 5293 } 5294 5295 ArraySet<Signature> set1 = new ArraySet<Signature>(); 5296 for (Signature sig : s1) { 5297 set1.add(sig); 5298 } 5299 ArraySet<Signature> set2 = new ArraySet<Signature>(); 5300 for (Signature sig : s2) { 5301 set2.add(sig); 5302 } 5303 // Make sure s2 contains all signatures in s1. 5304 if (set1.equals(set2)) { 5305 return PackageManager.SIGNATURE_MATCH; 5306 } 5307 return PackageManager.SIGNATURE_NO_MATCH; 5308 } 5309 5310 /** 5311 * If the database version for this type of package (internal storage or 5312 * external storage) is less than the version where package signatures 5313 * were updated, return true. 5314 */ 5315 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 5316 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 5317 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 5318 } 5319 5320 /** 5321 * Used for backward compatibility to make sure any packages with 5322 * certificate chains get upgraded to the new style. {@code existingSigs} 5323 * will be in the old format (since they were stored on disk from before the 5324 * system upgrade) and {@code scannedSigs} will be in the newer format. 5325 */ 5326 private int compareSignaturesCompat(PackageSignatures existingSigs, 5327 PackageParser.Package scannedPkg) { 5328 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 5329 return PackageManager.SIGNATURE_NO_MATCH; 5330 } 5331 5332 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 5333 for (Signature sig : existingSigs.mSignatures) { 5334 existingSet.add(sig); 5335 } 5336 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 5337 for (Signature sig : scannedPkg.mSignatures) { 5338 try { 5339 Signature[] chainSignatures = sig.getChainSignatures(); 5340 for (Signature chainSig : chainSignatures) { 5341 scannedCompatSet.add(chainSig); 5342 } 5343 } catch (CertificateEncodingException e) { 5344 scannedCompatSet.add(sig); 5345 } 5346 } 5347 /* 5348 * Make sure the expanded scanned set contains all signatures in the 5349 * existing one. 5350 */ 5351 if (scannedCompatSet.equals(existingSet)) { 5352 // Migrate the old signatures to the new scheme. 5353 existingSigs.assignSignatures(scannedPkg.mSignatures); 5354 // The new KeySets will be re-added later in the scanning process. 5355 synchronized (mPackages) { 5356 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 5357 } 5358 return PackageManager.SIGNATURE_MATCH; 5359 } 5360 return PackageManager.SIGNATURE_NO_MATCH; 5361 } 5362 5363 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 5364 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 5365 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 5366 } 5367 5368 private int compareSignaturesRecover(PackageSignatures existingSigs, 5369 PackageParser.Package scannedPkg) { 5370 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 5371 return PackageManager.SIGNATURE_NO_MATCH; 5372 } 5373 5374 String msg = null; 5375 try { 5376 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 5377 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 5378 + scannedPkg.packageName); 5379 return PackageManager.SIGNATURE_MATCH; 5380 } 5381 } catch (CertificateException e) { 5382 msg = e.getMessage(); 5383 } 5384 5385 logCriticalInfo(Log.INFO, 5386 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 5387 return PackageManager.SIGNATURE_NO_MATCH; 5388 } 5389 5390 @Override 5391 public List<String> getAllPackages() { 5392 synchronized (mPackages) { 5393 return new ArrayList<String>(mPackages.keySet()); 5394 } 5395 } 5396 5397 @Override 5398 public String[] getPackagesForUid(int uid) { 5399 final int userId = UserHandle.getUserId(uid); 5400 uid = UserHandle.getAppId(uid); 5401 // reader 5402 synchronized (mPackages) { 5403 Object obj = mSettings.getUserIdLPr(uid); 5404 if (obj instanceof SharedUserSetting) { 5405 final SharedUserSetting sus = (SharedUserSetting) obj; 5406 final int N = sus.packages.size(); 5407 String[] res = new String[N]; 5408 final Iterator<PackageSetting> it = sus.packages.iterator(); 5409 int i = 0; 5410 while (it.hasNext()) { 5411 PackageSetting ps = it.next(); 5412 if (ps.getInstalled(userId)) { 5413 res[i++] = ps.name; 5414 } else { 5415 res = ArrayUtils.removeElement(String.class, res, res[i]); 5416 } 5417 } 5418 return res; 5419 } else if (obj instanceof PackageSetting) { 5420 final PackageSetting ps = (PackageSetting) obj; 5421 if (ps.getInstalled(userId)) { 5422 return new String[]{ps.name}; 5423 } 5424 } 5425 } 5426 return null; 5427 } 5428 5429 @Override 5430 public String getNameForUid(int uid) { 5431 // reader 5432 synchronized (mPackages) { 5433 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5434 if (obj instanceof SharedUserSetting) { 5435 final SharedUserSetting sus = (SharedUserSetting) obj; 5436 return sus.name + ":" + sus.userId; 5437 } else if (obj instanceof PackageSetting) { 5438 final PackageSetting ps = (PackageSetting) obj; 5439 return ps.name; 5440 } 5441 } 5442 return null; 5443 } 5444 5445 @Override 5446 public int getUidForSharedUser(String sharedUserName) { 5447 if(sharedUserName == null) { 5448 return -1; 5449 } 5450 // reader 5451 synchronized (mPackages) { 5452 SharedUserSetting suid; 5453 try { 5454 suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 5455 if (suid != null) { 5456 return suid.userId; 5457 } 5458 } catch (PackageManagerException ignore) { 5459 // can't happen, but, still need to catch it 5460 } 5461 return -1; 5462 } 5463 } 5464 5465 @Override 5466 public int getFlagsForUid(int uid) { 5467 synchronized (mPackages) { 5468 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5469 if (obj instanceof SharedUserSetting) { 5470 final SharedUserSetting sus = (SharedUserSetting) obj; 5471 return sus.pkgFlags; 5472 } else if (obj instanceof PackageSetting) { 5473 final PackageSetting ps = (PackageSetting) obj; 5474 return ps.pkgFlags; 5475 } 5476 } 5477 return 0; 5478 } 5479 5480 @Override 5481 public int getPrivateFlagsForUid(int uid) { 5482 synchronized (mPackages) { 5483 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5484 if (obj instanceof SharedUserSetting) { 5485 final SharedUserSetting sus = (SharedUserSetting) obj; 5486 return sus.pkgPrivateFlags; 5487 } else if (obj instanceof PackageSetting) { 5488 final PackageSetting ps = (PackageSetting) obj; 5489 return ps.pkgPrivateFlags; 5490 } 5491 } 5492 return 0; 5493 } 5494 5495 @Override 5496 public boolean isUidPrivileged(int uid) { 5497 uid = UserHandle.getAppId(uid); 5498 // reader 5499 synchronized (mPackages) { 5500 Object obj = mSettings.getUserIdLPr(uid); 5501 if (obj instanceof SharedUserSetting) { 5502 final SharedUserSetting sus = (SharedUserSetting) obj; 5503 final Iterator<PackageSetting> it = sus.packages.iterator(); 5504 while (it.hasNext()) { 5505 if (it.next().isPrivileged()) { 5506 return true; 5507 } 5508 } 5509 } else if (obj instanceof PackageSetting) { 5510 final PackageSetting ps = (PackageSetting) obj; 5511 return ps.isPrivileged(); 5512 } 5513 } 5514 return false; 5515 } 5516 5517 @Override 5518 public String[] getAppOpPermissionPackages(String permissionName) { 5519 synchronized (mPackages) { 5520 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 5521 if (pkgs == null) { 5522 return null; 5523 } 5524 return pkgs.toArray(new String[pkgs.size()]); 5525 } 5526 } 5527 5528 @Override 5529 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 5530 int flags, int userId) { 5531 try { 5532 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 5533 5534 if (!sUserManager.exists(userId)) return null; 5535 flags = updateFlagsForResolve(flags, userId, intent); 5536 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5537 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 5538 5539 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5540 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 5541 flags, userId); 5542 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5543 5544 final ResolveInfo bestChoice = 5545 chooseBestActivity(intent, resolvedType, flags, query, userId); 5546 return bestChoice; 5547 } finally { 5548 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5549 } 5550 } 5551 5552 @Override 5553 public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) { 5554 if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) { 5555 throw new SecurityException( 5556 "findPersistentPreferredActivity can only be run by the system"); 5557 } 5558 if (!sUserManager.exists(userId)) { 5559 return null; 5560 } 5561 intent = updateIntentForResolve(intent); 5562 final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver()); 5563 final int flags = updateFlagsForResolve(0, userId, intent); 5564 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5565 userId); 5566 synchronized (mPackages) { 5567 return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false, 5568 userId); 5569 } 5570 } 5571 5572 @Override 5573 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 5574 IntentFilter filter, int match, ComponentName activity) { 5575 final int userId = UserHandle.getCallingUserId(); 5576 if (DEBUG_PREFERRED) { 5577 Log.v(TAG, "setLastChosenActivity intent=" + intent 5578 + " resolvedType=" + resolvedType 5579 + " flags=" + flags 5580 + " filter=" + filter 5581 + " match=" + match 5582 + " activity=" + activity); 5583 filter.dump(new PrintStreamPrinter(System.out), " "); 5584 } 5585 intent.setComponent(null); 5586 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5587 userId); 5588 // Find any earlier preferred or last chosen entries and nuke them 5589 findPreferredActivity(intent, resolvedType, 5590 flags, query, 0, false, true, false, userId); 5591 // Add the new activity as the last chosen for this filter 5592 addPreferredActivityInternal(filter, match, null, activity, false, userId, 5593 "Setting last chosen"); 5594 } 5595 5596 @Override 5597 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 5598 final int userId = UserHandle.getCallingUserId(); 5599 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 5600 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5601 userId); 5602 return findPreferredActivity(intent, resolvedType, flags, query, 0, 5603 false, false, false, userId); 5604 } 5605 5606 private boolean isEphemeralDisabled() { 5607 // ephemeral apps have been disabled across the board 5608 if (DISABLE_EPHEMERAL_APPS) { 5609 return true; 5610 } 5611 // system isn't up yet; can't read settings, so, assume no ephemeral apps 5612 if (!mSystemReady) { 5613 return true; 5614 } 5615 // we can't get a content resolver until the system is ready; these checks must happen last 5616 final ContentResolver resolver = mContext.getContentResolver(); 5617 if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) { 5618 return true; 5619 } 5620 return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0; 5621 } 5622 5623 private boolean isEphemeralAllowed( 5624 Intent intent, List<ResolveInfo> resolvedActivities, int userId, 5625 boolean skipPackageCheck) { 5626 // Short circuit and return early if possible. 5627 if (isEphemeralDisabled()) { 5628 return false; 5629 } 5630 final int callingUser = UserHandle.getCallingUserId(); 5631 if (callingUser != UserHandle.USER_SYSTEM) { 5632 return false; 5633 } 5634 if (mEphemeralResolverConnection == null) { 5635 return false; 5636 } 5637 if (mEphemeralInstallerComponent == null) { 5638 return false; 5639 } 5640 if (intent.getComponent() != null) { 5641 return false; 5642 } 5643 if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) { 5644 return false; 5645 } 5646 if (!skipPackageCheck && intent.getPackage() != null) { 5647 return false; 5648 } 5649 final boolean isWebUri = hasWebURI(intent); 5650 if (!isWebUri || intent.getData().getHost() == null) { 5651 return false; 5652 } 5653 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 5654 synchronized (mPackages) { 5655 final int count = (resolvedActivities == null ? 0 : resolvedActivities.size()); 5656 for (int n = 0; n < count; n++) { 5657 ResolveInfo info = resolvedActivities.get(n); 5658 String packageName = info.activityInfo.packageName; 5659 PackageSetting ps = mSettings.mPackages.get(packageName); 5660 if (ps != null) { 5661 // Try to get the status from User settings first 5662 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5663 int status = (int) (packedStatus >> 32); 5664 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 5665 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5666 if (DEBUG_EPHEMERAL) { 5667 Slog.v(TAG, "DENY ephemeral apps;" 5668 + " pkg: " + packageName + ", status: " + status); 5669 } 5670 return false; 5671 } 5672 } 5673 } 5674 } 5675 // We've exhausted all ways to deny ephemeral application; let the system look for them. 5676 return true; 5677 } 5678 5679 private void requestEphemeralResolutionPhaseTwo(EphemeralResponse responseObj, 5680 Intent origIntent, String resolvedType, Intent launchIntent, String callingPackage, 5681 int userId) { 5682 final Message msg = mHandler.obtainMessage(EPHEMERAL_RESOLUTION_PHASE_TWO, 5683 new EphemeralRequest(responseObj, origIntent, resolvedType, launchIntent, 5684 callingPackage, userId)); 5685 mHandler.sendMessage(msg); 5686 } 5687 5688 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 5689 int flags, List<ResolveInfo> query, int userId) { 5690 if (query != null) { 5691 final int N = query.size(); 5692 if (N == 1) { 5693 return query.get(0); 5694 } else if (N > 1) { 5695 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 5696 // If there is more than one activity with the same priority, 5697 // then let the user decide between them. 5698 ResolveInfo r0 = query.get(0); 5699 ResolveInfo r1 = query.get(1); 5700 if (DEBUG_INTENT_MATCHING || debug) { 5701 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 5702 + r1.activityInfo.name + "=" + r1.priority); 5703 } 5704 // If the first activity has a higher priority, or a different 5705 // default, then it is always desirable to pick it. 5706 if (r0.priority != r1.priority 5707 || r0.preferredOrder != r1.preferredOrder 5708 || r0.isDefault != r1.isDefault) { 5709 return query.get(0); 5710 } 5711 // If we have saved a preference for a preferred activity for 5712 // this Intent, use that. 5713 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 5714 flags, query, r0.priority, true, false, debug, userId); 5715 if (ri != null) { 5716 return ri; 5717 } 5718 ri = new ResolveInfo(mResolveInfo); 5719 ri.activityInfo = new ActivityInfo(ri.activityInfo); 5720 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 5721 // If all of the options come from the same package, show the application's 5722 // label and icon instead of the generic resolver's. 5723 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 5724 // and then throw away the ResolveInfo itself, meaning that the caller loses 5725 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 5726 // a fallback for this case; we only set the target package's resources on 5727 // the ResolveInfo, not the ActivityInfo. 5728 final String intentPackage = intent.getPackage(); 5729 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 5730 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 5731 ri.resolvePackageName = intentPackage; 5732 if (userNeedsBadging(userId)) { 5733 ri.noResourceId = true; 5734 } else { 5735 ri.icon = appi.icon; 5736 } 5737 ri.iconResourceId = appi.icon; 5738 ri.labelRes = appi.labelRes; 5739 } 5740 ri.activityInfo.applicationInfo = new ApplicationInfo( 5741 ri.activityInfo.applicationInfo); 5742 if (userId != 0) { 5743 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 5744 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 5745 } 5746 // Make sure that the resolver is displayable in car mode 5747 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 5748 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 5749 return ri; 5750 } 5751 } 5752 return null; 5753 } 5754 5755 /** 5756 * Return true if the given list is not empty and all of its contents have 5757 * an activityInfo with the given package name. 5758 */ 5759 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 5760 if (ArrayUtils.isEmpty(list)) { 5761 return false; 5762 } 5763 for (int i = 0, N = list.size(); i < N; i++) { 5764 final ResolveInfo ri = list.get(i); 5765 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 5766 if (ai == null || !packageName.equals(ai.packageName)) { 5767 return false; 5768 } 5769 } 5770 return true; 5771 } 5772 5773 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 5774 int flags, List<ResolveInfo> query, boolean debug, int userId) { 5775 final int N = query.size(); 5776 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 5777 .get(userId); 5778 // Get the list of persistent preferred activities that handle the intent 5779 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 5780 List<PersistentPreferredActivity> pprefs = ppir != null 5781 ? ppir.queryIntent(intent, resolvedType, 5782 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 5783 userId) 5784 : null; 5785 if (pprefs != null && pprefs.size() > 0) { 5786 final int M = pprefs.size(); 5787 for (int i=0; i<M; i++) { 5788 final PersistentPreferredActivity ppa = pprefs.get(i); 5789 if (DEBUG_PREFERRED || debug) { 5790 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 5791 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 5792 + "\n component=" + ppa.mComponent); 5793 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5794 } 5795 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 5796 flags | MATCH_DISABLED_COMPONENTS, userId); 5797 if (DEBUG_PREFERRED || debug) { 5798 Slog.v(TAG, "Found persistent preferred activity:"); 5799 if (ai != null) { 5800 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5801 } else { 5802 Slog.v(TAG, " null"); 5803 } 5804 } 5805 if (ai == null) { 5806 // This previously registered persistent preferred activity 5807 // component is no longer known. Ignore it and do NOT remove it. 5808 continue; 5809 } 5810 for (int j=0; j<N; j++) { 5811 final ResolveInfo ri = query.get(j); 5812 if (!ri.activityInfo.applicationInfo.packageName 5813 .equals(ai.applicationInfo.packageName)) { 5814 continue; 5815 } 5816 if (!ri.activityInfo.name.equals(ai.name)) { 5817 continue; 5818 } 5819 // Found a persistent preference that can handle the intent. 5820 if (DEBUG_PREFERRED || debug) { 5821 Slog.v(TAG, "Returning persistent preferred activity: " + 5822 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5823 } 5824 return ri; 5825 } 5826 } 5827 } 5828 return null; 5829 } 5830 5831 // TODO: handle preferred activities missing while user has amnesia 5832 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5833 List<ResolveInfo> query, int priority, boolean always, 5834 boolean removeMatches, boolean debug, int userId) { 5835 if (!sUserManager.exists(userId)) return null; 5836 flags = updateFlagsForResolve(flags, userId, intent); 5837 intent = updateIntentForResolve(intent); 5838 // writer 5839 synchronized (mPackages) { 5840 // Try to find a matching persistent preferred activity. 5841 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5842 debug, userId); 5843 5844 // If a persistent preferred activity matched, use it. 5845 if (pri != null) { 5846 return pri; 5847 } 5848 5849 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5850 // Get the list of preferred activities that handle the intent 5851 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5852 List<PreferredActivity> prefs = pir != null 5853 ? pir.queryIntent(intent, resolvedType, 5854 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 5855 userId) 5856 : null; 5857 if (prefs != null && prefs.size() > 0) { 5858 boolean changed = false; 5859 try { 5860 // First figure out how good the original match set is. 5861 // We will only allow preferred activities that came 5862 // from the same match quality. 5863 int match = 0; 5864 5865 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5866 5867 final int N = query.size(); 5868 for (int j=0; j<N; j++) { 5869 final ResolveInfo ri = query.get(j); 5870 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5871 + ": 0x" + Integer.toHexString(match)); 5872 if (ri.match > match) { 5873 match = ri.match; 5874 } 5875 } 5876 5877 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5878 + Integer.toHexString(match)); 5879 5880 match &= IntentFilter.MATCH_CATEGORY_MASK; 5881 final int M = prefs.size(); 5882 for (int i=0; i<M; i++) { 5883 final PreferredActivity pa = prefs.get(i); 5884 if (DEBUG_PREFERRED || debug) { 5885 Slog.v(TAG, "Checking PreferredActivity ds=" 5886 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5887 + "\n component=" + pa.mPref.mComponent); 5888 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5889 } 5890 if (pa.mPref.mMatch != match) { 5891 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5892 + Integer.toHexString(pa.mPref.mMatch)); 5893 continue; 5894 } 5895 // If it's not an "always" type preferred activity and that's what we're 5896 // looking for, skip it. 5897 if (always && !pa.mPref.mAlways) { 5898 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5899 continue; 5900 } 5901 final ActivityInfo ai = getActivityInfo( 5902 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5903 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5904 userId); 5905 if (DEBUG_PREFERRED || debug) { 5906 Slog.v(TAG, "Found preferred activity:"); 5907 if (ai != null) { 5908 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5909 } else { 5910 Slog.v(TAG, " null"); 5911 } 5912 } 5913 if (ai == null) { 5914 // This previously registered preferred activity 5915 // component is no longer known. Most likely an update 5916 // to the app was installed and in the new version this 5917 // component no longer exists. Clean it up by removing 5918 // it from the preferred activities list, and skip it. 5919 Slog.w(TAG, "Removing dangling preferred activity: " 5920 + pa.mPref.mComponent); 5921 pir.removeFilter(pa); 5922 changed = true; 5923 continue; 5924 } 5925 for (int j=0; j<N; j++) { 5926 final ResolveInfo ri = query.get(j); 5927 if (!ri.activityInfo.applicationInfo.packageName 5928 .equals(ai.applicationInfo.packageName)) { 5929 continue; 5930 } 5931 if (!ri.activityInfo.name.equals(ai.name)) { 5932 continue; 5933 } 5934 5935 if (removeMatches) { 5936 pir.removeFilter(pa); 5937 changed = true; 5938 if (DEBUG_PREFERRED) { 5939 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 5940 } 5941 break; 5942 } 5943 5944 // Okay we found a previously set preferred or last chosen app. 5945 // If the result set is different from when this 5946 // was created, we need to clear it and re-ask the 5947 // user their preference, if we're looking for an "always" type entry. 5948 if (always && !pa.mPref.sameSet(query)) { 5949 Slog.i(TAG, "Result set changed, dropping preferred activity for " 5950 + intent + " type " + resolvedType); 5951 if (DEBUG_PREFERRED) { 5952 Slog.v(TAG, "Removing preferred activity since set changed " 5953 + pa.mPref.mComponent); 5954 } 5955 pir.removeFilter(pa); 5956 // Re-add the filter as a "last chosen" entry (!always) 5957 PreferredActivity lastChosen = new PreferredActivity( 5958 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 5959 pir.addFilter(lastChosen); 5960 changed = true; 5961 return null; 5962 } 5963 5964 // Yay! Either the set matched or we're looking for the last chosen 5965 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 5966 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5967 return ri; 5968 } 5969 } 5970 } finally { 5971 if (changed) { 5972 if (DEBUG_PREFERRED) { 5973 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 5974 } 5975 scheduleWritePackageRestrictionsLocked(userId); 5976 } 5977 } 5978 } 5979 } 5980 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 5981 return null; 5982 } 5983 5984 /* 5985 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 5986 */ 5987 @Override 5988 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 5989 int targetUserId) { 5990 mContext.enforceCallingOrSelfPermission( 5991 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 5992 List<CrossProfileIntentFilter> matches = 5993 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 5994 if (matches != null) { 5995 int size = matches.size(); 5996 for (int i = 0; i < size; i++) { 5997 if (matches.get(i).getTargetUserId() == targetUserId) return true; 5998 } 5999 } 6000 if (hasWebURI(intent)) { 6001 // cross-profile app linking works only towards the parent. 6002 final UserInfo parent = getProfileParent(sourceUserId); 6003 synchronized(mPackages) { 6004 int flags = updateFlagsForResolve(0, parent.id, intent); 6005 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 6006 intent, resolvedType, flags, sourceUserId, parent.id); 6007 return xpDomainInfo != null; 6008 } 6009 } 6010 return false; 6011 } 6012 6013 private UserInfo getProfileParent(int userId) { 6014 final long identity = Binder.clearCallingIdentity(); 6015 try { 6016 return sUserManager.getProfileParent(userId); 6017 } finally { 6018 Binder.restoreCallingIdentity(identity); 6019 } 6020 } 6021 6022 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 6023 String resolvedType, int userId) { 6024 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 6025 if (resolver != null) { 6026 return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId); 6027 } 6028 return null; 6029 } 6030 6031 @Override 6032 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 6033 String resolvedType, int flags, int userId) { 6034 try { 6035 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 6036 6037 return new ParceledListSlice<>( 6038 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 6039 } finally { 6040 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6041 } 6042 } 6043 6044 /** 6045 * Returns the package name of the calling Uid if it's an instant app. If it isn't 6046 * instant, returns {@code null}. 6047 */ 6048 private String getInstantAppPackageName(int callingUid) { 6049 final int appId = UserHandle.getAppId(callingUid); 6050 synchronized (mPackages) { 6051 final Object obj = mSettings.getUserIdLPr(appId); 6052 if (obj instanceof PackageSetting) { 6053 final PackageSetting ps = (PackageSetting) obj; 6054 final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid)); 6055 return isInstantApp ? ps.pkg.packageName : null; 6056 } 6057 } 6058 return null; 6059 } 6060 6061 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 6062 String resolvedType, int flags, int userId) { 6063 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6064 final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid()); 6065 flags = updateFlagsForResolve(flags, userId, intent); 6066 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6067 false /* requireFullPermission */, false /* checkShell */, 6068 "query intent activities"); 6069 ComponentName comp = intent.getComponent(); 6070 if (comp == null) { 6071 if (intent.getSelector() != null) { 6072 intent = intent.getSelector(); 6073 comp = intent.getComponent(); 6074 } 6075 } 6076 6077 if (comp != null) { 6078 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6079 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 6080 if (ai != null) { 6081 // When specifying an explicit component, we prevent the activity from being 6082 // used when either 1) the calling package is normal and the activity is within 6083 // an ephemeral application or 2) the calling package is ephemeral and the 6084 // activity is not visible to ephemeral applications. 6085 final boolean matchInstantApp = 6086 (flags & PackageManager.MATCH_INSTANT) != 0; 6087 final boolean matchVisibleToInstantAppOnly = 6088 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 6089 final boolean isCallerInstantApp = 6090 instantAppPkgName != null; 6091 final boolean isTargetSameInstantApp = 6092 comp.getPackageName().equals(instantAppPkgName); 6093 final boolean isTargetInstantApp = 6094 (ai.applicationInfo.privateFlags 6095 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 6096 final boolean isTargetHiddenFromInstantApp = 6097 (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0; 6098 final boolean blockResolution = 6099 !isTargetSameInstantApp 6100 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 6101 || (matchVisibleToInstantAppOnly && isCallerInstantApp 6102 && isTargetHiddenFromInstantApp)); 6103 if (!blockResolution) { 6104 final ResolveInfo ri = new ResolveInfo(); 6105 ri.activityInfo = ai; 6106 list.add(ri); 6107 } 6108 } 6109 return list; 6110 } 6111 6112 // reader 6113 boolean sortResult = false; 6114 boolean addEphemeral = false; 6115 List<ResolveInfo> result; 6116 final String pkgName = intent.getPackage(); 6117 synchronized (mPackages) { 6118 if (pkgName == null) { 6119 List<CrossProfileIntentFilter> matchingFilters = 6120 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 6121 // Check for results that need to skip the current profile. 6122 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 6123 resolvedType, flags, userId); 6124 if (xpResolveInfo != null) { 6125 List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1); 6126 xpResult.add(xpResolveInfo); 6127 return filterForEphemeral( 6128 filterIfNotSystemUser(xpResult, userId), instantAppPkgName); 6129 } 6130 6131 // Check for results in the current profile. 6132 result = filterIfNotSystemUser(mActivities.queryIntent( 6133 intent, resolvedType, flags, userId), userId); 6134 addEphemeral = 6135 isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/); 6136 6137 // Check for cross profile results. 6138 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 6139 xpResolveInfo = queryCrossProfileIntents( 6140 matchingFilters, intent, resolvedType, flags, userId, 6141 hasNonNegativePriorityResult); 6142 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 6143 boolean isVisibleToUser = filterIfNotSystemUser( 6144 Collections.singletonList(xpResolveInfo), userId).size() > 0; 6145 if (isVisibleToUser) { 6146 result.add(xpResolveInfo); 6147 sortResult = true; 6148 } 6149 } 6150 if (hasWebURI(intent)) { 6151 CrossProfileDomainInfo xpDomainInfo = null; 6152 final UserInfo parent = getProfileParent(userId); 6153 if (parent != null) { 6154 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 6155 flags, userId, parent.id); 6156 } 6157 if (xpDomainInfo != null) { 6158 if (xpResolveInfo != null) { 6159 // If we didn't remove it, the cross-profile ResolveInfo would be twice 6160 // in the result. 6161 result.remove(xpResolveInfo); 6162 } 6163 if (result.size() == 0 && !addEphemeral) { 6164 // No result in current profile, but found candidate in parent user. 6165 // And we are not going to add emphemeral app, so we can return the 6166 // result straight away. 6167 result.add(xpDomainInfo.resolveInfo); 6168 return filterForEphemeral(result, instantAppPkgName); 6169 } 6170 } else if (result.size() <= 1 && !addEphemeral) { 6171 // No result in parent user and <= 1 result in current profile, and we 6172 // are not going to add emphemeral app, so we can return the result without 6173 // further processing. 6174 return filterForEphemeral(result, instantAppPkgName); 6175 } 6176 // We have more than one candidate (combining results from current and parent 6177 // profile), so we need filtering and sorting. 6178 result = filterCandidatesWithDomainPreferredActivitiesLPr( 6179 intent, flags, result, xpDomainInfo, userId); 6180 sortResult = true; 6181 } 6182 } else { 6183 final PackageParser.Package pkg = mPackages.get(pkgName); 6184 if (pkg != null) { 6185 result = filterForEphemeral(filterIfNotSystemUser( 6186 mActivities.queryIntentForPackage( 6187 intent, resolvedType, flags, pkg.activities, userId), 6188 userId), instantAppPkgName); 6189 } else { 6190 // the caller wants to resolve for a particular package; however, there 6191 // were no installed results, so, try to find an ephemeral result 6192 addEphemeral = isEphemeralAllowed( 6193 intent, null /*result*/, userId, true /*skipPackageCheck*/); 6194 result = new ArrayList<ResolveInfo>(); 6195 } 6196 } 6197 } 6198 if (addEphemeral) { 6199 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 6200 final EphemeralRequest requestObject = new EphemeralRequest( 6201 null /*responseObj*/, intent /*origIntent*/, resolvedType, 6202 null /*launchIntent*/, null /*callingPackage*/, userId); 6203 final EphemeralResponse intentInfo = EphemeralResolver.doEphemeralResolutionPhaseOne( 6204 mContext, mEphemeralResolverConnection, requestObject); 6205 if (intentInfo != null) { 6206 if (DEBUG_EPHEMERAL) { 6207 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 6208 } 6209 final ResolveInfo ephemeralInstaller = new ResolveInfo(mEphemeralInstallerInfo); 6210 ephemeralInstaller.ephemeralResponse = intentInfo; 6211 // make sure this resolver is the default 6212 ephemeralInstaller.isDefault = true; 6213 ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 6214 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 6215 // add a non-generic filter 6216 ephemeralInstaller.filter = new IntentFilter(intent.getAction()); 6217 ephemeralInstaller.filter.addDataPath( 6218 intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL); 6219 result.add(ephemeralInstaller); 6220 } 6221 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6222 } 6223 if (sortResult) { 6224 Collections.sort(result, mResolvePrioritySorter); 6225 } 6226 return filterForEphemeral(result, instantAppPkgName); 6227 } 6228 6229 private static class CrossProfileDomainInfo { 6230 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 6231 ResolveInfo resolveInfo; 6232 /* Best domain verification status of the activities found in the other profile */ 6233 int bestDomainVerificationStatus; 6234 } 6235 6236 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 6237 String resolvedType, int flags, int sourceUserId, int parentUserId) { 6238 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 6239 sourceUserId)) { 6240 return null; 6241 } 6242 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 6243 resolvedType, flags, parentUserId); 6244 6245 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 6246 return null; 6247 } 6248 CrossProfileDomainInfo result = null; 6249 int size = resultTargetUser.size(); 6250 for (int i = 0; i < size; i++) { 6251 ResolveInfo riTargetUser = resultTargetUser.get(i); 6252 // Intent filter verification is only for filters that specify a host. So don't return 6253 // those that handle all web uris. 6254 if (riTargetUser.handleAllWebDataURI) { 6255 continue; 6256 } 6257 String packageName = riTargetUser.activityInfo.packageName; 6258 PackageSetting ps = mSettings.mPackages.get(packageName); 6259 if (ps == null) { 6260 continue; 6261 } 6262 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 6263 int status = (int)(verificationState >> 32); 6264 if (result == null) { 6265 result = new CrossProfileDomainInfo(); 6266 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 6267 sourceUserId, parentUserId); 6268 result.bestDomainVerificationStatus = status; 6269 } else { 6270 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 6271 result.bestDomainVerificationStatus); 6272 } 6273 } 6274 // Don't consider matches with status NEVER across profiles. 6275 if (result != null && result.bestDomainVerificationStatus 6276 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6277 return null; 6278 } 6279 return result; 6280 } 6281 6282 /** 6283 * Verification statuses are ordered from the worse to the best, except for 6284 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 6285 */ 6286 private int bestDomainVerificationStatus(int status1, int status2) { 6287 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6288 return status2; 6289 } 6290 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6291 return status1; 6292 } 6293 return (int) MathUtils.max(status1, status2); 6294 } 6295 6296 private boolean isUserEnabled(int userId) { 6297 long callingId = Binder.clearCallingIdentity(); 6298 try { 6299 UserInfo userInfo = sUserManager.getUserInfo(userId); 6300 return userInfo != null && userInfo.isEnabled(); 6301 } finally { 6302 Binder.restoreCallingIdentity(callingId); 6303 } 6304 } 6305 6306 /** 6307 * Filter out activities with systemUserOnly flag set, when current user is not System. 6308 * 6309 * @return filtered list 6310 */ 6311 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 6312 if (userId == UserHandle.USER_SYSTEM) { 6313 return resolveInfos; 6314 } 6315 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 6316 ResolveInfo info = resolveInfos.get(i); 6317 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 6318 resolveInfos.remove(i); 6319 } 6320 } 6321 return resolveInfos; 6322 } 6323 6324 /** 6325 * Filters out ephemeral activities. 6326 * <p>When resolving for an ephemeral app, only activities that 1) are defined in the 6327 * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned. 6328 * 6329 * @param resolveInfos The pre-filtered list of resolved activities 6330 * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering 6331 * is performed. 6332 * @return A filtered list of resolved activities. 6333 */ 6334 private List<ResolveInfo> filterForEphemeral(List<ResolveInfo> resolveInfos, 6335 String ephemeralPkgName) { 6336 if (ephemeralPkgName == null) { 6337 return resolveInfos; 6338 } 6339 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 6340 ResolveInfo info = resolveInfos.get(i); 6341 final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp(); 6342 // allow activities that are defined in the provided package 6343 if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) { 6344 continue; 6345 } 6346 // allow activities that have been explicitly exposed to ephemeral apps 6347 if (!isEphemeralApp 6348 && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) { 6349 continue; 6350 } 6351 resolveInfos.remove(i); 6352 } 6353 return resolveInfos; 6354 } 6355 6356 /** 6357 * @param resolveInfos list of resolve infos in descending priority order 6358 * @return if the list contains a resolve info with non-negative priority 6359 */ 6360 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 6361 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 6362 } 6363 6364 private static boolean hasWebURI(Intent intent) { 6365 if (intent.getData() == null) { 6366 return false; 6367 } 6368 final String scheme = intent.getScheme(); 6369 if (TextUtils.isEmpty(scheme)) { 6370 return false; 6371 } 6372 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 6373 } 6374 6375 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 6376 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 6377 int userId) { 6378 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 6379 6380 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 6381 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 6382 candidates.size()); 6383 } 6384 6385 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 6386 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 6387 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 6388 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 6389 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 6390 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 6391 6392 synchronized (mPackages) { 6393 final int count = candidates.size(); 6394 // First, try to use linked apps. Partition the candidates into four lists: 6395 // one for the final results, one for the "do not use ever", one for "undefined status" 6396 // and finally one for "browser app type". 6397 for (int n=0; n<count; n++) { 6398 ResolveInfo info = candidates.get(n); 6399 String packageName = info.activityInfo.packageName; 6400 PackageSetting ps = mSettings.mPackages.get(packageName); 6401 if (ps != null) { 6402 // Add to the special match all list (Browser use case) 6403 if (info.handleAllWebDataURI) { 6404 matchAllList.add(info); 6405 continue; 6406 } 6407 // Try to get the status from User settings first 6408 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 6409 int status = (int)(packedStatus >> 32); 6410 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 6411 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 6412 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6413 Slog.i(TAG, " + always: " + info.activityInfo.packageName 6414 + " : linkgen=" + linkGeneration); 6415 } 6416 // Use link-enabled generation as preferredOrder, i.e. 6417 // prefer newly-enabled over earlier-enabled. 6418 info.preferredOrder = linkGeneration; 6419 alwaysList.add(info); 6420 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6421 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6422 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 6423 } 6424 neverList.add(info); 6425 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 6426 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6427 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 6428 } 6429 alwaysAskList.add(info); 6430 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 6431 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 6432 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6433 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 6434 } 6435 undefinedList.add(info); 6436 } 6437 } 6438 } 6439 6440 // We'll want to include browser possibilities in a few cases 6441 boolean includeBrowser = false; 6442 6443 // First try to add the "always" resolution(s) for the current user, if any 6444 if (alwaysList.size() > 0) { 6445 result.addAll(alwaysList); 6446 } else { 6447 // Add all undefined apps as we want them to appear in the disambiguation dialog. 6448 result.addAll(undefinedList); 6449 // Maybe add one for the other profile. 6450 if (xpDomainInfo != null && ( 6451 xpDomainInfo.bestDomainVerificationStatus 6452 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 6453 result.add(xpDomainInfo.resolveInfo); 6454 } 6455 includeBrowser = true; 6456 } 6457 6458 // The presence of any 'always ask' alternatives means we'll also offer browsers. 6459 // If there were 'always' entries their preferred order has been set, so we also 6460 // back that off to make the alternatives equivalent 6461 if (alwaysAskList.size() > 0) { 6462 for (ResolveInfo i : result) { 6463 i.preferredOrder = 0; 6464 } 6465 result.addAll(alwaysAskList); 6466 includeBrowser = true; 6467 } 6468 6469 if (includeBrowser) { 6470 // Also add browsers (all of them or only the default one) 6471 if (DEBUG_DOMAIN_VERIFICATION) { 6472 Slog.v(TAG, " ...including browsers in candidate set"); 6473 } 6474 if ((matchFlags & MATCH_ALL) != 0) { 6475 result.addAll(matchAllList); 6476 } else { 6477 // Browser/generic handling case. If there's a default browser, go straight 6478 // to that (but only if there is no other higher-priority match). 6479 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 6480 int maxMatchPrio = 0; 6481 ResolveInfo defaultBrowserMatch = null; 6482 final int numCandidates = matchAllList.size(); 6483 for (int n = 0; n < numCandidates; n++) { 6484 ResolveInfo info = matchAllList.get(n); 6485 // track the highest overall match priority... 6486 if (info.priority > maxMatchPrio) { 6487 maxMatchPrio = info.priority; 6488 } 6489 // ...and the highest-priority default browser match 6490 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 6491 if (defaultBrowserMatch == null 6492 || (defaultBrowserMatch.priority < info.priority)) { 6493 if (debug) { 6494 Slog.v(TAG, "Considering default browser match " + info); 6495 } 6496 defaultBrowserMatch = info; 6497 } 6498 } 6499 } 6500 if (defaultBrowserMatch != null 6501 && defaultBrowserMatch.priority >= maxMatchPrio 6502 && !TextUtils.isEmpty(defaultBrowserPackageName)) 6503 { 6504 if (debug) { 6505 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 6506 } 6507 result.add(defaultBrowserMatch); 6508 } else { 6509 result.addAll(matchAllList); 6510 } 6511 } 6512 6513 // If there is nothing selected, add all candidates and remove the ones that the user 6514 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 6515 if (result.size() == 0) { 6516 result.addAll(candidates); 6517 result.removeAll(neverList); 6518 } 6519 } 6520 } 6521 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 6522 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 6523 result.size()); 6524 for (ResolveInfo info : result) { 6525 Slog.v(TAG, " + " + info.activityInfo); 6526 } 6527 } 6528 return result; 6529 } 6530 6531 // Returns a packed value as a long: 6532 // 6533 // high 'int'-sized word: link status: undefined/ask/never/always. 6534 // low 'int'-sized word: relative priority among 'always' results. 6535 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 6536 long result = ps.getDomainVerificationStatusForUser(userId); 6537 // if none available, get the master status 6538 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 6539 if (ps.getIntentFilterVerificationInfo() != null) { 6540 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 6541 } 6542 } 6543 return result; 6544 } 6545 6546 private ResolveInfo querySkipCurrentProfileIntents( 6547 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 6548 int flags, int sourceUserId) { 6549 if (matchingFilters != null) { 6550 int size = matchingFilters.size(); 6551 for (int i = 0; i < size; i ++) { 6552 CrossProfileIntentFilter filter = matchingFilters.get(i); 6553 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 6554 // Checking if there are activities in the target user that can handle the 6555 // intent. 6556 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 6557 resolvedType, flags, sourceUserId); 6558 if (resolveInfo != null) { 6559 return resolveInfo; 6560 } 6561 } 6562 } 6563 } 6564 return null; 6565 } 6566 6567 // Return matching ResolveInfo in target user if any. 6568 private ResolveInfo queryCrossProfileIntents( 6569 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 6570 int flags, int sourceUserId, boolean matchInCurrentProfile) { 6571 if (matchingFilters != null) { 6572 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 6573 // match the same intent. For performance reasons, it is better not to 6574 // run queryIntent twice for the same userId 6575 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 6576 int size = matchingFilters.size(); 6577 for (int i = 0; i < size; i++) { 6578 CrossProfileIntentFilter filter = matchingFilters.get(i); 6579 int targetUserId = filter.getTargetUserId(); 6580 boolean skipCurrentProfile = 6581 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 6582 boolean skipCurrentProfileIfNoMatchFound = 6583 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 6584 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 6585 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 6586 // Checking if there are activities in the target user that can handle the 6587 // intent. 6588 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 6589 resolvedType, flags, sourceUserId); 6590 if (resolveInfo != null) return resolveInfo; 6591 alreadyTriedUserIds.put(targetUserId, true); 6592 } 6593 } 6594 } 6595 return null; 6596 } 6597 6598 /** 6599 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 6600 * will forward the intent to the filter's target user. 6601 * Otherwise, returns null. 6602 */ 6603 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 6604 String resolvedType, int flags, int sourceUserId) { 6605 int targetUserId = filter.getTargetUserId(); 6606 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 6607 resolvedType, flags, targetUserId); 6608 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 6609 // If all the matches in the target profile are suspended, return null. 6610 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 6611 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 6612 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 6613 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 6614 targetUserId); 6615 } 6616 } 6617 } 6618 return null; 6619 } 6620 6621 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 6622 int sourceUserId, int targetUserId) { 6623 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 6624 long ident = Binder.clearCallingIdentity(); 6625 boolean targetIsProfile; 6626 try { 6627 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 6628 } finally { 6629 Binder.restoreCallingIdentity(ident); 6630 } 6631 String className; 6632 if (targetIsProfile) { 6633 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 6634 } else { 6635 className = FORWARD_INTENT_TO_PARENT; 6636 } 6637 ComponentName forwardingActivityComponentName = new ComponentName( 6638 mAndroidApplication.packageName, className); 6639 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 6640 sourceUserId); 6641 if (!targetIsProfile) { 6642 forwardingActivityInfo.showUserIcon = targetUserId; 6643 forwardingResolveInfo.noResourceId = true; 6644 } 6645 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 6646 forwardingResolveInfo.priority = 0; 6647 forwardingResolveInfo.preferredOrder = 0; 6648 forwardingResolveInfo.match = 0; 6649 forwardingResolveInfo.isDefault = true; 6650 forwardingResolveInfo.filter = filter; 6651 forwardingResolveInfo.targetUserId = targetUserId; 6652 return forwardingResolveInfo; 6653 } 6654 6655 @Override 6656 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 6657 Intent[] specifics, String[] specificTypes, Intent intent, 6658 String resolvedType, int flags, int userId) { 6659 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 6660 specificTypes, intent, resolvedType, flags, userId)); 6661 } 6662 6663 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 6664 Intent[] specifics, String[] specificTypes, Intent intent, 6665 String resolvedType, int flags, int userId) { 6666 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6667 flags = updateFlagsForResolve(flags, userId, intent); 6668 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6669 false /* requireFullPermission */, false /* checkShell */, 6670 "query intent activity options"); 6671 final String resultsAction = intent.getAction(); 6672 6673 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 6674 | PackageManager.GET_RESOLVED_FILTER, userId); 6675 6676 if (DEBUG_INTENT_MATCHING) { 6677 Log.v(TAG, "Query " + intent + ": " + results); 6678 } 6679 6680 int specificsPos = 0; 6681 int N; 6682 6683 // todo: note that the algorithm used here is O(N^2). This 6684 // isn't a problem in our current environment, but if we start running 6685 // into situations where we have more than 5 or 10 matches then this 6686 // should probably be changed to something smarter... 6687 6688 // First we go through and resolve each of the specific items 6689 // that were supplied, taking care of removing any corresponding 6690 // duplicate items in the generic resolve list. 6691 if (specifics != null) { 6692 for (int i=0; i<specifics.length; i++) { 6693 final Intent sintent = specifics[i]; 6694 if (sintent == null) { 6695 continue; 6696 } 6697 6698 if (DEBUG_INTENT_MATCHING) { 6699 Log.v(TAG, "Specific #" + i + ": " + sintent); 6700 } 6701 6702 String action = sintent.getAction(); 6703 if (resultsAction != null && resultsAction.equals(action)) { 6704 // If this action was explicitly requested, then don't 6705 // remove things that have it. 6706 action = null; 6707 } 6708 6709 ResolveInfo ri = null; 6710 ActivityInfo ai = null; 6711 6712 ComponentName comp = sintent.getComponent(); 6713 if (comp == null) { 6714 ri = resolveIntent( 6715 sintent, 6716 specificTypes != null ? specificTypes[i] : null, 6717 flags, userId); 6718 if (ri == null) { 6719 continue; 6720 } 6721 if (ri == mResolveInfo) { 6722 // ACK! Must do something better with this. 6723 } 6724 ai = ri.activityInfo; 6725 comp = new ComponentName(ai.applicationInfo.packageName, 6726 ai.name); 6727 } else { 6728 ai = getActivityInfo(comp, flags, userId); 6729 if (ai == null) { 6730 continue; 6731 } 6732 } 6733 6734 // Look for any generic query activities that are duplicates 6735 // of this specific one, and remove them from the results. 6736 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 6737 N = results.size(); 6738 int j; 6739 for (j=specificsPos; j<N; j++) { 6740 ResolveInfo sri = results.get(j); 6741 if ((sri.activityInfo.name.equals(comp.getClassName()) 6742 && sri.activityInfo.applicationInfo.packageName.equals( 6743 comp.getPackageName())) 6744 || (action != null && sri.filter.matchAction(action))) { 6745 results.remove(j); 6746 if (DEBUG_INTENT_MATCHING) Log.v( 6747 TAG, "Removing duplicate item from " + j 6748 + " due to specific " + specificsPos); 6749 if (ri == null) { 6750 ri = sri; 6751 } 6752 j--; 6753 N--; 6754 } 6755 } 6756 6757 // Add this specific item to its proper place. 6758 if (ri == null) { 6759 ri = new ResolveInfo(); 6760 ri.activityInfo = ai; 6761 } 6762 results.add(specificsPos, ri); 6763 ri.specificIndex = i; 6764 specificsPos++; 6765 } 6766 } 6767 6768 // Now we go through the remaining generic results and remove any 6769 // duplicate actions that are found here. 6770 N = results.size(); 6771 for (int i=specificsPos; i<N-1; i++) { 6772 final ResolveInfo rii = results.get(i); 6773 if (rii.filter == null) { 6774 continue; 6775 } 6776 6777 // Iterate over all of the actions of this result's intent 6778 // filter... typically this should be just one. 6779 final Iterator<String> it = rii.filter.actionsIterator(); 6780 if (it == null) { 6781 continue; 6782 } 6783 while (it.hasNext()) { 6784 final String action = it.next(); 6785 if (resultsAction != null && resultsAction.equals(action)) { 6786 // If this action was explicitly requested, then don't 6787 // remove things that have it. 6788 continue; 6789 } 6790 for (int j=i+1; j<N; j++) { 6791 final ResolveInfo rij = results.get(j); 6792 if (rij.filter != null && rij.filter.hasAction(action)) { 6793 results.remove(j); 6794 if (DEBUG_INTENT_MATCHING) Log.v( 6795 TAG, "Removing duplicate item from " + j 6796 + " due to action " + action + " at " + i); 6797 j--; 6798 N--; 6799 } 6800 } 6801 } 6802 6803 // If the caller didn't request filter information, drop it now 6804 // so we don't have to marshall/unmarshall it. 6805 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6806 rii.filter = null; 6807 } 6808 } 6809 6810 // Filter out the caller activity if so requested. 6811 if (caller != null) { 6812 N = results.size(); 6813 for (int i=0; i<N; i++) { 6814 ActivityInfo ainfo = results.get(i).activityInfo; 6815 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 6816 && caller.getClassName().equals(ainfo.name)) { 6817 results.remove(i); 6818 break; 6819 } 6820 } 6821 } 6822 6823 // If the caller didn't request filter information, 6824 // drop them now so we don't have to 6825 // marshall/unmarshall it. 6826 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6827 N = results.size(); 6828 for (int i=0; i<N; i++) { 6829 results.get(i).filter = null; 6830 } 6831 } 6832 6833 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 6834 return results; 6835 } 6836 6837 @Override 6838 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 6839 String resolvedType, int flags, int userId) { 6840 return new ParceledListSlice<>( 6841 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 6842 } 6843 6844 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 6845 String resolvedType, int flags, int userId) { 6846 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6847 flags = updateFlagsForResolve(flags, userId, intent); 6848 ComponentName comp = intent.getComponent(); 6849 if (comp == null) { 6850 if (intent.getSelector() != null) { 6851 intent = intent.getSelector(); 6852 comp = intent.getComponent(); 6853 } 6854 } 6855 if (comp != null) { 6856 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6857 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 6858 if (ai != null) { 6859 ResolveInfo ri = new ResolveInfo(); 6860 ri.activityInfo = ai; 6861 list.add(ri); 6862 } 6863 return list; 6864 } 6865 6866 // reader 6867 synchronized (mPackages) { 6868 String pkgName = intent.getPackage(); 6869 if (pkgName == null) { 6870 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 6871 } 6872 final PackageParser.Package pkg = mPackages.get(pkgName); 6873 if (pkg != null) { 6874 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 6875 userId); 6876 } 6877 return Collections.emptyList(); 6878 } 6879 } 6880 6881 @Override 6882 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 6883 if (!sUserManager.exists(userId)) return null; 6884 flags = updateFlagsForResolve(flags, userId, intent); 6885 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 6886 if (query != null) { 6887 if (query.size() >= 1) { 6888 // If there is more than one service with the same priority, 6889 // just arbitrarily pick the first one. 6890 return query.get(0); 6891 } 6892 } 6893 return null; 6894 } 6895 6896 @Override 6897 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 6898 String resolvedType, int flags, int userId) { 6899 return new ParceledListSlice<>( 6900 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 6901 } 6902 6903 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 6904 String resolvedType, int flags, int userId) { 6905 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6906 flags = updateFlagsForResolve(flags, userId, intent); 6907 ComponentName comp = intent.getComponent(); 6908 if (comp == null) { 6909 if (intent.getSelector() != null) { 6910 intent = intent.getSelector(); 6911 comp = intent.getComponent(); 6912 } 6913 } 6914 if (comp != null) { 6915 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6916 final ServiceInfo si = getServiceInfo(comp, flags, userId); 6917 if (si != null) { 6918 final ResolveInfo ri = new ResolveInfo(); 6919 ri.serviceInfo = si; 6920 list.add(ri); 6921 } 6922 return list; 6923 } 6924 6925 // reader 6926 synchronized (mPackages) { 6927 String pkgName = intent.getPackage(); 6928 if (pkgName == null) { 6929 return mServices.queryIntent(intent, resolvedType, flags, userId); 6930 } 6931 final PackageParser.Package pkg = mPackages.get(pkgName); 6932 if (pkg != null) { 6933 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 6934 userId); 6935 } 6936 return Collections.emptyList(); 6937 } 6938 } 6939 6940 @Override 6941 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 6942 String resolvedType, int flags, int userId) { 6943 return new ParceledListSlice<>( 6944 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 6945 } 6946 6947 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 6948 Intent intent, String resolvedType, int flags, int userId) { 6949 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6950 flags = updateFlagsForResolve(flags, userId, intent); 6951 ComponentName comp = intent.getComponent(); 6952 if (comp == null) { 6953 if (intent.getSelector() != null) { 6954 intent = intent.getSelector(); 6955 comp = intent.getComponent(); 6956 } 6957 } 6958 if (comp != null) { 6959 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6960 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 6961 if (pi != null) { 6962 final ResolveInfo ri = new ResolveInfo(); 6963 ri.providerInfo = pi; 6964 list.add(ri); 6965 } 6966 return list; 6967 } 6968 6969 // reader 6970 synchronized (mPackages) { 6971 String pkgName = intent.getPackage(); 6972 if (pkgName == null) { 6973 return mProviders.queryIntent(intent, resolvedType, flags, userId); 6974 } 6975 final PackageParser.Package pkg = mPackages.get(pkgName); 6976 if (pkg != null) { 6977 return mProviders.queryIntentForPackage( 6978 intent, resolvedType, flags, pkg.providers, userId); 6979 } 6980 return Collections.emptyList(); 6981 } 6982 } 6983 6984 @Override 6985 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 6986 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6987 flags = updateFlagsForPackage(flags, userId, null); 6988 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 6989 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6990 true /* requireFullPermission */, false /* checkShell */, 6991 "get installed packages"); 6992 6993 // writer 6994 synchronized (mPackages) { 6995 ArrayList<PackageInfo> list; 6996 if (listUninstalled) { 6997 list = new ArrayList<>(mSettings.mPackages.size()); 6998 for (PackageSetting ps : mSettings.mPackages.values()) { 6999 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 7000 continue; 7001 } 7002 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 7003 if (pi != null) { 7004 list.add(pi); 7005 } 7006 } 7007 } else { 7008 list = new ArrayList<>(mPackages.size()); 7009 for (PackageParser.Package p : mPackages.values()) { 7010 if (filterSharedLibPackageLPr((PackageSetting) p.mExtras, 7011 Binder.getCallingUid(), userId)) { 7012 continue; 7013 } 7014 final PackageInfo pi = generatePackageInfo((PackageSetting) 7015 p.mExtras, flags, userId); 7016 if (pi != null) { 7017 list.add(pi); 7018 } 7019 } 7020 } 7021 7022 return new ParceledListSlice<>(list); 7023 } 7024 } 7025 7026 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 7027 String[] permissions, boolean[] tmp, int flags, int userId) { 7028 int numMatch = 0; 7029 final PermissionsState permissionsState = ps.getPermissionsState(); 7030 for (int i=0; i<permissions.length; i++) { 7031 final String permission = permissions[i]; 7032 if (permissionsState.hasPermission(permission, userId)) { 7033 tmp[i] = true; 7034 numMatch++; 7035 } else { 7036 tmp[i] = false; 7037 } 7038 } 7039 if (numMatch == 0) { 7040 return; 7041 } 7042 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 7043 7044 // The above might return null in cases of uninstalled apps or install-state 7045 // skew across users/profiles. 7046 if (pi != null) { 7047 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 7048 if (numMatch == permissions.length) { 7049 pi.requestedPermissions = permissions; 7050 } else { 7051 pi.requestedPermissions = new String[numMatch]; 7052 numMatch = 0; 7053 for (int i=0; i<permissions.length; i++) { 7054 if (tmp[i]) { 7055 pi.requestedPermissions[numMatch] = permissions[i]; 7056 numMatch++; 7057 } 7058 } 7059 } 7060 } 7061 list.add(pi); 7062 } 7063 } 7064 7065 @Override 7066 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 7067 String[] permissions, int flags, int userId) { 7068 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7069 flags = updateFlagsForPackage(flags, userId, permissions); 7070 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7071 true /* requireFullPermission */, false /* checkShell */, 7072 "get packages holding permissions"); 7073 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7074 7075 // writer 7076 synchronized (mPackages) { 7077 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 7078 boolean[] tmpBools = new boolean[permissions.length]; 7079 if (listUninstalled) { 7080 for (PackageSetting ps : mSettings.mPackages.values()) { 7081 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 7082 userId); 7083 } 7084 } else { 7085 for (PackageParser.Package pkg : mPackages.values()) { 7086 PackageSetting ps = (PackageSetting)pkg.mExtras; 7087 if (ps != null) { 7088 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 7089 userId); 7090 } 7091 } 7092 } 7093 7094 return new ParceledListSlice<PackageInfo>(list); 7095 } 7096 } 7097 7098 @Override 7099 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 7100 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7101 flags = updateFlagsForApplication(flags, userId, null); 7102 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7103 7104 // writer 7105 synchronized (mPackages) { 7106 ArrayList<ApplicationInfo> list; 7107 if (listUninstalled) { 7108 list = new ArrayList<>(mSettings.mPackages.size()); 7109 for (PackageSetting ps : mSettings.mPackages.values()) { 7110 ApplicationInfo ai; 7111 int effectiveFlags = flags; 7112 if (ps.isSystem()) { 7113 effectiveFlags |= PackageManager.MATCH_ANY_USER; 7114 } 7115 if (ps.pkg != null) { 7116 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 7117 continue; 7118 } 7119 ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags, 7120 ps.readUserState(userId), userId); 7121 if (ai != null) { 7122 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 7123 } 7124 } else { 7125 // Shared lib filtering done in generateApplicationInfoFromSettingsLPw 7126 // and already converts to externally visible package name 7127 ai = generateApplicationInfoFromSettingsLPw(ps.name, 7128 Binder.getCallingUid(), effectiveFlags, userId); 7129 } 7130 if (ai != null) { 7131 list.add(ai); 7132 } 7133 } 7134 } else { 7135 list = new ArrayList<>(mPackages.size()); 7136 for (PackageParser.Package p : mPackages.values()) { 7137 if (p.mExtras != null) { 7138 PackageSetting ps = (PackageSetting) p.mExtras; 7139 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 7140 continue; 7141 } 7142 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 7143 ps.readUserState(userId), userId); 7144 if (ai != null) { 7145 ai.packageName = resolveExternalPackageNameLPr(p); 7146 list.add(ai); 7147 } 7148 } 7149 } 7150 } 7151 7152 return new ParceledListSlice<>(list); 7153 } 7154 } 7155 7156 @Override 7157 public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) { 7158 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7159 return null; 7160 } 7161 7162 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS, 7163 "getEphemeralApplications"); 7164 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7165 true /* requireFullPermission */, false /* checkShell */, 7166 "getEphemeralApplications"); 7167 synchronized (mPackages) { 7168 List<InstantAppInfo> instantApps = mInstantAppRegistry 7169 .getInstantAppsLPr(userId); 7170 if (instantApps != null) { 7171 return new ParceledListSlice<>(instantApps); 7172 } 7173 } 7174 return null; 7175 } 7176 7177 @Override 7178 public boolean isInstantApp(String packageName, int userId) { 7179 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7180 true /* requireFullPermission */, false /* checkShell */, 7181 "isInstantApp"); 7182 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7183 return false; 7184 } 7185 7186 if (!isCallerSameApp(packageName)) { 7187 return false; 7188 } 7189 synchronized (mPackages) { 7190 final PackageSetting ps = mSettings.mPackages.get(packageName); 7191 if (ps != null) { 7192 return ps.getInstantApp(userId); 7193 } 7194 } 7195 return false; 7196 } 7197 7198 @Override 7199 public byte[] getInstantAppCookie(String packageName, int userId) { 7200 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7201 return null; 7202 } 7203 7204 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7205 true /* requireFullPermission */, false /* checkShell */, 7206 "getInstantAppCookie"); 7207 if (!isCallerSameApp(packageName)) { 7208 return null; 7209 } 7210 synchronized (mPackages) { 7211 return mInstantAppRegistry.getInstantAppCookieLPw( 7212 packageName, userId); 7213 } 7214 } 7215 7216 @Override 7217 public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) { 7218 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7219 return true; 7220 } 7221 7222 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7223 true /* requireFullPermission */, true /* checkShell */, 7224 "setInstantAppCookie"); 7225 if (!isCallerSameApp(packageName)) { 7226 return false; 7227 } 7228 synchronized (mPackages) { 7229 return mInstantAppRegistry.setInstantAppCookieLPw( 7230 packageName, cookie, userId); 7231 } 7232 } 7233 7234 @Override 7235 public Bitmap getInstantAppIcon(String packageName, int userId) { 7236 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7237 return null; 7238 } 7239 7240 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS, 7241 "getInstantAppIcon"); 7242 7243 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7244 true /* requireFullPermission */, false /* checkShell */, 7245 "getInstantAppIcon"); 7246 7247 synchronized (mPackages) { 7248 return mInstantAppRegistry.getInstantAppIconLPw( 7249 packageName, userId); 7250 } 7251 } 7252 7253 private boolean isCallerSameApp(String packageName) { 7254 PackageParser.Package pkg = mPackages.get(packageName); 7255 return pkg != null 7256 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 7257 } 7258 7259 @Override 7260 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 7261 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 7262 } 7263 7264 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 7265 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 7266 7267 // reader 7268 synchronized (mPackages) { 7269 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 7270 final int userId = UserHandle.getCallingUserId(); 7271 while (i.hasNext()) { 7272 final PackageParser.Package p = i.next(); 7273 if (p.applicationInfo == null) continue; 7274 7275 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 7276 && !p.applicationInfo.isDirectBootAware(); 7277 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 7278 && p.applicationInfo.isDirectBootAware(); 7279 7280 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 7281 && (!mSafeMode || isSystemApp(p)) 7282 && (matchesUnaware || matchesAware)) { 7283 PackageSetting ps = mSettings.mPackages.get(p.packageName); 7284 if (ps != null) { 7285 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 7286 ps.readUserState(userId), userId); 7287 if (ai != null) { 7288 finalList.add(ai); 7289 } 7290 } 7291 } 7292 } 7293 } 7294 7295 return finalList; 7296 } 7297 7298 @Override 7299 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 7300 if (!sUserManager.exists(userId)) return null; 7301 flags = updateFlagsForComponent(flags, userId, name); 7302 // reader 7303 synchronized (mPackages) { 7304 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 7305 PackageSetting ps = provider != null 7306 ? mSettings.mPackages.get(provider.owner.packageName) 7307 : null; 7308 return ps != null 7309 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 7310 ? PackageParser.generateProviderInfo(provider, flags, 7311 ps.readUserState(userId), userId) 7312 : null; 7313 } 7314 } 7315 7316 /** 7317 * @deprecated 7318 */ 7319 @Deprecated 7320 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 7321 // reader 7322 synchronized (mPackages) { 7323 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 7324 .entrySet().iterator(); 7325 final int userId = UserHandle.getCallingUserId(); 7326 while (i.hasNext()) { 7327 Map.Entry<String, PackageParser.Provider> entry = i.next(); 7328 PackageParser.Provider p = entry.getValue(); 7329 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 7330 7331 if (ps != null && p.syncable 7332 && (!mSafeMode || (p.info.applicationInfo.flags 7333 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 7334 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 7335 ps.readUserState(userId), userId); 7336 if (info != null) { 7337 outNames.add(entry.getKey()); 7338 outInfo.add(info); 7339 } 7340 } 7341 } 7342 } 7343 } 7344 7345 @Override 7346 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 7347 int uid, int flags) { 7348 final int userId = processName != null ? UserHandle.getUserId(uid) 7349 : UserHandle.getCallingUserId(); 7350 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7351 flags = updateFlagsForComponent(flags, userId, processName); 7352 7353 ArrayList<ProviderInfo> finalList = null; 7354 // reader 7355 synchronized (mPackages) { 7356 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 7357 while (i.hasNext()) { 7358 final PackageParser.Provider p = i.next(); 7359 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 7360 if (ps != null && p.info.authority != null 7361 && (processName == null 7362 || (p.info.processName.equals(processName) 7363 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 7364 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 7365 if (finalList == null) { 7366 finalList = new ArrayList<ProviderInfo>(3); 7367 } 7368 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 7369 ps.readUserState(userId), userId); 7370 if (info != null) { 7371 finalList.add(info); 7372 } 7373 } 7374 } 7375 } 7376 7377 if (finalList != null) { 7378 Collections.sort(finalList, mProviderInitOrderSorter); 7379 return new ParceledListSlice<ProviderInfo>(finalList); 7380 } 7381 7382 return ParceledListSlice.emptyList(); 7383 } 7384 7385 @Override 7386 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 7387 // reader 7388 synchronized (mPackages) { 7389 final PackageParser.Instrumentation i = mInstrumentation.get(name); 7390 return PackageParser.generateInstrumentationInfo(i, flags); 7391 } 7392 } 7393 7394 @Override 7395 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 7396 String targetPackage, int flags) { 7397 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 7398 } 7399 7400 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 7401 int flags) { 7402 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 7403 7404 // reader 7405 synchronized (mPackages) { 7406 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 7407 while (i.hasNext()) { 7408 final PackageParser.Instrumentation p = i.next(); 7409 if (targetPackage == null 7410 || targetPackage.equals(p.info.targetPackage)) { 7411 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 7412 flags); 7413 if (ii != null) { 7414 finalList.add(ii); 7415 } 7416 } 7417 } 7418 } 7419 7420 return finalList; 7421 } 7422 7423 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 7424 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 7425 if (overlays == null) { 7426 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 7427 return; 7428 } 7429 for (PackageParser.Package opkg : overlays.values()) { 7430 // Not much to do if idmap fails: we already logged the error 7431 // and we certainly don't want to abort installation of pkg simply 7432 // because an overlay didn't fit properly. For these reasons, 7433 // ignore the return value of createIdmapForPackagePairLI. 7434 createIdmapForPackagePairLI(pkg, opkg); 7435 } 7436 } 7437 7438 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 7439 PackageParser.Package opkg) { 7440 if (!opkg.mTrustedOverlay) { 7441 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 7442 opkg.baseCodePath + ": overlay not trusted"); 7443 return false; 7444 } 7445 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 7446 if (overlaySet == null) { 7447 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 7448 opkg.baseCodePath + " but target package has no known overlays"); 7449 return false; 7450 } 7451 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 7452 // TODO: generate idmap for split APKs 7453 try { 7454 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 7455 } catch (InstallerException e) { 7456 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 7457 + opkg.baseCodePath); 7458 return false; 7459 } 7460 PackageParser.Package[] overlayArray = 7461 overlaySet.values().toArray(new PackageParser.Package[0]); 7462 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 7463 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 7464 return p1.mOverlayPriority - p2.mOverlayPriority; 7465 } 7466 }; 7467 Arrays.sort(overlayArray, cmp); 7468 7469 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 7470 int i = 0; 7471 for (PackageParser.Package p : overlayArray) { 7472 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 7473 } 7474 return true; 7475 } 7476 7477 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 7478 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]"); 7479 try { 7480 scanDirLI(dir, parseFlags, scanFlags, currentTime); 7481 } finally { 7482 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7483 } 7484 } 7485 7486 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 7487 final File[] files = dir.listFiles(); 7488 if (ArrayUtils.isEmpty(files)) { 7489 Log.d(TAG, "No files in app dir " + dir); 7490 return; 7491 } 7492 7493 if (DEBUG_PACKAGE_SCANNING) { 7494 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 7495 + " flags=0x" + Integer.toHexString(parseFlags)); 7496 } 7497 ParallelPackageParser parallelPackageParser = new ParallelPackageParser( 7498 mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir); 7499 7500 // Submit files for parsing in parallel 7501 int fileCount = 0; 7502 for (File file : files) { 7503 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 7504 && !PackageInstallerService.isStageName(file.getName()); 7505 if (!isPackage) { 7506 // Ignore entries which are not packages 7507 continue; 7508 } 7509 parallelPackageParser.submit(file, parseFlags); 7510 fileCount++; 7511 } 7512 7513 // Process results one by one 7514 for (; fileCount > 0; fileCount--) { 7515 ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take(); 7516 Throwable throwable = parseResult.throwable; 7517 int errorCode = PackageManager.INSTALL_SUCCEEDED; 7518 7519 if (throwable == null) { 7520 // Static shared libraries have synthetic package names 7521 if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) { 7522 renameStaticSharedLibraryPackage(parseResult.pkg); 7523 } 7524 try { 7525 if (errorCode == PackageManager.INSTALL_SUCCEEDED) { 7526 scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags, 7527 currentTime, null); 7528 } 7529 } catch (PackageManagerException e) { 7530 errorCode = e.error; 7531 Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage()); 7532 } 7533 } else if (throwable instanceof PackageParser.PackageParserException) { 7534 PackageParser.PackageParserException e = (PackageParser.PackageParserException) 7535 throwable; 7536 errorCode = e.error; 7537 Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage()); 7538 } else { 7539 throw new IllegalStateException("Unexpected exception occurred while parsing " 7540 + parseResult.scanFile, throwable); 7541 } 7542 7543 // Delete invalid userdata apps 7544 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 7545 errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) { 7546 logCriticalInfo(Log.WARN, 7547 "Deleting invalid package at " + parseResult.scanFile); 7548 removeCodePathLI(parseResult.scanFile); 7549 } 7550 } 7551 parallelPackageParser.close(); 7552 } 7553 7554 private static File getSettingsProblemFile() { 7555 File dataDir = Environment.getDataDirectory(); 7556 File systemDir = new File(dataDir, "system"); 7557 File fname = new File(systemDir, "uiderrors.txt"); 7558 return fname; 7559 } 7560 7561 static void reportSettingsProblem(int priority, String msg) { 7562 logCriticalInfo(priority, msg); 7563 } 7564 7565 static void logCriticalInfo(int priority, String msg) { 7566 Slog.println(priority, TAG, msg); 7567 EventLogTags.writePmCriticalInfo(msg); 7568 try { 7569 File fname = getSettingsProblemFile(); 7570 FileOutputStream out = new FileOutputStream(fname, true); 7571 PrintWriter pw = new FastPrintWriter(out); 7572 SimpleDateFormat formatter = new SimpleDateFormat(); 7573 String dateString = formatter.format(new Date(System.currentTimeMillis())); 7574 pw.println(dateString + ": " + msg); 7575 pw.close(); 7576 FileUtils.setPermissions( 7577 fname.toString(), 7578 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 7579 -1, -1); 7580 } catch (java.io.IOException e) { 7581 } 7582 } 7583 7584 private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) { 7585 if (srcFile.isDirectory()) { 7586 final File baseFile = new File(pkg.baseCodePath); 7587 long maxModifiedTime = baseFile.lastModified(); 7588 if (pkg.splitCodePaths != null) { 7589 for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) { 7590 final File splitFile = new File(pkg.splitCodePaths[i]); 7591 maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified()); 7592 } 7593 } 7594 return maxModifiedTime; 7595 } 7596 return srcFile.lastModified(); 7597 } 7598 7599 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 7600 final int policyFlags) throws PackageManagerException { 7601 // When upgrading from pre-N MR1, verify the package time stamp using the package 7602 // directory and not the APK file. 7603 final long lastModifiedTime = mIsPreNMR1Upgrade 7604 ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile); 7605 if (ps != null 7606 && ps.codePath.equals(srcFile) 7607 && ps.timeStamp == lastModifiedTime 7608 && !isCompatSignatureUpdateNeeded(pkg) 7609 && !isRecoverSignatureUpdateNeeded(pkg)) { 7610 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 7611 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7612 ArraySet<PublicKey> signingKs; 7613 synchronized (mPackages) { 7614 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 7615 } 7616 if (ps.signatures.mSignatures != null 7617 && ps.signatures.mSignatures.length != 0 7618 && signingKs != null) { 7619 // Optimization: reuse the existing cached certificates 7620 // if the package appears to be unchanged. 7621 pkg.mSignatures = ps.signatures.mSignatures; 7622 pkg.mSigningKeys = signingKs; 7623 return; 7624 } 7625 7626 Slog.w(TAG, "PackageSetting for " + ps.name 7627 + " is missing signatures. Collecting certs again to recover them."); 7628 } else { 7629 Slog.i(TAG, srcFile.toString() + " changed; collecting certs"); 7630 } 7631 7632 try { 7633 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 7634 PackageParser.collectCertificates(pkg, policyFlags); 7635 } catch (PackageParserException e) { 7636 throw PackageManagerException.from(e); 7637 } finally { 7638 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7639 } 7640 } 7641 7642 /** 7643 * Traces a package scan. 7644 * @see #scanPackageLI(File, int, int, long, UserHandle) 7645 */ 7646 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 7647 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7648 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]"); 7649 try { 7650 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 7651 } finally { 7652 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7653 } 7654 } 7655 7656 /** 7657 * Scans a package and returns the newly parsed package. 7658 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 7659 */ 7660 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 7661 long currentTime, UserHandle user) throws PackageManagerException { 7662 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 7663 PackageParser pp = new PackageParser(); 7664 pp.setSeparateProcesses(mSeparateProcesses); 7665 pp.setOnlyCoreApps(mOnlyCore); 7666 pp.setDisplayMetrics(mMetrics); 7667 7668 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 7669 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 7670 } 7671 7672 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 7673 final PackageParser.Package pkg; 7674 try { 7675 pkg = pp.parsePackage(scanFile, parseFlags); 7676 } catch (PackageParserException e) { 7677 throw PackageManagerException.from(e); 7678 } finally { 7679 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7680 } 7681 7682 // Static shared libraries have synthetic package names 7683 if (pkg.applicationInfo.isStaticSharedLibrary()) { 7684 renameStaticSharedLibraryPackage(pkg); 7685 } 7686 7687 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 7688 } 7689 7690 /** 7691 * Scans a package and returns the newly parsed package. 7692 * @throws PackageManagerException on a parse error. 7693 */ 7694 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 7695 final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user) 7696 throws PackageManagerException { 7697 // If the package has children and this is the first dive in the function 7698 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 7699 // packages (parent and children) would be successfully scanned before the 7700 // actual scan since scanning mutates internal state and we want to atomically 7701 // install the package and its children. 7702 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7703 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7704 scanFlags |= SCAN_CHECK_ONLY; 7705 } 7706 } else { 7707 scanFlags &= ~SCAN_CHECK_ONLY; 7708 } 7709 7710 // Scan the parent 7711 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 7712 scanFlags, currentTime, user); 7713 7714 // Scan the children 7715 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7716 for (int i = 0; i < childCount; i++) { 7717 PackageParser.Package childPackage = pkg.childPackages.get(i); 7718 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 7719 currentTime, user); 7720 } 7721 7722 7723 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7724 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 7725 } 7726 7727 return scannedPkg; 7728 } 7729 7730 /** 7731 * Scans a package and returns the newly parsed package. 7732 * @throws PackageManagerException on a parse error. 7733 */ 7734 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 7735 int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user) 7736 throws PackageManagerException { 7737 PackageSetting ps = null; 7738 PackageSetting updatedPkg; 7739 // reader 7740 synchronized (mPackages) { 7741 // Look to see if we already know about this package. 7742 String oldName = mSettings.getRenamedPackageLPr(pkg.packageName); 7743 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 7744 // This package has been renamed to its original name. Let's 7745 // use that. 7746 ps = mSettings.getPackageLPr(oldName); 7747 } 7748 // If there was no original package, see one for the real package name. 7749 if (ps == null) { 7750 ps = mSettings.getPackageLPr(pkg.packageName); 7751 } 7752 // Check to see if this package could be hiding/updating a system 7753 // package. Must look for it either under the original or real 7754 // package name depending on our state. 7755 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 7756 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 7757 7758 // If this is a package we don't know about on the system partition, we 7759 // may need to remove disabled child packages on the system partition 7760 // or may need to not add child packages if the parent apk is updated 7761 // on the data partition and no longer defines this child package. 7762 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 7763 // If this is a parent package for an updated system app and this system 7764 // app got an OTA update which no longer defines some of the child packages 7765 // we have to prune them from the disabled system packages. 7766 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 7767 if (disabledPs != null) { 7768 final int scannedChildCount = (pkg.childPackages != null) 7769 ? pkg.childPackages.size() : 0; 7770 final int disabledChildCount = disabledPs.childPackageNames != null 7771 ? disabledPs.childPackageNames.size() : 0; 7772 for (int i = 0; i < disabledChildCount; i++) { 7773 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 7774 boolean disabledPackageAvailable = false; 7775 for (int j = 0; j < scannedChildCount; j++) { 7776 PackageParser.Package childPkg = pkg.childPackages.get(j); 7777 if (childPkg.packageName.equals(disabledChildPackageName)) { 7778 disabledPackageAvailable = true; 7779 break; 7780 } 7781 } 7782 if (!disabledPackageAvailable) { 7783 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 7784 } 7785 } 7786 } 7787 } 7788 } 7789 7790 boolean updatedPkgBetter = false; 7791 // First check if this is a system package that may involve an update 7792 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 7793 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 7794 // it needs to drop FLAG_PRIVILEGED. 7795 if (locationIsPrivileged(scanFile)) { 7796 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7797 } else { 7798 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7799 } 7800 7801 if (ps != null && !ps.codePath.equals(scanFile)) { 7802 // The path has changed from what was last scanned... check the 7803 // version of the new path against what we have stored to determine 7804 // what to do. 7805 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 7806 if (pkg.mVersionCode <= ps.versionCode) { 7807 // The system package has been updated and the code path does not match 7808 // Ignore entry. Skip it. 7809 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 7810 + " ignored: updated version " + ps.versionCode 7811 + " better than this " + pkg.mVersionCode); 7812 if (!updatedPkg.codePath.equals(scanFile)) { 7813 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 7814 + ps.name + " changing from " + updatedPkg.codePathString 7815 + " to " + scanFile); 7816 updatedPkg.codePath = scanFile; 7817 updatedPkg.codePathString = scanFile.toString(); 7818 updatedPkg.resourcePath = scanFile; 7819 updatedPkg.resourcePathString = scanFile.toString(); 7820 } 7821 updatedPkg.pkg = pkg; 7822 updatedPkg.versionCode = pkg.mVersionCode; 7823 7824 // Update the disabled system child packages to point to the package too. 7825 final int childCount = updatedPkg.childPackageNames != null 7826 ? updatedPkg.childPackageNames.size() : 0; 7827 for (int i = 0; i < childCount; i++) { 7828 String childPackageName = updatedPkg.childPackageNames.get(i); 7829 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 7830 childPackageName); 7831 if (updatedChildPkg != null) { 7832 updatedChildPkg.pkg = pkg; 7833 updatedChildPkg.versionCode = pkg.mVersionCode; 7834 } 7835 } 7836 7837 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 7838 + scanFile + " ignored: updated version " + ps.versionCode 7839 + " better than this " + pkg.mVersionCode); 7840 } else { 7841 // The current app on the system partition is better than 7842 // what we have updated to on the data partition; switch 7843 // back to the system partition version. 7844 // At this point, its safely assumed that package installation for 7845 // apps in system partition will go through. If not there won't be a working 7846 // version of the app 7847 // writer 7848 synchronized (mPackages) { 7849 // Just remove the loaded entries from package lists. 7850 mPackages.remove(ps.name); 7851 } 7852 7853 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7854 + " reverting from " + ps.codePathString 7855 + ": new version " + pkg.mVersionCode 7856 + " better than installed " + ps.versionCode); 7857 7858 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7859 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7860 synchronized (mInstallLock) { 7861 args.cleanUpResourcesLI(); 7862 } 7863 synchronized (mPackages) { 7864 mSettings.enableSystemPackageLPw(ps.name); 7865 } 7866 updatedPkgBetter = true; 7867 } 7868 } 7869 } 7870 7871 if (updatedPkg != null) { 7872 // An updated system app will not have the PARSE_IS_SYSTEM flag set 7873 // initially 7874 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 7875 7876 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 7877 // flag set initially 7878 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 7879 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 7880 } 7881 } 7882 7883 // Verify certificates against what was last scanned 7884 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 7885 7886 /* 7887 * A new system app appeared, but we already had a non-system one of the 7888 * same name installed earlier. 7889 */ 7890 boolean shouldHideSystemApp = false; 7891 if (updatedPkg == null && ps != null 7892 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 7893 /* 7894 * Check to make sure the signatures match first. If they don't, 7895 * wipe the installed application and its data. 7896 */ 7897 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 7898 != PackageManager.SIGNATURE_MATCH) { 7899 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 7900 + " signatures don't match existing userdata copy; removing"); 7901 try (PackageFreezer freezer = freezePackage(pkg.packageName, 7902 "scanPackageInternalLI")) { 7903 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 7904 } 7905 ps = null; 7906 } else { 7907 /* 7908 * If the newly-added system app is an older version than the 7909 * already installed version, hide it. It will be scanned later 7910 * and re-added like an update. 7911 */ 7912 if (pkg.mVersionCode <= ps.versionCode) { 7913 shouldHideSystemApp = true; 7914 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 7915 + " but new version " + pkg.mVersionCode + " better than installed " 7916 + ps.versionCode + "; hiding system"); 7917 } else { 7918 /* 7919 * The newly found system app is a newer version that the 7920 * one previously installed. Simply remove the 7921 * already-installed application and replace it with our own 7922 * while keeping the application data. 7923 */ 7924 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7925 + " reverting from " + ps.codePathString + ": new version " 7926 + pkg.mVersionCode + " better than installed " + ps.versionCode); 7927 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7928 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7929 synchronized (mInstallLock) { 7930 args.cleanUpResourcesLI(); 7931 } 7932 } 7933 } 7934 } 7935 7936 // The apk is forward locked (not public) if its code and resources 7937 // are kept in different files. (except for app in either system or 7938 // vendor path). 7939 // TODO grab this value from PackageSettings 7940 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7941 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 7942 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 7943 } 7944 } 7945 7946 // TODO: extend to support forward-locked splits 7947 String resourcePath = null; 7948 String baseResourcePath = null; 7949 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 7950 if (ps != null && ps.resourcePathString != null) { 7951 resourcePath = ps.resourcePathString; 7952 baseResourcePath = ps.resourcePathString; 7953 } else { 7954 // Should not happen at all. Just log an error. 7955 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 7956 } 7957 } else { 7958 resourcePath = pkg.codePath; 7959 baseResourcePath = pkg.baseCodePath; 7960 } 7961 7962 // Set application objects path explicitly. 7963 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 7964 pkg.setApplicationInfoCodePath(pkg.codePath); 7965 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 7966 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 7967 pkg.setApplicationInfoResourcePath(resourcePath); 7968 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 7969 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 7970 7971 final int userId = ((user == null) ? 0 : user.getIdentifier()); 7972 if (ps != null && ps.getInstantApp(userId)) { 7973 scanFlags |= SCAN_AS_INSTANT_APP; 7974 } 7975 7976 // Note that we invoke the following method only if we are about to unpack an application 7977 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 7978 | SCAN_UPDATE_SIGNATURE, currentTime, user); 7979 7980 /* 7981 * If the system app should be overridden by a previously installed 7982 * data, hide the system app now and let the /data/app scan pick it up 7983 * again. 7984 */ 7985 if (shouldHideSystemApp) { 7986 synchronized (mPackages) { 7987 mSettings.disableSystemPackageLPw(pkg.packageName, true); 7988 } 7989 } 7990 7991 return scannedPkg; 7992 } 7993 7994 private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) { 7995 // Derive the new package synthetic package name 7996 pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER 7997 + pkg.staticSharedLibVersion); 7998 } 7999 8000 private static String fixProcessName(String defProcessName, 8001 String processName) { 8002 if (processName == null) { 8003 return defProcessName; 8004 } 8005 return processName; 8006 } 8007 8008 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 8009 throws PackageManagerException { 8010 if (pkgSetting.signatures.mSignatures != null) { 8011 // Already existing package. Make sure signatures match 8012 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 8013 == PackageManager.SIGNATURE_MATCH; 8014 if (!match) { 8015 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 8016 == PackageManager.SIGNATURE_MATCH; 8017 } 8018 if (!match) { 8019 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 8020 == PackageManager.SIGNATURE_MATCH; 8021 } 8022 if (!match) { 8023 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 8024 + pkg.packageName + " signatures do not match the " 8025 + "previously installed version; ignoring!"); 8026 } 8027 } 8028 8029 // Check for shared user signatures 8030 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 8031 // Already existing package. Make sure signatures match 8032 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8033 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 8034 if (!match) { 8035 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 8036 == PackageManager.SIGNATURE_MATCH; 8037 } 8038 if (!match) { 8039 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 8040 == PackageManager.SIGNATURE_MATCH; 8041 } 8042 if (!match) { 8043 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 8044 "Package " + pkg.packageName 8045 + " has no signatures that match those in shared user " 8046 + pkgSetting.sharedUser.name + "; ignoring!"); 8047 } 8048 } 8049 } 8050 8051 /** 8052 * Enforces that only the system UID or root's UID can call a method exposed 8053 * via Binder. 8054 * 8055 * @param message used as message if SecurityException is thrown 8056 * @throws SecurityException if the caller is not system or root 8057 */ 8058 private static final void enforceSystemOrRoot(String message) { 8059 final int uid = Binder.getCallingUid(); 8060 if (uid != Process.SYSTEM_UID && uid != 0) { 8061 throw new SecurityException(message); 8062 } 8063 } 8064 8065 @Override 8066 public void performFstrimIfNeeded() { 8067 enforceSystemOrRoot("Only the system can request fstrim"); 8068 8069 // Before everything else, see whether we need to fstrim. 8070 try { 8071 IStorageManager sm = PackageHelper.getStorageManager(); 8072 if (sm != null) { 8073 boolean doTrim = false; 8074 final long interval = android.provider.Settings.Global.getLong( 8075 mContext.getContentResolver(), 8076 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 8077 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 8078 if (interval > 0) { 8079 final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance(); 8080 if (timeSinceLast > interval) { 8081 doTrim = true; 8082 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 8083 + "; running immediately"); 8084 } 8085 } 8086 if (doTrim) { 8087 final boolean dexOptDialogShown; 8088 synchronized (mPackages) { 8089 dexOptDialogShown = mDexOptDialogShown; 8090 } 8091 if (!isFirstBoot() && dexOptDialogShown) { 8092 try { 8093 ActivityManager.getService().showBootMessage( 8094 mContext.getResources().getString( 8095 R.string.android_upgrading_fstrim), true); 8096 } catch (RemoteException e) { 8097 } 8098 } 8099 sm.runMaintenance(); 8100 } 8101 } else { 8102 Slog.e(TAG, "storageManager service unavailable!"); 8103 } 8104 } catch (RemoteException e) { 8105 // Can't happen; StorageManagerService is local 8106 } 8107 } 8108 8109 @Override 8110 public void updatePackagesIfNeeded() { 8111 enforceSystemOrRoot("Only the system can request package update"); 8112 8113 // We need to re-extract after an OTA. 8114 boolean causeUpgrade = isUpgrade(); 8115 8116 // First boot or factory reset. 8117 // Note: we also handle devices that are upgrading to N right now as if it is their 8118 // first boot, as they do not have profile data. 8119 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 8120 8121 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 8122 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 8123 8124 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 8125 return; 8126 } 8127 8128 List<PackageParser.Package> pkgs; 8129 synchronized (mPackages) { 8130 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 8131 } 8132 8133 final long startTime = System.nanoTime(); 8134 final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */, 8135 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT)); 8136 8137 final int elapsedTimeSeconds = 8138 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 8139 8140 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]); 8141 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]); 8142 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]); 8143 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 8144 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 8145 } 8146 8147 /** 8148 * Performs dexopt on the set of packages in {@code packages} and returns an int array 8149 * containing statistics about the invocation. The array consists of three elements, 8150 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped} 8151 * and {@code numberOfPackagesFailed}. 8152 */ 8153 private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog, 8154 String compilerFilter) { 8155 8156 int numberOfPackagesVisited = 0; 8157 int numberOfPackagesOptimized = 0; 8158 int numberOfPackagesSkipped = 0; 8159 int numberOfPackagesFailed = 0; 8160 final int numberOfPackagesToDexopt = pkgs.size(); 8161 8162 for (PackageParser.Package pkg : pkgs) { 8163 numberOfPackagesVisited++; 8164 8165 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 8166 if (DEBUG_DEXOPT) { 8167 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 8168 } 8169 numberOfPackagesSkipped++; 8170 continue; 8171 } 8172 8173 if (DEBUG_DEXOPT) { 8174 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 8175 numberOfPackagesToDexopt + ": " + pkg.packageName); 8176 } 8177 8178 if (showDialog) { 8179 try { 8180 ActivityManager.getService().showBootMessage( 8181 mContext.getResources().getString(R.string.android_upgrading_apk, 8182 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 8183 } catch (RemoteException e) { 8184 } 8185 synchronized (mPackages) { 8186 mDexOptDialogShown = true; 8187 } 8188 } 8189 8190 // If the OTA updates a system app which was previously preopted to a non-preopted state 8191 // the app might end up being verified at runtime. That's because by default the apps 8192 // are verify-profile but for preopted apps there's no profile. 8193 // Do a hacky check to ensure that if we have no profiles (a reasonable indication 8194 // that before the OTA the app was preopted) the app gets compiled with a non-profile 8195 // filter (by default interpret-only). 8196 // Note that at this stage unused apps are already filtered. 8197 if (isSystemApp(pkg) && 8198 DexFile.isProfileGuidedCompilerFilter(compilerFilter) && 8199 !Environment.getReferenceProfile(pkg.packageName).exists()) { 8200 compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter); 8201 } 8202 8203 // checkProfiles is false to avoid merging profiles during boot which 8204 // might interfere with background compilation (b/28612421). 8205 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 8206 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 8207 // trade-off worth doing to save boot time work. 8208 int dexOptStatus = performDexOptTraced(pkg.packageName, 8209 false /* checkProfiles */, 8210 compilerFilter, 8211 false /* force */); 8212 switch (dexOptStatus) { 8213 case PackageDexOptimizer.DEX_OPT_PERFORMED: 8214 numberOfPackagesOptimized++; 8215 break; 8216 case PackageDexOptimizer.DEX_OPT_SKIPPED: 8217 numberOfPackagesSkipped++; 8218 break; 8219 case PackageDexOptimizer.DEX_OPT_FAILED: 8220 numberOfPackagesFailed++; 8221 break; 8222 default: 8223 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus); 8224 break; 8225 } 8226 } 8227 8228 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped, 8229 numberOfPackagesFailed }; 8230 } 8231 8232 @Override 8233 public void notifyPackageUse(String packageName, int reason) { 8234 synchronized (mPackages) { 8235 PackageParser.Package p = mPackages.get(packageName); 8236 if (p == null) { 8237 return; 8238 } 8239 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 8240 } 8241 } 8242 8243 @Override 8244 public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) { 8245 int userId = UserHandle.getCallingUserId(); 8246 ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId); 8247 if (ai == null) { 8248 Slog.w(TAG, "Loading a package that does not exist for the calling user. package=" 8249 + loadingPackageName + ", user=" + userId); 8250 return; 8251 } 8252 mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId); 8253 } 8254 8255 // TODO: this is not used nor needed. Delete it. 8256 @Override 8257 public boolean performDexOptIfNeeded(String packageName) { 8258 int dexOptStatus = performDexOptTraced(packageName, 8259 false /* checkProfiles */, getFullCompilerFilter(), false /* force */); 8260 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 8261 } 8262 8263 @Override 8264 public boolean performDexOpt(String packageName, 8265 boolean checkProfiles, int compileReason, boolean force) { 8266 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 8267 getCompilerFilterForReason(compileReason), force); 8268 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 8269 } 8270 8271 @Override 8272 public boolean performDexOptMode(String packageName, 8273 boolean checkProfiles, String targetCompilerFilter, boolean force) { 8274 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 8275 targetCompilerFilter, force); 8276 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 8277 } 8278 8279 private int performDexOptTraced(String packageName, 8280 boolean checkProfiles, String targetCompilerFilter, boolean force) { 8281 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 8282 try { 8283 return performDexOptInternal(packageName, checkProfiles, 8284 targetCompilerFilter, force); 8285 } finally { 8286 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8287 } 8288 } 8289 8290 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 8291 // if the package can now be considered up to date for the given filter. 8292 private int performDexOptInternal(String packageName, 8293 boolean checkProfiles, String targetCompilerFilter, boolean force) { 8294 PackageParser.Package p; 8295 synchronized (mPackages) { 8296 p = mPackages.get(packageName); 8297 if (p == null) { 8298 // Package could not be found. Report failure. 8299 return PackageDexOptimizer.DEX_OPT_FAILED; 8300 } 8301 mPackageUsage.maybeWriteAsync(mPackages); 8302 mCompilerStats.maybeWriteAsync(); 8303 } 8304 long callingId = Binder.clearCallingIdentity(); 8305 try { 8306 synchronized (mInstallLock) { 8307 return performDexOptInternalWithDependenciesLI(p, checkProfiles, 8308 targetCompilerFilter, force); 8309 } 8310 } finally { 8311 Binder.restoreCallingIdentity(callingId); 8312 } 8313 } 8314 8315 public ArraySet<String> getOptimizablePackages() { 8316 ArraySet<String> pkgs = new ArraySet<String>(); 8317 synchronized (mPackages) { 8318 for (PackageParser.Package p : mPackages.values()) { 8319 if (PackageDexOptimizer.canOptimizePackage(p)) { 8320 pkgs.add(p.packageName); 8321 } 8322 } 8323 } 8324 return pkgs; 8325 } 8326 8327 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 8328 boolean checkProfiles, String targetCompilerFilter, 8329 boolean force) { 8330 // Select the dex optimizer based on the force parameter. 8331 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 8332 // allocate an object here. 8333 PackageDexOptimizer pdo = force 8334 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 8335 : mPackageDexOptimizer; 8336 8337 // Optimize all dependencies first. Note: we ignore the return value and march on 8338 // on errors. 8339 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 8340 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 8341 if (!deps.isEmpty()) { 8342 for (PackageParser.Package depPackage : deps) { 8343 // TODO: Analyze and investigate if we (should) profile libraries. 8344 // Currently this will do a full compilation of the library by default. 8345 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 8346 false /* checkProfiles */, 8347 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY), 8348 getOrCreateCompilerPackageStats(depPackage)); 8349 } 8350 } 8351 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 8352 targetCompilerFilter, getOrCreateCompilerPackageStats(p)); 8353 } 8354 8355 // Performs dexopt on the used secondary dex files belonging to the given package. 8356 // Returns true if all dex files were process successfully (which could mean either dexopt or 8357 // skip). Returns false if any of the files caused errors. 8358 @Override 8359 public boolean performDexOptSecondary(String packageName, String compilerFilter, 8360 boolean force) { 8361 return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force); 8362 } 8363 8364 /** 8365 * Reconcile the information we have about the secondary dex files belonging to 8366 * {@code packagName} and the actual dex files. For all dex files that were 8367 * deleted, update the internal records and delete the generated oat files. 8368 */ 8369 @Override 8370 public void reconcileSecondaryDexFiles(String packageName) { 8371 mDexManager.reconcileSecondaryDexFiles(packageName); 8372 } 8373 8374 // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject 8375 // a reference there. 8376 /*package*/ DexManager getDexManager() { 8377 return mDexManager; 8378 } 8379 8380 /** 8381 * Execute the background dexopt job immediately. 8382 */ 8383 @Override 8384 public boolean runBackgroundDexoptJob() { 8385 return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext); 8386 } 8387 8388 List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 8389 if (p.usesLibraries != null || p.usesOptionalLibraries != null 8390 || p.usesStaticLibraries != null) { 8391 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 8392 Set<String> collectedNames = new HashSet<>(); 8393 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 8394 8395 retValue.remove(p); 8396 8397 return retValue; 8398 } else { 8399 return Collections.emptyList(); 8400 } 8401 } 8402 8403 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 8404 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) { 8405 if (!collectedNames.contains(p.packageName)) { 8406 collectedNames.add(p.packageName); 8407 collected.add(p); 8408 8409 if (p.usesLibraries != null) { 8410 findSharedNonSystemLibrariesRecursive(p.usesLibraries, 8411 null, collected, collectedNames); 8412 } 8413 if (p.usesOptionalLibraries != null) { 8414 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, 8415 null, collected, collectedNames); 8416 } 8417 if (p.usesStaticLibraries != null) { 8418 findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries, 8419 p.usesStaticLibrariesVersions, collected, collectedNames); 8420 } 8421 } 8422 } 8423 8424 private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions, 8425 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) { 8426 final int libNameCount = libs.size(); 8427 for (int i = 0; i < libNameCount; i++) { 8428 String libName = libs.get(i); 8429 int version = (versions != null && versions.length == libNameCount) 8430 ? versions[i] : PackageManager.VERSION_CODE_HIGHEST; 8431 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version); 8432 if (libPkg != null) { 8433 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 8434 } 8435 } 8436 } 8437 8438 private PackageParser.Package findSharedNonSystemLibrary(String name, int version) { 8439 synchronized (mPackages) { 8440 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version); 8441 if (libEntry != null) { 8442 return mPackages.get(libEntry.apk); 8443 } 8444 return null; 8445 } 8446 } 8447 8448 private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) { 8449 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 8450 if (versionedLib == null) { 8451 return null; 8452 } 8453 return versionedLib.get(version); 8454 } 8455 8456 private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) { 8457 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get( 8458 pkg.staticSharedLibName); 8459 if (versionedLib == null) { 8460 return null; 8461 } 8462 int previousLibVersion = -1; 8463 final int versionCount = versionedLib.size(); 8464 for (int i = 0; i < versionCount; i++) { 8465 final int libVersion = versionedLib.keyAt(i); 8466 if (libVersion < pkg.staticSharedLibVersion) { 8467 previousLibVersion = Math.max(previousLibVersion, libVersion); 8468 } 8469 } 8470 if (previousLibVersion >= 0) { 8471 return versionedLib.get(previousLibVersion); 8472 } 8473 return null; 8474 } 8475 8476 public void shutdown() { 8477 mPackageUsage.writeNow(mPackages); 8478 mCompilerStats.writeNow(); 8479 } 8480 8481 @Override 8482 public void dumpProfiles(String packageName) { 8483 PackageParser.Package pkg; 8484 synchronized (mPackages) { 8485 pkg = mPackages.get(packageName); 8486 if (pkg == null) { 8487 throw new IllegalArgumentException("Unknown package: " + packageName); 8488 } 8489 } 8490 /* Only the shell, root, or the app user should be able to dump profiles. */ 8491 int callingUid = Binder.getCallingUid(); 8492 if (callingUid != Process.SHELL_UID && 8493 callingUid != Process.ROOT_UID && 8494 callingUid != pkg.applicationInfo.uid) { 8495 throw new SecurityException("dumpProfiles"); 8496 } 8497 8498 synchronized (mInstallLock) { 8499 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles"); 8500 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 8501 try { 8502 List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly(); 8503 String codePaths = TextUtils.join(";", allCodePaths); 8504 mInstaller.dumpProfiles(sharedGid, packageName, codePaths); 8505 } catch (InstallerException e) { 8506 Slog.w(TAG, "Failed to dump profiles", e); 8507 } 8508 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8509 } 8510 } 8511 8512 @Override 8513 public void forceDexOpt(String packageName) { 8514 enforceSystemOrRoot("forceDexOpt"); 8515 8516 PackageParser.Package pkg; 8517 synchronized (mPackages) { 8518 pkg = mPackages.get(packageName); 8519 if (pkg == null) { 8520 throw new IllegalArgumentException("Unknown package: " + packageName); 8521 } 8522 } 8523 8524 synchronized (mInstallLock) { 8525 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 8526 8527 // Whoever is calling forceDexOpt wants a fully compiled package. 8528 // Don't use profiles since that may cause compilation to be skipped. 8529 final int res = performDexOptInternalWithDependenciesLI(pkg, 8530 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 8531 true /* force */); 8532 8533 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8534 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 8535 throw new IllegalStateException("Failed to dexopt: " + res); 8536 } 8537 } 8538 } 8539 8540 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 8541 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 8542 Slog.w(TAG, "Unable to update from " + oldPkg.name 8543 + " to " + newPkg.packageName 8544 + ": old package not in system partition"); 8545 return false; 8546 } else if (mPackages.get(oldPkg.name) != null) { 8547 Slog.w(TAG, "Unable to update from " + oldPkg.name 8548 + " to " + newPkg.packageName 8549 + ": old package still exists"); 8550 return false; 8551 } 8552 return true; 8553 } 8554 8555 void removeCodePathLI(File codePath) { 8556 if (codePath.isDirectory()) { 8557 try { 8558 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 8559 } catch (InstallerException e) { 8560 Slog.w(TAG, "Failed to remove code path", e); 8561 } 8562 } else { 8563 codePath.delete(); 8564 } 8565 } 8566 8567 private int[] resolveUserIds(int userId) { 8568 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 8569 } 8570 8571 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 8572 if (pkg == null) { 8573 Slog.wtf(TAG, "Package was null!", new Throwable()); 8574 return; 8575 } 8576 clearAppDataLeafLIF(pkg, userId, flags); 8577 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8578 for (int i = 0; i < childCount; i++) { 8579 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 8580 } 8581 } 8582 8583 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 8584 final PackageSetting ps; 8585 synchronized (mPackages) { 8586 ps = mSettings.mPackages.get(pkg.packageName); 8587 } 8588 for (int realUserId : resolveUserIds(userId)) { 8589 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 8590 try { 8591 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 8592 ceDataInode); 8593 } catch (InstallerException e) { 8594 Slog.w(TAG, String.valueOf(e)); 8595 } 8596 } 8597 } 8598 8599 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 8600 if (pkg == null) { 8601 Slog.wtf(TAG, "Package was null!", new Throwable()); 8602 return; 8603 } 8604 destroyAppDataLeafLIF(pkg, userId, flags); 8605 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8606 for (int i = 0; i < childCount; i++) { 8607 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 8608 } 8609 } 8610 8611 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 8612 final PackageSetting ps; 8613 synchronized (mPackages) { 8614 ps = mSettings.mPackages.get(pkg.packageName); 8615 } 8616 for (int realUserId : resolveUserIds(userId)) { 8617 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 8618 try { 8619 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 8620 ceDataInode); 8621 } catch (InstallerException e) { 8622 Slog.w(TAG, String.valueOf(e)); 8623 } 8624 } 8625 } 8626 8627 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 8628 if (pkg == null) { 8629 Slog.wtf(TAG, "Package was null!", new Throwable()); 8630 return; 8631 } 8632 destroyAppProfilesLeafLIF(pkg); 8633 destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */); 8634 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8635 for (int i = 0; i < childCount; i++) { 8636 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 8637 destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId, 8638 true /* removeBaseMarker */); 8639 } 8640 } 8641 8642 private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId, 8643 boolean removeBaseMarker) { 8644 if (pkg.isForwardLocked()) { 8645 return; 8646 } 8647 8648 for (String path : pkg.getAllCodePathsExcludingResourceOnly()) { 8649 try { 8650 path = PackageManagerServiceUtils.realpath(new File(path)); 8651 } catch (IOException e) { 8652 // TODO: Should we return early here ? 8653 Slog.w(TAG, "Failed to get canonical path", e); 8654 continue; 8655 } 8656 8657 final String useMarker = path.replace('/', '@'); 8658 for (int realUserId : resolveUserIds(userId)) { 8659 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId); 8660 if (removeBaseMarker) { 8661 File foreignUseMark = new File(profileDir, useMarker); 8662 if (foreignUseMark.exists()) { 8663 if (!foreignUseMark.delete()) { 8664 Slog.w(TAG, "Unable to delete foreign user mark for package: " 8665 + pkg.packageName); 8666 } 8667 } 8668 } 8669 8670 File[] markers = profileDir.listFiles(); 8671 if (markers != null) { 8672 final String searchString = "@" + pkg.packageName + "@"; 8673 // We also delete all markers that contain the package name we're 8674 // uninstalling. These are associated with secondary dex-files belonging 8675 // to the package. Reconstructing the path of these dex files is messy 8676 // in general. 8677 for (File marker : markers) { 8678 if (marker.getName().indexOf(searchString) > 0) { 8679 if (!marker.delete()) { 8680 Slog.w(TAG, "Unable to delete foreign user mark for package: " 8681 + pkg.packageName); 8682 } 8683 } 8684 } 8685 } 8686 } 8687 } 8688 } 8689 8690 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 8691 try { 8692 mInstaller.destroyAppProfiles(pkg.packageName); 8693 } catch (InstallerException e) { 8694 Slog.w(TAG, String.valueOf(e)); 8695 } 8696 } 8697 8698 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 8699 if (pkg == null) { 8700 Slog.wtf(TAG, "Package was null!", new Throwable()); 8701 return; 8702 } 8703 clearAppProfilesLeafLIF(pkg); 8704 // We don't remove the base foreign use marker when clearing profiles because 8705 // we will rename it when the app is updated. Unlike the actual profile contents, 8706 // the foreign use marker is good across installs. 8707 destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */); 8708 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8709 for (int i = 0; i < childCount; i++) { 8710 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 8711 } 8712 } 8713 8714 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 8715 try { 8716 mInstaller.clearAppProfiles(pkg.packageName); 8717 } catch (InstallerException e) { 8718 Slog.w(TAG, String.valueOf(e)); 8719 } 8720 } 8721 8722 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 8723 long lastUpdateTime) { 8724 // Set parent install/update time 8725 PackageSetting ps = (PackageSetting) pkg.mExtras; 8726 if (ps != null) { 8727 ps.firstInstallTime = firstInstallTime; 8728 ps.lastUpdateTime = lastUpdateTime; 8729 } 8730 // Set children install/update time 8731 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8732 for (int i = 0; i < childCount; i++) { 8733 PackageParser.Package childPkg = pkg.childPackages.get(i); 8734 ps = (PackageSetting) childPkg.mExtras; 8735 if (ps != null) { 8736 ps.firstInstallTime = firstInstallTime; 8737 ps.lastUpdateTime = lastUpdateTime; 8738 } 8739 } 8740 } 8741 8742 private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 8743 PackageParser.Package changingLib) { 8744 if (file.path != null) { 8745 usesLibraryFiles.add(file.path); 8746 return; 8747 } 8748 PackageParser.Package p = mPackages.get(file.apk); 8749 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 8750 // If we are doing this while in the middle of updating a library apk, 8751 // then we need to make sure to use that new apk for determining the 8752 // dependencies here. (We haven't yet finished committing the new apk 8753 // to the package manager state.) 8754 if (p == null || p.packageName.equals(changingLib.packageName)) { 8755 p = changingLib; 8756 } 8757 } 8758 if (p != null) { 8759 usesLibraryFiles.addAll(p.getAllCodePaths()); 8760 } 8761 } 8762 8763 private void updateSharedLibrariesLPr(PackageParser.Package pkg, 8764 PackageParser.Package changingLib) throws PackageManagerException { 8765 if (pkg == null) { 8766 return; 8767 } 8768 ArraySet<String> usesLibraryFiles = null; 8769 if (pkg.usesLibraries != null) { 8770 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries, 8771 null, null, pkg.packageName, changingLib, true, null); 8772 } 8773 if (pkg.usesStaticLibraries != null) { 8774 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries, 8775 pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests, 8776 pkg.packageName, changingLib, true, usesLibraryFiles); 8777 } 8778 if (pkg.usesOptionalLibraries != null) { 8779 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries, 8780 null, null, pkg.packageName, changingLib, false, usesLibraryFiles); 8781 } 8782 if (!ArrayUtils.isEmpty(usesLibraryFiles)) { 8783 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]); 8784 } else { 8785 pkg.usesLibraryFiles = null; 8786 } 8787 } 8788 8789 private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries, 8790 @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests, 8791 @NonNull String packageName, @Nullable PackageParser.Package changingLib, 8792 boolean required, @Nullable ArraySet<String> outUsedLibraries) 8793 throws PackageManagerException { 8794 final int libCount = requestedLibraries.size(); 8795 for (int i = 0; i < libCount; i++) { 8796 final String libName = requestedLibraries.get(i); 8797 final int libVersion = requiredVersions != null ? requiredVersions[i] 8798 : SharedLibraryInfo.VERSION_UNDEFINED; 8799 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion); 8800 if (libEntry == null) { 8801 if (required) { 8802 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8803 "Package " + packageName + " requires unavailable shared library " 8804 + libName + "; failing!"); 8805 } else { 8806 Slog.w(TAG, "Package " + packageName 8807 + " desires unavailable shared library " 8808 + libName + "; ignoring!"); 8809 } 8810 } else { 8811 if (requiredVersions != null && requiredCertDigests != null) { 8812 if (libEntry.info.getVersion() != requiredVersions[i]) { 8813 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8814 "Package " + packageName + " requires unavailable static shared" 8815 + " library " + libName + " version " 8816 + libEntry.info.getVersion() + "; failing!"); 8817 } 8818 8819 PackageParser.Package libPkg = mPackages.get(libEntry.apk); 8820 if (libPkg == null) { 8821 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8822 "Package " + packageName + " requires unavailable static shared" 8823 + " library; failing!"); 8824 } 8825 8826 String expectedCertDigest = requiredCertDigests[i]; 8827 String libCertDigest = PackageUtils.computeCertSha256Digest( 8828 libPkg.mSignatures[0]); 8829 if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) { 8830 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8831 "Package " + packageName + " requires differently signed" + 8832 " static shared library; failing!"); 8833 } 8834 } 8835 8836 if (outUsedLibraries == null) { 8837 outUsedLibraries = new ArraySet<>(); 8838 } 8839 addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib); 8840 } 8841 } 8842 return outUsedLibraries; 8843 } 8844 8845 private static boolean hasString(List<String> list, List<String> which) { 8846 if (list == null) { 8847 return false; 8848 } 8849 for (int i=list.size()-1; i>=0; i--) { 8850 for (int j=which.size()-1; j>=0; j--) { 8851 if (which.get(j).equals(list.get(i))) { 8852 return true; 8853 } 8854 } 8855 } 8856 return false; 8857 } 8858 8859 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 8860 PackageParser.Package changingPkg) { 8861 ArrayList<PackageParser.Package> res = null; 8862 for (PackageParser.Package pkg : mPackages.values()) { 8863 if (changingPkg != null 8864 && !hasString(pkg.usesLibraries, changingPkg.libraryNames) 8865 && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames) 8866 && !ArrayUtils.contains(pkg.usesStaticLibraries, 8867 changingPkg.staticSharedLibName)) { 8868 return null; 8869 } 8870 if (res == null) { 8871 res = new ArrayList<>(); 8872 } 8873 res.add(pkg); 8874 try { 8875 updateSharedLibrariesLPr(pkg, changingPkg); 8876 } catch (PackageManagerException e) { 8877 // If a system app update or an app and a required lib missing we 8878 // delete the package and for updated system apps keep the data as 8879 // it is better for the user to reinstall than to be in an limbo 8880 // state. Also libs disappearing under an app should never happen 8881 // - just in case. 8882 if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) { 8883 final int flags = pkg.isUpdatedSystemApp() 8884 ? PackageManager.DELETE_KEEP_DATA : 0; 8885 deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(), 8886 flags , null, true, null); 8887 } 8888 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 8889 } 8890 } 8891 return res; 8892 } 8893 8894 /** 8895 * Derive the value of the {@code cpuAbiOverride} based on the provided 8896 * value and an optional stored value from the package settings. 8897 */ 8898 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 8899 String cpuAbiOverride = null; 8900 8901 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 8902 cpuAbiOverride = null; 8903 } else if (abiOverride != null) { 8904 cpuAbiOverride = abiOverride; 8905 } else if (settings != null) { 8906 cpuAbiOverride = settings.cpuAbiOverrideString; 8907 } 8908 8909 return cpuAbiOverride; 8910 } 8911 8912 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 8913 final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user) 8914 throws PackageManagerException { 8915 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 8916 // If the package has children and this is the first dive in the function 8917 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 8918 // whether all packages (parent and children) would be successfully scanned 8919 // before the actual scan since scanning mutates internal state and we want 8920 // to atomically install the package and its children. 8921 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8922 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 8923 scanFlags |= SCAN_CHECK_ONLY; 8924 } 8925 } else { 8926 scanFlags &= ~SCAN_CHECK_ONLY; 8927 } 8928 8929 final PackageParser.Package scannedPkg; 8930 try { 8931 // Scan the parent 8932 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 8933 // Scan the children 8934 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8935 for (int i = 0; i < childCount; i++) { 8936 PackageParser.Package childPkg = pkg.childPackages.get(i); 8937 scanPackageLI(childPkg, policyFlags, 8938 scanFlags, currentTime, user); 8939 } 8940 } finally { 8941 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8942 } 8943 8944 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8945 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 8946 } 8947 8948 return scannedPkg; 8949 } 8950 8951 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 8952 int scanFlags, long currentTime, @Nullable UserHandle user) 8953 throws PackageManagerException { 8954 boolean success = false; 8955 try { 8956 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 8957 currentTime, user); 8958 success = true; 8959 return res; 8960 } finally { 8961 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 8962 // DELETE_DATA_ON_FAILURES is only used by frozen paths 8963 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 8964 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 8965 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 8966 } 8967 } 8968 } 8969 8970 /** 8971 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 8972 */ 8973 private static boolean apkHasCode(String fileName) { 8974 StrictJarFile jarFile = null; 8975 try { 8976 jarFile = new StrictJarFile(fileName, 8977 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 8978 return jarFile.findEntry("classes.dex") != null; 8979 } catch (IOException ignore) { 8980 } finally { 8981 try { 8982 if (jarFile != null) { 8983 jarFile.close(); 8984 } 8985 } catch (IOException ignore) {} 8986 } 8987 return false; 8988 } 8989 8990 /** 8991 * Enforces code policy for the package. This ensures that if an APK has 8992 * declared hasCode="true" in its manifest that the APK actually contains 8993 * code. 8994 * 8995 * @throws PackageManagerException If bytecode could not be found when it should exist 8996 */ 8997 private static void assertCodePolicy(PackageParser.Package pkg) 8998 throws PackageManagerException { 8999 final boolean shouldHaveCode = 9000 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 9001 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 9002 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 9003 "Package " + pkg.baseCodePath + " code is missing"); 9004 } 9005 9006 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 9007 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 9008 final boolean splitShouldHaveCode = 9009 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 9010 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 9011 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 9012 "Package " + pkg.splitCodePaths[i] + " code is missing"); 9013 } 9014 } 9015 } 9016 } 9017 9018 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 9019 final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user) 9020 throws PackageManagerException { 9021 if (DEBUG_PACKAGE_SCANNING) { 9022 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 9023 Log.d(TAG, "Scanning package " + pkg.packageName); 9024 } 9025 9026 applyPolicy(pkg, policyFlags); 9027 9028 assertPackageIsValid(pkg, policyFlags, scanFlags); 9029 9030 // Initialize package source and resource directories 9031 final File scanFile = new File(pkg.codePath); 9032 final File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 9033 final File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 9034 9035 SharedUserSetting suid = null; 9036 PackageSetting pkgSetting = null; 9037 9038 // Getting the package setting may have a side-effect, so if we 9039 // are only checking if scan would succeed, stash a copy of the 9040 // old setting to restore at the end. 9041 PackageSetting nonMutatedPs = null; 9042 9043 // We keep references to the derived CPU Abis from settings in oder to reuse 9044 // them in the case where we're not upgrading or booting for the first time. 9045 String primaryCpuAbiFromSettings = null; 9046 String secondaryCpuAbiFromSettings = null; 9047 9048 // writer 9049 synchronized (mPackages) { 9050 if (pkg.mSharedUserId != null) { 9051 // SIDE EFFECTS; may potentially allocate a new shared user 9052 suid = mSettings.getSharedUserLPw( 9053 pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/); 9054 if (DEBUG_PACKAGE_SCANNING) { 9055 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 9056 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 9057 + "): packages=" + suid.packages); 9058 } 9059 } 9060 9061 // Check if we are renaming from an original package name. 9062 PackageSetting origPackage = null; 9063 String realName = null; 9064 if (pkg.mOriginalPackages != null) { 9065 // This package may need to be renamed to a previously 9066 // installed name. Let's check on that... 9067 final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage); 9068 if (pkg.mOriginalPackages.contains(renamed)) { 9069 // This package had originally been installed as the 9070 // original name, and we have already taken care of 9071 // transitioning to the new one. Just update the new 9072 // one to continue using the old name. 9073 realName = pkg.mRealPackage; 9074 if (!pkg.packageName.equals(renamed)) { 9075 // Callers into this function may have already taken 9076 // care of renaming the package; only do it here if 9077 // it is not already done. 9078 pkg.setPackageName(renamed); 9079 } 9080 } else { 9081 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 9082 if ((origPackage = mSettings.getPackageLPr( 9083 pkg.mOriginalPackages.get(i))) != null) { 9084 // We do have the package already installed under its 9085 // original name... should we use it? 9086 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 9087 // New package is not compatible with original. 9088 origPackage = null; 9089 continue; 9090 } else if (origPackage.sharedUser != null) { 9091 // Make sure uid is compatible between packages. 9092 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 9093 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 9094 + " to " + pkg.packageName + ": old uid " 9095 + origPackage.sharedUser.name 9096 + " differs from " + pkg.mSharedUserId); 9097 origPackage = null; 9098 continue; 9099 } 9100 // TODO: Add case when shared user id is added [b/28144775] 9101 } else { 9102 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 9103 + pkg.packageName + " to old name " + origPackage.name); 9104 } 9105 break; 9106 } 9107 } 9108 } 9109 } 9110 9111 if (mTransferedPackages.contains(pkg.packageName)) { 9112 Slog.w(TAG, "Package " + pkg.packageName 9113 + " was transferred to another, but its .apk remains"); 9114 } 9115 9116 // See comments in nonMutatedPs declaration 9117 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 9118 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName); 9119 if (foundPs != null) { 9120 nonMutatedPs = new PackageSetting(foundPs); 9121 } 9122 } 9123 9124 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) { 9125 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName); 9126 if (foundPs != null) { 9127 primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString; 9128 secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString; 9129 } 9130 } 9131 9132 pkgSetting = mSettings.getPackageLPr(pkg.packageName); 9133 if (pkgSetting != null && pkgSetting.sharedUser != suid) { 9134 PackageManagerService.reportSettingsProblem(Log.WARN, 9135 "Package " + pkg.packageName + " shared user changed from " 9136 + (pkgSetting.sharedUser != null 9137 ? pkgSetting.sharedUser.name : "<nothing>") 9138 + " to " 9139 + (suid != null ? suid.name : "<nothing>") 9140 + "; replacing with new"); 9141 pkgSetting = null; 9142 } 9143 final PackageSetting oldPkgSetting = 9144 pkgSetting == null ? null : new PackageSetting(pkgSetting); 9145 final PackageSetting disabledPkgSetting = 9146 mSettings.getDisabledSystemPkgLPr(pkg.packageName); 9147 9148 String[] usesStaticLibraries = null; 9149 if (pkg.usesStaticLibraries != null) { 9150 usesStaticLibraries = new String[pkg.usesStaticLibraries.size()]; 9151 pkg.usesStaticLibraries.toArray(usesStaticLibraries); 9152 } 9153 9154 if (pkgSetting == null) { 9155 final String parentPackageName = (pkg.parentPackage != null) 9156 ? pkg.parentPackage.packageName : null; 9157 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 9158 // REMOVE SharedUserSetting from method; update in a separate call 9159 pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage, 9160 disabledPkgSetting, realName, suid, destCodeFile, destResourceFile, 9161 pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi, 9162 pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode, 9163 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user, 9164 true /*allowInstall*/, instantApp, parentPackageName, 9165 pkg.getChildPackageNames(), UserManagerService.getInstance(), 9166 usesStaticLibraries, pkg.usesStaticLibrariesVersions); 9167 // SIDE EFFECTS; updates system state; move elsewhere 9168 if (origPackage != null) { 9169 mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name); 9170 } 9171 mSettings.addUserToSettingLPw(pkgSetting); 9172 } else { 9173 // REMOVE SharedUserSetting from method; update in a separate call. 9174 // 9175 // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi, 9176 // secondaryCpuAbi are not known at this point so we always update them 9177 // to null here, only to reset them at a later point. 9178 Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile, 9179 pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi, 9180 pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags, 9181 pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(), 9182 UserManagerService.getInstance(), usesStaticLibraries, 9183 pkg.usesStaticLibrariesVersions); 9184 } 9185 // SIDE EFFECTS; persists system state to files on disk; move elsewhere 9186 mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting); 9187 9188 // SIDE EFFECTS; modifies system state; move elsewhere 9189 if (pkgSetting.origPackage != null) { 9190 // If we are first transitioning from an original package, 9191 // fix up the new package's name now. We need to do this after 9192 // looking up the package under its new name, so getPackageLP 9193 // can take care of fiddling things correctly. 9194 pkg.setPackageName(origPackage.name); 9195 9196 // File a report about this. 9197 String msg = "New package " + pkgSetting.realName 9198 + " renamed to replace old package " + pkgSetting.name; 9199 reportSettingsProblem(Log.WARN, msg); 9200 9201 // Make a note of it. 9202 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 9203 mTransferedPackages.add(origPackage.name); 9204 } 9205 9206 // No longer need to retain this. 9207 pkgSetting.origPackage = null; 9208 } 9209 9210 // SIDE EFFECTS; modifies system state; move elsewhere 9211 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 9212 // Make a note of it. 9213 mTransferedPackages.add(pkg.packageName); 9214 } 9215 9216 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 9217 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 9218 } 9219 9220 if ((scanFlags & SCAN_BOOTING) == 0 9221 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 9222 // Check all shared libraries and map to their actual file path. 9223 // We only do this here for apps not on a system dir, because those 9224 // are the only ones that can fail an install due to this. We 9225 // will take care of the system apps by updating all of their 9226 // library paths after the scan is done. Also during the initial 9227 // scan don't update any libs as we do this wholesale after all 9228 // apps are scanned to avoid dependency based scanning. 9229 updateSharedLibrariesLPr(pkg, null); 9230 } 9231 9232 if (mFoundPolicyFile) { 9233 SELinuxMMAC.assignSeInfoValue(pkg); 9234 } 9235 pkg.applicationInfo.uid = pkgSetting.appId; 9236 pkg.mExtras = pkgSetting; 9237 9238 9239 // Static shared libs have same package with different versions where 9240 // we internally use a synthetic package name to allow multiple versions 9241 // of the same package, therefore we need to compare signatures against 9242 // the package setting for the latest library version. 9243 PackageSetting signatureCheckPs = pkgSetting; 9244 if (pkg.applicationInfo.isStaticSharedLibrary()) { 9245 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg); 9246 if (libraryEntry != null) { 9247 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk); 9248 } 9249 } 9250 9251 if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) { 9252 if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) { 9253 // We just determined the app is signed correctly, so bring 9254 // over the latest parsed certs. 9255 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9256 } else { 9257 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 9258 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 9259 "Package " + pkg.packageName + " upgrade keys do not match the " 9260 + "previously installed version"); 9261 } else { 9262 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9263 String msg = "System package " + pkg.packageName 9264 + " signature changed; retaining data."; 9265 reportSettingsProblem(Log.WARN, msg); 9266 } 9267 } 9268 } else { 9269 try { 9270 // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService 9271 verifySignaturesLP(signatureCheckPs, pkg); 9272 // We just determined the app is signed correctly, so bring 9273 // over the latest parsed certs. 9274 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9275 } catch (PackageManagerException e) { 9276 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 9277 throw e; 9278 } 9279 // The signature has changed, but this package is in the system 9280 // image... let's recover! 9281 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9282 // However... if this package is part of a shared user, but it 9283 // doesn't match the signature of the shared user, let's fail. 9284 // What this means is that you can't change the signatures 9285 // associated with an overall shared user, which doesn't seem all 9286 // that unreasonable. 9287 if (signatureCheckPs.sharedUser != null) { 9288 if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures, 9289 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 9290 throw new PackageManagerException( 9291 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 9292 "Signature mismatch for shared user: " 9293 + pkgSetting.sharedUser); 9294 } 9295 } 9296 // File a report about this. 9297 String msg = "System package " + pkg.packageName 9298 + " signature changed; retaining data."; 9299 reportSettingsProblem(Log.WARN, msg); 9300 } 9301 } 9302 9303 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 9304 // This package wants to adopt ownership of permissions from 9305 // another package. 9306 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 9307 final String origName = pkg.mAdoptPermissions.get(i); 9308 final PackageSetting orig = mSettings.getPackageLPr(origName); 9309 if (orig != null) { 9310 if (verifyPackageUpdateLPr(orig, pkg)) { 9311 Slog.i(TAG, "Adopting permissions from " + origName + " to " 9312 + pkg.packageName); 9313 // SIDE EFFECTS; updates permissions system state; move elsewhere 9314 mSettings.transferPermissionsLPw(origName, pkg.packageName); 9315 } 9316 } 9317 } 9318 } 9319 } 9320 9321 pkg.applicationInfo.processName = fixProcessName( 9322 pkg.applicationInfo.packageName, 9323 pkg.applicationInfo.processName); 9324 9325 if (pkg != mPlatformPackage) { 9326 // Get all of our default paths setup 9327 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 9328 } 9329 9330 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 9331 9332 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 9333 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) { 9334 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi"); 9335 derivePackageAbi( 9336 pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir); 9337 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9338 9339 // Some system apps still use directory structure for native libraries 9340 // in which case we might end up not detecting abi solely based on apk 9341 // structure. Try to detect abi based on directory structure. 9342 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 9343 pkg.applicationInfo.primaryCpuAbi == null) { 9344 setBundledAppAbisAndRoots(pkg, pkgSetting); 9345 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 9346 } 9347 } else { 9348 // This is not a first boot or an upgrade, don't bother deriving the 9349 // ABI during the scan. Instead, trust the value that was stored in the 9350 // package setting. 9351 pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings; 9352 pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings; 9353 9354 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 9355 9356 if (DEBUG_ABI_SELECTION) { 9357 Slog.i(TAG, "Using ABIS and native lib paths from settings : " + 9358 pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " + 9359 pkg.applicationInfo.secondaryCpuAbi); 9360 } 9361 } 9362 } else { 9363 if ((scanFlags & SCAN_MOVE) != 0) { 9364 // We haven't run dex-opt for this move (since we've moved the compiled output too) 9365 // but we already have this packages package info in the PackageSetting. We just 9366 // use that and derive the native library path based on the new codepath. 9367 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 9368 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 9369 } 9370 9371 // Set native library paths again. For moves, the path will be updated based on the 9372 // ABIs we've determined above. For non-moves, the path will be updated based on the 9373 // ABIs we determined during compilation, but the path will depend on the final 9374 // package path (after the rename away from the stage path). 9375 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 9376 } 9377 9378 // This is a special case for the "system" package, where the ABI is 9379 // dictated by the zygote configuration (and init.rc). We should keep track 9380 // of this ABI so that we can deal with "normal" applications that run under 9381 // the same UID correctly. 9382 if (mPlatformPackage == pkg) { 9383 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 9384 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 9385 } 9386 9387 // If there's a mismatch between the abi-override in the package setting 9388 // and the abiOverride specified for the install. Warn about this because we 9389 // would've already compiled the app without taking the package setting into 9390 // account. 9391 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 9392 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 9393 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 9394 " for package " + pkg.packageName); 9395 } 9396 } 9397 9398 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9399 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9400 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 9401 9402 // Copy the derived override back to the parsed package, so that we can 9403 // update the package settings accordingly. 9404 pkg.cpuAbiOverride = cpuAbiOverride; 9405 9406 if (DEBUG_ABI_SELECTION) { 9407 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 9408 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 9409 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 9410 } 9411 9412 // Push the derived path down into PackageSettings so we know what to 9413 // clean up at uninstall time. 9414 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 9415 9416 if (DEBUG_ABI_SELECTION) { 9417 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 9418 " primary=" + pkg.applicationInfo.primaryCpuAbi + 9419 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 9420 } 9421 9422 // SIDE EFFECTS; removes DEX files from disk; move elsewhere 9423 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 9424 // We don't do this here during boot because we can do it all 9425 // at once after scanning all existing packages. 9426 // 9427 // We also do this *before* we perform dexopt on this package, so that 9428 // we can avoid redundant dexopts, and also to make sure we've got the 9429 // code and package path correct. 9430 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg); 9431 } 9432 9433 if (mFactoryTest && pkg.requestedPermissions.contains( 9434 android.Manifest.permission.FACTORY_TEST)) { 9435 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 9436 } 9437 9438 if (isSystemApp(pkg)) { 9439 pkgSetting.isOrphaned = true; 9440 } 9441 9442 // Take care of first install / last update times. 9443 final long scanFileTime = getLastModifiedTime(pkg, scanFile); 9444 if (currentTime != 0) { 9445 if (pkgSetting.firstInstallTime == 0) { 9446 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 9447 } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) { 9448 pkgSetting.lastUpdateTime = currentTime; 9449 } 9450 } else if (pkgSetting.firstInstallTime == 0) { 9451 // We need *something*. Take time time stamp of the file. 9452 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 9453 } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 9454 if (scanFileTime != pkgSetting.timeStamp) { 9455 // A package on the system image has changed; consider this 9456 // to be an update. 9457 pkgSetting.lastUpdateTime = scanFileTime; 9458 } 9459 } 9460 pkgSetting.setTimeStamp(scanFileTime); 9461 9462 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 9463 if (nonMutatedPs != null) { 9464 synchronized (mPackages) { 9465 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 9466 } 9467 } 9468 } else { 9469 final int userId = user == null ? 0 : user.getIdentifier(); 9470 // Modify state for the given package setting 9471 commitPackageSettings(pkg, pkgSetting, user, scanFlags, 9472 (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/); 9473 if (pkgSetting.getInstantApp(userId)) { 9474 mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId); 9475 } 9476 } 9477 return pkg; 9478 } 9479 9480 /** 9481 * Applies policy to the parsed package based upon the given policy flags. 9482 * Ensures the package is in a good state. 9483 * <p> 9484 * Implementation detail: This method must NOT have any side effect. It would 9485 * ideally be static, but, it requires locks to read system state. 9486 */ 9487 private void applyPolicy(PackageParser.Package pkg, int policyFlags) { 9488 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 9489 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 9490 if (pkg.applicationInfo.isDirectBootAware()) { 9491 // we're direct boot aware; set for all components 9492 for (PackageParser.Service s : pkg.services) { 9493 s.info.encryptionAware = s.info.directBootAware = true; 9494 } 9495 for (PackageParser.Provider p : pkg.providers) { 9496 p.info.encryptionAware = p.info.directBootAware = true; 9497 } 9498 for (PackageParser.Activity a : pkg.activities) { 9499 a.info.encryptionAware = a.info.directBootAware = true; 9500 } 9501 for (PackageParser.Activity r : pkg.receivers) { 9502 r.info.encryptionAware = r.info.directBootAware = true; 9503 } 9504 } 9505 } else { 9506 // Only allow system apps to be flagged as core apps. 9507 pkg.coreApp = false; 9508 // clear flags not applicable to regular apps 9509 pkg.applicationInfo.privateFlags &= 9510 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 9511 pkg.applicationInfo.privateFlags &= 9512 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 9513 } 9514 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 9515 9516 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 9517 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 9518 } 9519 9520 if (!isSystemApp(pkg)) { 9521 // Only system apps can use these features. 9522 pkg.mOriginalPackages = null; 9523 pkg.mRealPackage = null; 9524 pkg.mAdoptPermissions = null; 9525 } 9526 } 9527 9528 /** 9529 * Asserts the parsed package is valid according to the given policy. If the 9530 * package is invalid, for whatever reason, throws {@link PackgeManagerException}. 9531 * <p> 9532 * Implementation detail: This method must NOT have any side effects. It would 9533 * ideally be static, but, it requires locks to read system state. 9534 * 9535 * @throws PackageManagerException If the package fails any of the validation checks 9536 */ 9537 private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags) 9538 throws PackageManagerException { 9539 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 9540 assertCodePolicy(pkg); 9541 } 9542 9543 if (pkg.applicationInfo.getCodePath() == null || 9544 pkg.applicationInfo.getResourcePath() == null) { 9545 // Bail out. The resource and code paths haven't been set. 9546 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 9547 "Code and resource paths haven't been set correctly"); 9548 } 9549 9550 // Make sure we're not adding any bogus keyset info 9551 KeySetManagerService ksms = mSettings.mKeySetManagerService; 9552 ksms.assertScannedPackageValid(pkg); 9553 9554 synchronized (mPackages) { 9555 // The special "android" package can only be defined once 9556 if (pkg.packageName.equals("android")) { 9557 if (mAndroidApplication != null) { 9558 Slog.w(TAG, "*************************************************"); 9559 Slog.w(TAG, "Core android package being redefined. Skipping."); 9560 Slog.w(TAG, " codePath=" + pkg.codePath); 9561 Slog.w(TAG, "*************************************************"); 9562 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 9563 "Core android package being redefined. Skipping."); 9564 } 9565 } 9566 9567 // A package name must be unique; don't allow duplicates 9568 if (mPackages.containsKey(pkg.packageName)) { 9569 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 9570 "Application package " + pkg.packageName 9571 + " already installed. Skipping duplicate."); 9572 } 9573 9574 if (pkg.applicationInfo.isStaticSharedLibrary()) { 9575 // Static libs have a synthetic package name containing the version 9576 // but we still want the base name to be unique. 9577 if (mPackages.containsKey(pkg.manifestPackageName)) { 9578 throw new PackageManagerException( 9579 "Duplicate static shared lib provider package"); 9580 } 9581 9582 // Static shared libraries should have at least O target SDK 9583 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) { 9584 throw new PackageManagerException( 9585 "Packages declaring static-shared libs must target O SDK or higher"); 9586 } 9587 9588 // Package declaring static a shared lib cannot be instant apps 9589 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 9590 throw new PackageManagerException( 9591 "Packages declaring static-shared libs cannot be instant apps"); 9592 } 9593 9594 // Package declaring static a shared lib cannot be renamed since the package 9595 // name is synthetic and apps can't code around package manager internals. 9596 if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) { 9597 throw new PackageManagerException( 9598 "Packages declaring static-shared libs cannot be renamed"); 9599 } 9600 9601 // Package declaring static a shared lib cannot declare child packages 9602 if (!ArrayUtils.isEmpty(pkg.childPackages)) { 9603 throw new PackageManagerException( 9604 "Packages declaring static-shared libs cannot have child packages"); 9605 } 9606 9607 // Package declaring static a shared lib cannot declare dynamic libs 9608 if (!ArrayUtils.isEmpty(pkg.libraryNames)) { 9609 throw new PackageManagerException( 9610 "Packages declaring static-shared libs cannot declare dynamic libs"); 9611 } 9612 9613 // Package declaring static a shared lib cannot declare shared users 9614 if (pkg.mSharedUserId != null) { 9615 throw new PackageManagerException( 9616 "Packages declaring static-shared libs cannot declare shared users"); 9617 } 9618 9619 // Static shared libs cannot declare activities 9620 if (!pkg.activities.isEmpty()) { 9621 throw new PackageManagerException( 9622 "Static shared libs cannot declare activities"); 9623 } 9624 9625 // Static shared libs cannot declare services 9626 if (!pkg.services.isEmpty()) { 9627 throw new PackageManagerException( 9628 "Static shared libs cannot declare services"); 9629 } 9630 9631 // Static shared libs cannot declare providers 9632 if (!pkg.providers.isEmpty()) { 9633 throw new PackageManagerException( 9634 "Static shared libs cannot declare content providers"); 9635 } 9636 9637 // Static shared libs cannot declare receivers 9638 if (!pkg.receivers.isEmpty()) { 9639 throw new PackageManagerException( 9640 "Static shared libs cannot declare broadcast receivers"); 9641 } 9642 9643 // Static shared libs cannot declare permission groups 9644 if (!pkg.permissionGroups.isEmpty()) { 9645 throw new PackageManagerException( 9646 "Static shared libs cannot declare permission groups"); 9647 } 9648 9649 // Static shared libs cannot declare permissions 9650 if (!pkg.permissions.isEmpty()) { 9651 throw new PackageManagerException( 9652 "Static shared libs cannot declare permissions"); 9653 } 9654 9655 // Static shared libs cannot declare protected broadcasts 9656 if (pkg.protectedBroadcasts != null) { 9657 throw new PackageManagerException( 9658 "Static shared libs cannot declare protected broadcasts"); 9659 } 9660 9661 // Static shared libs cannot be overlay targets 9662 if (pkg.mOverlayTarget != null) { 9663 throw new PackageManagerException( 9664 "Static shared libs cannot be overlay targets"); 9665 } 9666 9667 // The version codes must be ordered as lib versions 9668 int minVersionCode = Integer.MIN_VALUE; 9669 int maxVersionCode = Integer.MAX_VALUE; 9670 9671 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get( 9672 pkg.staticSharedLibName); 9673 if (versionedLib != null) { 9674 final int versionCount = versionedLib.size(); 9675 for (int i = 0; i < versionCount; i++) { 9676 SharedLibraryInfo libInfo = versionedLib.valueAt(i).info; 9677 // TODO: We will change version code to long, so in the new API it is long 9678 final int libVersionCode = (int) libInfo.getDeclaringPackage() 9679 .getVersionCode(); 9680 if (libInfo.getVersion() < pkg.staticSharedLibVersion) { 9681 minVersionCode = Math.max(minVersionCode, libVersionCode + 1); 9682 } else if (libInfo.getVersion() > pkg.staticSharedLibVersion) { 9683 maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1); 9684 } else { 9685 minVersionCode = maxVersionCode = libVersionCode; 9686 break; 9687 } 9688 } 9689 } 9690 if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) { 9691 throw new PackageManagerException("Static shared" 9692 + " lib version codes must be ordered as lib versions"); 9693 } 9694 } 9695 9696 // Only privileged apps and updated privileged apps can add child packages. 9697 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 9698 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 9699 throw new PackageManagerException("Only privileged apps can add child " 9700 + "packages. Ignoring package " + pkg.packageName); 9701 } 9702 final int childCount = pkg.childPackages.size(); 9703 for (int i = 0; i < childCount; i++) { 9704 PackageParser.Package childPkg = pkg.childPackages.get(i); 9705 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 9706 childPkg.packageName)) { 9707 throw new PackageManagerException("Can't override child of " 9708 + "another disabled app. Ignoring package " + pkg.packageName); 9709 } 9710 } 9711 } 9712 9713 // If we're only installing presumed-existing packages, require that the 9714 // scanned APK is both already known and at the path previously established 9715 // for it. Previously unknown packages we pick up normally, but if we have an 9716 // a priori expectation about this package's install presence, enforce it. 9717 // With a singular exception for new system packages. When an OTA contains 9718 // a new system package, we allow the codepath to change from a system location 9719 // to the user-installed location. If we don't allow this change, any newer, 9720 // user-installed version of the application will be ignored. 9721 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 9722 if (mExpectingBetter.containsKey(pkg.packageName)) { 9723 logCriticalInfo(Log.WARN, 9724 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 9725 } else { 9726 PackageSetting known = mSettings.getPackageLPr(pkg.packageName); 9727 if (known != null) { 9728 if (DEBUG_PACKAGE_SCANNING) { 9729 Log.d(TAG, "Examining " + pkg.codePath 9730 + " and requiring known paths " + known.codePathString 9731 + " & " + known.resourcePathString); 9732 } 9733 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 9734 || !pkg.applicationInfo.getResourcePath().equals( 9735 known.resourcePathString)) { 9736 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 9737 "Application package " + pkg.packageName 9738 + " found at " + pkg.applicationInfo.getCodePath() 9739 + " but expected at " + known.codePathString 9740 + "; ignoring."); 9741 } 9742 } 9743 } 9744 } 9745 9746 // Verify that this new package doesn't have any content providers 9747 // that conflict with existing packages. Only do this if the 9748 // package isn't already installed, since we don't want to break 9749 // things that are installed. 9750 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 9751 final int N = pkg.providers.size(); 9752 int i; 9753 for (i=0; i<N; i++) { 9754 PackageParser.Provider p = pkg.providers.get(i); 9755 if (p.info.authority != null) { 9756 String names[] = p.info.authority.split(";"); 9757 for (int j = 0; j < names.length; j++) { 9758 if (mProvidersByAuthority.containsKey(names[j])) { 9759 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 9760 final String otherPackageName = 9761 ((other != null && other.getComponentName() != null) ? 9762 other.getComponentName().getPackageName() : "?"); 9763 throw new PackageManagerException( 9764 INSTALL_FAILED_CONFLICTING_PROVIDER, 9765 "Can't install because provider name " + names[j] 9766 + " (in package " + pkg.applicationInfo.packageName 9767 + ") is already used by " + otherPackageName); 9768 } 9769 } 9770 } 9771 } 9772 } 9773 } 9774 } 9775 9776 private boolean addSharedLibraryLPw(String path, String apk, String name, int version, 9777 int type, String declaringPackageName, int declaringVersionCode) { 9778 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 9779 if (versionedLib == null) { 9780 versionedLib = new SparseArray<>(); 9781 mSharedLibraries.put(name, versionedLib); 9782 if (type == SharedLibraryInfo.TYPE_STATIC) { 9783 mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib); 9784 } 9785 } else if (versionedLib.indexOfKey(version) >= 0) { 9786 return false; 9787 } 9788 SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name, 9789 version, type, declaringPackageName, declaringVersionCode); 9790 versionedLib.put(version, libEntry); 9791 return true; 9792 } 9793 9794 private boolean removeSharedLibraryLPw(String name, int version) { 9795 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 9796 if (versionedLib == null) { 9797 return false; 9798 } 9799 final int libIdx = versionedLib.indexOfKey(version); 9800 if (libIdx < 0) { 9801 return false; 9802 } 9803 SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx); 9804 versionedLib.remove(version); 9805 if (versionedLib.size() <= 0) { 9806 mSharedLibraries.remove(name); 9807 if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) { 9808 mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage() 9809 .getPackageName()); 9810 } 9811 } 9812 return true; 9813 } 9814 9815 /** 9816 * Adds a scanned package to the system. When this method is finished, the package will 9817 * be available for query, resolution, etc... 9818 */ 9819 private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting, 9820 UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException { 9821 final String pkgName = pkg.packageName; 9822 if (mCustomResolverComponentName != null && 9823 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 9824 setUpCustomResolverActivity(pkg); 9825 } 9826 9827 if (pkg.packageName.equals("android")) { 9828 synchronized (mPackages) { 9829 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 9830 // Set up information for our fall-back user intent resolution activity. 9831 mPlatformPackage = pkg; 9832 pkg.mVersionCode = mSdkVersion; 9833 mAndroidApplication = pkg.applicationInfo; 9834 if (!mResolverReplaced) { 9835 mResolveActivity.applicationInfo = mAndroidApplication; 9836 mResolveActivity.name = ResolverActivity.class.getName(); 9837 mResolveActivity.packageName = mAndroidApplication.packageName; 9838 mResolveActivity.processName = "system:ui"; 9839 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9840 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 9841 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 9842 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 9843 mResolveActivity.exported = true; 9844 mResolveActivity.enabled = true; 9845 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 9846 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 9847 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 9848 | ActivityInfo.CONFIG_SCREEN_LAYOUT 9849 | ActivityInfo.CONFIG_ORIENTATION 9850 | ActivityInfo.CONFIG_KEYBOARD 9851 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 9852 mResolveInfo.activityInfo = mResolveActivity; 9853 mResolveInfo.priority = 0; 9854 mResolveInfo.preferredOrder = 0; 9855 mResolveInfo.match = 0; 9856 mResolveComponentName = new ComponentName( 9857 mAndroidApplication.packageName, mResolveActivity.name); 9858 } 9859 } 9860 } 9861 } 9862 9863 ArrayList<PackageParser.Package> clientLibPkgs = null; 9864 // writer 9865 synchronized (mPackages) { 9866 boolean hasStaticSharedLibs = false; 9867 9868 // Any app can add new static shared libraries 9869 if (pkg.staticSharedLibName != null) { 9870 // Static shared libs don't allow renaming as they have synthetic package 9871 // names to allow install of multiple versions, so use name from manifest. 9872 if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName, 9873 pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC, 9874 pkg.manifestPackageName, pkg.mVersionCode)) { 9875 hasStaticSharedLibs = true; 9876 } else { 9877 Slog.w(TAG, "Package " + pkg.packageName + " library " 9878 + pkg.staticSharedLibName + " already exists; skipping"); 9879 } 9880 // Static shared libs cannot be updated once installed since they 9881 // use synthetic package name which includes the version code, so 9882 // not need to update other packages's shared lib dependencies. 9883 } 9884 9885 if (!hasStaticSharedLibs 9886 && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 9887 // Only system apps can add new dynamic shared libraries. 9888 if (pkg.libraryNames != null) { 9889 for (int i = 0; i < pkg.libraryNames.size(); i++) { 9890 String name = pkg.libraryNames.get(i); 9891 boolean allowed = false; 9892 if (pkg.isUpdatedSystemApp()) { 9893 // New library entries can only be added through the 9894 // system image. This is important to get rid of a lot 9895 // of nasty edge cases: for example if we allowed a non- 9896 // system update of the app to add a library, then uninstalling 9897 // the update would make the library go away, and assumptions 9898 // we made such as through app install filtering would now 9899 // have allowed apps on the device which aren't compatible 9900 // with it. Better to just have the restriction here, be 9901 // conservative, and create many fewer cases that can negatively 9902 // impact the user experience. 9903 final PackageSetting sysPs = mSettings 9904 .getDisabledSystemPkgLPr(pkg.packageName); 9905 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 9906 for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) { 9907 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 9908 allowed = true; 9909 break; 9910 } 9911 } 9912 } 9913 } else { 9914 allowed = true; 9915 } 9916 if (allowed) { 9917 if (!addSharedLibraryLPw(null, pkg.packageName, name, 9918 SharedLibraryInfo.VERSION_UNDEFINED, 9919 SharedLibraryInfo.TYPE_DYNAMIC, 9920 pkg.packageName, pkg.mVersionCode)) { 9921 Slog.w(TAG, "Package " + pkg.packageName + " library " 9922 + name + " already exists; skipping"); 9923 } 9924 } else { 9925 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 9926 + name + " that is not declared on system image; skipping"); 9927 } 9928 } 9929 9930 if ((scanFlags & SCAN_BOOTING) == 0) { 9931 // If we are not booting, we need to update any applications 9932 // that are clients of our shared library. If we are booting, 9933 // this will all be done once the scan is complete. 9934 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 9935 } 9936 } 9937 } 9938 } 9939 9940 if ((scanFlags & SCAN_BOOTING) != 0) { 9941 // No apps can run during boot scan, so they don't need to be frozen 9942 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 9943 // Caller asked to not kill app, so it's probably not frozen 9944 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 9945 // Caller asked us to ignore frozen check for some reason; they 9946 // probably didn't know the package name 9947 } else { 9948 // We're doing major surgery on this package, so it better be frozen 9949 // right now to keep it from launching 9950 checkPackageFrozen(pkgName); 9951 } 9952 9953 // Also need to kill any apps that are dependent on the library. 9954 if (clientLibPkgs != null) { 9955 for (int i=0; i<clientLibPkgs.size(); i++) { 9956 PackageParser.Package clientPkg = clientLibPkgs.get(i); 9957 killApplication(clientPkg.applicationInfo.packageName, 9958 clientPkg.applicationInfo.uid, "update lib"); 9959 } 9960 } 9961 9962 // writer 9963 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 9964 9965 boolean createIdmapFailed = false; 9966 synchronized (mPackages) { 9967 // We don't expect installation to fail beyond this point 9968 9969 if (pkgSetting.pkg != null) { 9970 // Note that |user| might be null during the initial boot scan. If a codePath 9971 // for an app has changed during a boot scan, it's due to an app update that's 9972 // part of the system partition and marker changes must be applied to all users. 9973 final int userId = ((user != null) ? user : UserHandle.ALL).getIdentifier(); 9974 final int[] userIds = resolveUserIds(userId); 9975 maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg, userIds); 9976 } 9977 9978 // Add the new setting to mSettings 9979 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 9980 // Add the new setting to mPackages 9981 mPackages.put(pkg.applicationInfo.packageName, pkg); 9982 // Make sure we don't accidentally delete its data. 9983 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 9984 while (iter.hasNext()) { 9985 PackageCleanItem item = iter.next(); 9986 if (pkgName.equals(item.packageName)) { 9987 iter.remove(); 9988 } 9989 } 9990 9991 // Add the package's KeySets to the global KeySetManagerService 9992 KeySetManagerService ksms = mSettings.mKeySetManagerService; 9993 ksms.addScannedPackageLPw(pkg); 9994 9995 int N = pkg.providers.size(); 9996 StringBuilder r = null; 9997 int i; 9998 for (i=0; i<N; i++) { 9999 PackageParser.Provider p = pkg.providers.get(i); 10000 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 10001 p.info.processName); 10002 mProviders.addProvider(p); 10003 p.syncable = p.info.isSyncable; 10004 if (p.info.authority != null) { 10005 String names[] = p.info.authority.split(";"); 10006 p.info.authority = null; 10007 for (int j = 0; j < names.length; j++) { 10008 if (j == 1 && p.syncable) { 10009 // We only want the first authority for a provider to possibly be 10010 // syncable, so if we already added this provider using a different 10011 // authority clear the syncable flag. We copy the provider before 10012 // changing it because the mProviders object contains a reference 10013 // to a provider that we don't want to change. 10014 // Only do this for the second authority since the resulting provider 10015 // object can be the same for all future authorities for this provider. 10016 p = new PackageParser.Provider(p); 10017 p.syncable = false; 10018 } 10019 if (!mProvidersByAuthority.containsKey(names[j])) { 10020 mProvidersByAuthority.put(names[j], p); 10021 if (p.info.authority == null) { 10022 p.info.authority = names[j]; 10023 } else { 10024 p.info.authority = p.info.authority + ";" + names[j]; 10025 } 10026 if (DEBUG_PACKAGE_SCANNING) { 10027 if (chatty) 10028 Log.d(TAG, "Registered content provider: " + names[j] 10029 + ", className = " + p.info.name + ", isSyncable = " 10030 + p.info.isSyncable); 10031 } 10032 } else { 10033 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 10034 Slog.w(TAG, "Skipping provider name " + names[j] + 10035 " (in package " + pkg.applicationInfo.packageName + 10036 "): name already used by " 10037 + ((other != null && other.getComponentName() != null) 10038 ? other.getComponentName().getPackageName() : "?")); 10039 } 10040 } 10041 } 10042 if (chatty) { 10043 if (r == null) { 10044 r = new StringBuilder(256); 10045 } else { 10046 r.append(' '); 10047 } 10048 r.append(p.info.name); 10049 } 10050 } 10051 if (r != null) { 10052 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 10053 } 10054 10055 N = pkg.services.size(); 10056 r = null; 10057 for (i=0; i<N; i++) { 10058 PackageParser.Service s = pkg.services.get(i); 10059 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 10060 s.info.processName); 10061 mServices.addService(s); 10062 if (chatty) { 10063 if (r == null) { 10064 r = new StringBuilder(256); 10065 } else { 10066 r.append(' '); 10067 } 10068 r.append(s.info.name); 10069 } 10070 } 10071 if (r != null) { 10072 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 10073 } 10074 10075 N = pkg.receivers.size(); 10076 r = null; 10077 for (i=0; i<N; i++) { 10078 PackageParser.Activity a = pkg.receivers.get(i); 10079 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 10080 a.info.processName); 10081 mReceivers.addActivity(a, "receiver"); 10082 if (chatty) { 10083 if (r == null) { 10084 r = new StringBuilder(256); 10085 } else { 10086 r.append(' '); 10087 } 10088 r.append(a.info.name); 10089 } 10090 } 10091 if (r != null) { 10092 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 10093 } 10094 10095 N = pkg.activities.size(); 10096 r = null; 10097 for (i=0; i<N; i++) { 10098 PackageParser.Activity a = pkg.activities.get(i); 10099 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 10100 a.info.processName); 10101 mActivities.addActivity(a, "activity"); 10102 if (chatty) { 10103 if (r == null) { 10104 r = new StringBuilder(256); 10105 } else { 10106 r.append(' '); 10107 } 10108 r.append(a.info.name); 10109 } 10110 } 10111 if (r != null) { 10112 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 10113 } 10114 10115 N = pkg.permissionGroups.size(); 10116 r = null; 10117 for (i=0; i<N; i++) { 10118 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 10119 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 10120 final String curPackageName = cur == null ? null : cur.info.packageName; 10121 // Dont allow ephemeral apps to define new permission groups. 10122 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 10123 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 10124 + pg.info.packageName 10125 + " ignored: instant apps cannot define new permission groups."); 10126 continue; 10127 } 10128 final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName); 10129 if (cur == null || isPackageUpdate) { 10130 mPermissionGroups.put(pg.info.name, pg); 10131 if (chatty) { 10132 if (r == null) { 10133 r = new StringBuilder(256); 10134 } else { 10135 r.append(' '); 10136 } 10137 if (isPackageUpdate) { 10138 r.append("UPD:"); 10139 } 10140 r.append(pg.info.name); 10141 } 10142 } else { 10143 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 10144 + pg.info.packageName + " ignored: original from " 10145 + cur.info.packageName); 10146 if (chatty) { 10147 if (r == null) { 10148 r = new StringBuilder(256); 10149 } else { 10150 r.append(' '); 10151 } 10152 r.append("DUP:"); 10153 r.append(pg.info.name); 10154 } 10155 } 10156 } 10157 if (r != null) { 10158 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 10159 } 10160 10161 N = pkg.permissions.size(); 10162 r = null; 10163 for (i=0; i<N; i++) { 10164 PackageParser.Permission p = pkg.permissions.get(i); 10165 10166 // Dont allow ephemeral apps to define new permissions. 10167 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 10168 Slog.w(TAG, "Permission " + p.info.name + " from package " 10169 + p.info.packageName 10170 + " ignored: instant apps cannot define new permissions."); 10171 continue; 10172 } 10173 10174 // Assume by default that we did not install this permission into the system. 10175 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 10176 10177 // Now that permission groups have a special meaning, we ignore permission 10178 // groups for legacy apps to prevent unexpected behavior. In particular, 10179 // permissions for one app being granted to someone just becase they happen 10180 // to be in a group defined by another app (before this had no implications). 10181 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 10182 p.group = mPermissionGroups.get(p.info.group); 10183 // Warn for a permission in an unknown group. 10184 if (p.info.group != null && p.group == null) { 10185 Slog.w(TAG, "Permission " + p.info.name + " from package " 10186 + p.info.packageName + " in an unknown group " + p.info.group); 10187 } 10188 } 10189 10190 ArrayMap<String, BasePermission> permissionMap = 10191 p.tree ? mSettings.mPermissionTrees 10192 : mSettings.mPermissions; 10193 BasePermission bp = permissionMap.get(p.info.name); 10194 10195 // Allow system apps to redefine non-system permissions 10196 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 10197 final boolean currentOwnerIsSystem = (bp.perm != null 10198 && isSystemApp(bp.perm.owner)); 10199 if (isSystemApp(p.owner)) { 10200 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 10201 // It's a built-in permission and no owner, take ownership now 10202 bp.packageSetting = pkgSetting; 10203 bp.perm = p; 10204 bp.uid = pkg.applicationInfo.uid; 10205 bp.sourcePackage = p.info.packageName; 10206 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 10207 } else if (!currentOwnerIsSystem) { 10208 String msg = "New decl " + p.owner + " of permission " 10209 + p.info.name + " is system; overriding " + bp.sourcePackage; 10210 reportSettingsProblem(Log.WARN, msg); 10211 bp = null; 10212 } 10213 } 10214 } 10215 10216 if (bp == null) { 10217 bp = new BasePermission(p.info.name, p.info.packageName, 10218 BasePermission.TYPE_NORMAL); 10219 permissionMap.put(p.info.name, bp); 10220 } 10221 10222 if (bp.perm == null) { 10223 if (bp.sourcePackage == null 10224 || bp.sourcePackage.equals(p.info.packageName)) { 10225 BasePermission tree = findPermissionTreeLP(p.info.name); 10226 if (tree == null 10227 || tree.sourcePackage.equals(p.info.packageName)) { 10228 bp.packageSetting = pkgSetting; 10229 bp.perm = p; 10230 bp.uid = pkg.applicationInfo.uid; 10231 bp.sourcePackage = p.info.packageName; 10232 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 10233 if (chatty) { 10234 if (r == null) { 10235 r = new StringBuilder(256); 10236 } else { 10237 r.append(' '); 10238 } 10239 r.append(p.info.name); 10240 } 10241 } else { 10242 Slog.w(TAG, "Permission " + p.info.name + " from package " 10243 + p.info.packageName + " ignored: base tree " 10244 + tree.name + " is from package " 10245 + tree.sourcePackage); 10246 } 10247 } else { 10248 Slog.w(TAG, "Permission " + p.info.name + " from package " 10249 + p.info.packageName + " ignored: original from " 10250 + bp.sourcePackage); 10251 } 10252 } else if (chatty) { 10253 if (r == null) { 10254 r = new StringBuilder(256); 10255 } else { 10256 r.append(' '); 10257 } 10258 r.append("DUP:"); 10259 r.append(p.info.name); 10260 } 10261 if (bp.perm == p) { 10262 bp.protectionLevel = p.info.protectionLevel; 10263 } 10264 } 10265 10266 if (r != null) { 10267 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 10268 } 10269 10270 N = pkg.instrumentation.size(); 10271 r = null; 10272 for (i=0; i<N; i++) { 10273 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 10274 a.info.packageName = pkg.applicationInfo.packageName; 10275 a.info.sourceDir = pkg.applicationInfo.sourceDir; 10276 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 10277 a.info.splitNames = pkg.splitNames; 10278 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 10279 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 10280 a.info.splitDependencies = pkg.applicationInfo.splitDependencies; 10281 a.info.dataDir = pkg.applicationInfo.dataDir; 10282 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 10283 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 10284 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 10285 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 10286 mInstrumentation.put(a.getComponentName(), a); 10287 if (chatty) { 10288 if (r == null) { 10289 r = new StringBuilder(256); 10290 } else { 10291 r.append(' '); 10292 } 10293 r.append(a.info.name); 10294 } 10295 } 10296 if (r != null) { 10297 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 10298 } 10299 10300 if (pkg.protectedBroadcasts != null) { 10301 N = pkg.protectedBroadcasts.size(); 10302 for (i=0; i<N; i++) { 10303 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 10304 } 10305 } 10306 10307 // Create idmap files for pairs of (packages, overlay packages). 10308 // Note: "android", ie framework-res.apk, is handled by native layers. 10309 if (pkg.mOverlayTarget != null) { 10310 // This is an overlay package. 10311 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 10312 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 10313 mOverlays.put(pkg.mOverlayTarget, 10314 new ArrayMap<String, PackageParser.Package>()); 10315 } 10316 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 10317 map.put(pkg.packageName, pkg); 10318 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 10319 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 10320 createIdmapFailed = true; 10321 } 10322 } 10323 } else if (mOverlays.containsKey(pkg.packageName) && 10324 !pkg.packageName.equals("android")) { 10325 // This is a regular package, with one or more known overlay packages. 10326 createIdmapsForPackageLI(pkg); 10327 } 10328 } 10329 10330 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10331 10332 if (createIdmapFailed) { 10333 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 10334 "scanPackageLI failed to createIdmap"); 10335 } 10336 } 10337 10338 private static void maybeRenameForeignDexMarkers(PackageParser.Package existing, 10339 PackageParser.Package update, int[] userIds) { 10340 if (existing.applicationInfo == null || update.applicationInfo == null) { 10341 // This isn't due to an app installation. 10342 return; 10343 } 10344 10345 final File oldCodePath = new File(existing.applicationInfo.getCodePath()); 10346 final File newCodePath = new File(update.applicationInfo.getCodePath()); 10347 10348 // The codePath hasn't changed, so there's nothing for us to do. 10349 if (Objects.equals(oldCodePath, newCodePath)) { 10350 return; 10351 } 10352 10353 File canonicalNewCodePath; 10354 try { 10355 canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath)); 10356 } catch (IOException e) { 10357 Slog.w(TAG, "Failed to get canonical path.", e); 10358 return; 10359 } 10360 10361 // This is a bit of a hack. The oldCodePath doesn't exist at this point (because 10362 // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume 10363 // that the last component of the path (i.e, the name) doesn't need canonicalization 10364 // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now 10365 // but may change in the future. Hopefully this function won't exist at that point. 10366 final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(), 10367 oldCodePath.getName()); 10368 10369 // Calculate the prefixes of the markers. These are just the paths with "/" replaced 10370 // with "@". 10371 String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@'); 10372 if (!oldMarkerPrefix.endsWith("@")) { 10373 oldMarkerPrefix += "@"; 10374 } 10375 String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@'); 10376 if (!newMarkerPrefix.endsWith("@")) { 10377 newMarkerPrefix += "@"; 10378 } 10379 10380 List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly(); 10381 List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size()); 10382 for (String updatedPath : updatedPaths) { 10383 String updatedPathName = new File(updatedPath).getName(); 10384 markerSuffixes.add(updatedPathName.replace('/', '@')); 10385 } 10386 10387 for (int userId : userIds) { 10388 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId); 10389 10390 for (String markerSuffix : markerSuffixes) { 10391 File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix); 10392 File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix); 10393 if (oldForeignUseMark.exists()) { 10394 try { 10395 Os.rename(oldForeignUseMark.getAbsolutePath(), 10396 newForeignUseMark.getAbsolutePath()); 10397 } catch (ErrnoException e) { 10398 Slog.w(TAG, "Failed to rename foreign use marker", e); 10399 oldForeignUseMark.delete(); 10400 } 10401 } 10402 } 10403 } 10404 } 10405 10406 /** 10407 * Derive the ABI of a non-system package located at {@code scanFile}. This information 10408 * is derived purely on the basis of the contents of {@code scanFile} and 10409 * {@code cpuAbiOverride}. 10410 * 10411 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 10412 */ 10413 private static void derivePackageAbi(PackageParser.Package pkg, File scanFile, 10414 String cpuAbiOverride, boolean extractLibs, 10415 File appLib32InstallDir) 10416 throws PackageManagerException { 10417 // Give ourselves some initial paths; we'll come back for another 10418 // pass once we've determined ABI below. 10419 setNativeLibraryPaths(pkg, appLib32InstallDir); 10420 10421 // We would never need to extract libs for forward-locked and external packages, 10422 // since the container service will do it for us. We shouldn't attempt to 10423 // extract libs from system app when it was not updated. 10424 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 10425 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 10426 extractLibs = false; 10427 } 10428 10429 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 10430 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 10431 10432 NativeLibraryHelper.Handle handle = null; 10433 try { 10434 handle = NativeLibraryHelper.Handle.create(pkg); 10435 // TODO(multiArch): This can be null for apps that didn't go through the 10436 // usual installation process. We can calculate it again, like we 10437 // do during install time. 10438 // 10439 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 10440 // unnecessary. 10441 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 10442 10443 // Null out the abis so that they can be recalculated. 10444 pkg.applicationInfo.primaryCpuAbi = null; 10445 pkg.applicationInfo.secondaryCpuAbi = null; 10446 if (isMultiArch(pkg.applicationInfo)) { 10447 // Warn if we've set an abiOverride for multi-lib packages.. 10448 // By definition, we need to copy both 32 and 64 bit libraries for 10449 // such packages. 10450 if (pkg.cpuAbiOverride != null 10451 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 10452 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 10453 } 10454 10455 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 10456 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 10457 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 10458 if (extractLibs) { 10459 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 10460 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 10461 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 10462 useIsaSpecificSubdirs); 10463 } else { 10464 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 10465 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 10466 } 10467 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10468 } 10469 10470 maybeThrowExceptionForMultiArchCopy( 10471 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 10472 10473 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 10474 if (extractLibs) { 10475 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 10476 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 10477 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 10478 useIsaSpecificSubdirs); 10479 } else { 10480 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 10481 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 10482 } 10483 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10484 } 10485 10486 maybeThrowExceptionForMultiArchCopy( 10487 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 10488 10489 if (abi64 >= 0) { 10490 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 10491 } 10492 10493 if (abi32 >= 0) { 10494 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 10495 if (abi64 >= 0) { 10496 if (pkg.use32bitAbi) { 10497 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 10498 pkg.applicationInfo.primaryCpuAbi = abi; 10499 } else { 10500 pkg.applicationInfo.secondaryCpuAbi = abi; 10501 } 10502 } else { 10503 pkg.applicationInfo.primaryCpuAbi = abi; 10504 } 10505 } 10506 10507 } else { 10508 String[] abiList = (cpuAbiOverride != null) ? 10509 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 10510 10511 // Enable gross and lame hacks for apps that are built with old 10512 // SDK tools. We must scan their APKs for renderscript bitcode and 10513 // not launch them if it's present. Don't bother checking on devices 10514 // that don't have 64 bit support. 10515 boolean needsRenderScriptOverride = false; 10516 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 10517 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 10518 abiList = Build.SUPPORTED_32_BIT_ABIS; 10519 needsRenderScriptOverride = true; 10520 } 10521 10522 final int copyRet; 10523 if (extractLibs) { 10524 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 10525 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 10526 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 10527 } else { 10528 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 10529 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 10530 } 10531 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10532 10533 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 10534 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 10535 "Error unpackaging native libs for app, errorCode=" + copyRet); 10536 } 10537 10538 if (copyRet >= 0) { 10539 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 10540 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 10541 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 10542 } else if (needsRenderScriptOverride) { 10543 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 10544 } 10545 } 10546 } catch (IOException ioe) { 10547 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 10548 } finally { 10549 IoUtils.closeQuietly(handle); 10550 } 10551 10552 // Now that we've calculated the ABIs and determined if it's an internal app, 10553 // we will go ahead and populate the nativeLibraryPath. 10554 setNativeLibraryPaths(pkg, appLib32InstallDir); 10555 } 10556 10557 /** 10558 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 10559 * i.e, so that all packages can be run inside a single process if required. 10560 * 10561 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 10562 * this function will either try and make the ABI for all packages in {@code packagesForUser} 10563 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 10564 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 10565 * updating a package that belongs to a shared user. 10566 * 10567 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 10568 * adds unnecessary complexity. 10569 */ 10570 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 10571 PackageParser.Package scannedPackage) { 10572 String requiredInstructionSet = null; 10573 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 10574 requiredInstructionSet = VMRuntime.getInstructionSet( 10575 scannedPackage.applicationInfo.primaryCpuAbi); 10576 } 10577 10578 PackageSetting requirer = null; 10579 for (PackageSetting ps : packagesForUser) { 10580 // If packagesForUser contains scannedPackage, we skip it. This will happen 10581 // when scannedPackage is an update of an existing package. Without this check, 10582 // we will never be able to change the ABI of any package belonging to a shared 10583 // user, even if it's compatible with other packages. 10584 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 10585 if (ps.primaryCpuAbiString == null) { 10586 continue; 10587 } 10588 10589 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 10590 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 10591 // We have a mismatch between instruction sets (say arm vs arm64) warn about 10592 // this but there's not much we can do. 10593 String errorMessage = "Instruction set mismatch, " 10594 + ((requirer == null) ? "[caller]" : requirer) 10595 + " requires " + requiredInstructionSet + " whereas " + ps 10596 + " requires " + instructionSet; 10597 Slog.w(TAG, errorMessage); 10598 } 10599 10600 if (requiredInstructionSet == null) { 10601 requiredInstructionSet = instructionSet; 10602 requirer = ps; 10603 } 10604 } 10605 } 10606 10607 if (requiredInstructionSet != null) { 10608 String adjustedAbi; 10609 if (requirer != null) { 10610 // requirer != null implies that either scannedPackage was null or that scannedPackage 10611 // did not require an ABI, in which case we have to adjust scannedPackage to match 10612 // the ABI of the set (which is the same as requirer's ABI) 10613 adjustedAbi = requirer.primaryCpuAbiString; 10614 if (scannedPackage != null) { 10615 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 10616 } 10617 } else { 10618 // requirer == null implies that we're updating all ABIs in the set to 10619 // match scannedPackage. 10620 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 10621 } 10622 10623 for (PackageSetting ps : packagesForUser) { 10624 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 10625 if (ps.primaryCpuAbiString != null) { 10626 continue; 10627 } 10628 10629 ps.primaryCpuAbiString = adjustedAbi; 10630 if (ps.pkg != null && ps.pkg.applicationInfo != null && 10631 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 10632 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 10633 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 10634 + " (requirer=" 10635 + (requirer == null ? "null" : requirer.pkg.packageName) 10636 + ", scannedPackage=" 10637 + (scannedPackage != null ? scannedPackage.packageName : "null") 10638 + ")"); 10639 try { 10640 mInstaller.rmdex(ps.codePathString, 10641 getDexCodeInstructionSet(getPreferredInstructionSet())); 10642 } catch (InstallerException ignored) { 10643 } 10644 } 10645 } 10646 } 10647 } 10648 } 10649 10650 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 10651 synchronized (mPackages) { 10652 mResolverReplaced = true; 10653 // Set up information for custom user intent resolution activity. 10654 mResolveActivity.applicationInfo = pkg.applicationInfo; 10655 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 10656 mResolveActivity.packageName = pkg.applicationInfo.packageName; 10657 mResolveActivity.processName = pkg.applicationInfo.packageName; 10658 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 10659 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 10660 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 10661 mResolveActivity.theme = 0; 10662 mResolveActivity.exported = true; 10663 mResolveActivity.enabled = true; 10664 mResolveInfo.activityInfo = mResolveActivity; 10665 mResolveInfo.priority = 0; 10666 mResolveInfo.preferredOrder = 0; 10667 mResolveInfo.match = 0; 10668 mResolveComponentName = mCustomResolverComponentName; 10669 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 10670 mResolveComponentName); 10671 } 10672 } 10673 10674 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 10675 if (installerComponent == null) { 10676 if (DEBUG_EPHEMERAL) { 10677 Slog.d(TAG, "Clear ephemeral installer activity"); 10678 } 10679 mEphemeralInstallerActivity.applicationInfo = null; 10680 return; 10681 } 10682 10683 if (DEBUG_EPHEMERAL) { 10684 Slog.d(TAG, "Set ephemeral installer activity: " + installerComponent); 10685 } 10686 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 10687 // Set up information for ephemeral installer activity 10688 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 10689 mEphemeralInstallerActivity.name = installerComponent.getClassName(); 10690 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 10691 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 10692 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 10693 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS 10694 | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 10695 mEphemeralInstallerActivity.theme = 0; 10696 mEphemeralInstallerActivity.exported = true; 10697 mEphemeralInstallerActivity.enabled = true; 10698 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 10699 mEphemeralInstallerInfo.priority = 0; 10700 mEphemeralInstallerInfo.preferredOrder = 1; 10701 mEphemeralInstallerInfo.isDefault = true; 10702 mEphemeralInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 10703 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 10704 } 10705 10706 private static String calculateBundledApkRoot(final String codePathString) { 10707 final File codePath = new File(codePathString); 10708 final File codeRoot; 10709 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 10710 codeRoot = Environment.getRootDirectory(); 10711 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 10712 codeRoot = Environment.getOemDirectory(); 10713 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 10714 codeRoot = Environment.getVendorDirectory(); 10715 } else { 10716 // Unrecognized code path; take its top real segment as the apk root: 10717 // e.g. /something/app/blah.apk => /something 10718 try { 10719 File f = codePath.getCanonicalFile(); 10720 File parent = f.getParentFile(); // non-null because codePath is a file 10721 File tmp; 10722 while ((tmp = parent.getParentFile()) != null) { 10723 f = parent; 10724 parent = tmp; 10725 } 10726 codeRoot = f; 10727 Slog.w(TAG, "Unrecognized code path " 10728 + codePath + " - using " + codeRoot); 10729 } catch (IOException e) { 10730 // Can't canonicalize the code path -- shenanigans? 10731 Slog.w(TAG, "Can't canonicalize code path " + codePath); 10732 return Environment.getRootDirectory().getPath(); 10733 } 10734 } 10735 return codeRoot.getPath(); 10736 } 10737 10738 /** 10739 * Derive and set the location of native libraries for the given package, 10740 * which varies depending on where and how the package was installed. 10741 */ 10742 private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) { 10743 final ApplicationInfo info = pkg.applicationInfo; 10744 final String codePath = pkg.codePath; 10745 final File codeFile = new File(codePath); 10746 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 10747 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 10748 10749 info.nativeLibraryRootDir = null; 10750 info.nativeLibraryRootRequiresIsa = false; 10751 info.nativeLibraryDir = null; 10752 info.secondaryNativeLibraryDir = null; 10753 10754 if (isApkFile(codeFile)) { 10755 // Monolithic install 10756 if (bundledApp) { 10757 // If "/system/lib64/apkname" exists, assume that is the per-package 10758 // native library directory to use; otherwise use "/system/lib/apkname". 10759 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 10760 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 10761 getPrimaryInstructionSet(info)); 10762 10763 // This is a bundled system app so choose the path based on the ABI. 10764 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 10765 // is just the default path. 10766 final String apkName = deriveCodePathName(codePath); 10767 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 10768 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 10769 apkName).getAbsolutePath(); 10770 10771 if (info.secondaryCpuAbi != null) { 10772 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 10773 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 10774 secondaryLibDir, apkName).getAbsolutePath(); 10775 } 10776 } else if (asecApp) { 10777 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 10778 .getAbsolutePath(); 10779 } else { 10780 final String apkName = deriveCodePathName(codePath); 10781 info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName) 10782 .getAbsolutePath(); 10783 } 10784 10785 info.nativeLibraryRootRequiresIsa = false; 10786 info.nativeLibraryDir = info.nativeLibraryRootDir; 10787 } else { 10788 // Cluster install 10789 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 10790 info.nativeLibraryRootRequiresIsa = true; 10791 10792 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 10793 getPrimaryInstructionSet(info)).getAbsolutePath(); 10794 10795 if (info.secondaryCpuAbi != null) { 10796 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 10797 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 10798 } 10799 } 10800 } 10801 10802 /** 10803 * Calculate the abis and roots for a bundled app. These can uniquely 10804 * be determined from the contents of the system partition, i.e whether 10805 * it contains 64 or 32 bit shared libraries etc. We do not validate any 10806 * of this information, and instead assume that the system was built 10807 * sensibly. 10808 */ 10809 private static void setBundledAppAbisAndRoots(PackageParser.Package pkg, 10810 PackageSetting pkgSetting) { 10811 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 10812 10813 // If "/system/lib64/apkname" exists, assume that is the per-package 10814 // native library directory to use; otherwise use "/system/lib/apkname". 10815 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 10816 setBundledAppAbi(pkg, apkRoot, apkName); 10817 // pkgSetting might be null during rescan following uninstall of updates 10818 // to a bundled app, so accommodate that possibility. The settings in 10819 // that case will be established later from the parsed package. 10820 // 10821 // If the settings aren't null, sync them up with what we've just derived. 10822 // note that apkRoot isn't stored in the package settings. 10823 if (pkgSetting != null) { 10824 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 10825 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 10826 } 10827 } 10828 10829 /** 10830 * Deduces the ABI of a bundled app and sets the relevant fields on the 10831 * parsed pkg object. 10832 * 10833 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 10834 * under which system libraries are installed. 10835 * @param apkName the name of the installed package. 10836 */ 10837 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 10838 final File codeFile = new File(pkg.codePath); 10839 10840 final boolean has64BitLibs; 10841 final boolean has32BitLibs; 10842 if (isApkFile(codeFile)) { 10843 // Monolithic install 10844 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 10845 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 10846 } else { 10847 // Cluster install 10848 final File rootDir = new File(codeFile, LIB_DIR_NAME); 10849 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 10850 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 10851 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 10852 has64BitLibs = (new File(rootDir, isa)).exists(); 10853 } else { 10854 has64BitLibs = false; 10855 } 10856 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 10857 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 10858 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 10859 has32BitLibs = (new File(rootDir, isa)).exists(); 10860 } else { 10861 has32BitLibs = false; 10862 } 10863 } 10864 10865 if (has64BitLibs && !has32BitLibs) { 10866 // The package has 64 bit libs, but not 32 bit libs. Its primary 10867 // ABI should be 64 bit. We can safely assume here that the bundled 10868 // native libraries correspond to the most preferred ABI in the list. 10869 10870 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 10871 pkg.applicationInfo.secondaryCpuAbi = null; 10872 } else if (has32BitLibs && !has64BitLibs) { 10873 // The package has 32 bit libs but not 64 bit libs. Its primary 10874 // ABI should be 32 bit. 10875 10876 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 10877 pkg.applicationInfo.secondaryCpuAbi = null; 10878 } else if (has32BitLibs && has64BitLibs) { 10879 // The application has both 64 and 32 bit bundled libraries. We check 10880 // here that the app declares multiArch support, and warn if it doesn't. 10881 // 10882 // We will be lenient here and record both ABIs. The primary will be the 10883 // ABI that's higher on the list, i.e, a device that's configured to prefer 10884 // 64 bit apps will see a 64 bit primary ABI, 10885 10886 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 10887 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 10888 } 10889 10890 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 10891 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 10892 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 10893 } else { 10894 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 10895 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 10896 } 10897 } else { 10898 pkg.applicationInfo.primaryCpuAbi = null; 10899 pkg.applicationInfo.secondaryCpuAbi = null; 10900 } 10901 } 10902 10903 private void killApplication(String pkgName, int appId, String reason) { 10904 killApplication(pkgName, appId, UserHandle.USER_ALL, reason); 10905 } 10906 10907 private void killApplication(String pkgName, int appId, int userId, String reason) { 10908 // Request the ActivityManager to kill the process(only for existing packages) 10909 // so that we do not end up in a confused state while the user is still using the older 10910 // version of the application while the new one gets installed. 10911 final long token = Binder.clearCallingIdentity(); 10912 try { 10913 IActivityManager am = ActivityManager.getService(); 10914 if (am != null) { 10915 try { 10916 am.killApplication(pkgName, appId, userId, reason); 10917 } catch (RemoteException e) { 10918 } 10919 } 10920 } finally { 10921 Binder.restoreCallingIdentity(token); 10922 } 10923 } 10924 10925 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 10926 // Remove the parent package setting 10927 PackageSetting ps = (PackageSetting) pkg.mExtras; 10928 if (ps != null) { 10929 removePackageLI(ps, chatty); 10930 } 10931 // Remove the child package setting 10932 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 10933 for (int i = 0; i < childCount; i++) { 10934 PackageParser.Package childPkg = pkg.childPackages.get(i); 10935 ps = (PackageSetting) childPkg.mExtras; 10936 if (ps != null) { 10937 removePackageLI(ps, chatty); 10938 } 10939 } 10940 } 10941 10942 void removePackageLI(PackageSetting ps, boolean chatty) { 10943 if (DEBUG_INSTALL) { 10944 if (chatty) 10945 Log.d(TAG, "Removing package " + ps.name); 10946 } 10947 10948 // writer 10949 synchronized (mPackages) { 10950 mPackages.remove(ps.name); 10951 final PackageParser.Package pkg = ps.pkg; 10952 if (pkg != null) { 10953 cleanPackageDataStructuresLILPw(pkg, chatty); 10954 } 10955 } 10956 } 10957 10958 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 10959 if (DEBUG_INSTALL) { 10960 if (chatty) 10961 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 10962 } 10963 10964 // writer 10965 synchronized (mPackages) { 10966 // Remove the parent package 10967 mPackages.remove(pkg.applicationInfo.packageName); 10968 cleanPackageDataStructuresLILPw(pkg, chatty); 10969 10970 // Remove the child packages 10971 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 10972 for (int i = 0; i < childCount; i++) { 10973 PackageParser.Package childPkg = pkg.childPackages.get(i); 10974 mPackages.remove(childPkg.applicationInfo.packageName); 10975 cleanPackageDataStructuresLILPw(childPkg, chatty); 10976 } 10977 } 10978 } 10979 10980 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 10981 int N = pkg.providers.size(); 10982 StringBuilder r = null; 10983 int i; 10984 for (i=0; i<N; i++) { 10985 PackageParser.Provider p = pkg.providers.get(i); 10986 mProviders.removeProvider(p); 10987 if (p.info.authority == null) { 10988 10989 /* There was another ContentProvider with this authority when 10990 * this app was installed so this authority is null, 10991 * Ignore it as we don't have to unregister the provider. 10992 */ 10993 continue; 10994 } 10995 String names[] = p.info.authority.split(";"); 10996 for (int j = 0; j < names.length; j++) { 10997 if (mProvidersByAuthority.get(names[j]) == p) { 10998 mProvidersByAuthority.remove(names[j]); 10999 if (DEBUG_REMOVE) { 11000 if (chatty) 11001 Log.d(TAG, "Unregistered content provider: " + names[j] 11002 + ", className = " + p.info.name + ", isSyncable = " 11003 + p.info.isSyncable); 11004 } 11005 } 11006 } 11007 if (DEBUG_REMOVE && chatty) { 11008 if (r == null) { 11009 r = new StringBuilder(256); 11010 } else { 11011 r.append(' '); 11012 } 11013 r.append(p.info.name); 11014 } 11015 } 11016 if (r != null) { 11017 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 11018 } 11019 11020 N = pkg.services.size(); 11021 r = null; 11022 for (i=0; i<N; i++) { 11023 PackageParser.Service s = pkg.services.get(i); 11024 mServices.removeService(s); 11025 if (chatty) { 11026 if (r == null) { 11027 r = new StringBuilder(256); 11028 } else { 11029 r.append(' '); 11030 } 11031 r.append(s.info.name); 11032 } 11033 } 11034 if (r != null) { 11035 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 11036 } 11037 11038 N = pkg.receivers.size(); 11039 r = null; 11040 for (i=0; i<N; i++) { 11041 PackageParser.Activity a = pkg.receivers.get(i); 11042 mReceivers.removeActivity(a, "receiver"); 11043 if (DEBUG_REMOVE && chatty) { 11044 if (r == null) { 11045 r = new StringBuilder(256); 11046 } else { 11047 r.append(' '); 11048 } 11049 r.append(a.info.name); 11050 } 11051 } 11052 if (r != null) { 11053 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 11054 } 11055 11056 N = pkg.activities.size(); 11057 r = null; 11058 for (i=0; i<N; i++) { 11059 PackageParser.Activity a = pkg.activities.get(i); 11060 mActivities.removeActivity(a, "activity"); 11061 if (DEBUG_REMOVE && chatty) { 11062 if (r == null) { 11063 r = new StringBuilder(256); 11064 } else { 11065 r.append(' '); 11066 } 11067 r.append(a.info.name); 11068 } 11069 } 11070 if (r != null) { 11071 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 11072 } 11073 11074 N = pkg.permissions.size(); 11075 r = null; 11076 for (i=0; i<N; i++) { 11077 PackageParser.Permission p = pkg.permissions.get(i); 11078 BasePermission bp = mSettings.mPermissions.get(p.info.name); 11079 if (bp == null) { 11080 bp = mSettings.mPermissionTrees.get(p.info.name); 11081 } 11082 if (bp != null && bp.perm == p) { 11083 bp.perm = null; 11084 if (DEBUG_REMOVE && chatty) { 11085 if (r == null) { 11086 r = new StringBuilder(256); 11087 } else { 11088 r.append(' '); 11089 } 11090 r.append(p.info.name); 11091 } 11092 } 11093 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 11094 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 11095 if (appOpPkgs != null) { 11096 appOpPkgs.remove(pkg.packageName); 11097 } 11098 } 11099 } 11100 if (r != null) { 11101 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 11102 } 11103 11104 N = pkg.requestedPermissions.size(); 11105 r = null; 11106 for (i=0; i<N; i++) { 11107 String perm = pkg.requestedPermissions.get(i); 11108 BasePermission bp = mSettings.mPermissions.get(perm); 11109 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 11110 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 11111 if (appOpPkgs != null) { 11112 appOpPkgs.remove(pkg.packageName); 11113 if (appOpPkgs.isEmpty()) { 11114 mAppOpPermissionPackages.remove(perm); 11115 } 11116 } 11117 } 11118 } 11119 if (r != null) { 11120 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 11121 } 11122 11123 N = pkg.instrumentation.size(); 11124 r = null; 11125 for (i=0; i<N; i++) { 11126 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 11127 mInstrumentation.remove(a.getComponentName()); 11128 if (DEBUG_REMOVE && chatty) { 11129 if (r == null) { 11130 r = new StringBuilder(256); 11131 } else { 11132 r.append(' '); 11133 } 11134 r.append(a.info.name); 11135 } 11136 } 11137 if (r != null) { 11138 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 11139 } 11140 11141 r = null; 11142 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 11143 // Only system apps can hold shared libraries. 11144 if (pkg.libraryNames != null) { 11145 for (i = 0; i < pkg.libraryNames.size(); i++) { 11146 String name = pkg.libraryNames.get(i); 11147 if (removeSharedLibraryLPw(name, 0)) { 11148 if (DEBUG_REMOVE && chatty) { 11149 if (r == null) { 11150 r = new StringBuilder(256); 11151 } else { 11152 r.append(' '); 11153 } 11154 r.append(name); 11155 } 11156 } 11157 } 11158 } 11159 } 11160 11161 r = null; 11162 11163 // Any package can hold static shared libraries. 11164 if (pkg.staticSharedLibName != null) { 11165 if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) { 11166 if (DEBUG_REMOVE && chatty) { 11167 if (r == null) { 11168 r = new StringBuilder(256); 11169 } else { 11170 r.append(' '); 11171 } 11172 r.append(pkg.staticSharedLibName); 11173 } 11174 } 11175 } 11176 11177 if (r != null) { 11178 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 11179 } 11180 } 11181 11182 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 11183 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 11184 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 11185 return true; 11186 } 11187 } 11188 return false; 11189 } 11190 11191 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 11192 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 11193 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 11194 11195 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 11196 // Update the parent permissions 11197 updatePermissionsLPw(pkg.packageName, pkg, flags); 11198 // Update the child permissions 11199 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 11200 for (int i = 0; i < childCount; i++) { 11201 PackageParser.Package childPkg = pkg.childPackages.get(i); 11202 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 11203 } 11204 } 11205 11206 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 11207 int flags) { 11208 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 11209 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 11210 } 11211 11212 private void updatePermissionsLPw(String changingPkg, 11213 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 11214 // Make sure there are no dangling permission trees. 11215 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 11216 while (it.hasNext()) { 11217 final BasePermission bp = it.next(); 11218 if (bp.packageSetting == null) { 11219 // We may not yet have parsed the package, so just see if 11220 // we still know about its settings. 11221 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 11222 } 11223 if (bp.packageSetting == null) { 11224 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 11225 + " from package " + bp.sourcePackage); 11226 it.remove(); 11227 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 11228 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 11229 Slog.i(TAG, "Removing old permission tree: " + bp.name 11230 + " from package " + bp.sourcePackage); 11231 flags |= UPDATE_PERMISSIONS_ALL; 11232 it.remove(); 11233 } 11234 } 11235 } 11236 11237 // Make sure all dynamic permissions have been assigned to a package, 11238 // and make sure there are no dangling permissions. 11239 it = mSettings.mPermissions.values().iterator(); 11240 while (it.hasNext()) { 11241 final BasePermission bp = it.next(); 11242 if (bp.type == BasePermission.TYPE_DYNAMIC) { 11243 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 11244 + bp.name + " pkg=" + bp.sourcePackage 11245 + " info=" + bp.pendingInfo); 11246 if (bp.packageSetting == null && bp.pendingInfo != null) { 11247 final BasePermission tree = findPermissionTreeLP(bp.name); 11248 if (tree != null && tree.perm != null) { 11249 bp.packageSetting = tree.packageSetting; 11250 bp.perm = new PackageParser.Permission(tree.perm.owner, 11251 new PermissionInfo(bp.pendingInfo)); 11252 bp.perm.info.packageName = tree.perm.info.packageName; 11253 bp.perm.info.name = bp.name; 11254 bp.uid = tree.uid; 11255 } 11256 } 11257 } 11258 if (bp.packageSetting == null) { 11259 // We may not yet have parsed the package, so just see if 11260 // we still know about its settings. 11261 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 11262 } 11263 if (bp.packageSetting == null) { 11264 Slog.w(TAG, "Removing dangling permission: " + bp.name 11265 + " from package " + bp.sourcePackage); 11266 it.remove(); 11267 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 11268 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 11269 Slog.i(TAG, "Removing old permission: " + bp.name 11270 + " from package " + bp.sourcePackage); 11271 flags |= UPDATE_PERMISSIONS_ALL; 11272 it.remove(); 11273 } 11274 } 11275 } 11276 11277 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 11278 // Now update the permissions for all packages, in particular 11279 // replace the granted permissions of the system packages. 11280 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 11281 for (PackageParser.Package pkg : mPackages.values()) { 11282 if (pkg != pkgInfo) { 11283 // Only replace for packages on requested volume 11284 final String volumeUuid = getVolumeUuidForPackage(pkg); 11285 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 11286 && Objects.equals(replaceVolumeUuid, volumeUuid); 11287 grantPermissionsLPw(pkg, replace, changingPkg); 11288 } 11289 } 11290 } 11291 11292 if (pkgInfo != null) { 11293 // Only replace for packages on requested volume 11294 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 11295 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 11296 && Objects.equals(replaceVolumeUuid, volumeUuid); 11297 grantPermissionsLPw(pkgInfo, replace, changingPkg); 11298 } 11299 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11300 } 11301 11302 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 11303 String packageOfInterest) { 11304 // IMPORTANT: There are two types of permissions: install and runtime. 11305 // Install time permissions are granted when the app is installed to 11306 // all device users and users added in the future. Runtime permissions 11307 // are granted at runtime explicitly to specific users. Normal and signature 11308 // protected permissions are install time permissions. Dangerous permissions 11309 // are install permissions if the app's target SDK is Lollipop MR1 or older, 11310 // otherwise they are runtime permissions. This function does not manage 11311 // runtime permissions except for the case an app targeting Lollipop MR1 11312 // being upgraded to target a newer SDK, in which case dangerous permissions 11313 // are transformed from install time to runtime ones. 11314 11315 final PackageSetting ps = (PackageSetting) pkg.mExtras; 11316 if (ps == null) { 11317 return; 11318 } 11319 11320 PermissionsState permissionsState = ps.getPermissionsState(); 11321 PermissionsState origPermissions = permissionsState; 11322 11323 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 11324 11325 boolean runtimePermissionsRevoked = false; 11326 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 11327 11328 boolean changedInstallPermission = false; 11329 11330 if (replace) { 11331 ps.installPermissionsFixed = false; 11332 if (!ps.isSharedUser()) { 11333 origPermissions = new PermissionsState(permissionsState); 11334 permissionsState.reset(); 11335 } else { 11336 // We need to know only about runtime permission changes since the 11337 // calling code always writes the install permissions state but 11338 // the runtime ones are written only if changed. The only cases of 11339 // changed runtime permissions here are promotion of an install to 11340 // runtime and revocation of a runtime from a shared user. 11341 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 11342 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 11343 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 11344 runtimePermissionsRevoked = true; 11345 } 11346 } 11347 } 11348 11349 permissionsState.setGlobalGids(mGlobalGids); 11350 11351 final int N = pkg.requestedPermissions.size(); 11352 for (int i=0; i<N; i++) { 11353 final String name = pkg.requestedPermissions.get(i); 11354 final BasePermission bp = mSettings.mPermissions.get(name); 11355 11356 if (DEBUG_INSTALL) { 11357 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 11358 } 11359 11360 if (bp == null || bp.packageSetting == null) { 11361 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 11362 Slog.w(TAG, "Unknown permission " + name 11363 + " in package " + pkg.packageName); 11364 } 11365 continue; 11366 } 11367 11368 11369 // Limit ephemeral apps to ephemeral allowed permissions. 11370 if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) { 11371 Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package " 11372 + pkg.packageName); 11373 continue; 11374 } 11375 11376 final String perm = bp.name; 11377 boolean allowedSig = false; 11378 int grant = GRANT_DENIED; 11379 11380 // Keep track of app op permissions. 11381 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 11382 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 11383 if (pkgs == null) { 11384 pkgs = new ArraySet<>(); 11385 mAppOpPermissionPackages.put(bp.name, pkgs); 11386 } 11387 pkgs.add(pkg.packageName); 11388 } 11389 11390 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 11391 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 11392 >= Build.VERSION_CODES.M; 11393 switch (level) { 11394 case PermissionInfo.PROTECTION_NORMAL: { 11395 // For all apps normal permissions are install time ones. 11396 grant = GRANT_INSTALL; 11397 } break; 11398 11399 case PermissionInfo.PROTECTION_DANGEROUS: { 11400 // If a permission review is required for legacy apps we represent 11401 // their permissions as always granted runtime ones since we need 11402 // to keep the review required permission flag per user while an 11403 // install permission's state is shared across all users. 11404 if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) { 11405 // For legacy apps dangerous permissions are install time ones. 11406 grant = GRANT_INSTALL; 11407 } else if (origPermissions.hasInstallPermission(bp.name)) { 11408 // For legacy apps that became modern, install becomes runtime. 11409 grant = GRANT_UPGRADE; 11410 } else if (mPromoteSystemApps 11411 && isSystemApp(ps) 11412 && mExistingSystemPackages.contains(ps.name)) { 11413 // For legacy system apps, install becomes runtime. 11414 // We cannot check hasInstallPermission() for system apps since those 11415 // permissions were granted implicitly and not persisted pre-M. 11416 grant = GRANT_UPGRADE; 11417 } else { 11418 // For modern apps keep runtime permissions unchanged. 11419 grant = GRANT_RUNTIME; 11420 } 11421 } break; 11422 11423 case PermissionInfo.PROTECTION_SIGNATURE: { 11424 // For all apps signature permissions are install time ones. 11425 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 11426 if (allowedSig) { 11427 grant = GRANT_INSTALL; 11428 } 11429 } break; 11430 } 11431 11432 if (DEBUG_INSTALL) { 11433 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 11434 } 11435 11436 if (grant != GRANT_DENIED) { 11437 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 11438 // If this is an existing, non-system package, then 11439 // we can't add any new permissions to it. 11440 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 11441 // Except... if this is a permission that was added 11442 // to the platform (note: need to only do this when 11443 // updating the platform). 11444 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 11445 grant = GRANT_DENIED; 11446 } 11447 } 11448 } 11449 11450 switch (grant) { 11451 case GRANT_INSTALL: { 11452 // Revoke this as runtime permission to handle the case of 11453 // a runtime permission being downgraded to an install one. 11454 // Also in permission review mode we keep dangerous permissions 11455 // for legacy apps 11456 for (int userId : UserManagerService.getInstance().getUserIds()) { 11457 if (origPermissions.getRuntimePermissionState( 11458 bp.name, userId) != null) { 11459 // Revoke the runtime permission and clear the flags. 11460 origPermissions.revokeRuntimePermission(bp, userId); 11461 origPermissions.updatePermissionFlags(bp, userId, 11462 PackageManager.MASK_PERMISSION_FLAGS, 0); 11463 // If we revoked a permission permission, we have to write. 11464 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11465 changedRuntimePermissionUserIds, userId); 11466 } 11467 } 11468 // Grant an install permission. 11469 if (permissionsState.grantInstallPermission(bp) != 11470 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11471 changedInstallPermission = true; 11472 } 11473 } break; 11474 11475 case GRANT_RUNTIME: { 11476 // Grant previously granted runtime permissions. 11477 for (int userId : UserManagerService.getInstance().getUserIds()) { 11478 PermissionState permissionState = origPermissions 11479 .getRuntimePermissionState(bp.name, userId); 11480 int flags = permissionState != null 11481 ? permissionState.getFlags() : 0; 11482 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 11483 // Don't propagate the permission in a permission review mode if 11484 // the former was revoked, i.e. marked to not propagate on upgrade. 11485 // Note that in a permission review mode install permissions are 11486 // represented as constantly granted runtime ones since we need to 11487 // keep a per user state associated with the permission. Also the 11488 // revoke on upgrade flag is no longer applicable and is reset. 11489 final boolean revokeOnUpgrade = (flags & PackageManager 11490 .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 11491 if (revokeOnUpgrade) { 11492 flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 11493 // Since we changed the flags, we have to write. 11494 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11495 changedRuntimePermissionUserIds, userId); 11496 } 11497 if (!mPermissionReviewRequired || !revokeOnUpgrade) { 11498 if (permissionsState.grantRuntimePermission(bp, userId) == 11499 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11500 // If we cannot put the permission as it was, 11501 // we have to write. 11502 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11503 changedRuntimePermissionUserIds, userId); 11504 } 11505 } 11506 11507 // If the app supports runtime permissions no need for a review. 11508 if (mPermissionReviewRequired 11509 && appSupportsRuntimePermissions 11510 && (flags & PackageManager 11511 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 11512 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 11513 // Since we changed the flags, we have to write. 11514 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11515 changedRuntimePermissionUserIds, userId); 11516 } 11517 } else if (mPermissionReviewRequired 11518 && !appSupportsRuntimePermissions) { 11519 // For legacy apps that need a permission review, every new 11520 // runtime permission is granted but it is pending a review. 11521 // We also need to review only platform defined runtime 11522 // permissions as these are the only ones the platform knows 11523 // how to disable the API to simulate revocation as legacy 11524 // apps don't expect to run with revoked permissions. 11525 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 11526 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 11527 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 11528 // We changed the flags, hence have to write. 11529 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11530 changedRuntimePermissionUserIds, userId); 11531 } 11532 } 11533 if (permissionsState.grantRuntimePermission(bp, userId) 11534 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 11535 // We changed the permission, hence have to write. 11536 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11537 changedRuntimePermissionUserIds, userId); 11538 } 11539 } 11540 // Propagate the permission flags. 11541 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 11542 } 11543 } break; 11544 11545 case GRANT_UPGRADE: { 11546 // Grant runtime permissions for a previously held install permission. 11547 PermissionState permissionState = origPermissions 11548 .getInstallPermissionState(bp.name); 11549 final int flags = permissionState != null ? permissionState.getFlags() : 0; 11550 11551 if (origPermissions.revokeInstallPermission(bp) 11552 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 11553 // We will be transferring the permission flags, so clear them. 11554 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 11555 PackageManager.MASK_PERMISSION_FLAGS, 0); 11556 changedInstallPermission = true; 11557 } 11558 11559 // If the permission is not to be promoted to runtime we ignore it and 11560 // also its other flags as they are not applicable to install permissions. 11561 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 11562 for (int userId : currentUserIds) { 11563 if (permissionsState.grantRuntimePermission(bp, userId) != 11564 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11565 // Transfer the permission flags. 11566 permissionsState.updatePermissionFlags(bp, userId, 11567 flags, flags); 11568 // If we granted the permission, we have to write. 11569 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11570 changedRuntimePermissionUserIds, userId); 11571 } 11572 } 11573 } 11574 } break; 11575 11576 default: { 11577 if (packageOfInterest == null 11578 || packageOfInterest.equals(pkg.packageName)) { 11579 Slog.w(TAG, "Not granting permission " + perm 11580 + " to package " + pkg.packageName 11581 + " because it was previously installed without"); 11582 } 11583 } break; 11584 } 11585 } else { 11586 if (permissionsState.revokeInstallPermission(bp) != 11587 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11588 // Also drop the permission flags. 11589 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 11590 PackageManager.MASK_PERMISSION_FLAGS, 0); 11591 changedInstallPermission = true; 11592 Slog.i(TAG, "Un-granting permission " + perm 11593 + " from package " + pkg.packageName 11594 + " (protectionLevel=" + bp.protectionLevel 11595 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 11596 + ")"); 11597 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 11598 // Don't print warning for app op permissions, since it is fine for them 11599 // not to be granted, there is a UI for the user to decide. 11600 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 11601 Slog.w(TAG, "Not granting permission " + perm 11602 + " to package " + pkg.packageName 11603 + " (protectionLevel=" + bp.protectionLevel 11604 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 11605 + ")"); 11606 } 11607 } 11608 } 11609 } 11610 11611 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 11612 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 11613 // This is the first that we have heard about this package, so the 11614 // permissions we have now selected are fixed until explicitly 11615 // changed. 11616 ps.installPermissionsFixed = true; 11617 } 11618 11619 // Persist the runtime permissions state for users with changes. If permissions 11620 // were revoked because no app in the shared user declares them we have to 11621 // write synchronously to avoid losing runtime permissions state. 11622 for (int userId : changedRuntimePermissionUserIds) { 11623 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 11624 } 11625 } 11626 11627 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 11628 boolean allowed = false; 11629 final int NP = PackageParser.NEW_PERMISSIONS.length; 11630 for (int ip=0; ip<NP; ip++) { 11631 final PackageParser.NewPermissionInfo npi 11632 = PackageParser.NEW_PERMISSIONS[ip]; 11633 if (npi.name.equals(perm) 11634 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 11635 allowed = true; 11636 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 11637 + pkg.packageName); 11638 break; 11639 } 11640 } 11641 return allowed; 11642 } 11643 11644 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 11645 BasePermission bp, PermissionsState origPermissions) { 11646 boolean privilegedPermission = (bp.protectionLevel 11647 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0; 11648 boolean privappPermissionsDisable = 11649 RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE; 11650 boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage); 11651 boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName); 11652 if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp() 11653 && !platformPackage && platformPermission) { 11654 ArraySet<String> wlPermissions = SystemConfig.getInstance() 11655 .getPrivAppPermissions(pkg.packageName); 11656 boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm); 11657 if (!whitelisted) { 11658 Slog.w(TAG, "Privileged permission " + perm + " for package " 11659 + pkg.packageName + " - not in privapp-permissions whitelist"); 11660 if (!mSystemReady) { 11661 if (mPrivappPermissionsViolations == null) { 11662 mPrivappPermissionsViolations = new ArraySet<>(); 11663 } 11664 mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm); 11665 } 11666 if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) { 11667 return false; 11668 } 11669 } 11670 } 11671 boolean allowed = (compareSignatures( 11672 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 11673 == PackageManager.SIGNATURE_MATCH) 11674 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 11675 == PackageManager.SIGNATURE_MATCH); 11676 if (!allowed && privilegedPermission) { 11677 if (isSystemApp(pkg)) { 11678 // For updated system applications, a system permission 11679 // is granted only if it had been defined by the original application. 11680 if (pkg.isUpdatedSystemApp()) { 11681 final PackageSetting sysPs = mSettings 11682 .getDisabledSystemPkgLPr(pkg.packageName); 11683 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 11684 // If the original was granted this permission, we take 11685 // that grant decision as read and propagate it to the 11686 // update. 11687 if (sysPs.isPrivileged()) { 11688 allowed = true; 11689 } 11690 } else { 11691 // The system apk may have been updated with an older 11692 // version of the one on the data partition, but which 11693 // granted a new system permission that it didn't have 11694 // before. In this case we do want to allow the app to 11695 // now get the new permission if the ancestral apk is 11696 // privileged to get it. 11697 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 11698 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 11699 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 11700 allowed = true; 11701 break; 11702 } 11703 } 11704 } 11705 // Also if a privileged parent package on the system image or any of 11706 // its children requested a privileged permission, the updated child 11707 // packages can also get the permission. 11708 if (pkg.parentPackage != null) { 11709 final PackageSetting disabledSysParentPs = mSettings 11710 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 11711 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 11712 && disabledSysParentPs.isPrivileged()) { 11713 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 11714 allowed = true; 11715 } else if (disabledSysParentPs.pkg.childPackages != null) { 11716 final int count = disabledSysParentPs.pkg.childPackages.size(); 11717 for (int i = 0; i < count; i++) { 11718 PackageParser.Package disabledSysChildPkg = 11719 disabledSysParentPs.pkg.childPackages.get(i); 11720 if (isPackageRequestingPermission(disabledSysChildPkg, 11721 perm)) { 11722 allowed = true; 11723 break; 11724 } 11725 } 11726 } 11727 } 11728 } 11729 } 11730 } else { 11731 allowed = isPrivilegedApp(pkg); 11732 } 11733 } 11734 } 11735 if (!allowed) { 11736 if (!allowed && (bp.protectionLevel 11737 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 11738 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 11739 // If this was a previously normal/dangerous permission that got moved 11740 // to a system permission as part of the runtime permission redesign, then 11741 // we still want to blindly grant it to old apps. 11742 allowed = true; 11743 } 11744 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 11745 && pkg.packageName.equals(mRequiredInstallerPackage)) { 11746 // If this permission is to be granted to the system installer and 11747 // this app is an installer, then it gets the permission. 11748 allowed = true; 11749 } 11750 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 11751 && pkg.packageName.equals(mRequiredVerifierPackage)) { 11752 // If this permission is to be granted to the system verifier and 11753 // this app is a verifier, then it gets the permission. 11754 allowed = true; 11755 } 11756 if (!allowed && (bp.protectionLevel 11757 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 11758 && isSystemApp(pkg)) { 11759 // Any pre-installed system app is allowed to get this permission. 11760 allowed = true; 11761 } 11762 if (!allowed && (bp.protectionLevel 11763 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 11764 // For development permissions, a development permission 11765 // is granted only if it was already granted. 11766 allowed = origPermissions.hasInstallPermission(perm); 11767 } 11768 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 11769 && pkg.packageName.equals(mSetupWizardPackage)) { 11770 // If this permission is to be granted to the system setup wizard and 11771 // this app is a setup wizard, then it gets the permission. 11772 allowed = true; 11773 } 11774 } 11775 return allowed; 11776 } 11777 11778 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 11779 final int permCount = pkg.requestedPermissions.size(); 11780 for (int j = 0; j < permCount; j++) { 11781 String requestedPermission = pkg.requestedPermissions.get(j); 11782 if (permission.equals(requestedPermission)) { 11783 return true; 11784 } 11785 } 11786 return false; 11787 } 11788 11789 final class ActivityIntentResolver 11790 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 11791 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 11792 boolean defaultOnly, int userId) { 11793 if (!sUserManager.exists(userId)) return null; 11794 mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0); 11795 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 11796 } 11797 11798 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 11799 int userId) { 11800 if (!sUserManager.exists(userId)) return null; 11801 mFlags = flags; 11802 return super.queryIntent(intent, resolvedType, 11803 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 11804 userId); 11805 } 11806 11807 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 11808 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 11809 if (!sUserManager.exists(userId)) return null; 11810 if (packageActivities == null) { 11811 return null; 11812 } 11813 mFlags = flags; 11814 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 11815 final int N = packageActivities.size(); 11816 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 11817 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 11818 11819 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 11820 for (int i = 0; i < N; ++i) { 11821 intentFilters = packageActivities.get(i).intents; 11822 if (intentFilters != null && intentFilters.size() > 0) { 11823 PackageParser.ActivityIntentInfo[] array = 11824 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 11825 intentFilters.toArray(array); 11826 listCut.add(array); 11827 } 11828 } 11829 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 11830 } 11831 11832 /** 11833 * Finds a privileged activity that matches the specified activity names. 11834 */ 11835 private PackageParser.Activity findMatchingActivity( 11836 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 11837 for (PackageParser.Activity sysActivity : activityList) { 11838 if (sysActivity.info.name.equals(activityInfo.name)) { 11839 return sysActivity; 11840 } 11841 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 11842 return sysActivity; 11843 } 11844 if (sysActivity.info.targetActivity != null) { 11845 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 11846 return sysActivity; 11847 } 11848 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 11849 return sysActivity; 11850 } 11851 } 11852 } 11853 return null; 11854 } 11855 11856 public class IterGenerator<E> { 11857 public Iterator<E> generate(ActivityIntentInfo info) { 11858 return null; 11859 } 11860 } 11861 11862 public class ActionIterGenerator extends IterGenerator<String> { 11863 @Override 11864 public Iterator<String> generate(ActivityIntentInfo info) { 11865 return info.actionsIterator(); 11866 } 11867 } 11868 11869 public class CategoriesIterGenerator extends IterGenerator<String> { 11870 @Override 11871 public Iterator<String> generate(ActivityIntentInfo info) { 11872 return info.categoriesIterator(); 11873 } 11874 } 11875 11876 public class SchemesIterGenerator extends IterGenerator<String> { 11877 @Override 11878 public Iterator<String> generate(ActivityIntentInfo info) { 11879 return info.schemesIterator(); 11880 } 11881 } 11882 11883 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 11884 @Override 11885 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 11886 return info.authoritiesIterator(); 11887 } 11888 } 11889 11890 /** 11891 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 11892 * MODIFIED. Do not pass in a list that should not be changed. 11893 */ 11894 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 11895 IterGenerator<T> generator, Iterator<T> searchIterator) { 11896 // loop through the set of actions; every one must be found in the intent filter 11897 while (searchIterator.hasNext()) { 11898 // we must have at least one filter in the list to consider a match 11899 if (intentList.size() == 0) { 11900 break; 11901 } 11902 11903 final T searchAction = searchIterator.next(); 11904 11905 // loop through the set of intent filters 11906 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 11907 while (intentIter.hasNext()) { 11908 final ActivityIntentInfo intentInfo = intentIter.next(); 11909 boolean selectionFound = false; 11910 11911 // loop through the intent filter's selection criteria; at least one 11912 // of them must match the searched criteria 11913 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 11914 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 11915 final T intentSelection = intentSelectionIter.next(); 11916 if (intentSelection != null && intentSelection.equals(searchAction)) { 11917 selectionFound = true; 11918 break; 11919 } 11920 } 11921 11922 // the selection criteria wasn't found in this filter's set; this filter 11923 // is not a potential match 11924 if (!selectionFound) { 11925 intentIter.remove(); 11926 } 11927 } 11928 } 11929 } 11930 11931 private boolean isProtectedAction(ActivityIntentInfo filter) { 11932 final Iterator<String> actionsIter = filter.actionsIterator(); 11933 while (actionsIter != null && actionsIter.hasNext()) { 11934 final String filterAction = actionsIter.next(); 11935 if (PROTECTED_ACTIONS.contains(filterAction)) { 11936 return true; 11937 } 11938 } 11939 return false; 11940 } 11941 11942 /** 11943 * Adjusts the priority of the given intent filter according to policy. 11944 * <p> 11945 * <ul> 11946 * <li>The priority for non privileged applications is capped to '0'</li> 11947 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 11948 * <li>The priority for unbundled updates to privileged applications is capped to the 11949 * priority defined on the system partition</li> 11950 * </ul> 11951 * <p> 11952 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 11953 * allowed to obtain any priority on any action. 11954 */ 11955 private void adjustPriority( 11956 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 11957 // nothing to do; priority is fine as-is 11958 if (intent.getPriority() <= 0) { 11959 return; 11960 } 11961 11962 final ActivityInfo activityInfo = intent.activity.info; 11963 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 11964 11965 final boolean privilegedApp = 11966 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 11967 if (!privilegedApp) { 11968 // non-privileged applications can never define a priority >0 11969 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 11970 + " package: " + applicationInfo.packageName 11971 + " activity: " + intent.activity.className 11972 + " origPrio: " + intent.getPriority()); 11973 intent.setPriority(0); 11974 return; 11975 } 11976 11977 if (systemActivities == null) { 11978 // the system package is not disabled; we're parsing the system partition 11979 if (isProtectedAction(intent)) { 11980 if (mDeferProtectedFilters) { 11981 // We can't deal with these just yet. No component should ever obtain a 11982 // >0 priority for a protected actions, with ONE exception -- the setup 11983 // wizard. The setup wizard, however, cannot be known until we're able to 11984 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 11985 // until all intent filters have been processed. Chicken, meet egg. 11986 // Let the filter temporarily have a high priority and rectify the 11987 // priorities after all system packages have been scanned. 11988 mProtectedFilters.add(intent); 11989 if (DEBUG_FILTERS) { 11990 Slog.i(TAG, "Protected action; save for later;" 11991 + " package: " + applicationInfo.packageName 11992 + " activity: " + intent.activity.className 11993 + " origPrio: " + intent.getPriority()); 11994 } 11995 return; 11996 } else { 11997 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 11998 Slog.i(TAG, "No setup wizard;" 11999 + " All protected intents capped to priority 0"); 12000 } 12001 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 12002 if (DEBUG_FILTERS) { 12003 Slog.i(TAG, "Found setup wizard;" 12004 + " allow priority " + intent.getPriority() + ";" 12005 + " package: " + intent.activity.info.packageName 12006 + " activity: " + intent.activity.className 12007 + " priority: " + intent.getPriority()); 12008 } 12009 // setup wizard gets whatever it wants 12010 return; 12011 } 12012 Slog.w(TAG, "Protected action; cap priority to 0;" 12013 + " package: " + intent.activity.info.packageName 12014 + " activity: " + intent.activity.className 12015 + " origPrio: " + intent.getPriority()); 12016 intent.setPriority(0); 12017 return; 12018 } 12019 } 12020 // privileged apps on the system image get whatever priority they request 12021 return; 12022 } 12023 12024 // privileged app unbundled update ... try to find the same activity 12025 final PackageParser.Activity foundActivity = 12026 findMatchingActivity(systemActivities, activityInfo); 12027 if (foundActivity == null) { 12028 // this is a new activity; it cannot obtain >0 priority 12029 if (DEBUG_FILTERS) { 12030 Slog.i(TAG, "New activity; cap priority to 0;" 12031 + " package: " + applicationInfo.packageName 12032 + " activity: " + intent.activity.className 12033 + " origPrio: " + intent.getPriority()); 12034 } 12035 intent.setPriority(0); 12036 return; 12037 } 12038 12039 // found activity, now check for filter equivalence 12040 12041 // a shallow copy is enough; we modify the list, not its contents 12042 final List<ActivityIntentInfo> intentListCopy = 12043 new ArrayList<>(foundActivity.intents); 12044 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 12045 12046 // find matching action subsets 12047 final Iterator<String> actionsIterator = intent.actionsIterator(); 12048 if (actionsIterator != null) { 12049 getIntentListSubset( 12050 intentListCopy, new ActionIterGenerator(), actionsIterator); 12051 if (intentListCopy.size() == 0) { 12052 // no more intents to match; we're not equivalent 12053 if (DEBUG_FILTERS) { 12054 Slog.i(TAG, "Mismatched action; cap priority to 0;" 12055 + " package: " + applicationInfo.packageName 12056 + " activity: " + intent.activity.className 12057 + " origPrio: " + intent.getPriority()); 12058 } 12059 intent.setPriority(0); 12060 return; 12061 } 12062 } 12063 12064 // find matching category subsets 12065 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 12066 if (categoriesIterator != null) { 12067 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 12068 categoriesIterator); 12069 if (intentListCopy.size() == 0) { 12070 // no more intents to match; we're not equivalent 12071 if (DEBUG_FILTERS) { 12072 Slog.i(TAG, "Mismatched category; cap priority to 0;" 12073 + " package: " + applicationInfo.packageName 12074 + " activity: " + intent.activity.className 12075 + " origPrio: " + intent.getPriority()); 12076 } 12077 intent.setPriority(0); 12078 return; 12079 } 12080 } 12081 12082 // find matching schemes subsets 12083 final Iterator<String> schemesIterator = intent.schemesIterator(); 12084 if (schemesIterator != null) { 12085 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 12086 schemesIterator); 12087 if (intentListCopy.size() == 0) { 12088 // no more intents to match; we're not equivalent 12089 if (DEBUG_FILTERS) { 12090 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 12091 + " package: " + applicationInfo.packageName 12092 + " activity: " + intent.activity.className 12093 + " origPrio: " + intent.getPriority()); 12094 } 12095 intent.setPriority(0); 12096 return; 12097 } 12098 } 12099 12100 // find matching authorities subsets 12101 final Iterator<IntentFilter.AuthorityEntry> 12102 authoritiesIterator = intent.authoritiesIterator(); 12103 if (authoritiesIterator != null) { 12104 getIntentListSubset(intentListCopy, 12105 new AuthoritiesIterGenerator(), 12106 authoritiesIterator); 12107 if (intentListCopy.size() == 0) { 12108 // no more intents to match; we're not equivalent 12109 if (DEBUG_FILTERS) { 12110 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 12111 + " package: " + applicationInfo.packageName 12112 + " activity: " + intent.activity.className 12113 + " origPrio: " + intent.getPriority()); 12114 } 12115 intent.setPriority(0); 12116 return; 12117 } 12118 } 12119 12120 // we found matching filter(s); app gets the max priority of all intents 12121 int cappedPriority = 0; 12122 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 12123 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 12124 } 12125 if (intent.getPriority() > cappedPriority) { 12126 if (DEBUG_FILTERS) { 12127 Slog.i(TAG, "Found matching filter(s);" 12128 + " cap priority to " + cappedPriority + ";" 12129 + " package: " + applicationInfo.packageName 12130 + " activity: " + intent.activity.className 12131 + " origPrio: " + intent.getPriority()); 12132 } 12133 intent.setPriority(cappedPriority); 12134 return; 12135 } 12136 // all this for nothing; the requested priority was <= what was on the system 12137 } 12138 12139 public final void addActivity(PackageParser.Activity a, String type) { 12140 mActivities.put(a.getComponentName(), a); 12141 if (DEBUG_SHOW_INFO) 12142 Log.v( 12143 TAG, " " + type + " " + 12144 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 12145 if (DEBUG_SHOW_INFO) 12146 Log.v(TAG, " Class=" + a.info.name); 12147 final int NI = a.intents.size(); 12148 for (int j=0; j<NI; j++) { 12149 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 12150 if ("activity".equals(type)) { 12151 final PackageSetting ps = 12152 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 12153 final List<PackageParser.Activity> systemActivities = 12154 ps != null && ps.pkg != null ? ps.pkg.activities : null; 12155 adjustPriority(systemActivities, intent); 12156 } 12157 if (DEBUG_SHOW_INFO) { 12158 Log.v(TAG, " IntentFilter:"); 12159 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12160 } 12161 if (!intent.debugCheck()) { 12162 Log.w(TAG, "==> For Activity " + a.info.name); 12163 } 12164 addFilter(intent); 12165 } 12166 } 12167 12168 public final void removeActivity(PackageParser.Activity a, String type) { 12169 mActivities.remove(a.getComponentName()); 12170 if (DEBUG_SHOW_INFO) { 12171 Log.v(TAG, " " + type + " " 12172 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 12173 : a.info.name) + ":"); 12174 Log.v(TAG, " Class=" + a.info.name); 12175 } 12176 final int NI = a.intents.size(); 12177 for (int j=0; j<NI; j++) { 12178 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 12179 if (DEBUG_SHOW_INFO) { 12180 Log.v(TAG, " IntentFilter:"); 12181 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12182 } 12183 removeFilter(intent); 12184 } 12185 } 12186 12187 @Override 12188 protected boolean allowFilterResult( 12189 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 12190 ActivityInfo filterAi = filter.activity.info; 12191 for (int i=dest.size()-1; i>=0; i--) { 12192 ActivityInfo destAi = dest.get(i).activityInfo; 12193 if (destAi.name == filterAi.name 12194 && destAi.packageName == filterAi.packageName) { 12195 return false; 12196 } 12197 } 12198 return true; 12199 } 12200 12201 @Override 12202 protected ActivityIntentInfo[] newArray(int size) { 12203 return new ActivityIntentInfo[size]; 12204 } 12205 12206 @Override 12207 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 12208 if (!sUserManager.exists(userId)) return true; 12209 PackageParser.Package p = filter.activity.owner; 12210 if (p != null) { 12211 PackageSetting ps = (PackageSetting)p.mExtras; 12212 if (ps != null) { 12213 // System apps are never considered stopped for purposes of 12214 // filtering, because there may be no way for the user to 12215 // actually re-launch them. 12216 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 12217 && ps.getStopped(userId); 12218 } 12219 } 12220 return false; 12221 } 12222 12223 @Override 12224 protected boolean isPackageForFilter(String packageName, 12225 PackageParser.ActivityIntentInfo info) { 12226 return packageName.equals(info.activity.owner.packageName); 12227 } 12228 12229 @Override 12230 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 12231 int match, int userId) { 12232 if (!sUserManager.exists(userId)) return null; 12233 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 12234 return null; 12235 } 12236 final PackageParser.Activity activity = info.activity; 12237 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 12238 if (ps == null) { 12239 return null; 12240 } 12241 final PackageUserState userState = ps.readUserState(userId); 12242 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 12243 userState, userId); 12244 if (ai == null) { 12245 return null; 12246 } 12247 final boolean matchVisibleToInstantApp = 12248 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 12249 final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 12250 // throw out filters that aren't visible to ephemeral apps 12251 if (matchVisibleToInstantApp 12252 && !(info.isVisibleToInstantApp() || userState.instantApp)) { 12253 return null; 12254 } 12255 // throw out ephemeral filters if we're not explicitly requesting them 12256 if (!isInstantApp && userState.instantApp) { 12257 return null; 12258 } 12259 final ResolveInfo res = new ResolveInfo(); 12260 res.activityInfo = ai; 12261 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 12262 res.filter = info; 12263 } 12264 if (info != null) { 12265 res.handleAllWebDataURI = info.handleAllWebDataURI(); 12266 } 12267 res.priority = info.getPriority(); 12268 res.preferredOrder = activity.owner.mPreferredOrder; 12269 //System.out.println("Result: " + res.activityInfo.className + 12270 // " = " + res.priority); 12271 res.match = match; 12272 res.isDefault = info.hasDefault; 12273 res.labelRes = info.labelRes; 12274 res.nonLocalizedLabel = info.nonLocalizedLabel; 12275 if (userNeedsBadging(userId)) { 12276 res.noResourceId = true; 12277 } else { 12278 res.icon = info.icon; 12279 } 12280 res.iconResourceId = info.icon; 12281 res.system = res.activityInfo.applicationInfo.isSystemApp(); 12282 return res; 12283 } 12284 12285 @Override 12286 protected void sortResults(List<ResolveInfo> results) { 12287 Collections.sort(results, mResolvePrioritySorter); 12288 } 12289 12290 @Override 12291 protected void dumpFilter(PrintWriter out, String prefix, 12292 PackageParser.ActivityIntentInfo filter) { 12293 out.print(prefix); out.print( 12294 Integer.toHexString(System.identityHashCode(filter.activity))); 12295 out.print(' '); 12296 filter.activity.printComponentShortName(out); 12297 out.print(" filter "); 12298 out.println(Integer.toHexString(System.identityHashCode(filter))); 12299 } 12300 12301 @Override 12302 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 12303 return filter.activity; 12304 } 12305 12306 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12307 PackageParser.Activity activity = (PackageParser.Activity)label; 12308 out.print(prefix); out.print( 12309 Integer.toHexString(System.identityHashCode(activity))); 12310 out.print(' '); 12311 activity.printComponentShortName(out); 12312 if (count > 1) { 12313 out.print(" ("); out.print(count); out.print(" filters)"); 12314 } 12315 out.println(); 12316 } 12317 12318 // Keys are String (activity class name), values are Activity. 12319 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 12320 = new ArrayMap<ComponentName, PackageParser.Activity>(); 12321 private int mFlags; 12322 } 12323 12324 private final class ServiceIntentResolver 12325 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 12326 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12327 boolean defaultOnly, int userId) { 12328 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 12329 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 12330 } 12331 12332 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12333 int userId) { 12334 if (!sUserManager.exists(userId)) return null; 12335 mFlags = flags; 12336 return super.queryIntent(intent, resolvedType, 12337 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12338 userId); 12339 } 12340 12341 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12342 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 12343 if (!sUserManager.exists(userId)) return null; 12344 if (packageServices == null) { 12345 return null; 12346 } 12347 mFlags = flags; 12348 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 12349 final int N = packageServices.size(); 12350 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 12351 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 12352 12353 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 12354 for (int i = 0; i < N; ++i) { 12355 intentFilters = packageServices.get(i).intents; 12356 if (intentFilters != null && intentFilters.size() > 0) { 12357 PackageParser.ServiceIntentInfo[] array = 12358 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 12359 intentFilters.toArray(array); 12360 listCut.add(array); 12361 } 12362 } 12363 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 12364 } 12365 12366 public final void addService(PackageParser.Service s) { 12367 mServices.put(s.getComponentName(), s); 12368 if (DEBUG_SHOW_INFO) { 12369 Log.v(TAG, " " 12370 + (s.info.nonLocalizedLabel != null 12371 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 12372 Log.v(TAG, " Class=" + s.info.name); 12373 } 12374 final int NI = s.intents.size(); 12375 int j; 12376 for (j=0; j<NI; j++) { 12377 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 12378 if (DEBUG_SHOW_INFO) { 12379 Log.v(TAG, " IntentFilter:"); 12380 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12381 } 12382 if (!intent.debugCheck()) { 12383 Log.w(TAG, "==> For Service " + s.info.name); 12384 } 12385 addFilter(intent); 12386 } 12387 } 12388 12389 public final void removeService(PackageParser.Service s) { 12390 mServices.remove(s.getComponentName()); 12391 if (DEBUG_SHOW_INFO) { 12392 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 12393 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 12394 Log.v(TAG, " Class=" + s.info.name); 12395 } 12396 final int NI = s.intents.size(); 12397 int j; 12398 for (j=0; j<NI; j++) { 12399 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 12400 if (DEBUG_SHOW_INFO) { 12401 Log.v(TAG, " IntentFilter:"); 12402 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12403 } 12404 removeFilter(intent); 12405 } 12406 } 12407 12408 @Override 12409 protected boolean allowFilterResult( 12410 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 12411 ServiceInfo filterSi = filter.service.info; 12412 for (int i=dest.size()-1; i>=0; i--) { 12413 ServiceInfo destAi = dest.get(i).serviceInfo; 12414 if (destAi.name == filterSi.name 12415 && destAi.packageName == filterSi.packageName) { 12416 return false; 12417 } 12418 } 12419 return true; 12420 } 12421 12422 @Override 12423 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 12424 return new PackageParser.ServiceIntentInfo[size]; 12425 } 12426 12427 @Override 12428 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 12429 if (!sUserManager.exists(userId)) return true; 12430 PackageParser.Package p = filter.service.owner; 12431 if (p != null) { 12432 PackageSetting ps = (PackageSetting)p.mExtras; 12433 if (ps != null) { 12434 // System apps are never considered stopped for purposes of 12435 // filtering, because there may be no way for the user to 12436 // actually re-launch them. 12437 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 12438 && ps.getStopped(userId); 12439 } 12440 } 12441 return false; 12442 } 12443 12444 @Override 12445 protected boolean isPackageForFilter(String packageName, 12446 PackageParser.ServiceIntentInfo info) { 12447 return packageName.equals(info.service.owner.packageName); 12448 } 12449 12450 @Override 12451 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 12452 int match, int userId) { 12453 if (!sUserManager.exists(userId)) return null; 12454 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 12455 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 12456 return null; 12457 } 12458 final PackageParser.Service service = info.service; 12459 PackageSetting ps = (PackageSetting) service.owner.mExtras; 12460 if (ps == null) { 12461 return null; 12462 } 12463 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 12464 ps.readUserState(userId), userId); 12465 if (si == null) { 12466 return null; 12467 } 12468 final ResolveInfo res = new ResolveInfo(); 12469 res.serviceInfo = si; 12470 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 12471 res.filter = filter; 12472 } 12473 res.priority = info.getPriority(); 12474 res.preferredOrder = service.owner.mPreferredOrder; 12475 res.match = match; 12476 res.isDefault = info.hasDefault; 12477 res.labelRes = info.labelRes; 12478 res.nonLocalizedLabel = info.nonLocalizedLabel; 12479 res.icon = info.icon; 12480 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 12481 return res; 12482 } 12483 12484 @Override 12485 protected void sortResults(List<ResolveInfo> results) { 12486 Collections.sort(results, mResolvePrioritySorter); 12487 } 12488 12489 @Override 12490 protected void dumpFilter(PrintWriter out, String prefix, 12491 PackageParser.ServiceIntentInfo filter) { 12492 out.print(prefix); out.print( 12493 Integer.toHexString(System.identityHashCode(filter.service))); 12494 out.print(' '); 12495 filter.service.printComponentShortName(out); 12496 out.print(" filter "); 12497 out.println(Integer.toHexString(System.identityHashCode(filter))); 12498 } 12499 12500 @Override 12501 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 12502 return filter.service; 12503 } 12504 12505 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12506 PackageParser.Service service = (PackageParser.Service)label; 12507 out.print(prefix); out.print( 12508 Integer.toHexString(System.identityHashCode(service))); 12509 out.print(' '); 12510 service.printComponentShortName(out); 12511 if (count > 1) { 12512 out.print(" ("); out.print(count); out.print(" filters)"); 12513 } 12514 out.println(); 12515 } 12516 12517// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 12518// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 12519// final List<ResolveInfo> retList = Lists.newArrayList(); 12520// while (i.hasNext()) { 12521// final ResolveInfo resolveInfo = (ResolveInfo) i; 12522// if (isEnabledLP(resolveInfo.serviceInfo)) { 12523// retList.add(resolveInfo); 12524// } 12525// } 12526// return retList; 12527// } 12528 12529 // Keys are String (activity class name), values are Activity. 12530 private final ArrayMap<ComponentName, PackageParser.Service> mServices 12531 = new ArrayMap<ComponentName, PackageParser.Service>(); 12532 private int mFlags; 12533 } 12534 12535 private final class ProviderIntentResolver 12536 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 12537 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12538 boolean defaultOnly, int userId) { 12539 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 12540 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 12541 } 12542 12543 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12544 int userId) { 12545 if (!sUserManager.exists(userId)) 12546 return null; 12547 mFlags = flags; 12548 return super.queryIntent(intent, resolvedType, 12549 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12550 userId); 12551 } 12552 12553 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12554 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 12555 if (!sUserManager.exists(userId)) 12556 return null; 12557 if (packageProviders == null) { 12558 return null; 12559 } 12560 mFlags = flags; 12561 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 12562 final int N = packageProviders.size(); 12563 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 12564 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 12565 12566 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 12567 for (int i = 0; i < N; ++i) { 12568 intentFilters = packageProviders.get(i).intents; 12569 if (intentFilters != null && intentFilters.size() > 0) { 12570 PackageParser.ProviderIntentInfo[] array = 12571 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 12572 intentFilters.toArray(array); 12573 listCut.add(array); 12574 } 12575 } 12576 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 12577 } 12578 12579 public final void addProvider(PackageParser.Provider p) { 12580 if (mProviders.containsKey(p.getComponentName())) { 12581 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 12582 return; 12583 } 12584 12585 mProviders.put(p.getComponentName(), p); 12586 if (DEBUG_SHOW_INFO) { 12587 Log.v(TAG, " " 12588 + (p.info.nonLocalizedLabel != null 12589 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 12590 Log.v(TAG, " Class=" + p.info.name); 12591 } 12592 final int NI = p.intents.size(); 12593 int j; 12594 for (j = 0; j < NI; j++) { 12595 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 12596 if (DEBUG_SHOW_INFO) { 12597 Log.v(TAG, " IntentFilter:"); 12598 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12599 } 12600 if (!intent.debugCheck()) { 12601 Log.w(TAG, "==> For Provider " + p.info.name); 12602 } 12603 addFilter(intent); 12604 } 12605 } 12606 12607 public final void removeProvider(PackageParser.Provider p) { 12608 mProviders.remove(p.getComponentName()); 12609 if (DEBUG_SHOW_INFO) { 12610 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 12611 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 12612 Log.v(TAG, " Class=" + p.info.name); 12613 } 12614 final int NI = p.intents.size(); 12615 int j; 12616 for (j = 0; j < NI; j++) { 12617 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 12618 if (DEBUG_SHOW_INFO) { 12619 Log.v(TAG, " IntentFilter:"); 12620 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12621 } 12622 removeFilter(intent); 12623 } 12624 } 12625 12626 @Override 12627 protected boolean allowFilterResult( 12628 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 12629 ProviderInfo filterPi = filter.provider.info; 12630 for (int i = dest.size() - 1; i >= 0; i--) { 12631 ProviderInfo destPi = dest.get(i).providerInfo; 12632 if (destPi.name == filterPi.name 12633 && destPi.packageName == filterPi.packageName) { 12634 return false; 12635 } 12636 } 12637 return true; 12638 } 12639 12640 @Override 12641 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 12642 return new PackageParser.ProviderIntentInfo[size]; 12643 } 12644 12645 @Override 12646 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 12647 if (!sUserManager.exists(userId)) 12648 return true; 12649 PackageParser.Package p = filter.provider.owner; 12650 if (p != null) { 12651 PackageSetting ps = (PackageSetting) p.mExtras; 12652 if (ps != null) { 12653 // System apps are never considered stopped for purposes of 12654 // filtering, because there may be no way for the user to 12655 // actually re-launch them. 12656 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 12657 && ps.getStopped(userId); 12658 } 12659 } 12660 return false; 12661 } 12662 12663 @Override 12664 protected boolean isPackageForFilter(String packageName, 12665 PackageParser.ProviderIntentInfo info) { 12666 return packageName.equals(info.provider.owner.packageName); 12667 } 12668 12669 @Override 12670 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 12671 int match, int userId) { 12672 if (!sUserManager.exists(userId)) 12673 return null; 12674 final PackageParser.ProviderIntentInfo info = filter; 12675 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 12676 return null; 12677 } 12678 final PackageParser.Provider provider = info.provider; 12679 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 12680 if (ps == null) { 12681 return null; 12682 } 12683 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 12684 ps.readUserState(userId), userId); 12685 if (pi == null) { 12686 return null; 12687 } 12688 final ResolveInfo res = new ResolveInfo(); 12689 res.providerInfo = pi; 12690 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 12691 res.filter = filter; 12692 } 12693 res.priority = info.getPriority(); 12694 res.preferredOrder = provider.owner.mPreferredOrder; 12695 res.match = match; 12696 res.isDefault = info.hasDefault; 12697 res.labelRes = info.labelRes; 12698 res.nonLocalizedLabel = info.nonLocalizedLabel; 12699 res.icon = info.icon; 12700 res.system = res.providerInfo.applicationInfo.isSystemApp(); 12701 return res; 12702 } 12703 12704 @Override 12705 protected void sortResults(List<ResolveInfo> results) { 12706 Collections.sort(results, mResolvePrioritySorter); 12707 } 12708 12709 @Override 12710 protected void dumpFilter(PrintWriter out, String prefix, 12711 PackageParser.ProviderIntentInfo filter) { 12712 out.print(prefix); 12713 out.print( 12714 Integer.toHexString(System.identityHashCode(filter.provider))); 12715 out.print(' '); 12716 filter.provider.printComponentShortName(out); 12717 out.print(" filter "); 12718 out.println(Integer.toHexString(System.identityHashCode(filter))); 12719 } 12720 12721 @Override 12722 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 12723 return filter.provider; 12724 } 12725 12726 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12727 PackageParser.Provider provider = (PackageParser.Provider)label; 12728 out.print(prefix); out.print( 12729 Integer.toHexString(System.identityHashCode(provider))); 12730 out.print(' '); 12731 provider.printComponentShortName(out); 12732 if (count > 1) { 12733 out.print(" ("); out.print(count); out.print(" filters)"); 12734 } 12735 out.println(); 12736 } 12737 12738 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 12739 = new ArrayMap<ComponentName, PackageParser.Provider>(); 12740 private int mFlags; 12741 } 12742 12743 static final class EphemeralIntentResolver 12744 extends IntentResolver<EphemeralResponse, EphemeralResponse> { 12745 /** 12746 * The result that has the highest defined order. Ordering applies on a 12747 * per-package basis. Mapping is from package name to Pair of order and 12748 * EphemeralResolveInfo. 12749 * <p> 12750 * NOTE: This is implemented as a field variable for convenience and efficiency. 12751 * By having a field variable, we're able to track filter ordering as soon as 12752 * a non-zero order is defined. Otherwise, multiple loops across the result set 12753 * would be needed to apply ordering. If the intent resolver becomes re-entrant, 12754 * this needs to be contained entirely within {@link #filterResults()}. 12755 */ 12756 final ArrayMap<String, Pair<Integer, EphemeralResolveInfo>> mOrderResult = new ArrayMap<>(); 12757 12758 @Override 12759 protected EphemeralResponse[] newArray(int size) { 12760 return new EphemeralResponse[size]; 12761 } 12762 12763 @Override 12764 protected boolean isPackageForFilter(String packageName, EphemeralResponse responseObj) { 12765 return true; 12766 } 12767 12768 @Override 12769 protected EphemeralResponse newResult(EphemeralResponse responseObj, int match, 12770 int userId) { 12771 if (!sUserManager.exists(userId)) { 12772 return null; 12773 } 12774 final String packageName = responseObj.resolveInfo.getPackageName(); 12775 final Integer order = responseObj.getOrder(); 12776 final Pair<Integer, EphemeralResolveInfo> lastOrderResult = 12777 mOrderResult.get(packageName); 12778 // ordering is enabled and this item's order isn't high enough 12779 if (lastOrderResult != null && lastOrderResult.first >= order) { 12780 return null; 12781 } 12782 final EphemeralResolveInfo res = responseObj.resolveInfo; 12783 if (order > 0) { 12784 // non-zero order, enable ordering 12785 mOrderResult.put(packageName, new Pair<>(order, res)); 12786 } 12787 return responseObj; 12788 } 12789 12790 @Override 12791 protected void filterResults(List<EphemeralResponse> results) { 12792 // only do work if ordering is enabled [most of the time it won't be] 12793 if (mOrderResult.size() == 0) { 12794 return; 12795 } 12796 int resultSize = results.size(); 12797 for (int i = 0; i < resultSize; i++) { 12798 final EphemeralResolveInfo info = results.get(i).resolveInfo; 12799 final String packageName = info.getPackageName(); 12800 final Pair<Integer, EphemeralResolveInfo> savedInfo = mOrderResult.get(packageName); 12801 if (savedInfo == null) { 12802 // package doesn't having ordering 12803 continue; 12804 } 12805 if (savedInfo.second == info) { 12806 // circled back to the highest ordered item; remove from order list 12807 mOrderResult.remove(savedInfo); 12808 if (mOrderResult.size() == 0) { 12809 // no more ordered items 12810 break; 12811 } 12812 continue; 12813 } 12814 // item has a worse order, remove it from the result list 12815 results.remove(i); 12816 resultSize--; 12817 i--; 12818 } 12819 } 12820 } 12821 12822 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 12823 new Comparator<ResolveInfo>() { 12824 public int compare(ResolveInfo r1, ResolveInfo r2) { 12825 int v1 = r1.priority; 12826 int v2 = r2.priority; 12827 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 12828 if (v1 != v2) { 12829 return (v1 > v2) ? -1 : 1; 12830 } 12831 v1 = r1.preferredOrder; 12832 v2 = r2.preferredOrder; 12833 if (v1 != v2) { 12834 return (v1 > v2) ? -1 : 1; 12835 } 12836 if (r1.isDefault != r2.isDefault) { 12837 return r1.isDefault ? -1 : 1; 12838 } 12839 v1 = r1.match; 12840 v2 = r2.match; 12841 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 12842 if (v1 != v2) { 12843 return (v1 > v2) ? -1 : 1; 12844 } 12845 if (r1.system != r2.system) { 12846 return r1.system ? -1 : 1; 12847 } 12848 if (r1.activityInfo != null) { 12849 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 12850 } 12851 if (r1.serviceInfo != null) { 12852 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 12853 } 12854 if (r1.providerInfo != null) { 12855 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 12856 } 12857 return 0; 12858 } 12859 }; 12860 12861 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 12862 new Comparator<ProviderInfo>() { 12863 public int compare(ProviderInfo p1, ProviderInfo p2) { 12864 final int v1 = p1.initOrder; 12865 final int v2 = p2.initOrder; 12866 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 12867 } 12868 }; 12869 12870 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 12871 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 12872 final int[] userIds) { 12873 mHandler.post(new Runnable() { 12874 @Override 12875 public void run() { 12876 try { 12877 final IActivityManager am = ActivityManager.getService(); 12878 if (am == null) return; 12879 final int[] resolvedUserIds; 12880 if (userIds == null) { 12881 resolvedUserIds = am.getRunningUserIds(); 12882 } else { 12883 resolvedUserIds = userIds; 12884 } 12885 for (int id : resolvedUserIds) { 12886 final Intent intent = new Intent(action, 12887 pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null); 12888 if (extras != null) { 12889 intent.putExtras(extras); 12890 } 12891 if (targetPkg != null) { 12892 intent.setPackage(targetPkg); 12893 } 12894 // Modify the UID when posting to other users 12895 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 12896 if (uid > 0 && UserHandle.getUserId(uid) != id) { 12897 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 12898 intent.putExtra(Intent.EXTRA_UID, uid); 12899 } 12900 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 12901 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 12902 if (DEBUG_BROADCASTS) { 12903 RuntimeException here = new RuntimeException("here"); 12904 here.fillInStackTrace(); 12905 Slog.d(TAG, "Sending to user " + id + ": " 12906 + intent.toShortString(false, true, false, false) 12907 + " " + intent.getExtras(), here); 12908 } 12909 am.broadcastIntent(null, intent, null, finishedReceiver, 12910 0, null, null, null, android.app.AppOpsManager.OP_NONE, 12911 null, finishedReceiver != null, false, id); 12912 } 12913 } catch (RemoteException ex) { 12914 } 12915 } 12916 }); 12917 } 12918 12919 /** 12920 * Check if the external storage media is available. This is true if there 12921 * is a mounted external storage medium or if the external storage is 12922 * emulated. 12923 */ 12924 private boolean isExternalMediaAvailable() { 12925 return mMediaMounted || Environment.isExternalStorageEmulated(); 12926 } 12927 12928 @Override 12929 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 12930 // writer 12931 synchronized (mPackages) { 12932 if (!isExternalMediaAvailable()) { 12933 // If the external storage is no longer mounted at this point, 12934 // the caller may not have been able to delete all of this 12935 // packages files and can not delete any more. Bail. 12936 return null; 12937 } 12938 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 12939 if (lastPackage != null) { 12940 pkgs.remove(lastPackage); 12941 } 12942 if (pkgs.size() > 0) { 12943 return pkgs.get(0); 12944 } 12945 } 12946 return null; 12947 } 12948 12949 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 12950 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 12951 userId, andCode ? 1 : 0, packageName); 12952 if (mSystemReady) { 12953 msg.sendToTarget(); 12954 } else { 12955 if (mPostSystemReadyMessages == null) { 12956 mPostSystemReadyMessages = new ArrayList<>(); 12957 } 12958 mPostSystemReadyMessages.add(msg); 12959 } 12960 } 12961 12962 void startCleaningPackages() { 12963 // reader 12964 if (!isExternalMediaAvailable()) { 12965 return; 12966 } 12967 synchronized (mPackages) { 12968 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 12969 return; 12970 } 12971 } 12972 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 12973 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 12974 IActivityManager am = ActivityManager.getService(); 12975 if (am != null) { 12976 try { 12977 am.startService(null, intent, null, -1, null, mContext.getOpPackageName(), 12978 UserHandle.USER_SYSTEM); 12979 } catch (RemoteException e) { 12980 } 12981 } 12982 } 12983 12984 @Override 12985 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 12986 int installFlags, String installerPackageName, int userId) { 12987 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 12988 12989 final int callingUid = Binder.getCallingUid(); 12990 enforceCrossUserPermission(callingUid, userId, 12991 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 12992 12993 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 12994 try { 12995 if (observer != null) { 12996 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 12997 } 12998 } catch (RemoteException re) { 12999 } 13000 return; 13001 } 13002 13003 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 13004 installFlags |= PackageManager.INSTALL_FROM_ADB; 13005 13006 } else { 13007 // Caller holds INSTALL_PACKAGES permission, so we're less strict 13008 // about installerPackageName. 13009 13010 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 13011 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 13012 } 13013 13014 UserHandle user; 13015 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 13016 user = UserHandle.ALL; 13017 } else { 13018 user = new UserHandle(userId); 13019 } 13020 13021 // Only system components can circumvent runtime permissions when installing. 13022 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 13023 && mContext.checkCallingOrSelfPermission(Manifest.permission 13024 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 13025 throw new SecurityException("You need the " 13026 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 13027 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 13028 } 13029 13030 final File originFile = new File(originPath); 13031 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 13032 13033 final Message msg = mHandler.obtainMessage(INIT_COPY); 13034 final VerificationInfo verificationInfo = new VerificationInfo( 13035 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 13036 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 13037 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 13038 null /*packageAbiOverride*/, null /*grantedPermissions*/, 13039 null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN); 13040 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 13041 msg.obj = params; 13042 13043 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 13044 System.identityHashCode(msg.obj)); 13045 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 13046 System.identityHashCode(msg.obj)); 13047 13048 mHandler.sendMessage(msg); 13049 } 13050 13051 13052 /** 13053 * Ensure that the install reason matches what we know about the package installer (e.g. whether 13054 * it is acting on behalf on an enterprise or the user). 13055 * 13056 * Note that the ordering of the conditionals in this method is important. The checks we perform 13057 * are as follows, in this order: 13058 * 13059 * 1) If the install is being performed by a system app, we can trust the app to have set the 13060 * install reason correctly. Thus, we pass through the install reason unchanged, no matter 13061 * what it is. 13062 * 2) If the install is being performed by a device or profile owner app, the install reason 13063 * should be enterprise policy. However, we cannot be sure that the device or profile owner 13064 * set the install reason correctly. If the app targets an older SDK version where install 13065 * reasons did not exist yet, or if the app author simply forgot, the install reason may be 13066 * unset or wrong. Thus, we force the install reason to be enterprise policy. 13067 * 3) In all other cases, the install is being performed by a regular app that is neither part 13068 * of the system nor a device or profile owner. We have no reason to believe that this app is 13069 * acting on behalf of the enterprise admin. Thus, we check whether the install reason was 13070 * set to enterprise policy and if so, change it to unknown instead. 13071 */ 13072 private int fixUpInstallReason(String installerPackageName, int installerUid, 13073 int installReason) { 13074 if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid) 13075 == PERMISSION_GRANTED) { 13076 // If the install is being performed by a system app, we trust that app to have set the 13077 // install reason correctly. 13078 return installReason; 13079 } 13080 13081 final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 13082 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 13083 if (dpm != null) { 13084 ComponentName owner = null; 13085 try { 13086 owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */); 13087 if (owner == null) { 13088 owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid)); 13089 } 13090 } catch (RemoteException e) { 13091 } 13092 if (owner != null && owner.getPackageName().equals(installerPackageName)) { 13093 // If the install is being performed by a device or profile owner, the install 13094 // reason should be enterprise policy. 13095 return PackageManager.INSTALL_REASON_POLICY; 13096 } 13097 } 13098 13099 if (installReason == PackageManager.INSTALL_REASON_POLICY) { 13100 // If the install is being performed by a regular app (i.e. neither system app nor 13101 // device or profile owner), we have no reason to believe that the app is acting on 13102 // behalf of an enterprise. If the app set the install reason to enterprise policy, 13103 // change it to unknown instead. 13104 return PackageManager.INSTALL_REASON_UNKNOWN; 13105 } 13106 13107 // If the install is being performed by a regular app and the install reason was set to any 13108 // value but enterprise policy, leave the install reason unchanged. 13109 return installReason; 13110 } 13111 13112 void installStage(String packageName, File stagedDir, String stagedCid, 13113 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 13114 String installerPackageName, int installerUid, UserHandle user, 13115 Certificate[][] certificates) { 13116 if (DEBUG_EPHEMERAL) { 13117 if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) { 13118 Slog.d(TAG, "Ephemeral install of " + packageName); 13119 } 13120 } 13121 final VerificationInfo verificationInfo = new VerificationInfo( 13122 sessionParams.originatingUri, sessionParams.referrerUri, 13123 sessionParams.originatingUid, installerUid); 13124 13125 final OriginInfo origin; 13126 if (stagedDir != null) { 13127 origin = OriginInfo.fromStagedFile(stagedDir); 13128 } else { 13129 origin = OriginInfo.fromStagedContainer(stagedCid); 13130 } 13131 13132 final Message msg = mHandler.obtainMessage(INIT_COPY); 13133 final int installReason = fixUpInstallReason(installerPackageName, installerUid, 13134 sessionParams.installReason); 13135 final InstallParams params = new InstallParams(origin, null, observer, 13136 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 13137 verificationInfo, user, sessionParams.abiOverride, 13138 sessionParams.grantedRuntimePermissions, certificates, installReason); 13139 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 13140 msg.obj = params; 13141 13142 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 13143 System.identityHashCode(msg.obj)); 13144 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 13145 System.identityHashCode(msg.obj)); 13146 13147 mHandler.sendMessage(msg); 13148 } 13149 13150 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 13151 int userId) { 13152 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 13153 sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId); 13154 } 13155 13156 private void sendPackageAddedForNewUsers(String packageName, boolean isSystem, 13157 int appId, int... userIds) { 13158 if (ArrayUtils.isEmpty(userIds)) { 13159 return; 13160 } 13161 Bundle extras = new Bundle(1); 13162 // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast 13163 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId)); 13164 13165 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 13166 packageName, extras, 0, null, null, userIds); 13167 if (isSystem) { 13168 mHandler.post(() -> { 13169 for (int userId : userIds) { 13170 sendBootCompletedBroadcastToSystemApp(packageName, userId); 13171 } 13172 } 13173 ); 13174 } 13175 } 13176 13177 /** 13178 * The just-installed/enabled app is bundled on the system, so presumed to be able to run 13179 * automatically without needing an explicit launch. 13180 * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones. 13181 */ 13182 private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) { 13183 // If user is not running, the app didn't miss any broadcast 13184 if (!mUserManagerInternal.isUserRunning(userId)) { 13185 return; 13186 } 13187 final IActivityManager am = ActivityManager.getService(); 13188 try { 13189 // Deliver LOCKED_BOOT_COMPLETED first 13190 Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED) 13191 .setPackage(packageName); 13192 final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED}; 13193 am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions, 13194 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 13195 13196 // Deliver BOOT_COMPLETED only if user is unlocked 13197 if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) { 13198 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName); 13199 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions, 13200 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 13201 } 13202 } catch (RemoteException e) { 13203 throw e.rethrowFromSystemServer(); 13204 } 13205 } 13206 13207 @Override 13208 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 13209 int userId) { 13210 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13211 PackageSetting pkgSetting; 13212 final int uid = Binder.getCallingUid(); 13213 enforceCrossUserPermission(uid, userId, 13214 true /* requireFullPermission */, true /* checkShell */, 13215 "setApplicationHiddenSetting for user " + userId); 13216 13217 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 13218 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 13219 return false; 13220 } 13221 13222 long callingId = Binder.clearCallingIdentity(); 13223 try { 13224 boolean sendAdded = false; 13225 boolean sendRemoved = false; 13226 // writer 13227 synchronized (mPackages) { 13228 pkgSetting = mSettings.mPackages.get(packageName); 13229 if (pkgSetting == null) { 13230 return false; 13231 } 13232 // Do not allow "android" is being disabled 13233 if ("android".equals(packageName)) { 13234 Slog.w(TAG, "Cannot hide package: android"); 13235 return false; 13236 } 13237 // Cannot hide static shared libs as they are considered 13238 // a part of the using app (emulating static linking). Also 13239 // static libs are installed always on internal storage. 13240 PackageParser.Package pkg = mPackages.get(packageName); 13241 if (pkg != null && pkg.staticSharedLibName != null) { 13242 Slog.w(TAG, "Cannot hide package: " + packageName 13243 + " providing static shared library: " 13244 + pkg.staticSharedLibName); 13245 return false; 13246 } 13247 // Only allow protected packages to hide themselves. 13248 if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId) 13249 && mProtectedPackages.isPackageStateProtected(userId, packageName)) { 13250 Slog.w(TAG, "Not hiding protected package: " + packageName); 13251 return false; 13252 } 13253 13254 if (pkgSetting.getHidden(userId) != hidden) { 13255 pkgSetting.setHidden(hidden, userId); 13256 mSettings.writePackageRestrictionsLPr(userId); 13257 if (hidden) { 13258 sendRemoved = true; 13259 } else { 13260 sendAdded = true; 13261 } 13262 } 13263 } 13264 if (sendAdded) { 13265 sendPackageAddedForUser(packageName, pkgSetting, userId); 13266 return true; 13267 } 13268 if (sendRemoved) { 13269 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 13270 "hiding pkg"); 13271 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 13272 return true; 13273 } 13274 } finally { 13275 Binder.restoreCallingIdentity(callingId); 13276 } 13277 return false; 13278 } 13279 13280 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 13281 int userId) { 13282 final PackageRemovedInfo info = new PackageRemovedInfo(); 13283 info.removedPackage = packageName; 13284 info.removedUsers = new int[] {userId}; 13285 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 13286 info.sendPackageRemovedBroadcasts(true /*killApp*/); 13287 } 13288 13289 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 13290 if (pkgList.length > 0) { 13291 Bundle extras = new Bundle(1); 13292 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 13293 13294 sendPackageBroadcast( 13295 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 13296 : Intent.ACTION_PACKAGES_UNSUSPENDED, 13297 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 13298 new int[] {userId}); 13299 } 13300 } 13301 13302 /** 13303 * Returns true if application is not found or there was an error. Otherwise it returns 13304 * the hidden state of the package for the given user. 13305 */ 13306 @Override 13307 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 13308 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13309 enforceCrossUserPermission(Binder.getCallingUid(), userId, 13310 true /* requireFullPermission */, false /* checkShell */, 13311 "getApplicationHidden for user " + userId); 13312 PackageSetting pkgSetting; 13313 long callingId = Binder.clearCallingIdentity(); 13314 try { 13315 // writer 13316 synchronized (mPackages) { 13317 pkgSetting = mSettings.mPackages.get(packageName); 13318 if (pkgSetting == null) { 13319 return true; 13320 } 13321 return pkgSetting.getHidden(userId); 13322 } 13323 } finally { 13324 Binder.restoreCallingIdentity(callingId); 13325 } 13326 } 13327 13328 /** 13329 * @hide 13330 */ 13331 @Override 13332 public int installExistingPackageAsUser(String packageName, int userId, int installFlags, 13333 int installReason) { 13334 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 13335 null); 13336 PackageSetting pkgSetting; 13337 final int uid = Binder.getCallingUid(); 13338 enforceCrossUserPermission(uid, userId, 13339 true /* requireFullPermission */, true /* checkShell */, 13340 "installExistingPackage for user " + userId); 13341 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 13342 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 13343 } 13344 13345 long callingId = Binder.clearCallingIdentity(); 13346 try { 13347 boolean installed = false; 13348 final boolean instantApp = 13349 (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 13350 final boolean fullApp = 13351 (installFlags & PackageManager.INSTALL_FULL_APP) != 0; 13352 13353 // writer 13354 synchronized (mPackages) { 13355 pkgSetting = mSettings.mPackages.get(packageName); 13356 if (pkgSetting == null) { 13357 return PackageManager.INSTALL_FAILED_INVALID_URI; 13358 } 13359 if (!pkgSetting.getInstalled(userId)) { 13360 pkgSetting.setInstalled(true, userId); 13361 pkgSetting.setHidden(false, userId); 13362 pkgSetting.setInstallReason(installReason, userId); 13363 mSettings.writePackageRestrictionsLPr(userId); 13364 mSettings.writeKernelMappingLPr(pkgSetting); 13365 installed = true; 13366 } else if (fullApp && pkgSetting.getInstantApp(userId)) { 13367 // upgrade app from instant to full; we don't allow app downgrade 13368 installed = true; 13369 } 13370 setInstantAppForUser(pkgSetting, userId, instantApp, fullApp); 13371 } 13372 13373 if (installed) { 13374 if (pkgSetting.pkg != null) { 13375 synchronized (mInstallLock) { 13376 // We don't need to freeze for a brand new install 13377 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 13378 } 13379 } 13380 sendPackageAddedForUser(packageName, pkgSetting, userId); 13381 synchronized (mPackages) { 13382 updateSequenceNumberLP(packageName, new int[]{ userId }); 13383 } 13384 } 13385 } finally { 13386 Binder.restoreCallingIdentity(callingId); 13387 } 13388 13389 return PackageManager.INSTALL_SUCCEEDED; 13390 } 13391 13392 void setInstantAppForUser(PackageSetting pkgSetting, int userId, 13393 boolean instantApp, boolean fullApp) { 13394 // no state specified; do nothing 13395 if (!instantApp && !fullApp) { 13396 return; 13397 } 13398 if (userId != UserHandle.USER_ALL) { 13399 if (instantApp && !pkgSetting.getInstantApp(userId)) { 13400 pkgSetting.setInstantApp(true /*instantApp*/, userId); 13401 } else if (fullApp && pkgSetting.getInstantApp(userId)) { 13402 pkgSetting.setInstantApp(false /*instantApp*/, userId); 13403 } 13404 } else { 13405 for (int currentUserId : sUserManager.getUserIds()) { 13406 if (instantApp && !pkgSetting.getInstantApp(currentUserId)) { 13407 pkgSetting.setInstantApp(true /*instantApp*/, currentUserId); 13408 } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) { 13409 pkgSetting.setInstantApp(false /*instantApp*/, currentUserId); 13410 } 13411 } 13412 } 13413 } 13414 13415 boolean isUserRestricted(int userId, String restrictionKey) { 13416 Bundle restrictions = sUserManager.getUserRestrictions(userId); 13417 if (restrictions.getBoolean(restrictionKey, false)) { 13418 Log.w(TAG, "User is restricted: " + restrictionKey); 13419 return true; 13420 } 13421 return false; 13422 } 13423 13424 @Override 13425 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 13426 int userId) { 13427 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13428 enforceCrossUserPermission(Binder.getCallingUid(), userId, 13429 true /* requireFullPermission */, true /* checkShell */, 13430 "setPackagesSuspended for user " + userId); 13431 13432 if (ArrayUtils.isEmpty(packageNames)) { 13433 return packageNames; 13434 } 13435 13436 // List of package names for whom the suspended state has changed. 13437 List<String> changedPackages = new ArrayList<>(packageNames.length); 13438 // List of package names for whom the suspended state is not set as requested in this 13439 // method. 13440 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 13441 long callingId = Binder.clearCallingIdentity(); 13442 try { 13443 for (int i = 0; i < packageNames.length; i++) { 13444 String packageName = packageNames[i]; 13445 boolean changed = false; 13446 final int appId; 13447 synchronized (mPackages) { 13448 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 13449 if (pkgSetting == null) { 13450 Slog.w(TAG, "Could not find package setting for package \"" + packageName 13451 + "\". Skipping suspending/un-suspending."); 13452 unactionedPackages.add(packageName); 13453 continue; 13454 } 13455 appId = pkgSetting.appId; 13456 if (pkgSetting.getSuspended(userId) != suspended) { 13457 if (!canSuspendPackageForUserLocked(packageName, userId)) { 13458 unactionedPackages.add(packageName); 13459 continue; 13460 } 13461 pkgSetting.setSuspended(suspended, userId); 13462 mSettings.writePackageRestrictionsLPr(userId); 13463 changed = true; 13464 changedPackages.add(packageName); 13465 } 13466 } 13467 13468 if (changed && suspended) { 13469 killApplication(packageName, UserHandle.getUid(userId, appId), 13470 "suspending package"); 13471 } 13472 } 13473 } finally { 13474 Binder.restoreCallingIdentity(callingId); 13475 } 13476 13477 if (!changedPackages.isEmpty()) { 13478 sendPackagesSuspendedForUser(changedPackages.toArray( 13479 new String[changedPackages.size()]), userId, suspended); 13480 } 13481 13482 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 13483 } 13484 13485 @Override 13486 public boolean isPackageSuspendedForUser(String packageName, int userId) { 13487 enforceCrossUserPermission(Binder.getCallingUid(), userId, 13488 true /* requireFullPermission */, false /* checkShell */, 13489 "isPackageSuspendedForUser for user " + userId); 13490 synchronized (mPackages) { 13491 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 13492 if (pkgSetting == null) { 13493 throw new IllegalArgumentException("Unknown target package: " + packageName); 13494 } 13495 return pkgSetting.getSuspended(userId); 13496 } 13497 } 13498 13499 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 13500 if (isPackageDeviceAdmin(packageName, userId)) { 13501 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13502 + "\": has an active device admin"); 13503 return false; 13504 } 13505 13506 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 13507 if (packageName.equals(activeLauncherPackageName)) { 13508 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13509 + "\": contains the active launcher"); 13510 return false; 13511 } 13512 13513 if (packageName.equals(mRequiredInstallerPackage)) { 13514 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13515 + "\": required for package installation"); 13516 return false; 13517 } 13518 13519 if (packageName.equals(mRequiredUninstallerPackage)) { 13520 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13521 + "\": required for package uninstallation"); 13522 return false; 13523 } 13524 13525 if (packageName.equals(mRequiredVerifierPackage)) { 13526 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13527 + "\": required for package verification"); 13528 return false; 13529 } 13530 13531 if (packageName.equals(getDefaultDialerPackageName(userId))) { 13532 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13533 + "\": is the default dialer"); 13534 return false; 13535 } 13536 13537 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 13538 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13539 + "\": protected package"); 13540 return false; 13541 } 13542 13543 // Cannot suspend static shared libs as they are considered 13544 // a part of the using app (emulating static linking). Also 13545 // static libs are installed always on internal storage. 13546 PackageParser.Package pkg = mPackages.get(packageName); 13547 if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) { 13548 Slog.w(TAG, "Cannot suspend package: " + packageName 13549 + " providing static shared library: " 13550 + pkg.staticSharedLibName); 13551 return false; 13552 } 13553 13554 return true; 13555 } 13556 13557 private String getActiveLauncherPackageName(int userId) { 13558 Intent intent = new Intent(Intent.ACTION_MAIN); 13559 intent.addCategory(Intent.CATEGORY_HOME); 13560 ResolveInfo resolveInfo = resolveIntent( 13561 intent, 13562 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 13563 PackageManager.MATCH_DEFAULT_ONLY, 13564 userId); 13565 13566 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 13567 } 13568 13569 private String getDefaultDialerPackageName(int userId) { 13570 synchronized (mPackages) { 13571 return mSettings.getDefaultDialerPackageNameLPw(userId); 13572 } 13573 } 13574 13575 @Override 13576 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 13577 mContext.enforceCallingOrSelfPermission( 13578 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13579 "Only package verification agents can verify applications"); 13580 13581 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 13582 final PackageVerificationResponse response = new PackageVerificationResponse( 13583 verificationCode, Binder.getCallingUid()); 13584 msg.arg1 = id; 13585 msg.obj = response; 13586 mHandler.sendMessage(msg); 13587 } 13588 13589 @Override 13590 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 13591 long millisecondsToDelay) { 13592 mContext.enforceCallingOrSelfPermission( 13593 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13594 "Only package verification agents can extend verification timeouts"); 13595 13596 final PackageVerificationState state = mPendingVerification.get(id); 13597 final PackageVerificationResponse response = new PackageVerificationResponse( 13598 verificationCodeAtTimeout, Binder.getCallingUid()); 13599 13600 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 13601 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 13602 } 13603 if (millisecondsToDelay < 0) { 13604 millisecondsToDelay = 0; 13605 } 13606 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 13607 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 13608 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 13609 } 13610 13611 if ((state != null) && !state.timeoutExtended()) { 13612 state.extendTimeout(); 13613 13614 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 13615 msg.arg1 = id; 13616 msg.obj = response; 13617 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 13618 } 13619 } 13620 13621 private void broadcastPackageVerified(int verificationId, Uri packageUri, 13622 int verificationCode, UserHandle user) { 13623 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 13624 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 13625 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 13626 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 13627 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 13628 13629 mContext.sendBroadcastAsUser(intent, user, 13630 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 13631 } 13632 13633 private ComponentName matchComponentForVerifier(String packageName, 13634 List<ResolveInfo> receivers) { 13635 ActivityInfo targetReceiver = null; 13636 13637 final int NR = receivers.size(); 13638 for (int i = 0; i < NR; i++) { 13639 final ResolveInfo info = receivers.get(i); 13640 if (info.activityInfo == null) { 13641 continue; 13642 } 13643 13644 if (packageName.equals(info.activityInfo.packageName)) { 13645 targetReceiver = info.activityInfo; 13646 break; 13647 } 13648 } 13649 13650 if (targetReceiver == null) { 13651 return null; 13652 } 13653 13654 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 13655 } 13656 13657 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 13658 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 13659 if (pkgInfo.verifiers.length == 0) { 13660 return null; 13661 } 13662 13663 final int N = pkgInfo.verifiers.length; 13664 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 13665 for (int i = 0; i < N; i++) { 13666 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 13667 13668 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 13669 receivers); 13670 if (comp == null) { 13671 continue; 13672 } 13673 13674 final int verifierUid = getUidForVerifier(verifierInfo); 13675 if (verifierUid == -1) { 13676 continue; 13677 } 13678 13679 if (DEBUG_VERIFY) { 13680 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 13681 + " with the correct signature"); 13682 } 13683 sufficientVerifiers.add(comp); 13684 verificationState.addSufficientVerifier(verifierUid); 13685 } 13686 13687 return sufficientVerifiers; 13688 } 13689 13690 private int getUidForVerifier(VerifierInfo verifierInfo) { 13691 synchronized (mPackages) { 13692 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 13693 if (pkg == null) { 13694 return -1; 13695 } else if (pkg.mSignatures.length != 1) { 13696 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 13697 + " has more than one signature; ignoring"); 13698 return -1; 13699 } 13700 13701 /* 13702 * If the public key of the package's signature does not match 13703 * our expected public key, then this is a different package and 13704 * we should skip. 13705 */ 13706 13707 final byte[] expectedPublicKey; 13708 try { 13709 final Signature verifierSig = pkg.mSignatures[0]; 13710 final PublicKey publicKey = verifierSig.getPublicKey(); 13711 expectedPublicKey = publicKey.getEncoded(); 13712 } catch (CertificateException e) { 13713 return -1; 13714 } 13715 13716 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 13717 13718 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 13719 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 13720 + " does not have the expected public key; ignoring"); 13721 return -1; 13722 } 13723 13724 return pkg.applicationInfo.uid; 13725 } 13726 } 13727 13728 @Override 13729 public void finishPackageInstall(int token, boolean didLaunch) { 13730 enforceSystemOrRoot("Only the system is allowed to finish installs"); 13731 13732 if (DEBUG_INSTALL) { 13733 Slog.v(TAG, "BM finishing package install for " + token); 13734 } 13735 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 13736 13737 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 13738 mHandler.sendMessage(msg); 13739 } 13740 13741 /** 13742 * Get the verification agent timeout. 13743 * 13744 * @return verification timeout in milliseconds 13745 */ 13746 private long getVerificationTimeout() { 13747 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 13748 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 13749 DEFAULT_VERIFICATION_TIMEOUT); 13750 } 13751 13752 /** 13753 * Get the default verification agent response code. 13754 * 13755 * @return default verification response code 13756 */ 13757 private int getDefaultVerificationResponse() { 13758 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13759 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 13760 DEFAULT_VERIFICATION_RESPONSE); 13761 } 13762 13763 /** 13764 * Check whether or not package verification has been enabled. 13765 * 13766 * @return true if verification should be performed 13767 */ 13768 private boolean isVerificationEnabled(int userId, int installFlags) { 13769 if (!DEFAULT_VERIFY_ENABLE) { 13770 return false; 13771 } 13772 // Ephemeral apps don't get the full verification treatment 13773 if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) { 13774 if (DEBUG_EPHEMERAL) { 13775 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 13776 } 13777 return false; 13778 } 13779 13780 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 13781 13782 // Check if installing from ADB 13783 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 13784 // Do not run verification in a test harness environment 13785 if (ActivityManager.isRunningInTestHarness()) { 13786 return false; 13787 } 13788 if (ensureVerifyAppsEnabled) { 13789 return true; 13790 } 13791 // Check if the developer does not want package verification for ADB installs 13792 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13793 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 13794 return false; 13795 } 13796 } 13797 13798 if (ensureVerifyAppsEnabled) { 13799 return true; 13800 } 13801 13802 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13803 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 13804 } 13805 13806 @Override 13807 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 13808 throws RemoteException { 13809 mContext.enforceCallingOrSelfPermission( 13810 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 13811 "Only intentfilter verification agents can verify applications"); 13812 13813 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 13814 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 13815 Binder.getCallingUid(), verificationCode, failedDomains); 13816 msg.arg1 = id; 13817 msg.obj = response; 13818 mHandler.sendMessage(msg); 13819 } 13820 13821 @Override 13822 public int getIntentVerificationStatus(String packageName, int userId) { 13823 synchronized (mPackages) { 13824 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 13825 } 13826 } 13827 13828 @Override 13829 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 13830 mContext.enforceCallingOrSelfPermission( 13831 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13832 13833 boolean result = false; 13834 synchronized (mPackages) { 13835 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 13836 } 13837 if (result) { 13838 scheduleWritePackageRestrictionsLocked(userId); 13839 } 13840 return result; 13841 } 13842 13843 @Override 13844 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 13845 String packageName) { 13846 synchronized (mPackages) { 13847 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 13848 } 13849 } 13850 13851 @Override 13852 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 13853 if (TextUtils.isEmpty(packageName)) { 13854 return ParceledListSlice.emptyList(); 13855 } 13856 synchronized (mPackages) { 13857 PackageParser.Package pkg = mPackages.get(packageName); 13858 if (pkg == null || pkg.activities == null) { 13859 return ParceledListSlice.emptyList(); 13860 } 13861 final int count = pkg.activities.size(); 13862 ArrayList<IntentFilter> result = new ArrayList<>(); 13863 for (int n=0; n<count; n++) { 13864 PackageParser.Activity activity = pkg.activities.get(n); 13865 if (activity.intents != null && activity.intents.size() > 0) { 13866 result.addAll(activity.intents); 13867 } 13868 } 13869 return new ParceledListSlice<>(result); 13870 } 13871 } 13872 13873 @Override 13874 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 13875 mContext.enforceCallingOrSelfPermission( 13876 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13877 13878 synchronized (mPackages) { 13879 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 13880 if (packageName != null) { 13881 result |= updateIntentVerificationStatus(packageName, 13882 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 13883 userId); 13884 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 13885 packageName, userId); 13886 } 13887 return result; 13888 } 13889 } 13890 13891 @Override 13892 public String getDefaultBrowserPackageName(int userId) { 13893 synchronized (mPackages) { 13894 return mSettings.getDefaultBrowserPackageNameLPw(userId); 13895 } 13896 } 13897 13898 /** 13899 * Get the "allow unknown sources" setting. 13900 * 13901 * @return the current "allow unknown sources" setting 13902 */ 13903 private int getUnknownSourcesSettings() { 13904 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 13905 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 13906 -1); 13907 } 13908 13909 @Override 13910 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 13911 final int uid = Binder.getCallingUid(); 13912 // writer 13913 synchronized (mPackages) { 13914 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 13915 if (targetPackageSetting == null) { 13916 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 13917 } 13918 13919 PackageSetting installerPackageSetting; 13920 if (installerPackageName != null) { 13921 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 13922 if (installerPackageSetting == null) { 13923 throw new IllegalArgumentException("Unknown installer package: " 13924 + installerPackageName); 13925 } 13926 } else { 13927 installerPackageSetting = null; 13928 } 13929 13930 Signature[] callerSignature; 13931 Object obj = mSettings.getUserIdLPr(uid); 13932 if (obj != null) { 13933 if (obj instanceof SharedUserSetting) { 13934 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 13935 } else if (obj instanceof PackageSetting) { 13936 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 13937 } else { 13938 throw new SecurityException("Bad object " + obj + " for uid " + uid); 13939 } 13940 } else { 13941 throw new SecurityException("Unknown calling UID: " + uid); 13942 } 13943 13944 // Verify: can't set installerPackageName to a package that is 13945 // not signed with the same cert as the caller. 13946 if (installerPackageSetting != null) { 13947 if (compareSignatures(callerSignature, 13948 installerPackageSetting.signatures.mSignatures) 13949 != PackageManager.SIGNATURE_MATCH) { 13950 throw new SecurityException( 13951 "Caller does not have same cert as new installer package " 13952 + installerPackageName); 13953 } 13954 } 13955 13956 // Verify: if target already has an installer package, it must 13957 // be signed with the same cert as the caller. 13958 if (targetPackageSetting.installerPackageName != null) { 13959 PackageSetting setting = mSettings.mPackages.get( 13960 targetPackageSetting.installerPackageName); 13961 // If the currently set package isn't valid, then it's always 13962 // okay to change it. 13963 if (setting != null) { 13964 if (compareSignatures(callerSignature, 13965 setting.signatures.mSignatures) 13966 != PackageManager.SIGNATURE_MATCH) { 13967 throw new SecurityException( 13968 "Caller does not have same cert as old installer package " 13969 + targetPackageSetting.installerPackageName); 13970 } 13971 } 13972 } 13973 13974 // Okay! 13975 targetPackageSetting.installerPackageName = installerPackageName; 13976 if (installerPackageName != null) { 13977 mSettings.mInstallerPackages.add(installerPackageName); 13978 } 13979 scheduleWriteSettingsLocked(); 13980 } 13981 } 13982 13983 @Override 13984 public void setApplicationCategoryHint(String packageName, int categoryHint, 13985 String callerPackageName) { 13986 mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(), 13987 callerPackageName); 13988 synchronized (mPackages) { 13989 PackageSetting ps = mSettings.mPackages.get(packageName); 13990 if (ps == null) { 13991 throw new IllegalArgumentException("Unknown target package " + packageName); 13992 } 13993 13994 if (!Objects.equals(callerPackageName, ps.installerPackageName)) { 13995 throw new IllegalArgumentException("Calling package " + callerPackageName 13996 + " is not installer for " + packageName); 13997 } 13998 13999 if (ps.categoryHint != categoryHint) { 14000 ps.categoryHint = categoryHint; 14001 scheduleWriteSettingsLocked(); 14002 } 14003 } 14004 } 14005 14006 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 14007 // Queue up an async operation since the package installation may take a little while. 14008 mHandler.post(new Runnable() { 14009 public void run() { 14010 mHandler.removeCallbacks(this); 14011 // Result object to be returned 14012 PackageInstalledInfo res = new PackageInstalledInfo(); 14013 res.setReturnCode(currentStatus); 14014 res.uid = -1; 14015 res.pkg = null; 14016 res.removedInfo = null; 14017 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14018 args.doPreInstall(res.returnCode); 14019 synchronized (mInstallLock) { 14020 installPackageTracedLI(args, res); 14021 } 14022 args.doPostInstall(res.returnCode, res.uid); 14023 } 14024 14025 // A restore should be performed at this point if (a) the install 14026 // succeeded, (b) the operation is not an update, and (c) the new 14027 // package has not opted out of backup participation. 14028 final boolean update = res.removedInfo != null 14029 && res.removedInfo.removedPackage != null; 14030 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 14031 boolean doRestore = !update 14032 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 14033 14034 // Set up the post-install work request bookkeeping. This will be used 14035 // and cleaned up by the post-install event handling regardless of whether 14036 // there's a restore pass performed. Token values are >= 1. 14037 int token; 14038 if (mNextInstallToken < 0) mNextInstallToken = 1; 14039 token = mNextInstallToken++; 14040 14041 PostInstallData data = new PostInstallData(args, res); 14042 mRunningInstalls.put(token, data); 14043 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 14044 14045 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 14046 // Pass responsibility to the Backup Manager. It will perform a 14047 // restore if appropriate, then pass responsibility back to the 14048 // Package Manager to run the post-install observer callbacks 14049 // and broadcasts. 14050 IBackupManager bm = IBackupManager.Stub.asInterface( 14051 ServiceManager.getService(Context.BACKUP_SERVICE)); 14052 if (bm != null) { 14053 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 14054 + " to BM for possible restore"); 14055 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 14056 try { 14057 // TODO: http://b/22388012 14058 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 14059 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 14060 } else { 14061 doRestore = false; 14062 } 14063 } catch (RemoteException e) { 14064 // can't happen; the backup manager is local 14065 } catch (Exception e) { 14066 Slog.e(TAG, "Exception trying to enqueue restore", e); 14067 doRestore = false; 14068 } 14069 } else { 14070 Slog.e(TAG, "Backup Manager not found!"); 14071 doRestore = false; 14072 } 14073 } 14074 14075 if (!doRestore) { 14076 // No restore possible, or the Backup Manager was mysteriously not 14077 // available -- just fire the post-install work request directly. 14078 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 14079 14080 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 14081 14082 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 14083 mHandler.sendMessage(msg); 14084 } 14085 } 14086 }); 14087 } 14088 14089 /** 14090 * Callback from PackageSettings whenever an app is first transitioned out of the 14091 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 14092 * the app was "launched" for a restoreAtInstall operation. Therefore we check 14093 * here whether the app is the target of an ongoing install, and only send the 14094 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 14095 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 14096 * handling. 14097 */ 14098 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 14099 // Serialize this with the rest of the install-process message chain. In the 14100 // restore-at-install case, this Runnable will necessarily run before the 14101 // POST_INSTALL message is processed, so the contents of mRunningInstalls 14102 // are coherent. In the non-restore case, the app has already completed install 14103 // and been launched through some other means, so it is not in a problematic 14104 // state for observers to see the FIRST_LAUNCH signal. 14105 mHandler.post(new Runnable() { 14106 @Override 14107 public void run() { 14108 for (int i = 0; i < mRunningInstalls.size(); i++) { 14109 final PostInstallData data = mRunningInstalls.valueAt(i); 14110 if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14111 continue; 14112 } 14113 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 14114 // right package; but is it for the right user? 14115 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 14116 if (userId == data.res.newUsers[uIndex]) { 14117 if (DEBUG_BACKUP) { 14118 Slog.i(TAG, "Package " + pkgName 14119 + " being restored so deferring FIRST_LAUNCH"); 14120 } 14121 return; 14122 } 14123 } 14124 } 14125 } 14126 // didn't find it, so not being restored 14127 if (DEBUG_BACKUP) { 14128 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 14129 } 14130 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 14131 } 14132 }); 14133 } 14134 14135 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 14136 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 14137 installerPkg, null, userIds); 14138 } 14139 14140 private abstract class HandlerParams { 14141 private static final int MAX_RETRIES = 4; 14142 14143 /** 14144 * Number of times startCopy() has been attempted and had a non-fatal 14145 * error. 14146 */ 14147 private int mRetries = 0; 14148 14149 /** User handle for the user requesting the information or installation. */ 14150 private final UserHandle mUser; 14151 String traceMethod; 14152 int traceCookie; 14153 14154 HandlerParams(UserHandle user) { 14155 mUser = user; 14156 } 14157 14158 UserHandle getUser() { 14159 return mUser; 14160 } 14161 14162 HandlerParams setTraceMethod(String traceMethod) { 14163 this.traceMethod = traceMethod; 14164 return this; 14165 } 14166 14167 HandlerParams setTraceCookie(int traceCookie) { 14168 this.traceCookie = traceCookie; 14169 return this; 14170 } 14171 14172 final boolean startCopy() { 14173 boolean res; 14174 try { 14175 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 14176 14177 if (++mRetries > MAX_RETRIES) { 14178 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 14179 mHandler.sendEmptyMessage(MCS_GIVE_UP); 14180 handleServiceError(); 14181 return false; 14182 } else { 14183 handleStartCopy(); 14184 res = true; 14185 } 14186 } catch (RemoteException e) { 14187 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 14188 mHandler.sendEmptyMessage(MCS_RECONNECT); 14189 res = false; 14190 } 14191 handleReturnCode(); 14192 return res; 14193 } 14194 14195 final void serviceError() { 14196 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 14197 handleServiceError(); 14198 handleReturnCode(); 14199 } 14200 14201 abstract void handleStartCopy() throws RemoteException; 14202 abstract void handleServiceError(); 14203 abstract void handleReturnCode(); 14204 } 14205 14206 class MeasureParams extends HandlerParams { 14207 private final PackageStats mStats; 14208 private boolean mSuccess; 14209 14210 private final IPackageStatsObserver mObserver; 14211 14212 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 14213 super(new UserHandle(stats.userHandle)); 14214 mObserver = observer; 14215 mStats = stats; 14216 } 14217 14218 @Override 14219 public String toString() { 14220 return "MeasureParams{" 14221 + Integer.toHexString(System.identityHashCode(this)) 14222 + " " + mStats.packageName + "}"; 14223 } 14224 14225 @Override 14226 void handleStartCopy() throws RemoteException { 14227 synchronized (mInstallLock) { 14228 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 14229 } 14230 14231 if (mSuccess) { 14232 boolean mounted = false; 14233 try { 14234 final String status = Environment.getExternalStorageState(); 14235 mounted = (Environment.MEDIA_MOUNTED.equals(status) 14236 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 14237 } catch (Exception e) { 14238 } 14239 14240 if (mounted) { 14241 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 14242 14243 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 14244 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 14245 14246 mStats.externalDataSize = calculateDirectorySize(mContainerService, 14247 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 14248 14249 // Always subtract cache size, since it's a subdirectory 14250 mStats.externalDataSize -= mStats.externalCacheSize; 14251 14252 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 14253 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 14254 14255 mStats.externalObbSize = calculateDirectorySize(mContainerService, 14256 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 14257 } 14258 } 14259 } 14260 14261 @Override 14262 void handleReturnCode() { 14263 if (mObserver != null) { 14264 try { 14265 mObserver.onGetStatsCompleted(mStats, mSuccess); 14266 } catch (RemoteException e) { 14267 Slog.i(TAG, "Observer no longer exists."); 14268 } 14269 } 14270 } 14271 14272 @Override 14273 void handleServiceError() { 14274 Slog.e(TAG, "Could not measure application " + mStats.packageName 14275 + " external storage"); 14276 } 14277 } 14278 14279 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 14280 throws RemoteException { 14281 long result = 0; 14282 for (File path : paths) { 14283 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 14284 } 14285 return result; 14286 } 14287 14288 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 14289 for (File path : paths) { 14290 try { 14291 mcs.clearDirectory(path.getAbsolutePath()); 14292 } catch (RemoteException e) { 14293 } 14294 } 14295 } 14296 14297 static class OriginInfo { 14298 /** 14299 * Location where install is coming from, before it has been 14300 * copied/renamed into place. This could be a single monolithic APK 14301 * file, or a cluster directory. This location may be untrusted. 14302 */ 14303 final File file; 14304 final String cid; 14305 14306 /** 14307 * Flag indicating that {@link #file} or {@link #cid} has already been 14308 * staged, meaning downstream users don't need to defensively copy the 14309 * contents. 14310 */ 14311 final boolean staged; 14312 14313 /** 14314 * Flag indicating that {@link #file} or {@link #cid} is an already 14315 * installed app that is being moved. 14316 */ 14317 final boolean existing; 14318 14319 final String resolvedPath; 14320 final File resolvedFile; 14321 14322 static OriginInfo fromNothing() { 14323 return new OriginInfo(null, null, false, false); 14324 } 14325 14326 static OriginInfo fromUntrustedFile(File file) { 14327 return new OriginInfo(file, null, false, false); 14328 } 14329 14330 static OriginInfo fromExistingFile(File file) { 14331 return new OriginInfo(file, null, false, true); 14332 } 14333 14334 static OriginInfo fromStagedFile(File file) { 14335 return new OriginInfo(file, null, true, false); 14336 } 14337 14338 static OriginInfo fromStagedContainer(String cid) { 14339 return new OriginInfo(null, cid, true, false); 14340 } 14341 14342 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 14343 this.file = file; 14344 this.cid = cid; 14345 this.staged = staged; 14346 this.existing = existing; 14347 14348 if (cid != null) { 14349 resolvedPath = PackageHelper.getSdDir(cid); 14350 resolvedFile = new File(resolvedPath); 14351 } else if (file != null) { 14352 resolvedPath = file.getAbsolutePath(); 14353 resolvedFile = file; 14354 } else { 14355 resolvedPath = null; 14356 resolvedFile = null; 14357 } 14358 } 14359 } 14360 14361 static class MoveInfo { 14362 final int moveId; 14363 final String fromUuid; 14364 final String toUuid; 14365 final String packageName; 14366 final String dataAppName; 14367 final int appId; 14368 final String seinfo; 14369 final int targetSdkVersion; 14370 14371 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 14372 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 14373 this.moveId = moveId; 14374 this.fromUuid = fromUuid; 14375 this.toUuid = toUuid; 14376 this.packageName = packageName; 14377 this.dataAppName = dataAppName; 14378 this.appId = appId; 14379 this.seinfo = seinfo; 14380 this.targetSdkVersion = targetSdkVersion; 14381 } 14382 } 14383 14384 static class VerificationInfo { 14385 /** A constant used to indicate that a uid value is not present. */ 14386 public static final int NO_UID = -1; 14387 14388 /** URI referencing where the package was downloaded from. */ 14389 final Uri originatingUri; 14390 14391 /** HTTP referrer URI associated with the originatingURI. */ 14392 final Uri referrer; 14393 14394 /** UID of the application that the install request originated from. */ 14395 final int originatingUid; 14396 14397 /** UID of application requesting the install */ 14398 final int installerUid; 14399 14400 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 14401 this.originatingUri = originatingUri; 14402 this.referrer = referrer; 14403 this.originatingUid = originatingUid; 14404 this.installerUid = installerUid; 14405 } 14406 } 14407 14408 class InstallParams extends HandlerParams { 14409 final OriginInfo origin; 14410 final MoveInfo move; 14411 final IPackageInstallObserver2 observer; 14412 int installFlags; 14413 final String installerPackageName; 14414 final String volumeUuid; 14415 private InstallArgs mArgs; 14416 private int mRet; 14417 final String packageAbiOverride; 14418 final String[] grantedRuntimePermissions; 14419 final VerificationInfo verificationInfo; 14420 final Certificate[][] certificates; 14421 final int installReason; 14422 14423 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 14424 int installFlags, String installerPackageName, String volumeUuid, 14425 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 14426 String[] grantedPermissions, Certificate[][] certificates, int installReason) { 14427 super(user); 14428 this.origin = origin; 14429 this.move = move; 14430 this.observer = observer; 14431 this.installFlags = installFlags; 14432 this.installerPackageName = installerPackageName; 14433 this.volumeUuid = volumeUuid; 14434 this.verificationInfo = verificationInfo; 14435 this.packageAbiOverride = packageAbiOverride; 14436 this.grantedRuntimePermissions = grantedPermissions; 14437 this.certificates = certificates; 14438 this.installReason = installReason; 14439 } 14440 14441 @Override 14442 public String toString() { 14443 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 14444 + " file=" + origin.file + " cid=" + origin.cid + "}"; 14445 } 14446 14447 private int installLocationPolicy(PackageInfoLite pkgLite) { 14448 String packageName = pkgLite.packageName; 14449 int installLocation = pkgLite.installLocation; 14450 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14451 // reader 14452 synchronized (mPackages) { 14453 // Currently installed package which the new package is attempting to replace or 14454 // null if no such package is installed. 14455 PackageParser.Package installedPkg = mPackages.get(packageName); 14456 // Package which currently owns the data which the new package will own if installed. 14457 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 14458 // will be null whereas dataOwnerPkg will contain information about the package 14459 // which was uninstalled while keeping its data. 14460 PackageParser.Package dataOwnerPkg = installedPkg; 14461 if (dataOwnerPkg == null) { 14462 PackageSetting ps = mSettings.mPackages.get(packageName); 14463 if (ps != null) { 14464 dataOwnerPkg = ps.pkg; 14465 } 14466 } 14467 14468 if (dataOwnerPkg != null) { 14469 // If installed, the package will get access to data left on the device by its 14470 // predecessor. As a security measure, this is permited only if this is not a 14471 // version downgrade or if the predecessor package is marked as debuggable and 14472 // a downgrade is explicitly requested. 14473 // 14474 // On debuggable platform builds, downgrades are permitted even for 14475 // non-debuggable packages to make testing easier. Debuggable platform builds do 14476 // not offer security guarantees and thus it's OK to disable some security 14477 // mechanisms to make debugging/testing easier on those builds. However, even on 14478 // debuggable builds downgrades of packages are permitted only if requested via 14479 // installFlags. This is because we aim to keep the behavior of debuggable 14480 // platform builds as close as possible to the behavior of non-debuggable 14481 // platform builds. 14482 final boolean downgradeRequested = 14483 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 14484 final boolean packageDebuggable = 14485 (dataOwnerPkg.applicationInfo.flags 14486 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 14487 final boolean downgradePermitted = 14488 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 14489 if (!downgradePermitted) { 14490 try { 14491 checkDowngrade(dataOwnerPkg, pkgLite); 14492 } catch (PackageManagerException e) { 14493 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 14494 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 14495 } 14496 } 14497 } 14498 14499 if (installedPkg != null) { 14500 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14501 // Check for updated system application. 14502 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 14503 if (onSd) { 14504 Slog.w(TAG, "Cannot install update to system app on sdcard"); 14505 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 14506 } 14507 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14508 } else { 14509 if (onSd) { 14510 // Install flag overrides everything. 14511 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14512 } 14513 // If current upgrade specifies particular preference 14514 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 14515 // Application explicitly specified internal. 14516 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14517 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 14518 // App explictly prefers external. Let policy decide 14519 } else { 14520 // Prefer previous location 14521 if (isExternal(installedPkg)) { 14522 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14523 } 14524 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14525 } 14526 } 14527 } else { 14528 // Invalid install. Return error code 14529 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 14530 } 14531 } 14532 } 14533 // All the special cases have been taken care of. 14534 // Return result based on recommended install location. 14535 if (onSd) { 14536 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14537 } 14538 return pkgLite.recommendedInstallLocation; 14539 } 14540 14541 /* 14542 * Invoke remote method to get package information and install 14543 * location values. Override install location based on default 14544 * policy if needed and then create install arguments based 14545 * on the install location. 14546 */ 14547 public void handleStartCopy() throws RemoteException { 14548 int ret = PackageManager.INSTALL_SUCCEEDED; 14549 14550 // If we're already staged, we've firmly committed to an install location 14551 if (origin.staged) { 14552 if (origin.file != null) { 14553 installFlags |= PackageManager.INSTALL_INTERNAL; 14554 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 14555 } else if (origin.cid != null) { 14556 installFlags |= PackageManager.INSTALL_EXTERNAL; 14557 installFlags &= ~PackageManager.INSTALL_INTERNAL; 14558 } else { 14559 throw new IllegalStateException("Invalid stage location"); 14560 } 14561 } 14562 14563 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14564 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 14565 final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 14566 PackageInfoLite pkgLite = null; 14567 14568 if (onInt && onSd) { 14569 // Check if both bits are set. 14570 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 14571 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14572 } else if (onSd && ephemeral) { 14573 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 14574 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14575 } else { 14576 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 14577 packageAbiOverride); 14578 14579 if (DEBUG_EPHEMERAL && ephemeral) { 14580 Slog.v(TAG, "pkgLite for install: " + pkgLite); 14581 } 14582 14583 /* 14584 * If we have too little free space, try to free cache 14585 * before giving up. 14586 */ 14587 if (!origin.staged && pkgLite.recommendedInstallLocation 14588 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 14589 // TODO: focus freeing disk space on the target device 14590 final StorageManager storage = StorageManager.from(mContext); 14591 final long lowThreshold = storage.getStorageLowBytes( 14592 Environment.getDataDirectory()); 14593 14594 final long sizeBytes = mContainerService.calculateInstalledSize( 14595 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 14596 14597 try { 14598 mInstaller.freeCache(null, sizeBytes + lowThreshold, 0); 14599 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 14600 installFlags, packageAbiOverride); 14601 } catch (InstallerException e) { 14602 Slog.w(TAG, "Failed to free cache", e); 14603 } 14604 14605 /* 14606 * The cache free must have deleted the file we 14607 * downloaded to install. 14608 * 14609 * TODO: fix the "freeCache" call to not delete 14610 * the file we care about. 14611 */ 14612 if (pkgLite.recommendedInstallLocation 14613 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 14614 pkgLite.recommendedInstallLocation 14615 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 14616 } 14617 } 14618 } 14619 14620 if (ret == PackageManager.INSTALL_SUCCEEDED) { 14621 int loc = pkgLite.recommendedInstallLocation; 14622 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 14623 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14624 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 14625 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 14626 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 14627 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 14628 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 14629 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 14630 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 14631 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 14632 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 14633 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 14634 } else { 14635 // Override with defaults if needed. 14636 loc = installLocationPolicy(pkgLite); 14637 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 14638 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 14639 } else if (!onSd && !onInt) { 14640 // Override install location with flags 14641 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 14642 // Set the flag to install on external media. 14643 installFlags |= PackageManager.INSTALL_EXTERNAL; 14644 installFlags &= ~PackageManager.INSTALL_INTERNAL; 14645 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 14646 if (DEBUG_EPHEMERAL) { 14647 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 14648 } 14649 installFlags |= PackageManager.INSTALL_INSTANT_APP; 14650 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 14651 |PackageManager.INSTALL_INTERNAL); 14652 } else { 14653 // Make sure the flag for installing on external 14654 // media is unset 14655 installFlags |= PackageManager.INSTALL_INTERNAL; 14656 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 14657 } 14658 } 14659 } 14660 } 14661 14662 final InstallArgs args = createInstallArgs(this); 14663 mArgs = args; 14664 14665 if (ret == PackageManager.INSTALL_SUCCEEDED) { 14666 // TODO: http://b/22976637 14667 // Apps installed for "all" users use the device owner to verify the app 14668 UserHandle verifierUser = getUser(); 14669 if (verifierUser == UserHandle.ALL) { 14670 verifierUser = UserHandle.SYSTEM; 14671 } 14672 14673 /* 14674 * Determine if we have any installed package verifiers. If we 14675 * do, then we'll defer to them to verify the packages. 14676 */ 14677 final int requiredUid = mRequiredVerifierPackage == null ? -1 14678 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 14679 verifierUser.getIdentifier()); 14680 if (!origin.existing && requiredUid != -1 14681 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 14682 final Intent verification = new Intent( 14683 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 14684 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 14685 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 14686 PACKAGE_MIME_TYPE); 14687 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 14688 14689 // Query all live verifiers based on current user state 14690 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 14691 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 14692 14693 if (DEBUG_VERIFY) { 14694 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 14695 + verification.toString() + " with " + pkgLite.verifiers.length 14696 + " optional verifiers"); 14697 } 14698 14699 final int verificationId = mPendingVerificationToken++; 14700 14701 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 14702 14703 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 14704 installerPackageName); 14705 14706 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 14707 installFlags); 14708 14709 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 14710 pkgLite.packageName); 14711 14712 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 14713 pkgLite.versionCode); 14714 14715 if (verificationInfo != null) { 14716 if (verificationInfo.originatingUri != null) { 14717 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 14718 verificationInfo.originatingUri); 14719 } 14720 if (verificationInfo.referrer != null) { 14721 verification.putExtra(Intent.EXTRA_REFERRER, 14722 verificationInfo.referrer); 14723 } 14724 if (verificationInfo.originatingUid >= 0) { 14725 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 14726 verificationInfo.originatingUid); 14727 } 14728 if (verificationInfo.installerUid >= 0) { 14729 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 14730 verificationInfo.installerUid); 14731 } 14732 } 14733 14734 final PackageVerificationState verificationState = new PackageVerificationState( 14735 requiredUid, args); 14736 14737 mPendingVerification.append(verificationId, verificationState); 14738 14739 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 14740 receivers, verificationState); 14741 14742 DeviceIdleController.LocalService idleController = getDeviceIdleController(); 14743 final long idleDuration = getVerificationTimeout(); 14744 14745 /* 14746 * If any sufficient verifiers were listed in the package 14747 * manifest, attempt to ask them. 14748 */ 14749 if (sufficientVerifiers != null) { 14750 final int N = sufficientVerifiers.size(); 14751 if (N == 0) { 14752 Slog.i(TAG, "Additional verifiers required, but none installed."); 14753 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 14754 } else { 14755 for (int i = 0; i < N; i++) { 14756 final ComponentName verifierComponent = sufficientVerifiers.get(i); 14757 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 14758 verifierComponent.getPackageName(), idleDuration, 14759 verifierUser.getIdentifier(), false, "package verifier"); 14760 14761 final Intent sufficientIntent = new Intent(verification); 14762 sufficientIntent.setComponent(verifierComponent); 14763 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 14764 } 14765 } 14766 } 14767 14768 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 14769 mRequiredVerifierPackage, receivers); 14770 if (ret == PackageManager.INSTALL_SUCCEEDED 14771 && mRequiredVerifierPackage != null) { 14772 Trace.asyncTraceBegin( 14773 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 14774 /* 14775 * Send the intent to the required verification agent, 14776 * but only start the verification timeout after the 14777 * target BroadcastReceivers have run. 14778 */ 14779 verification.setComponent(requiredVerifierComponent); 14780 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 14781 requiredVerifierComponent.getPackageName(), idleDuration, 14782 verifierUser.getIdentifier(), false, "package verifier"); 14783 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 14784 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 14785 new BroadcastReceiver() { 14786 @Override 14787 public void onReceive(Context context, Intent intent) { 14788 final Message msg = mHandler 14789 .obtainMessage(CHECK_PENDING_VERIFICATION); 14790 msg.arg1 = verificationId; 14791 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 14792 } 14793 }, null, 0, null, null); 14794 14795 /* 14796 * We don't want the copy to proceed until verification 14797 * succeeds, so null out this field. 14798 */ 14799 mArgs = null; 14800 } 14801 } else { 14802 /* 14803 * No package verification is enabled, so immediately start 14804 * the remote call to initiate copy using temporary file. 14805 */ 14806 ret = args.copyApk(mContainerService, true); 14807 } 14808 } 14809 14810 mRet = ret; 14811 } 14812 14813 @Override 14814 void handleReturnCode() { 14815 // If mArgs is null, then MCS couldn't be reached. When it 14816 // reconnects, it will try again to install. At that point, this 14817 // will succeed. 14818 if (mArgs != null) { 14819 processPendingInstall(mArgs, mRet); 14820 } 14821 } 14822 14823 @Override 14824 void handleServiceError() { 14825 mArgs = createInstallArgs(this); 14826 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 14827 } 14828 14829 public boolean isForwardLocked() { 14830 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 14831 } 14832 } 14833 14834 /** 14835 * Used during creation of InstallArgs 14836 * 14837 * @param installFlags package installation flags 14838 * @return true if should be installed on external storage 14839 */ 14840 private static boolean installOnExternalAsec(int installFlags) { 14841 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 14842 return false; 14843 } 14844 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 14845 return true; 14846 } 14847 return false; 14848 } 14849 14850 /** 14851 * Used during creation of InstallArgs 14852 * 14853 * @param installFlags package installation flags 14854 * @return true if should be installed as forward locked 14855 */ 14856 private static boolean installForwardLocked(int installFlags) { 14857 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 14858 } 14859 14860 private InstallArgs createInstallArgs(InstallParams params) { 14861 if (params.move != null) { 14862 return new MoveInstallArgs(params); 14863 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 14864 return new AsecInstallArgs(params); 14865 } else { 14866 return new FileInstallArgs(params); 14867 } 14868 } 14869 14870 /** 14871 * Create args that describe an existing installed package. Typically used 14872 * when cleaning up old installs, or used as a move source. 14873 */ 14874 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 14875 String resourcePath, String[] instructionSets) { 14876 final boolean isInAsec; 14877 if (installOnExternalAsec(installFlags)) { 14878 /* Apps on SD card are always in ASEC containers. */ 14879 isInAsec = true; 14880 } else if (installForwardLocked(installFlags) 14881 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 14882 /* 14883 * Forward-locked apps are only in ASEC containers if they're the 14884 * new style 14885 */ 14886 isInAsec = true; 14887 } else { 14888 isInAsec = false; 14889 } 14890 14891 if (isInAsec) { 14892 return new AsecInstallArgs(codePath, instructionSets, 14893 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 14894 } else { 14895 return new FileInstallArgs(codePath, resourcePath, instructionSets); 14896 } 14897 } 14898 14899 static abstract class InstallArgs { 14900 /** @see InstallParams#origin */ 14901 final OriginInfo origin; 14902 /** @see InstallParams#move */ 14903 final MoveInfo move; 14904 14905 final IPackageInstallObserver2 observer; 14906 // Always refers to PackageManager flags only 14907 final int installFlags; 14908 final String installerPackageName; 14909 final String volumeUuid; 14910 final UserHandle user; 14911 final String abiOverride; 14912 final String[] installGrantPermissions; 14913 /** If non-null, drop an async trace when the install completes */ 14914 final String traceMethod; 14915 final int traceCookie; 14916 final Certificate[][] certificates; 14917 final int installReason; 14918 14919 // The list of instruction sets supported by this app. This is currently 14920 // only used during the rmdex() phase to clean up resources. We can get rid of this 14921 // if we move dex files under the common app path. 14922 /* nullable */ String[] instructionSets; 14923 14924 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 14925 int installFlags, String installerPackageName, String volumeUuid, 14926 UserHandle user, String[] instructionSets, 14927 String abiOverride, String[] installGrantPermissions, 14928 String traceMethod, int traceCookie, Certificate[][] certificates, 14929 int installReason) { 14930 this.origin = origin; 14931 this.move = move; 14932 this.installFlags = installFlags; 14933 this.observer = observer; 14934 this.installerPackageName = installerPackageName; 14935 this.volumeUuid = volumeUuid; 14936 this.user = user; 14937 this.instructionSets = instructionSets; 14938 this.abiOverride = abiOverride; 14939 this.installGrantPermissions = installGrantPermissions; 14940 this.traceMethod = traceMethod; 14941 this.traceCookie = traceCookie; 14942 this.certificates = certificates; 14943 this.installReason = installReason; 14944 } 14945 14946 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 14947 abstract int doPreInstall(int status); 14948 14949 /** 14950 * Rename package into final resting place. All paths on the given 14951 * scanned package should be updated to reflect the rename. 14952 */ 14953 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 14954 abstract int doPostInstall(int status, int uid); 14955 14956 /** @see PackageSettingBase#codePathString */ 14957 abstract String getCodePath(); 14958 /** @see PackageSettingBase#resourcePathString */ 14959 abstract String getResourcePath(); 14960 14961 // Need installer lock especially for dex file removal. 14962 abstract void cleanUpResourcesLI(); 14963 abstract boolean doPostDeleteLI(boolean delete); 14964 14965 /** 14966 * Called before the source arguments are copied. This is used mostly 14967 * for MoveParams when it needs to read the source file to put it in the 14968 * destination. 14969 */ 14970 int doPreCopy() { 14971 return PackageManager.INSTALL_SUCCEEDED; 14972 } 14973 14974 /** 14975 * Called after the source arguments are copied. This is used mostly for 14976 * MoveParams when it needs to read the source file to put it in the 14977 * destination. 14978 */ 14979 int doPostCopy(int uid) { 14980 return PackageManager.INSTALL_SUCCEEDED; 14981 } 14982 14983 protected boolean isFwdLocked() { 14984 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 14985 } 14986 14987 protected boolean isExternalAsec() { 14988 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14989 } 14990 14991 protected boolean isEphemeral() { 14992 return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 14993 } 14994 14995 UserHandle getUser() { 14996 return user; 14997 } 14998 } 14999 15000 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 15001 if (!allCodePaths.isEmpty()) { 15002 if (instructionSets == null) { 15003 throw new IllegalStateException("instructionSet == null"); 15004 } 15005 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 15006 for (String codePath : allCodePaths) { 15007 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 15008 try { 15009 mInstaller.rmdex(codePath, dexCodeInstructionSet); 15010 } catch (InstallerException ignored) { 15011 } 15012 } 15013 } 15014 } 15015 } 15016 15017 /** 15018 * Logic to handle installation of non-ASEC applications, including copying 15019 * and renaming logic. 15020 */ 15021 class FileInstallArgs extends InstallArgs { 15022 private File codeFile; 15023 private File resourceFile; 15024 15025 // Example topology: 15026 // /data/app/com.example/base.apk 15027 // /data/app/com.example/split_foo.apk 15028 // /data/app/com.example/lib/arm/libfoo.so 15029 // /data/app/com.example/lib/arm64/libfoo.so 15030 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 15031 15032 /** New install */ 15033 FileInstallArgs(InstallParams params) { 15034 super(params.origin, params.move, params.observer, params.installFlags, 15035 params.installerPackageName, params.volumeUuid, 15036 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 15037 params.grantedRuntimePermissions, 15038 params.traceMethod, params.traceCookie, params.certificates, 15039 params.installReason); 15040 if (isFwdLocked()) { 15041 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 15042 } 15043 } 15044 15045 /** Existing install */ 15046 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 15047 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 15048 null, null, null, 0, null /*certificates*/, 15049 PackageManager.INSTALL_REASON_UNKNOWN); 15050 this.codeFile = (codePath != null) ? new File(codePath) : null; 15051 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 15052 } 15053 15054 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 15055 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 15056 try { 15057 return doCopyApk(imcs, temp); 15058 } finally { 15059 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15060 } 15061 } 15062 15063 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 15064 if (origin.staged) { 15065 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 15066 codeFile = origin.file; 15067 resourceFile = origin.file; 15068 return PackageManager.INSTALL_SUCCEEDED; 15069 } 15070 15071 try { 15072 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 15073 final File tempDir = 15074 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 15075 codeFile = tempDir; 15076 resourceFile = tempDir; 15077 } catch (IOException e) { 15078 Slog.w(TAG, "Failed to create copy file: " + e); 15079 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 15080 } 15081 15082 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 15083 @Override 15084 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 15085 if (!FileUtils.isValidExtFilename(name)) { 15086 throw new IllegalArgumentException("Invalid filename: " + name); 15087 } 15088 try { 15089 final File file = new File(codeFile, name); 15090 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 15091 O_RDWR | O_CREAT, 0644); 15092 Os.chmod(file.getAbsolutePath(), 0644); 15093 return new ParcelFileDescriptor(fd); 15094 } catch (ErrnoException e) { 15095 throw new RemoteException("Failed to open: " + e.getMessage()); 15096 } 15097 } 15098 }; 15099 15100 int ret = PackageManager.INSTALL_SUCCEEDED; 15101 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 15102 if (ret != PackageManager.INSTALL_SUCCEEDED) { 15103 Slog.e(TAG, "Failed to copy package"); 15104 return ret; 15105 } 15106 15107 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 15108 NativeLibraryHelper.Handle handle = null; 15109 try { 15110 handle = NativeLibraryHelper.Handle.create(codeFile); 15111 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 15112 abiOverride); 15113 } catch (IOException e) { 15114 Slog.e(TAG, "Copying native libraries failed", e); 15115 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15116 } finally { 15117 IoUtils.closeQuietly(handle); 15118 } 15119 15120 return ret; 15121 } 15122 15123 int doPreInstall(int status) { 15124 if (status != PackageManager.INSTALL_SUCCEEDED) { 15125 cleanUp(); 15126 } 15127 return status; 15128 } 15129 15130 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15131 if (status != PackageManager.INSTALL_SUCCEEDED) { 15132 cleanUp(); 15133 return false; 15134 } 15135 15136 final File targetDir = codeFile.getParentFile(); 15137 final File beforeCodeFile = codeFile; 15138 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 15139 15140 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 15141 try { 15142 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 15143 } catch (ErrnoException e) { 15144 Slog.w(TAG, "Failed to rename", e); 15145 return false; 15146 } 15147 15148 if (!SELinux.restoreconRecursive(afterCodeFile)) { 15149 Slog.w(TAG, "Failed to restorecon"); 15150 return false; 15151 } 15152 15153 // Reflect the rename internally 15154 codeFile = afterCodeFile; 15155 resourceFile = afterCodeFile; 15156 15157 // Reflect the rename in scanned details 15158 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 15159 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 15160 afterCodeFile, pkg.baseCodePath)); 15161 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 15162 afterCodeFile, pkg.splitCodePaths)); 15163 15164 // Reflect the rename in app info 15165 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15166 pkg.setApplicationInfoCodePath(pkg.codePath); 15167 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15168 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15169 pkg.setApplicationInfoResourcePath(pkg.codePath); 15170 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15171 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15172 15173 return true; 15174 } 15175 15176 int doPostInstall(int status, int uid) { 15177 if (status != PackageManager.INSTALL_SUCCEEDED) { 15178 cleanUp(); 15179 } 15180 return status; 15181 } 15182 15183 @Override 15184 String getCodePath() { 15185 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 15186 } 15187 15188 @Override 15189 String getResourcePath() { 15190 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 15191 } 15192 15193 private boolean cleanUp() { 15194 if (codeFile == null || !codeFile.exists()) { 15195 return false; 15196 } 15197 15198 removeCodePathLI(codeFile); 15199 15200 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 15201 resourceFile.delete(); 15202 } 15203 15204 return true; 15205 } 15206 15207 void cleanUpResourcesLI() { 15208 // Try enumerating all code paths before deleting 15209 List<String> allCodePaths = Collections.EMPTY_LIST; 15210 if (codeFile != null && codeFile.exists()) { 15211 try { 15212 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 15213 allCodePaths = pkg.getAllCodePaths(); 15214 } catch (PackageParserException e) { 15215 // Ignored; we tried our best 15216 } 15217 } 15218 15219 cleanUp(); 15220 removeDexFiles(allCodePaths, instructionSets); 15221 } 15222 15223 boolean doPostDeleteLI(boolean delete) { 15224 // XXX err, shouldn't we respect the delete flag? 15225 cleanUpResourcesLI(); 15226 return true; 15227 } 15228 } 15229 15230 private boolean isAsecExternal(String cid) { 15231 final String asecPath = PackageHelper.getSdFilesystem(cid); 15232 return !asecPath.startsWith(mAsecInternalPath); 15233 } 15234 15235 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 15236 PackageManagerException { 15237 if (copyRet < 0) { 15238 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 15239 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 15240 throw new PackageManagerException(copyRet, message); 15241 } 15242 } 15243 } 15244 15245 /** 15246 * Extract the StorageManagerService "container ID" from the full code path of an 15247 * .apk. 15248 */ 15249 static String cidFromCodePath(String fullCodePath) { 15250 int eidx = fullCodePath.lastIndexOf("/"); 15251 String subStr1 = fullCodePath.substring(0, eidx); 15252 int sidx = subStr1.lastIndexOf("/"); 15253 return subStr1.substring(sidx+1, eidx); 15254 } 15255 15256 /** 15257 * Logic to handle installation of ASEC applications, including copying and 15258 * renaming logic. 15259 */ 15260 class AsecInstallArgs extends InstallArgs { 15261 static final String RES_FILE_NAME = "pkg.apk"; 15262 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 15263 15264 String cid; 15265 String packagePath; 15266 String resourcePath; 15267 15268 /** New install */ 15269 AsecInstallArgs(InstallParams params) { 15270 super(params.origin, params.move, params.observer, params.installFlags, 15271 params.installerPackageName, params.volumeUuid, 15272 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 15273 params.grantedRuntimePermissions, 15274 params.traceMethod, params.traceCookie, params.certificates, 15275 params.installReason); 15276 } 15277 15278 /** Existing install */ 15279 AsecInstallArgs(String fullCodePath, String[] instructionSets, 15280 boolean isExternal, boolean isForwardLocked) { 15281 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 15282 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 15283 instructionSets, null, null, null, 0, null /*certificates*/, 15284 PackageManager.INSTALL_REASON_UNKNOWN); 15285 // Hackily pretend we're still looking at a full code path 15286 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 15287 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 15288 } 15289 15290 // Extract cid from fullCodePath 15291 int eidx = fullCodePath.lastIndexOf("/"); 15292 String subStr1 = fullCodePath.substring(0, eidx); 15293 int sidx = subStr1.lastIndexOf("/"); 15294 cid = subStr1.substring(sidx+1, eidx); 15295 setMountPath(subStr1); 15296 } 15297 15298 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 15299 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 15300 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 15301 instructionSets, null, null, null, 0, null /*certificates*/, 15302 PackageManager.INSTALL_REASON_UNKNOWN); 15303 this.cid = cid; 15304 setMountPath(PackageHelper.getSdDir(cid)); 15305 } 15306 15307 void createCopyFile() { 15308 cid = mInstallerService.allocateExternalStageCidLegacy(); 15309 } 15310 15311 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 15312 if (origin.staged && origin.cid != null) { 15313 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 15314 cid = origin.cid; 15315 setMountPath(PackageHelper.getSdDir(cid)); 15316 return PackageManager.INSTALL_SUCCEEDED; 15317 } 15318 15319 if (temp) { 15320 createCopyFile(); 15321 } else { 15322 /* 15323 * Pre-emptively destroy the container since it's destroyed if 15324 * copying fails due to it existing anyway. 15325 */ 15326 PackageHelper.destroySdDir(cid); 15327 } 15328 15329 final String newMountPath = imcs.copyPackageToContainer( 15330 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 15331 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 15332 15333 if (newMountPath != null) { 15334 setMountPath(newMountPath); 15335 return PackageManager.INSTALL_SUCCEEDED; 15336 } else { 15337 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15338 } 15339 } 15340 15341 @Override 15342 String getCodePath() { 15343 return packagePath; 15344 } 15345 15346 @Override 15347 String getResourcePath() { 15348 return resourcePath; 15349 } 15350 15351 int doPreInstall(int status) { 15352 if (status != PackageManager.INSTALL_SUCCEEDED) { 15353 // Destroy container 15354 PackageHelper.destroySdDir(cid); 15355 } else { 15356 boolean mounted = PackageHelper.isContainerMounted(cid); 15357 if (!mounted) { 15358 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 15359 Process.SYSTEM_UID); 15360 if (newMountPath != null) { 15361 setMountPath(newMountPath); 15362 } else { 15363 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15364 } 15365 } 15366 } 15367 return status; 15368 } 15369 15370 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15371 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 15372 String newMountPath = null; 15373 if (PackageHelper.isContainerMounted(cid)) { 15374 // Unmount the container 15375 if (!PackageHelper.unMountSdDir(cid)) { 15376 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 15377 return false; 15378 } 15379 } 15380 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 15381 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 15382 " which might be stale. Will try to clean up."); 15383 // Clean up the stale container and proceed to recreate. 15384 if (!PackageHelper.destroySdDir(newCacheId)) { 15385 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 15386 return false; 15387 } 15388 // Successfully cleaned up stale container. Try to rename again. 15389 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 15390 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 15391 + " inspite of cleaning it up."); 15392 return false; 15393 } 15394 } 15395 if (!PackageHelper.isContainerMounted(newCacheId)) { 15396 Slog.w(TAG, "Mounting container " + newCacheId); 15397 newMountPath = PackageHelper.mountSdDir(newCacheId, 15398 getEncryptKey(), Process.SYSTEM_UID); 15399 } else { 15400 newMountPath = PackageHelper.getSdDir(newCacheId); 15401 } 15402 if (newMountPath == null) { 15403 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 15404 return false; 15405 } 15406 Log.i(TAG, "Succesfully renamed " + cid + 15407 " to " + newCacheId + 15408 " at new path: " + newMountPath); 15409 cid = newCacheId; 15410 15411 final File beforeCodeFile = new File(packagePath); 15412 setMountPath(newMountPath); 15413 final File afterCodeFile = new File(packagePath); 15414 15415 // Reflect the rename in scanned details 15416 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 15417 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 15418 afterCodeFile, pkg.baseCodePath)); 15419 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 15420 afterCodeFile, pkg.splitCodePaths)); 15421 15422 // Reflect the rename in app info 15423 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15424 pkg.setApplicationInfoCodePath(pkg.codePath); 15425 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15426 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15427 pkg.setApplicationInfoResourcePath(pkg.codePath); 15428 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15429 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15430 15431 return true; 15432 } 15433 15434 private void setMountPath(String mountPath) { 15435 final File mountFile = new File(mountPath); 15436 15437 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 15438 if (monolithicFile.exists()) { 15439 packagePath = monolithicFile.getAbsolutePath(); 15440 if (isFwdLocked()) { 15441 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 15442 } else { 15443 resourcePath = packagePath; 15444 } 15445 } else { 15446 packagePath = mountFile.getAbsolutePath(); 15447 resourcePath = packagePath; 15448 } 15449 } 15450 15451 int doPostInstall(int status, int uid) { 15452 if (status != PackageManager.INSTALL_SUCCEEDED) { 15453 cleanUp(); 15454 } else { 15455 final int groupOwner; 15456 final String protectedFile; 15457 if (isFwdLocked()) { 15458 groupOwner = UserHandle.getSharedAppGid(uid); 15459 protectedFile = RES_FILE_NAME; 15460 } else { 15461 groupOwner = -1; 15462 protectedFile = null; 15463 } 15464 15465 if (uid < Process.FIRST_APPLICATION_UID 15466 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 15467 Slog.e(TAG, "Failed to finalize " + cid); 15468 PackageHelper.destroySdDir(cid); 15469 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15470 } 15471 15472 boolean mounted = PackageHelper.isContainerMounted(cid); 15473 if (!mounted) { 15474 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 15475 } 15476 } 15477 return status; 15478 } 15479 15480 private void cleanUp() { 15481 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 15482 15483 // Destroy secure container 15484 PackageHelper.destroySdDir(cid); 15485 } 15486 15487 private List<String> getAllCodePaths() { 15488 final File codeFile = new File(getCodePath()); 15489 if (codeFile != null && codeFile.exists()) { 15490 try { 15491 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 15492 return pkg.getAllCodePaths(); 15493 } catch (PackageParserException e) { 15494 // Ignored; we tried our best 15495 } 15496 } 15497 return Collections.EMPTY_LIST; 15498 } 15499 15500 void cleanUpResourcesLI() { 15501 // Enumerate all code paths before deleting 15502 cleanUpResourcesLI(getAllCodePaths()); 15503 } 15504 15505 private void cleanUpResourcesLI(List<String> allCodePaths) { 15506 cleanUp(); 15507 removeDexFiles(allCodePaths, instructionSets); 15508 } 15509 15510 String getPackageName() { 15511 return getAsecPackageName(cid); 15512 } 15513 15514 boolean doPostDeleteLI(boolean delete) { 15515 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 15516 final List<String> allCodePaths = getAllCodePaths(); 15517 boolean mounted = PackageHelper.isContainerMounted(cid); 15518 if (mounted) { 15519 // Unmount first 15520 if (PackageHelper.unMountSdDir(cid)) { 15521 mounted = false; 15522 } 15523 } 15524 if (!mounted && delete) { 15525 cleanUpResourcesLI(allCodePaths); 15526 } 15527 return !mounted; 15528 } 15529 15530 @Override 15531 int doPreCopy() { 15532 if (isFwdLocked()) { 15533 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 15534 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 15535 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15536 } 15537 } 15538 15539 return PackageManager.INSTALL_SUCCEEDED; 15540 } 15541 15542 @Override 15543 int doPostCopy(int uid) { 15544 if (isFwdLocked()) { 15545 if (uid < Process.FIRST_APPLICATION_UID 15546 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 15547 RES_FILE_NAME)) { 15548 Slog.e(TAG, "Failed to finalize " + cid); 15549 PackageHelper.destroySdDir(cid); 15550 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15551 } 15552 } 15553 15554 return PackageManager.INSTALL_SUCCEEDED; 15555 } 15556 } 15557 15558 /** 15559 * Logic to handle movement of existing installed applications. 15560 */ 15561 class MoveInstallArgs extends InstallArgs { 15562 private File codeFile; 15563 private File resourceFile; 15564 15565 /** New install */ 15566 MoveInstallArgs(InstallParams params) { 15567 super(params.origin, params.move, params.observer, params.installFlags, 15568 params.installerPackageName, params.volumeUuid, 15569 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 15570 params.grantedRuntimePermissions, 15571 params.traceMethod, params.traceCookie, params.certificates, 15572 params.installReason); 15573 } 15574 15575 int copyApk(IMediaContainerService imcs, boolean temp) { 15576 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 15577 + move.fromUuid + " to " + move.toUuid); 15578 synchronized (mInstaller) { 15579 try { 15580 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 15581 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 15582 } catch (InstallerException e) { 15583 Slog.w(TAG, "Failed to move app", e); 15584 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15585 } 15586 } 15587 15588 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 15589 resourceFile = codeFile; 15590 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 15591 15592 return PackageManager.INSTALL_SUCCEEDED; 15593 } 15594 15595 int doPreInstall(int status) { 15596 if (status != PackageManager.INSTALL_SUCCEEDED) { 15597 cleanUp(move.toUuid); 15598 } 15599 return status; 15600 } 15601 15602 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15603 if (status != PackageManager.INSTALL_SUCCEEDED) { 15604 cleanUp(move.toUuid); 15605 return false; 15606 } 15607 15608 // Reflect the move in app info 15609 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15610 pkg.setApplicationInfoCodePath(pkg.codePath); 15611 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15612 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15613 pkg.setApplicationInfoResourcePath(pkg.codePath); 15614 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15615 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15616 15617 return true; 15618 } 15619 15620 int doPostInstall(int status, int uid) { 15621 if (status == PackageManager.INSTALL_SUCCEEDED) { 15622 cleanUp(move.fromUuid); 15623 } else { 15624 cleanUp(move.toUuid); 15625 } 15626 return status; 15627 } 15628 15629 @Override 15630 String getCodePath() { 15631 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 15632 } 15633 15634 @Override 15635 String getResourcePath() { 15636 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 15637 } 15638 15639 private boolean cleanUp(String volumeUuid) { 15640 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 15641 move.dataAppName); 15642 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 15643 final int[] userIds = sUserManager.getUserIds(); 15644 synchronized (mInstallLock) { 15645 // Clean up both app data and code 15646 // All package moves are frozen until finished 15647 for (int userId : userIds) { 15648 try { 15649 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 15650 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 15651 } catch (InstallerException e) { 15652 Slog.w(TAG, String.valueOf(e)); 15653 } 15654 } 15655 removeCodePathLI(codeFile); 15656 } 15657 return true; 15658 } 15659 15660 void cleanUpResourcesLI() { 15661 throw new UnsupportedOperationException(); 15662 } 15663 15664 boolean doPostDeleteLI(boolean delete) { 15665 throw new UnsupportedOperationException(); 15666 } 15667 } 15668 15669 static String getAsecPackageName(String packageCid) { 15670 int idx = packageCid.lastIndexOf("-"); 15671 if (idx == -1) { 15672 return packageCid; 15673 } 15674 return packageCid.substring(0, idx); 15675 } 15676 15677 // Utility method used to create code paths based on package name and available index. 15678 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 15679 String idxStr = ""; 15680 int idx = 1; 15681 // Fall back to default value of idx=1 if prefix is not 15682 // part of oldCodePath 15683 if (oldCodePath != null) { 15684 String subStr = oldCodePath; 15685 // Drop the suffix right away 15686 if (suffix != null && subStr.endsWith(suffix)) { 15687 subStr = subStr.substring(0, subStr.length() - suffix.length()); 15688 } 15689 // If oldCodePath already contains prefix find out the 15690 // ending index to either increment or decrement. 15691 int sidx = subStr.lastIndexOf(prefix); 15692 if (sidx != -1) { 15693 subStr = subStr.substring(sidx + prefix.length()); 15694 if (subStr != null) { 15695 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 15696 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 15697 } 15698 try { 15699 idx = Integer.parseInt(subStr); 15700 if (idx <= 1) { 15701 idx++; 15702 } else { 15703 idx--; 15704 } 15705 } catch(NumberFormatException e) { 15706 } 15707 } 15708 } 15709 } 15710 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 15711 return prefix + idxStr; 15712 } 15713 15714 private File getNextCodePath(File targetDir, String packageName) { 15715 File result; 15716 SecureRandom random = new SecureRandom(); 15717 byte[] bytes = new byte[16]; 15718 do { 15719 random.nextBytes(bytes); 15720 String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP); 15721 result = new File(targetDir, packageName + "-" + suffix); 15722 } while (result.exists()); 15723 return result; 15724 } 15725 15726 // Utility method that returns the relative package path with respect 15727 // to the installation directory. Like say for /data/data/com.test-1.apk 15728 // string com.test-1 is returned. 15729 static String deriveCodePathName(String codePath) { 15730 if (codePath == null) { 15731 return null; 15732 } 15733 final File codeFile = new File(codePath); 15734 final String name = codeFile.getName(); 15735 if (codeFile.isDirectory()) { 15736 return name; 15737 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 15738 final int lastDot = name.lastIndexOf('.'); 15739 return name.substring(0, lastDot); 15740 } else { 15741 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 15742 return null; 15743 } 15744 } 15745 15746 static class PackageInstalledInfo { 15747 String name; 15748 int uid; 15749 // The set of users that originally had this package installed. 15750 int[] origUsers; 15751 // The set of users that now have this package installed. 15752 int[] newUsers; 15753 PackageParser.Package pkg; 15754 int returnCode; 15755 String returnMsg; 15756 PackageRemovedInfo removedInfo; 15757 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 15758 15759 public void setError(int code, String msg) { 15760 setReturnCode(code); 15761 setReturnMessage(msg); 15762 Slog.w(TAG, msg); 15763 } 15764 15765 public void setError(String msg, PackageParserException e) { 15766 setReturnCode(e.error); 15767 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 15768 Slog.w(TAG, msg, e); 15769 } 15770 15771 public void setError(String msg, PackageManagerException e) { 15772 returnCode = e.error; 15773 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 15774 Slog.w(TAG, msg, e); 15775 } 15776 15777 public void setReturnCode(int returnCode) { 15778 this.returnCode = returnCode; 15779 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15780 for (int i = 0; i < childCount; i++) { 15781 addedChildPackages.valueAt(i).returnCode = returnCode; 15782 } 15783 } 15784 15785 private void setReturnMessage(String returnMsg) { 15786 this.returnMsg = returnMsg; 15787 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15788 for (int i = 0; i < childCount; i++) { 15789 addedChildPackages.valueAt(i).returnMsg = returnMsg; 15790 } 15791 } 15792 15793 // In some error cases we want to convey more info back to the observer 15794 String origPackage; 15795 String origPermission; 15796 } 15797 15798 /* 15799 * Install a non-existing package. 15800 */ 15801 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 15802 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 15803 PackageInstalledInfo res, int installReason) { 15804 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 15805 15806 // Remember this for later, in case we need to rollback this install 15807 String pkgName = pkg.packageName; 15808 15809 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 15810 15811 synchronized(mPackages) { 15812 final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName); 15813 if (renamedPackage != null) { 15814 // A package with the same name is already installed, though 15815 // it has been renamed to an older name. The package we 15816 // are trying to install should be installed as an update to 15817 // the existing one, but that has not been requested, so bail. 15818 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 15819 + " without first uninstalling package running as " 15820 + renamedPackage); 15821 return; 15822 } 15823 if (mPackages.containsKey(pkgName)) { 15824 // Don't allow installation over an existing package with the same name. 15825 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 15826 + " without first uninstalling."); 15827 return; 15828 } 15829 } 15830 15831 try { 15832 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 15833 System.currentTimeMillis(), user); 15834 15835 updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason); 15836 15837 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 15838 prepareAppDataAfterInstallLIF(newPackage); 15839 15840 } else { 15841 // Remove package from internal structures, but keep around any 15842 // data that might have already existed 15843 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 15844 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 15845 } 15846 } catch (PackageManagerException e) { 15847 res.setError("Package couldn't be installed in " + pkg.codePath, e); 15848 } 15849 15850 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15851 } 15852 15853 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 15854 // Can't rotate keys during boot or if sharedUser. 15855 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 15856 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 15857 return false; 15858 } 15859 // app is using upgradeKeySets; make sure all are valid 15860 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15861 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 15862 for (int i = 0; i < upgradeKeySets.length; i++) { 15863 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 15864 Slog.wtf(TAG, "Package " 15865 + (oldPs.name != null ? oldPs.name : "<null>") 15866 + " contains upgrade-key-set reference to unknown key-set: " 15867 + upgradeKeySets[i] 15868 + " reverting to signatures check."); 15869 return false; 15870 } 15871 } 15872 return true; 15873 } 15874 15875 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 15876 // Upgrade keysets are being used. Determine if new package has a superset of the 15877 // required keys. 15878 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 15879 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15880 for (int i = 0; i < upgradeKeySets.length; i++) { 15881 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 15882 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 15883 return true; 15884 } 15885 } 15886 return false; 15887 } 15888 15889 private static void updateDigest(MessageDigest digest, File file) throws IOException { 15890 try (DigestInputStream digestStream = 15891 new DigestInputStream(new FileInputStream(file), digest)) { 15892 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 15893 } 15894 } 15895 15896 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 15897 UserHandle user, String installerPackageName, PackageInstalledInfo res, 15898 int installReason) { 15899 final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 15900 15901 final PackageParser.Package oldPackage; 15902 final String pkgName = pkg.packageName; 15903 final int[] allUsers; 15904 final int[] installedUsers; 15905 15906 synchronized(mPackages) { 15907 oldPackage = mPackages.get(pkgName); 15908 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 15909 15910 // don't allow upgrade to target a release SDK from a pre-release SDK 15911 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 15912 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 15913 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 15914 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 15915 if (oldTargetsPreRelease 15916 && !newTargetsPreRelease 15917 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 15918 Slog.w(TAG, "Can't install package targeting released sdk"); 15919 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 15920 return; 15921 } 15922 15923 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15924 15925 // don't allow an upgrade from full to ephemeral 15926 if (isInstantApp && !ps.getInstantApp(user.getIdentifier())) { 15927 // can't downgrade from full to instant 15928 Slog.w(TAG, "Can't replace app with instant app: " + pkgName); 15929 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 15930 return; 15931 } 15932 15933 // verify signatures are valid 15934 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 15935 if (!checkUpgradeKeySetLP(ps, pkg)) { 15936 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 15937 "New package not signed by keys specified by upgrade-keysets: " 15938 + pkgName); 15939 return; 15940 } 15941 } else { 15942 // default to original signature matching 15943 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 15944 != PackageManager.SIGNATURE_MATCH) { 15945 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 15946 "New package has a different signature: " + pkgName); 15947 return; 15948 } 15949 } 15950 15951 // don't allow a system upgrade unless the upgrade hash matches 15952 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 15953 byte[] digestBytes = null; 15954 try { 15955 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 15956 updateDigest(digest, new File(pkg.baseCodePath)); 15957 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 15958 for (String path : pkg.splitCodePaths) { 15959 updateDigest(digest, new File(path)); 15960 } 15961 } 15962 digestBytes = digest.digest(); 15963 } catch (NoSuchAlgorithmException | IOException e) { 15964 res.setError(INSTALL_FAILED_INVALID_APK, 15965 "Could not compute hash: " + pkgName); 15966 return; 15967 } 15968 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 15969 res.setError(INSTALL_FAILED_INVALID_APK, 15970 "New package fails restrict-update check: " + pkgName); 15971 return; 15972 } 15973 // retain upgrade restriction 15974 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 15975 } 15976 15977 // Check for shared user id changes 15978 String invalidPackageName = 15979 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 15980 if (invalidPackageName != null) { 15981 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 15982 "Package " + invalidPackageName + " tried to change user " 15983 + oldPackage.mSharedUserId); 15984 return; 15985 } 15986 15987 // In case of rollback, remember per-user/profile install state 15988 allUsers = sUserManager.getUserIds(); 15989 installedUsers = ps.queryInstalledUsers(allUsers, true); 15990 } 15991 15992 // Update what is removed 15993 res.removedInfo = new PackageRemovedInfo(); 15994 res.removedInfo.uid = oldPackage.applicationInfo.uid; 15995 res.removedInfo.removedPackage = oldPackage.packageName; 15996 res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null; 15997 res.removedInfo.isUpdate = true; 15998 res.removedInfo.origUsers = installedUsers; 15999 final PackageSetting ps = mSettings.getPackageLPr(pkgName); 16000 res.removedInfo.installReasons = new SparseArray<>(installedUsers.length); 16001 for (int i = 0; i < installedUsers.length; i++) { 16002 final int userId = installedUsers[i]; 16003 res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId)); 16004 } 16005 16006 final int childCount = (oldPackage.childPackages != null) 16007 ? oldPackage.childPackages.size() : 0; 16008 for (int i = 0; i < childCount; i++) { 16009 boolean childPackageUpdated = false; 16010 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 16011 final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 16012 if (res.addedChildPackages != null) { 16013 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 16014 if (childRes != null) { 16015 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 16016 childRes.removedInfo.removedPackage = childPkg.packageName; 16017 childRes.removedInfo.isUpdate = true; 16018 childRes.removedInfo.installReasons = res.removedInfo.installReasons; 16019 childPackageUpdated = true; 16020 } 16021 } 16022 if (!childPackageUpdated) { 16023 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 16024 childRemovedRes.removedPackage = childPkg.packageName; 16025 childRemovedRes.isUpdate = false; 16026 childRemovedRes.dataRemoved = true; 16027 synchronized (mPackages) { 16028 if (childPs != null) { 16029 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 16030 } 16031 } 16032 if (res.removedInfo.removedChildPackages == null) { 16033 res.removedInfo.removedChildPackages = new ArrayMap<>(); 16034 } 16035 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 16036 } 16037 } 16038 16039 boolean sysPkg = (isSystemApp(oldPackage)); 16040 if (sysPkg) { 16041 // Set the system/privileged flags as needed 16042 final boolean privileged = 16043 (oldPackage.applicationInfo.privateFlags 16044 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 16045 final int systemPolicyFlags = policyFlags 16046 | PackageParser.PARSE_IS_SYSTEM 16047 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 16048 16049 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 16050 user, allUsers, installerPackageName, res, installReason); 16051 } else { 16052 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 16053 user, allUsers, installerPackageName, res, installReason); 16054 } 16055 } 16056 16057 public List<String> getPreviousCodePaths(String packageName) { 16058 final PackageSetting ps = mSettings.mPackages.get(packageName); 16059 final List<String> result = new ArrayList<String>(); 16060 if (ps != null && ps.oldCodePaths != null) { 16061 result.addAll(ps.oldCodePaths); 16062 } 16063 return result; 16064 } 16065 16066 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 16067 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 16068 int[] allUsers, String installerPackageName, PackageInstalledInfo res, 16069 int installReason) { 16070 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 16071 + deletedPackage); 16072 16073 String pkgName = deletedPackage.packageName; 16074 boolean deletedPkg = true; 16075 boolean addedPkg = false; 16076 boolean updatedSettings = false; 16077 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 16078 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 16079 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 16080 16081 final long origUpdateTime = (pkg.mExtras != null) 16082 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 16083 16084 // First delete the existing package while retaining the data directory 16085 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 16086 res.removedInfo, true, pkg)) { 16087 // If the existing package wasn't successfully deleted 16088 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 16089 deletedPkg = false; 16090 } else { 16091 // Successfully deleted the old package; proceed with replace. 16092 16093 // If deleted package lived in a container, give users a chance to 16094 // relinquish resources before killing. 16095 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 16096 if (DEBUG_INSTALL) { 16097 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 16098 } 16099 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 16100 final ArrayList<String> pkgList = new ArrayList<String>(1); 16101 pkgList.add(deletedPackage.applicationInfo.packageName); 16102 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 16103 } 16104 16105 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 16106 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16107 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 16108 16109 try { 16110 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 16111 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 16112 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 16113 installReason); 16114 16115 // Update the in-memory copy of the previous code paths. 16116 PackageSetting ps = mSettings.mPackages.get(pkgName); 16117 if (!killApp) { 16118 if (ps.oldCodePaths == null) { 16119 ps.oldCodePaths = new ArraySet<>(); 16120 } 16121 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 16122 if (deletedPackage.splitCodePaths != null) { 16123 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 16124 } 16125 } else { 16126 ps.oldCodePaths = null; 16127 } 16128 if (ps.childPackageNames != null) { 16129 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 16130 final String childPkgName = ps.childPackageNames.get(i); 16131 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 16132 childPs.oldCodePaths = ps.oldCodePaths; 16133 } 16134 } 16135 // set instant app status, but, only if it's explicitly specified 16136 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 16137 final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0; 16138 setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp); 16139 prepareAppDataAfterInstallLIF(newPackage); 16140 addedPkg = true; 16141 } catch (PackageManagerException e) { 16142 res.setError("Package couldn't be installed in " + pkg.codePath, e); 16143 } 16144 } 16145 16146 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 16147 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 16148 16149 // Revert all internal state mutations and added folders for the failed install 16150 if (addedPkg) { 16151 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 16152 res.removedInfo, true, null); 16153 } 16154 16155 // Restore the old package 16156 if (deletedPkg) { 16157 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 16158 File restoreFile = new File(deletedPackage.codePath); 16159 // Parse old package 16160 boolean oldExternal = isExternal(deletedPackage); 16161 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 16162 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 16163 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 16164 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 16165 try { 16166 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 16167 null); 16168 } catch (PackageManagerException e) { 16169 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 16170 + e.getMessage()); 16171 return; 16172 } 16173 16174 synchronized (mPackages) { 16175 // Ensure the installer package name up to date 16176 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 16177 16178 // Update permissions for restored package 16179 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 16180 16181 mSettings.writeLPr(); 16182 } 16183 16184 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 16185 } 16186 } else { 16187 synchronized (mPackages) { 16188 PackageSetting ps = mSettings.getPackageLPr(pkg.packageName); 16189 if (ps != null) { 16190 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 16191 if (res.removedInfo.removedChildPackages != null) { 16192 final int childCount = res.removedInfo.removedChildPackages.size(); 16193 // Iterate in reverse as we may modify the collection 16194 for (int i = childCount - 1; i >= 0; i--) { 16195 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 16196 if (res.addedChildPackages.containsKey(childPackageName)) { 16197 res.removedInfo.removedChildPackages.removeAt(i); 16198 } else { 16199 PackageRemovedInfo childInfo = res.removedInfo 16200 .removedChildPackages.valueAt(i); 16201 childInfo.removedForAllUsers = mPackages.get( 16202 childInfo.removedPackage) == null; 16203 } 16204 } 16205 } 16206 } 16207 } 16208 } 16209 } 16210 16211 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 16212 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 16213 int[] allUsers, String installerPackageName, PackageInstalledInfo res, 16214 int installReason) { 16215 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 16216 + ", old=" + deletedPackage); 16217 16218 final boolean disabledSystem; 16219 16220 // Remove existing system package 16221 removePackageLI(deletedPackage, true); 16222 16223 synchronized (mPackages) { 16224 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 16225 } 16226 if (!disabledSystem) { 16227 // We didn't need to disable the .apk as a current system package, 16228 // which means we are replacing another update that is already 16229 // installed. We need to make sure to delete the older one's .apk. 16230 res.removedInfo.args = createInstallArgsForExisting(0, 16231 deletedPackage.applicationInfo.getCodePath(), 16232 deletedPackage.applicationInfo.getResourcePath(), 16233 getAppDexInstructionSets(deletedPackage.applicationInfo)); 16234 } else { 16235 res.removedInfo.args = null; 16236 } 16237 16238 // Successfully disabled the old package. Now proceed with re-installation 16239 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 16240 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16241 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 16242 16243 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16244 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 16245 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 16246 16247 PackageParser.Package newPackage = null; 16248 try { 16249 // Add the package to the internal data structures 16250 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 16251 16252 // Set the update and install times 16253 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 16254 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 16255 System.currentTimeMillis()); 16256 16257 // Update the package dynamic state if succeeded 16258 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 16259 // Now that the install succeeded make sure we remove data 16260 // directories for any child package the update removed. 16261 final int deletedChildCount = (deletedPackage.childPackages != null) 16262 ? deletedPackage.childPackages.size() : 0; 16263 final int newChildCount = (newPackage.childPackages != null) 16264 ? newPackage.childPackages.size() : 0; 16265 for (int i = 0; i < deletedChildCount; i++) { 16266 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 16267 boolean childPackageDeleted = true; 16268 for (int j = 0; j < newChildCount; j++) { 16269 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 16270 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 16271 childPackageDeleted = false; 16272 break; 16273 } 16274 } 16275 if (childPackageDeleted) { 16276 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 16277 deletedChildPkg.packageName); 16278 if (ps != null && res.removedInfo.removedChildPackages != null) { 16279 PackageRemovedInfo removedChildRes = res.removedInfo 16280 .removedChildPackages.get(deletedChildPkg.packageName); 16281 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 16282 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 16283 } 16284 } 16285 } 16286 16287 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 16288 installReason); 16289 prepareAppDataAfterInstallLIF(newPackage); 16290 } 16291 } catch (PackageManagerException e) { 16292 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 16293 res.setError("Package couldn't be installed in " + pkg.codePath, e); 16294 } 16295 16296 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 16297 // Re installation failed. Restore old information 16298 // Remove new pkg information 16299 if (newPackage != null) { 16300 removeInstalledPackageLI(newPackage, true); 16301 } 16302 // Add back the old system package 16303 try { 16304 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 16305 } catch (PackageManagerException e) { 16306 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 16307 } 16308 16309 synchronized (mPackages) { 16310 if (disabledSystem) { 16311 enableSystemPackageLPw(deletedPackage); 16312 } 16313 16314 // Ensure the installer package name up to date 16315 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 16316 16317 // Update permissions for restored package 16318 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 16319 16320 mSettings.writeLPr(); 16321 } 16322 16323 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 16324 + " after failed upgrade"); 16325 } 16326 } 16327 16328 /** 16329 * Checks whether the parent or any of the child packages have a change shared 16330 * user. For a package to be a valid update the shred users of the parent and 16331 * the children should match. We may later support changing child shared users. 16332 * @param oldPkg The updated package. 16333 * @param newPkg The update package. 16334 * @return The shared user that change between the versions. 16335 */ 16336 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 16337 PackageParser.Package newPkg) { 16338 // Check parent shared user 16339 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 16340 return newPkg.packageName; 16341 } 16342 // Check child shared users 16343 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 16344 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 16345 for (int i = 0; i < newChildCount; i++) { 16346 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 16347 // If this child was present, did it have the same shared user? 16348 for (int j = 0; j < oldChildCount; j++) { 16349 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 16350 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 16351 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 16352 return newChildPkg.packageName; 16353 } 16354 } 16355 } 16356 return null; 16357 } 16358 16359 private void removeNativeBinariesLI(PackageSetting ps) { 16360 // Remove the lib path for the parent package 16361 if (ps != null) { 16362 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 16363 // Remove the lib path for the child packages 16364 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 16365 for (int i = 0; i < childCount; i++) { 16366 PackageSetting childPs = null; 16367 synchronized (mPackages) { 16368 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 16369 } 16370 if (childPs != null) { 16371 NativeLibraryHelper.removeNativeBinariesLI(childPs 16372 .legacyNativeLibraryPathString); 16373 } 16374 } 16375 } 16376 } 16377 16378 private void enableSystemPackageLPw(PackageParser.Package pkg) { 16379 // Enable the parent package 16380 mSettings.enableSystemPackageLPw(pkg.packageName); 16381 // Enable the child packages 16382 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16383 for (int i = 0; i < childCount; i++) { 16384 PackageParser.Package childPkg = pkg.childPackages.get(i); 16385 mSettings.enableSystemPackageLPw(childPkg.packageName); 16386 } 16387 } 16388 16389 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 16390 PackageParser.Package newPkg) { 16391 // Disable the parent package (parent always replaced) 16392 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 16393 // Disable the child packages 16394 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 16395 for (int i = 0; i < childCount; i++) { 16396 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 16397 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 16398 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 16399 } 16400 return disabled; 16401 } 16402 16403 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 16404 String installerPackageName) { 16405 // Enable the parent package 16406 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 16407 // Enable the child packages 16408 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16409 for (int i = 0; i < childCount; i++) { 16410 PackageParser.Package childPkg = pkg.childPackages.get(i); 16411 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 16412 } 16413 } 16414 16415 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 16416 // Collect all used permissions in the UID 16417 ArraySet<String> usedPermissions = new ArraySet<>(); 16418 final int packageCount = su.packages.size(); 16419 for (int i = 0; i < packageCount; i++) { 16420 PackageSetting ps = su.packages.valueAt(i); 16421 if (ps.pkg == null) { 16422 continue; 16423 } 16424 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 16425 for (int j = 0; j < requestedPermCount; j++) { 16426 String permission = ps.pkg.requestedPermissions.get(j); 16427 BasePermission bp = mSettings.mPermissions.get(permission); 16428 if (bp != null) { 16429 usedPermissions.add(permission); 16430 } 16431 } 16432 } 16433 16434 PermissionsState permissionsState = su.getPermissionsState(); 16435 // Prune install permissions 16436 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 16437 final int installPermCount = installPermStates.size(); 16438 for (int i = installPermCount - 1; i >= 0; i--) { 16439 PermissionState permissionState = installPermStates.get(i); 16440 if (!usedPermissions.contains(permissionState.getName())) { 16441 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 16442 if (bp != null) { 16443 permissionsState.revokeInstallPermission(bp); 16444 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 16445 PackageManager.MASK_PERMISSION_FLAGS, 0); 16446 } 16447 } 16448 } 16449 16450 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 16451 16452 // Prune runtime permissions 16453 for (int userId : allUserIds) { 16454 List<PermissionState> runtimePermStates = permissionsState 16455 .getRuntimePermissionStates(userId); 16456 final int runtimePermCount = runtimePermStates.size(); 16457 for (int i = runtimePermCount - 1; i >= 0; i--) { 16458 PermissionState permissionState = runtimePermStates.get(i); 16459 if (!usedPermissions.contains(permissionState.getName())) { 16460 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 16461 if (bp != null) { 16462 permissionsState.revokeRuntimePermission(bp, userId); 16463 permissionsState.updatePermissionFlags(bp, userId, 16464 PackageManager.MASK_PERMISSION_FLAGS, 0); 16465 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 16466 runtimePermissionChangedUserIds, userId); 16467 } 16468 } 16469 } 16470 } 16471 16472 return runtimePermissionChangedUserIds; 16473 } 16474 16475 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 16476 int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) { 16477 // Update the parent package setting 16478 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 16479 res, user, installReason); 16480 // Update the child packages setting 16481 final int childCount = (newPackage.childPackages != null) 16482 ? newPackage.childPackages.size() : 0; 16483 for (int i = 0; i < childCount; i++) { 16484 PackageParser.Package childPackage = newPackage.childPackages.get(i); 16485 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 16486 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 16487 childRes.origUsers, childRes, user, installReason); 16488 } 16489 } 16490 16491 private void updateSettingsInternalLI(PackageParser.Package newPackage, 16492 String installerPackageName, int[] allUsers, int[] installedForUsers, 16493 PackageInstalledInfo res, UserHandle user, int installReason) { 16494 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 16495 16496 String pkgName = newPackage.packageName; 16497 synchronized (mPackages) { 16498 //write settings. the installStatus will be incomplete at this stage. 16499 //note that the new package setting would have already been 16500 //added to mPackages. It hasn't been persisted yet. 16501 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 16502 // TODO: Remove this write? It's also written at the end of this method 16503 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 16504 mSettings.writeLPr(); 16505 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16506 } 16507 16508 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 16509 synchronized (mPackages) { 16510 updatePermissionsLPw(newPackage.packageName, newPackage, 16511 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 16512 ? UPDATE_PERMISSIONS_ALL : 0)); 16513 // For system-bundled packages, we assume that installing an upgraded version 16514 // of the package implies that the user actually wants to run that new code, 16515 // so we enable the package. 16516 PackageSetting ps = mSettings.mPackages.get(pkgName); 16517 final int userId = user.getIdentifier(); 16518 if (ps != null) { 16519 if (isSystemApp(newPackage)) { 16520 if (DEBUG_INSTALL) { 16521 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 16522 } 16523 // Enable system package for requested users 16524 if (res.origUsers != null) { 16525 for (int origUserId : res.origUsers) { 16526 if (userId == UserHandle.USER_ALL || userId == origUserId) { 16527 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 16528 origUserId, installerPackageName); 16529 } 16530 } 16531 } 16532 // Also convey the prior install/uninstall state 16533 if (allUsers != null && installedForUsers != null) { 16534 for (int currentUserId : allUsers) { 16535 final boolean installed = ArrayUtils.contains( 16536 installedForUsers, currentUserId); 16537 if (DEBUG_INSTALL) { 16538 Slog.d(TAG, " user " + currentUserId + " => " + installed); 16539 } 16540 ps.setInstalled(installed, currentUserId); 16541 } 16542 // these install state changes will be persisted in the 16543 // upcoming call to mSettings.writeLPr(). 16544 } 16545 } 16546 // It's implied that when a user requests installation, they want the app to be 16547 // installed and enabled. 16548 if (userId != UserHandle.USER_ALL) { 16549 ps.setInstalled(true, userId); 16550 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 16551 } 16552 16553 // When replacing an existing package, preserve the original install reason for all 16554 // users that had the package installed before. 16555 final Set<Integer> previousUserIds = new ArraySet<>(); 16556 if (res.removedInfo != null && res.removedInfo.installReasons != null) { 16557 final int installReasonCount = res.removedInfo.installReasons.size(); 16558 for (int i = 0; i < installReasonCount; i++) { 16559 final int previousUserId = res.removedInfo.installReasons.keyAt(i); 16560 final int previousInstallReason = res.removedInfo.installReasons.valueAt(i); 16561 ps.setInstallReason(previousInstallReason, previousUserId); 16562 previousUserIds.add(previousUserId); 16563 } 16564 } 16565 16566 // Set install reason for users that are having the package newly installed. 16567 if (userId == UserHandle.USER_ALL) { 16568 for (int currentUserId : sUserManager.getUserIds()) { 16569 if (!previousUserIds.contains(currentUserId)) { 16570 ps.setInstallReason(installReason, currentUserId); 16571 } 16572 } 16573 } else if (!previousUserIds.contains(userId)) { 16574 ps.setInstallReason(installReason, userId); 16575 } 16576 mSettings.writeKernelMappingLPr(ps); 16577 } 16578 res.name = pkgName; 16579 res.uid = newPackage.applicationInfo.uid; 16580 res.pkg = newPackage; 16581 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 16582 mSettings.setInstallerPackageName(pkgName, installerPackageName); 16583 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16584 //to update install status 16585 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 16586 mSettings.writeLPr(); 16587 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16588 } 16589 16590 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16591 } 16592 16593 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 16594 try { 16595 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 16596 installPackageLI(args, res); 16597 } finally { 16598 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16599 } 16600 } 16601 16602 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 16603 final int installFlags = args.installFlags; 16604 final String installerPackageName = args.installerPackageName; 16605 final String volumeUuid = args.volumeUuid; 16606 final File tmpPackageFile = new File(args.getCodePath()); 16607 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 16608 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 16609 || (args.volumeUuid != null)); 16610 final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0); 16611 final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0); 16612 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 16613 boolean replace = false; 16614 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 16615 if (args.move != null) { 16616 // moving a complete application; perform an initial scan on the new install location 16617 scanFlags |= SCAN_INITIAL; 16618 } 16619 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 16620 scanFlags |= SCAN_DONT_KILL_APP; 16621 } 16622 if (instantApp) { 16623 scanFlags |= SCAN_AS_INSTANT_APP; 16624 } 16625 if (fullApp) { 16626 scanFlags |= SCAN_AS_FULL_APP; 16627 } 16628 16629 // Result object to be returned 16630 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16631 16632 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 16633 16634 // Sanity check 16635 if (instantApp && (forwardLocked || onExternal)) { 16636 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 16637 + " external=" + onExternal); 16638 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 16639 return; 16640 } 16641 16642 // Retrieve PackageSettings and parse package 16643 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 16644 | PackageParser.PARSE_ENFORCE_CODE 16645 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 16646 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 16647 | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0) 16648 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 16649 PackageParser pp = new PackageParser(); 16650 pp.setSeparateProcesses(mSeparateProcesses); 16651 pp.setDisplayMetrics(mMetrics); 16652 16653 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 16654 final PackageParser.Package pkg; 16655 try { 16656 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 16657 } catch (PackageParserException e) { 16658 res.setError("Failed parse during installPackageLI", e); 16659 return; 16660 } finally { 16661 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16662 } 16663 16664// // Ephemeral apps must have target SDK >= O. 16665// // TODO: Update conditional and error message when O gets locked down 16666// if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) { 16667// res.setError(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID, 16668// "Ephemeral apps must have target SDK version of at least O"); 16669// return; 16670// } 16671 16672 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16673 // Static shared libraries have synthetic package names 16674 renameStaticSharedLibraryPackage(pkg); 16675 16676 // No static shared libs on external storage 16677 if (onExternal) { 16678 Slog.i(TAG, "Static shared libs can only be installed on internal storage."); 16679 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 16680 "Packages declaring static-shared libs cannot be updated"); 16681 return; 16682 } 16683 } 16684 16685 // If we are installing a clustered package add results for the children 16686 if (pkg.childPackages != null) { 16687 synchronized (mPackages) { 16688 final int childCount = pkg.childPackages.size(); 16689 for (int i = 0; i < childCount; i++) { 16690 PackageParser.Package childPkg = pkg.childPackages.get(i); 16691 PackageInstalledInfo childRes = new PackageInstalledInfo(); 16692 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16693 childRes.pkg = childPkg; 16694 childRes.name = childPkg.packageName; 16695 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 16696 if (childPs != null) { 16697 childRes.origUsers = childPs.queryInstalledUsers( 16698 sUserManager.getUserIds(), true); 16699 } 16700 if ((mPackages.containsKey(childPkg.packageName))) { 16701 childRes.removedInfo = new PackageRemovedInfo(); 16702 childRes.removedInfo.removedPackage = childPkg.packageName; 16703 } 16704 if (res.addedChildPackages == null) { 16705 res.addedChildPackages = new ArrayMap<>(); 16706 } 16707 res.addedChildPackages.put(childPkg.packageName, childRes); 16708 } 16709 } 16710 } 16711 16712 // If package doesn't declare API override, mark that we have an install 16713 // time CPU ABI override. 16714 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 16715 pkg.cpuAbiOverride = args.abiOverride; 16716 } 16717 16718 String pkgName = res.name = pkg.packageName; 16719 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 16720 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 16721 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 16722 return; 16723 } 16724 } 16725 16726 try { 16727 // either use what we've been given or parse directly from the APK 16728 if (args.certificates != null) { 16729 try { 16730 PackageParser.populateCertificates(pkg, args.certificates); 16731 } catch (PackageParserException e) { 16732 // there was something wrong with the certificates we were given; 16733 // try to pull them from the APK 16734 PackageParser.collectCertificates(pkg, parseFlags); 16735 } 16736 } else { 16737 PackageParser.collectCertificates(pkg, parseFlags); 16738 } 16739 } catch (PackageParserException e) { 16740 res.setError("Failed collect during installPackageLI", e); 16741 return; 16742 } 16743 16744 // Get rid of all references to package scan path via parser. 16745 pp = null; 16746 String oldCodePath = null; 16747 boolean systemApp = false; 16748 synchronized (mPackages) { 16749 // Check if installing already existing package 16750 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 16751 String oldName = mSettings.getRenamedPackageLPr(pkgName); 16752 if (pkg.mOriginalPackages != null 16753 && pkg.mOriginalPackages.contains(oldName) 16754 && mPackages.containsKey(oldName)) { 16755 // This package is derived from an original package, 16756 // and this device has been updating from that original 16757 // name. We must continue using the original name, so 16758 // rename the new package here. 16759 pkg.setPackageName(oldName); 16760 pkgName = pkg.packageName; 16761 replace = true; 16762 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 16763 + oldName + " pkgName=" + pkgName); 16764 } else if (mPackages.containsKey(pkgName)) { 16765 // This package, under its official name, already exists 16766 // on the device; we should replace it. 16767 replace = true; 16768 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 16769 } 16770 16771 // Child packages are installed through the parent package 16772 if (pkg.parentPackage != null) { 16773 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 16774 "Package " + pkg.packageName + " is child of package " 16775 + pkg.parentPackage.parentPackage + ". Child packages " 16776 + "can be updated only through the parent package."); 16777 return; 16778 } 16779 16780 if (replace) { 16781 // Prevent apps opting out from runtime permissions 16782 PackageParser.Package oldPackage = mPackages.get(pkgName); 16783 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 16784 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 16785 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 16786 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 16787 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 16788 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 16789 + " doesn't support runtime permissions but the old" 16790 + " target SDK " + oldTargetSdk + " does."); 16791 return; 16792 } 16793 16794 // Prevent installing of child packages 16795 if (oldPackage.parentPackage != null) { 16796 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 16797 "Package " + pkg.packageName + " is child of package " 16798 + oldPackage.parentPackage + ". Child packages " 16799 + "can be updated only through the parent package."); 16800 return; 16801 } 16802 } 16803 } 16804 16805 PackageSetting ps = mSettings.mPackages.get(pkgName); 16806 if (ps != null) { 16807 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 16808 16809 // Static shared libs have same package with different versions where 16810 // we internally use a synthetic package name to allow multiple versions 16811 // of the same package, therefore we need to compare signatures against 16812 // the package setting for the latest library version. 16813 PackageSetting signatureCheckPs = ps; 16814 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16815 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg); 16816 if (libraryEntry != null) { 16817 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk); 16818 } 16819 } 16820 16821 // Quick sanity check that we're signed correctly if updating; 16822 // we'll check this again later when scanning, but we want to 16823 // bail early here before tripping over redefined permissions. 16824 if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) { 16825 if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) { 16826 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 16827 + pkg.packageName + " upgrade keys do not match the " 16828 + "previously installed version"); 16829 return; 16830 } 16831 } else { 16832 try { 16833 verifySignaturesLP(signatureCheckPs, pkg); 16834 } catch (PackageManagerException e) { 16835 res.setError(e.error, e.getMessage()); 16836 return; 16837 } 16838 } 16839 16840 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 16841 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 16842 systemApp = (ps.pkg.applicationInfo.flags & 16843 ApplicationInfo.FLAG_SYSTEM) != 0; 16844 } 16845 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 16846 } 16847 16848 // Check whether the newly-scanned package wants to define an already-defined perm 16849 int N = pkg.permissions.size(); 16850 for (int i = N-1; i >= 0; i--) { 16851 PackageParser.Permission perm = pkg.permissions.get(i); 16852 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 16853 if (bp != null) { 16854 // If the defining package is signed with our cert, it's okay. This 16855 // also includes the "updating the same package" case, of course. 16856 // "updating same package" could also involve key-rotation. 16857 final boolean sigsOk; 16858 if (bp.sourcePackage.equals(pkg.packageName) 16859 && (bp.packageSetting instanceof PackageSetting) 16860 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 16861 scanFlags))) { 16862 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 16863 } else { 16864 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 16865 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 16866 } 16867 if (!sigsOk) { 16868 // If the owning package is the system itself, we log but allow 16869 // install to proceed; we fail the install on all other permission 16870 // redefinitions. 16871 if (!bp.sourcePackage.equals("android")) { 16872 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 16873 + pkg.packageName + " attempting to redeclare permission " 16874 + perm.info.name + " already owned by " + bp.sourcePackage); 16875 res.origPermission = perm.info.name; 16876 res.origPackage = bp.sourcePackage; 16877 return; 16878 } else { 16879 Slog.w(TAG, "Package " + pkg.packageName 16880 + " attempting to redeclare system permission " 16881 + perm.info.name + "; ignoring new declaration"); 16882 pkg.permissions.remove(i); 16883 } 16884 } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) { 16885 // Prevent apps to change protection level to dangerous from any other 16886 // type as this would allow a privilege escalation where an app adds a 16887 // normal/signature permission in other app's group and later redefines 16888 // it as dangerous leading to the group auto-grant. 16889 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE) 16890 == PermissionInfo.PROTECTION_DANGEROUS) { 16891 if (bp != null && !bp.isRuntime()) { 16892 Slog.w(TAG, "Package " + pkg.packageName + " trying to change a " 16893 + "non-runtime permission " + perm.info.name 16894 + " to runtime; keeping old protection level"); 16895 perm.info.protectionLevel = bp.protectionLevel; 16896 } 16897 } 16898 } 16899 } 16900 } 16901 } 16902 16903 if (systemApp) { 16904 if (onExternal) { 16905 // Abort update; system app can't be replaced with app on sdcard 16906 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 16907 "Cannot install updates to system apps on sdcard"); 16908 return; 16909 } else if (instantApp) { 16910 // Abort update; system app can't be replaced with an instant app 16911 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID, 16912 "Cannot update a system app with an instant app"); 16913 return; 16914 } 16915 } 16916 16917 if (args.move != null) { 16918 // We did an in-place move, so dex is ready to roll 16919 scanFlags |= SCAN_NO_DEX; 16920 scanFlags |= SCAN_MOVE; 16921 16922 synchronized (mPackages) { 16923 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16924 if (ps == null) { 16925 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 16926 "Missing settings for moved package " + pkgName); 16927 } 16928 16929 // We moved the entire application as-is, so bring over the 16930 // previously derived ABI information. 16931 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 16932 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 16933 } 16934 16935 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 16936 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 16937 scanFlags |= SCAN_NO_DEX; 16938 16939 try { 16940 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 16941 args.abiOverride : pkg.cpuAbiOverride); 16942 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 16943 true /*extractLibs*/, mAppLib32InstallDir); 16944 } catch (PackageManagerException pme) { 16945 Slog.e(TAG, "Error deriving application ABI", pme); 16946 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 16947 return; 16948 } 16949 16950 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 16951 // Do not run PackageDexOptimizer through the local performDexOpt 16952 // method because `pkg` may not be in `mPackages` yet. 16953 // 16954 // Also, don't fail application installs if the dexopt step fails. 16955 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 16956 null /* instructionSets */, false /* checkProfiles */, 16957 getCompilerFilterForReason(REASON_INSTALL), 16958 getOrCreateCompilerPackageStats(pkg)); 16959 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16960 16961 // Notify BackgroundDexOptJobService that the package has been changed. 16962 // If this is an update of a package which used to fail to compile, 16963 // BDOS will remove it from its blacklist. 16964 // TODO: Layering violation 16965 BackgroundDexOptJobService.notifyPackageChanged(pkg.packageName); 16966 } 16967 16968 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 16969 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 16970 return; 16971 } 16972 16973 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 16974 16975 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 16976 "installPackageLI")) { 16977 if (replace) { 16978 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16979 // Static libs have a synthetic package name containing the version 16980 // and cannot be updated as an update would get a new package name, 16981 // unless this is the exact same version code which is useful for 16982 // development. 16983 PackageParser.Package existingPkg = mPackages.get(pkg.packageName); 16984 if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) { 16985 res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring " 16986 + "static-shared libs cannot be updated"); 16987 return; 16988 } 16989 } 16990 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 16991 installerPackageName, res, args.installReason); 16992 } else { 16993 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 16994 args.user, installerPackageName, volumeUuid, res, args.installReason); 16995 } 16996 } 16997 synchronized (mPackages) { 16998 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16999 if (ps != null) { 17000 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 17001 } 17002 17003 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 17004 for (int i = 0; i < childCount; i++) { 17005 PackageParser.Package childPkg = pkg.childPackages.get(i); 17006 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 17007 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 17008 if (childPs != null) { 17009 childRes.newUsers = childPs.queryInstalledUsers( 17010 sUserManager.getUserIds(), true); 17011 } 17012 } 17013 17014 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 17015 updateSequenceNumberLP(pkgName, res.newUsers); 17016 } 17017 } 17018 } 17019 17020 private void startIntentFilterVerifications(int userId, boolean replacing, 17021 PackageParser.Package pkg) { 17022 if (mIntentFilterVerifierComponent == null) { 17023 Slog.w(TAG, "No IntentFilter verification will not be done as " 17024 + "there is no IntentFilterVerifier available!"); 17025 return; 17026 } 17027 17028 final int verifierUid = getPackageUid( 17029 mIntentFilterVerifierComponent.getPackageName(), 17030 MATCH_DEBUG_TRIAGED_MISSING, 17031 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 17032 17033 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 17034 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 17035 mHandler.sendMessage(msg); 17036 17037 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 17038 for (int i = 0; i < childCount; i++) { 17039 PackageParser.Package childPkg = pkg.childPackages.get(i); 17040 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 17041 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 17042 mHandler.sendMessage(msg); 17043 } 17044 } 17045 17046 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 17047 PackageParser.Package pkg) { 17048 int size = pkg.activities.size(); 17049 if (size == 0) { 17050 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17051 "No activity, so no need to verify any IntentFilter!"); 17052 return; 17053 } 17054 17055 final boolean hasDomainURLs = hasDomainURLs(pkg); 17056 if (!hasDomainURLs) { 17057 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17058 "No domain URLs, so no need to verify any IntentFilter!"); 17059 return; 17060 } 17061 17062 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 17063 + " if any IntentFilter from the " + size 17064 + " Activities needs verification ..."); 17065 17066 int count = 0; 17067 final String packageName = pkg.packageName; 17068 17069 synchronized (mPackages) { 17070 // If this is a new install and we see that we've already run verification for this 17071 // package, we have nothing to do: it means the state was restored from backup. 17072 if (!replacing) { 17073 IntentFilterVerificationInfo ivi = 17074 mSettings.getIntentFilterVerificationLPr(packageName); 17075 if (ivi != null) { 17076 if (DEBUG_DOMAIN_VERIFICATION) { 17077 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 17078 + ivi.getStatusString()); 17079 } 17080 return; 17081 } 17082 } 17083 17084 // If any filters need to be verified, then all need to be. 17085 boolean needToVerify = false; 17086 for (PackageParser.Activity a : pkg.activities) { 17087 for (ActivityIntentInfo filter : a.intents) { 17088 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 17089 if (DEBUG_DOMAIN_VERIFICATION) { 17090 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 17091 } 17092 needToVerify = true; 17093 break; 17094 } 17095 } 17096 } 17097 17098 if (needToVerify) { 17099 final int verificationId = mIntentFilterVerificationToken++; 17100 for (PackageParser.Activity a : pkg.activities) { 17101 for (ActivityIntentInfo filter : a.intents) { 17102 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 17103 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17104 "Verification needed for IntentFilter:" + filter.toString()); 17105 mIntentFilterVerifier.addOneIntentFilterVerification( 17106 verifierUid, userId, verificationId, filter, packageName); 17107 count++; 17108 } 17109 } 17110 } 17111 } 17112 } 17113 17114 if (count > 0) { 17115 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 17116 + " IntentFilter verification" + (count > 1 ? "s" : "") 17117 + " for userId:" + userId); 17118 mIntentFilterVerifier.startVerifications(userId); 17119 } else { 17120 if (DEBUG_DOMAIN_VERIFICATION) { 17121 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 17122 } 17123 } 17124 } 17125 17126 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 17127 final ComponentName cn = filter.activity.getComponentName(); 17128 final String packageName = cn.getPackageName(); 17129 17130 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 17131 packageName); 17132 if (ivi == null) { 17133 return true; 17134 } 17135 int status = ivi.getStatus(); 17136 switch (status) { 17137 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 17138 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 17139 return true; 17140 17141 default: 17142 // Nothing to do 17143 return false; 17144 } 17145 } 17146 17147 private static boolean isMultiArch(ApplicationInfo info) { 17148 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 17149 } 17150 17151 private static boolean isExternal(PackageParser.Package pkg) { 17152 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 17153 } 17154 17155 private static boolean isExternal(PackageSetting ps) { 17156 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 17157 } 17158 17159 private static boolean isSystemApp(PackageParser.Package pkg) { 17160 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 17161 } 17162 17163 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 17164 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 17165 } 17166 17167 private static boolean hasDomainURLs(PackageParser.Package pkg) { 17168 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 17169 } 17170 17171 private static boolean isSystemApp(PackageSetting ps) { 17172 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 17173 } 17174 17175 private static boolean isUpdatedSystemApp(PackageSetting ps) { 17176 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 17177 } 17178 17179 private int packageFlagsToInstallFlags(PackageSetting ps) { 17180 int installFlags = 0; 17181 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 17182 // This existing package was an external ASEC install when we have 17183 // the external flag without a UUID 17184 installFlags |= PackageManager.INSTALL_EXTERNAL; 17185 } 17186 if (ps.isForwardLocked()) { 17187 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 17188 } 17189 return installFlags; 17190 } 17191 17192 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 17193 if (isExternal(pkg)) { 17194 if (TextUtils.isEmpty(pkg.volumeUuid)) { 17195 return StorageManager.UUID_PRIMARY_PHYSICAL; 17196 } else { 17197 return pkg.volumeUuid; 17198 } 17199 } else { 17200 return StorageManager.UUID_PRIVATE_INTERNAL; 17201 } 17202 } 17203 17204 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 17205 if (isExternal(pkg)) { 17206 if (TextUtils.isEmpty(pkg.volumeUuid)) { 17207 return mSettings.getExternalVersion(); 17208 } else { 17209 return mSettings.findOrCreateVersion(pkg.volumeUuid); 17210 } 17211 } else { 17212 return mSettings.getInternalVersion(); 17213 } 17214 } 17215 17216 private void deleteTempPackageFiles() { 17217 final FilenameFilter filter = new FilenameFilter() { 17218 public boolean accept(File dir, String name) { 17219 return name.startsWith("vmdl") && name.endsWith(".tmp"); 17220 } 17221 }; 17222 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 17223 file.delete(); 17224 } 17225 } 17226 17227 @Override 17228 public void deletePackageAsUser(String packageName, int versionCode, 17229 IPackageDeleteObserver observer, int userId, int flags) { 17230 deletePackageVersioned(new VersionedPackage(packageName, versionCode), 17231 new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags); 17232 } 17233 17234 @Override 17235 public void deletePackageVersioned(VersionedPackage versionedPackage, 17236 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 17237 mContext.enforceCallingOrSelfPermission( 17238 android.Manifest.permission.DELETE_PACKAGES, null); 17239 Preconditions.checkNotNull(versionedPackage); 17240 Preconditions.checkNotNull(observer); 17241 Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(), 17242 PackageManager.VERSION_CODE_HIGHEST, 17243 Integer.MAX_VALUE, "versionCode must be >= -1"); 17244 17245 final String packageName = versionedPackage.getPackageName(); 17246 // TODO: We will change version code to long, so in the new API it is long 17247 final int versionCode = (int) versionedPackage.getVersionCode(); 17248 final String internalPackageName; 17249 synchronized (mPackages) { 17250 // Normalize package name to handle renamed packages and static libs 17251 internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(), 17252 // TODO: We will change version code to long, so in the new API it is long 17253 (int) versionedPackage.getVersionCode()); 17254 } 17255 17256 final int uid = Binder.getCallingUid(); 17257 if (!isOrphaned(internalPackageName) 17258 && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) { 17259 try { 17260 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 17261 intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null)); 17262 intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder()); 17263 observer.onUserActionRequired(intent); 17264 } catch (RemoteException re) { 17265 } 17266 return; 17267 } 17268 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 17269 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 17270 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 17271 mContext.enforceCallingOrSelfPermission( 17272 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 17273 "deletePackage for user " + userId); 17274 } 17275 17276 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 17277 try { 17278 observer.onPackageDeleted(packageName, 17279 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 17280 } catch (RemoteException re) { 17281 } 17282 return; 17283 } 17284 17285 if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) { 17286 try { 17287 observer.onPackageDeleted(packageName, 17288 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 17289 } catch (RemoteException re) { 17290 } 17291 return; 17292 } 17293 17294 if (DEBUG_REMOVE) { 17295 Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId 17296 + " deleteAllUsers: " + deleteAllUsers + " version=" 17297 + (versionCode == PackageManager.VERSION_CODE_HIGHEST 17298 ? "VERSION_CODE_HIGHEST" : versionCode)); 17299 } 17300 // Queue up an async operation since the package deletion may take a little while. 17301 mHandler.post(new Runnable() { 17302 public void run() { 17303 mHandler.removeCallbacks(this); 17304 int returnCode; 17305 if (!deleteAllUsers) { 17306 returnCode = deletePackageX(internalPackageName, versionCode, 17307 userId, deleteFlags); 17308 } else { 17309 int[] blockUninstallUserIds = getBlockUninstallForUsers( 17310 internalPackageName, users); 17311 // If nobody is blocking uninstall, proceed with delete for all users 17312 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 17313 returnCode = deletePackageX(internalPackageName, versionCode, 17314 userId, deleteFlags); 17315 } else { 17316 // Otherwise uninstall individually for users with blockUninstalls=false 17317 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 17318 for (int userId : users) { 17319 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 17320 returnCode = deletePackageX(internalPackageName, versionCode, 17321 userId, userFlags); 17322 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 17323 Slog.w(TAG, "Package delete failed for user " + userId 17324 + ", returnCode " + returnCode); 17325 } 17326 } 17327 } 17328 // The app has only been marked uninstalled for certain users. 17329 // We still need to report that delete was blocked 17330 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 17331 } 17332 } 17333 try { 17334 observer.onPackageDeleted(packageName, returnCode, null); 17335 } catch (RemoteException e) { 17336 Log.i(TAG, "Observer no longer exists."); 17337 } //end catch 17338 } //end run 17339 }); 17340 } 17341 17342 private String resolveExternalPackageNameLPr(PackageParser.Package pkg) { 17343 if (pkg.staticSharedLibName != null) { 17344 return pkg.manifestPackageName; 17345 } 17346 return pkg.packageName; 17347 } 17348 17349 private String resolveInternalPackageNameLPr(String packageName, int versionCode) { 17350 // Handle renamed packages 17351 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 17352 packageName = normalizedPackageName != null ? normalizedPackageName : packageName; 17353 17354 // Is this a static library? 17355 SparseArray<SharedLibraryEntry> versionedLib = 17356 mStaticLibsByDeclaringPackage.get(packageName); 17357 if (versionedLib == null || versionedLib.size() <= 0) { 17358 return packageName; 17359 } 17360 17361 // Figure out which lib versions the caller can see 17362 SparseIntArray versionsCallerCanSee = null; 17363 final int callingAppId = UserHandle.getAppId(Binder.getCallingUid()); 17364 if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID 17365 && callingAppId != Process.ROOT_UID) { 17366 versionsCallerCanSee = new SparseIntArray(); 17367 String libName = versionedLib.valueAt(0).info.getName(); 17368 String[] uidPackages = getPackagesForUid(Binder.getCallingUid()); 17369 if (uidPackages != null) { 17370 for (String uidPackage : uidPackages) { 17371 PackageSetting ps = mSettings.getPackageLPr(uidPackage); 17372 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 17373 if (libIdx >= 0) { 17374 final int libVersion = ps.usesStaticLibrariesVersions[libIdx]; 17375 versionsCallerCanSee.append(libVersion, libVersion); 17376 } 17377 } 17378 } 17379 } 17380 17381 // Caller can see nothing - done 17382 if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) { 17383 return packageName; 17384 } 17385 17386 // Find the version the caller can see and the app version code 17387 SharedLibraryEntry highestVersion = null; 17388 final int versionCount = versionedLib.size(); 17389 for (int i = 0; i < versionCount; i++) { 17390 SharedLibraryEntry libEntry = versionedLib.valueAt(i); 17391 if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey( 17392 libEntry.info.getVersion()) < 0) { 17393 continue; 17394 } 17395 // TODO: We will change version code to long, so in the new API it is long 17396 final int libVersionCode = (int) libEntry.info.getDeclaringPackage().getVersionCode(); 17397 if (versionCode != PackageManager.VERSION_CODE_HIGHEST) { 17398 if (libVersionCode == versionCode) { 17399 return libEntry.apk; 17400 } 17401 } else if (highestVersion == null) { 17402 highestVersion = libEntry; 17403 } else if (libVersionCode > highestVersion.info 17404 .getDeclaringPackage().getVersionCode()) { 17405 highestVersion = libEntry; 17406 } 17407 } 17408 17409 if (highestVersion != null) { 17410 return highestVersion.apk; 17411 } 17412 17413 return packageName; 17414 } 17415 17416 private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) { 17417 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID 17418 || callingUid == Process.SYSTEM_UID) { 17419 return true; 17420 } 17421 final int callingUserId = UserHandle.getUserId(callingUid); 17422 // If the caller installed the pkgName, then allow it to silently uninstall. 17423 if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) { 17424 return true; 17425 } 17426 17427 // Allow package verifier to silently uninstall. 17428 if (mRequiredVerifierPackage != null && 17429 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) { 17430 return true; 17431 } 17432 17433 // Allow package uninstaller to silently uninstall. 17434 if (mRequiredUninstallerPackage != null && 17435 callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) { 17436 return true; 17437 } 17438 17439 // Allow storage manager to silently uninstall. 17440 if (mStorageManagerPackage != null && 17441 callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) { 17442 return true; 17443 } 17444 return false; 17445 } 17446 17447 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 17448 int[] result = EMPTY_INT_ARRAY; 17449 for (int userId : userIds) { 17450 if (getBlockUninstallForUser(packageName, userId)) { 17451 result = ArrayUtils.appendInt(result, userId); 17452 } 17453 } 17454 return result; 17455 } 17456 17457 @Override 17458 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 17459 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 17460 } 17461 17462 private boolean isPackageDeviceAdmin(String packageName, int userId) { 17463 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 17464 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 17465 try { 17466 if (dpm != null) { 17467 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 17468 /* callingUserOnly =*/ false); 17469 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 17470 : deviceOwnerComponentName.getPackageName(); 17471 // Does the package contains the device owner? 17472 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 17473 // this check is probably not needed, since DO should be registered as a device 17474 // admin on some user too. (Original bug for this: b/17657954) 17475 if (packageName.equals(deviceOwnerPackageName)) { 17476 return true; 17477 } 17478 // Does it contain a device admin for any user? 17479 int[] users; 17480 if (userId == UserHandle.USER_ALL) { 17481 users = sUserManager.getUserIds(); 17482 } else { 17483 users = new int[]{userId}; 17484 } 17485 for (int i = 0; i < users.length; ++i) { 17486 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 17487 return true; 17488 } 17489 } 17490 } 17491 } catch (RemoteException e) { 17492 } 17493 return false; 17494 } 17495 17496 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 17497 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 17498 } 17499 17500 /** 17501 * This method is an internal method that could be get invoked either 17502 * to delete an installed package or to clean up a failed installation. 17503 * After deleting an installed package, a broadcast is sent to notify any 17504 * listeners that the package has been removed. For cleaning up a failed 17505 * installation, the broadcast is not necessary since the package's 17506 * installation wouldn't have sent the initial broadcast either 17507 * The key steps in deleting a package are 17508 * deleting the package information in internal structures like mPackages, 17509 * deleting the packages base directories through installd 17510 * updating mSettings to reflect current status 17511 * persisting settings for later use 17512 * sending a broadcast if necessary 17513 */ 17514 private int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) { 17515 final PackageRemovedInfo info = new PackageRemovedInfo(); 17516 final boolean res; 17517 17518 final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 17519 ? UserHandle.USER_ALL : userId; 17520 17521 if (isPackageDeviceAdmin(packageName, removeUser)) { 17522 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 17523 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 17524 } 17525 17526 PackageSetting uninstalledPs = null; 17527 17528 // for the uninstall-updates case and restricted profiles, remember the per- 17529 // user handle installed state 17530 int[] allUsers; 17531 synchronized (mPackages) { 17532 uninstalledPs = mSettings.mPackages.get(packageName); 17533 if (uninstalledPs == null) { 17534 Slog.w(TAG, "Not removing non-existent package " + packageName); 17535 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17536 } 17537 17538 if (versionCode != PackageManager.VERSION_CODE_HIGHEST 17539 && uninstalledPs.versionCode != versionCode) { 17540 Slog.w(TAG, "Not removing package " + packageName + " with versionCode " 17541 + uninstalledPs.versionCode + " != " + versionCode); 17542 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17543 } 17544 17545 // Static shared libs can be declared by any package, so let us not 17546 // allow removing a package if it provides a lib others depend on. 17547 PackageParser.Package pkg = mPackages.get(packageName); 17548 if (pkg != null && pkg.staticSharedLibName != null) { 17549 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName, 17550 pkg.staticSharedLibVersion); 17551 if (libEntry != null) { 17552 List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr( 17553 libEntry.info, 0, userId); 17554 if (!ArrayUtils.isEmpty(libClientPackages)) { 17555 Slog.w(TAG, "Not removing package " + pkg.manifestPackageName 17556 + " hosting lib " + libEntry.info.getName() + " version " 17557 + libEntry.info.getVersion() + " used by " + libClientPackages); 17558 return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY; 17559 } 17560 } 17561 } 17562 17563 allUsers = sUserManager.getUserIds(); 17564 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 17565 } 17566 17567 final int freezeUser; 17568 if (isUpdatedSystemApp(uninstalledPs) 17569 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) { 17570 // We're downgrading a system app, which will apply to all users, so 17571 // freeze them all during the downgrade 17572 freezeUser = UserHandle.USER_ALL; 17573 } else { 17574 freezeUser = removeUser; 17575 } 17576 17577 synchronized (mInstallLock) { 17578 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 17579 try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser, 17580 deleteFlags, "deletePackageX")) { 17581 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers, 17582 deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null); 17583 } 17584 synchronized (mPackages) { 17585 if (res) { 17586 mInstantAppRegistry.onPackageUninstalledLPw(uninstalledPs.pkg, 17587 info.removedUsers); 17588 updateSequenceNumberLP(packageName, info.removedUsers); 17589 } 17590 } 17591 } 17592 17593 if (res) { 17594 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 17595 info.sendPackageRemovedBroadcasts(killApp); 17596 info.sendSystemPackageUpdatedBroadcasts(); 17597 info.sendSystemPackageAppearedBroadcasts(); 17598 } 17599 // Force a gc here. 17600 Runtime.getRuntime().gc(); 17601 // Delete the resources here after sending the broadcast to let 17602 // other processes clean up before deleting resources. 17603 if (info.args != null) { 17604 synchronized (mInstallLock) { 17605 info.args.doPostDeleteLI(true); 17606 } 17607 } 17608 17609 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17610 } 17611 17612 class PackageRemovedInfo { 17613 String removedPackage; 17614 int uid = -1; 17615 int removedAppId = -1; 17616 int[] origUsers; 17617 int[] removedUsers = null; 17618 SparseArray<Integer> installReasons; 17619 boolean isRemovedPackageSystemUpdate = false; 17620 boolean isUpdate; 17621 boolean dataRemoved; 17622 boolean removedForAllUsers; 17623 boolean isStaticSharedLib; 17624 // Clean up resources deleted packages. 17625 InstallArgs args = null; 17626 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 17627 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 17628 17629 void sendPackageRemovedBroadcasts(boolean killApp) { 17630 sendPackageRemovedBroadcastInternal(killApp); 17631 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 17632 for (int i = 0; i < childCount; i++) { 17633 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 17634 childInfo.sendPackageRemovedBroadcastInternal(killApp); 17635 } 17636 } 17637 17638 void sendSystemPackageUpdatedBroadcasts() { 17639 if (isRemovedPackageSystemUpdate) { 17640 sendSystemPackageUpdatedBroadcastsInternal(); 17641 final int childCount = (removedChildPackages != null) 17642 ? removedChildPackages.size() : 0; 17643 for (int i = 0; i < childCount; i++) { 17644 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 17645 if (childInfo.isRemovedPackageSystemUpdate) { 17646 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 17647 } 17648 } 17649 } 17650 } 17651 17652 void sendSystemPackageAppearedBroadcasts() { 17653 final int packageCount = (appearedChildPackages != null) 17654 ? appearedChildPackages.size() : 0; 17655 for (int i = 0; i < packageCount; i++) { 17656 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 17657 sendPackageAddedForNewUsers(installedInfo.name, true, 17658 UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers); 17659 } 17660 } 17661 17662 private void sendSystemPackageUpdatedBroadcastsInternal() { 17663 Bundle extras = new Bundle(2); 17664 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 17665 extras.putBoolean(Intent.EXTRA_REPLACING, true); 17666 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 17667 extras, 0, null, null, null); 17668 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 17669 extras, 0, null, null, null); 17670 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 17671 null, 0, removedPackage, null, null); 17672 } 17673 17674 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 17675 // Don't send static shared library removal broadcasts as these 17676 // libs are visible only the the apps that depend on them an one 17677 // cannot remove the library if it has a dependency. 17678 if (isStaticSharedLib) { 17679 return; 17680 } 17681 Bundle extras = new Bundle(2); 17682 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 17683 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 17684 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 17685 if (isUpdate || isRemovedPackageSystemUpdate) { 17686 extras.putBoolean(Intent.EXTRA_REPLACING, true); 17687 } 17688 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 17689 if (removedPackage != null) { 17690 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 17691 extras, 0, null, null, removedUsers); 17692 if (dataRemoved && !isRemovedPackageSystemUpdate) { 17693 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 17694 removedPackage, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, 17695 null, null, removedUsers); 17696 } 17697 } 17698 if (removedAppId >= 0) { 17699 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 17700 removedUsers); 17701 } 17702 } 17703 } 17704 17705 /* 17706 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 17707 * flag is not set, the data directory is removed as well. 17708 * make sure this flag is set for partially installed apps. If not its meaningless to 17709 * delete a partially installed application. 17710 */ 17711 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 17712 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 17713 String packageName = ps.name; 17714 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 17715 // Retrieve object to delete permissions for shared user later on 17716 final PackageParser.Package deletedPkg; 17717 final PackageSetting deletedPs; 17718 // reader 17719 synchronized (mPackages) { 17720 deletedPkg = mPackages.get(packageName); 17721 deletedPs = mSettings.mPackages.get(packageName); 17722 if (outInfo != null) { 17723 outInfo.removedPackage = packageName; 17724 outInfo.isStaticSharedLib = deletedPkg != null 17725 && deletedPkg.staticSharedLibName != null; 17726 outInfo.removedUsers = deletedPs != null 17727 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 17728 : null; 17729 } 17730 } 17731 17732 removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0); 17733 17734 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 17735 final PackageParser.Package resolvedPkg; 17736 if (deletedPkg != null) { 17737 resolvedPkg = deletedPkg; 17738 } else { 17739 // We don't have a parsed package when it lives on an ejected 17740 // adopted storage device, so fake something together 17741 resolvedPkg = new PackageParser.Package(ps.name); 17742 resolvedPkg.setVolumeUuid(ps.volumeUuid); 17743 } 17744 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 17745 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 17746 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 17747 if (outInfo != null) { 17748 outInfo.dataRemoved = true; 17749 } 17750 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 17751 } 17752 17753 int removedAppId = -1; 17754 17755 // writer 17756 synchronized (mPackages) { 17757 boolean installedStateChanged = false; 17758 if (deletedPs != null) { 17759 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 17760 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 17761 clearDefaultBrowserIfNeeded(packageName); 17762 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 17763 removedAppId = mSettings.removePackageLPw(packageName); 17764 if (outInfo != null) { 17765 outInfo.removedAppId = removedAppId; 17766 } 17767 updatePermissionsLPw(deletedPs.name, null, 0); 17768 if (deletedPs.sharedUser != null) { 17769 // Remove permissions associated with package. Since runtime 17770 // permissions are per user we have to kill the removed package 17771 // or packages running under the shared user of the removed 17772 // package if revoking the permissions requested only by the removed 17773 // package is successful and this causes a change in gids. 17774 for (int userId : UserManagerService.getInstance().getUserIds()) { 17775 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 17776 userId); 17777 if (userIdToKill == UserHandle.USER_ALL 17778 || userIdToKill >= UserHandle.USER_SYSTEM) { 17779 // If gids changed for this user, kill all affected packages. 17780 mHandler.post(new Runnable() { 17781 @Override 17782 public void run() { 17783 // This has to happen with no lock held. 17784 killApplication(deletedPs.name, deletedPs.appId, 17785 KILL_APP_REASON_GIDS_CHANGED); 17786 } 17787 }); 17788 break; 17789 } 17790 } 17791 } 17792 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 17793 } 17794 // make sure to preserve per-user disabled state if this removal was just 17795 // a downgrade of a system app to the factory package 17796 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 17797 if (DEBUG_REMOVE) { 17798 Slog.d(TAG, "Propagating install state across downgrade"); 17799 } 17800 for (int userId : allUserHandles) { 17801 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 17802 if (DEBUG_REMOVE) { 17803 Slog.d(TAG, " user " + userId + " => " + installed); 17804 } 17805 if (installed != ps.getInstalled(userId)) { 17806 installedStateChanged = true; 17807 } 17808 ps.setInstalled(installed, userId); 17809 } 17810 } 17811 } 17812 // can downgrade to reader 17813 if (writeSettings) { 17814 // Save settings now 17815 mSettings.writeLPr(); 17816 } 17817 if (installedStateChanged) { 17818 mSettings.writeKernelMappingLPr(ps); 17819 } 17820 } 17821 if (removedAppId != -1) { 17822 // A user ID was deleted here. Go through all users and remove it 17823 // from KeyStore. 17824 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId); 17825 } 17826 } 17827 17828 static boolean locationIsPrivileged(File path) { 17829 try { 17830 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 17831 .getCanonicalPath(); 17832 return path.getCanonicalPath().startsWith(privilegedAppDir); 17833 } catch (IOException e) { 17834 Slog.e(TAG, "Unable to access code path " + path); 17835 } 17836 return false; 17837 } 17838 17839 /* 17840 * Tries to delete system package. 17841 */ 17842 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 17843 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 17844 boolean writeSettings) { 17845 if (deletedPs.parentPackageName != null) { 17846 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 17847 return false; 17848 } 17849 17850 final boolean applyUserRestrictions 17851 = (allUserHandles != null) && (outInfo.origUsers != null); 17852 final PackageSetting disabledPs; 17853 // Confirm if the system package has been updated 17854 // An updated system app can be deleted. This will also have to restore 17855 // the system pkg from system partition 17856 // reader 17857 synchronized (mPackages) { 17858 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 17859 } 17860 17861 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 17862 + " disabledPs=" + disabledPs); 17863 17864 if (disabledPs == null) { 17865 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 17866 return false; 17867 } else if (DEBUG_REMOVE) { 17868 Slog.d(TAG, "Deleting system pkg from data partition"); 17869 } 17870 17871 if (DEBUG_REMOVE) { 17872 if (applyUserRestrictions) { 17873 Slog.d(TAG, "Remembering install states:"); 17874 for (int userId : allUserHandles) { 17875 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 17876 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 17877 } 17878 } 17879 } 17880 17881 // Delete the updated package 17882 outInfo.isRemovedPackageSystemUpdate = true; 17883 if (outInfo.removedChildPackages != null) { 17884 final int childCount = (deletedPs.childPackageNames != null) 17885 ? deletedPs.childPackageNames.size() : 0; 17886 for (int i = 0; i < childCount; i++) { 17887 String childPackageName = deletedPs.childPackageNames.get(i); 17888 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 17889 .contains(childPackageName)) { 17890 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 17891 childPackageName); 17892 if (childInfo != null) { 17893 childInfo.isRemovedPackageSystemUpdate = true; 17894 } 17895 } 17896 } 17897 } 17898 17899 if (disabledPs.versionCode < deletedPs.versionCode) { 17900 // Delete data for downgrades 17901 flags &= ~PackageManager.DELETE_KEEP_DATA; 17902 } else { 17903 // Preserve data by setting flag 17904 flags |= PackageManager.DELETE_KEEP_DATA; 17905 } 17906 17907 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 17908 outInfo, writeSettings, disabledPs.pkg); 17909 if (!ret) { 17910 return false; 17911 } 17912 17913 // writer 17914 synchronized (mPackages) { 17915 // Reinstate the old system package 17916 enableSystemPackageLPw(disabledPs.pkg); 17917 // Remove any native libraries from the upgraded package. 17918 removeNativeBinariesLI(deletedPs); 17919 } 17920 17921 // Install the system package 17922 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 17923 int parseFlags = mDefParseFlags 17924 | PackageParser.PARSE_MUST_BE_APK 17925 | PackageParser.PARSE_IS_SYSTEM 17926 | PackageParser.PARSE_IS_SYSTEM_DIR; 17927 if (locationIsPrivileged(disabledPs.codePath)) { 17928 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 17929 } 17930 17931 final PackageParser.Package newPkg; 17932 try { 17933 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */, 17934 0 /* currentTime */, null); 17935 } catch (PackageManagerException e) { 17936 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 17937 + e.getMessage()); 17938 return false; 17939 } 17940 17941 try { 17942 // update shared libraries for the newly re-installed system package 17943 updateSharedLibrariesLPr(newPkg, null); 17944 } catch (PackageManagerException e) { 17945 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 17946 } 17947 17948 prepareAppDataAfterInstallLIF(newPkg); 17949 17950 // writer 17951 synchronized (mPackages) { 17952 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 17953 17954 // Propagate the permissions state as we do not want to drop on the floor 17955 // runtime permissions. The update permissions method below will take 17956 // care of removing obsolete permissions and grant install permissions. 17957 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 17958 updatePermissionsLPw(newPkg.packageName, newPkg, 17959 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 17960 17961 if (applyUserRestrictions) { 17962 boolean installedStateChanged = false; 17963 if (DEBUG_REMOVE) { 17964 Slog.d(TAG, "Propagating install state across reinstall"); 17965 } 17966 for (int userId : allUserHandles) { 17967 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 17968 if (DEBUG_REMOVE) { 17969 Slog.d(TAG, " user " + userId + " => " + installed); 17970 } 17971 if (installed != ps.getInstalled(userId)) { 17972 installedStateChanged = true; 17973 } 17974 ps.setInstalled(installed, userId); 17975 17976 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 17977 } 17978 // Regardless of writeSettings we need to ensure that this restriction 17979 // state propagation is persisted 17980 mSettings.writeAllUsersPackageRestrictionsLPr(); 17981 if (installedStateChanged) { 17982 mSettings.writeKernelMappingLPr(ps); 17983 } 17984 } 17985 // can downgrade to reader here 17986 if (writeSettings) { 17987 mSettings.writeLPr(); 17988 } 17989 } 17990 return true; 17991 } 17992 17993 private boolean deleteInstalledPackageLIF(PackageSetting ps, 17994 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 17995 PackageRemovedInfo outInfo, boolean writeSettings, 17996 PackageParser.Package replacingPackage) { 17997 synchronized (mPackages) { 17998 if (outInfo != null) { 17999 outInfo.uid = ps.appId; 18000 } 18001 18002 if (outInfo != null && outInfo.removedChildPackages != null) { 18003 final int childCount = (ps.childPackageNames != null) 18004 ? ps.childPackageNames.size() : 0; 18005 for (int i = 0; i < childCount; i++) { 18006 String childPackageName = ps.childPackageNames.get(i); 18007 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 18008 if (childPs == null) { 18009 return false; 18010 } 18011 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 18012 childPackageName); 18013 if (childInfo != null) { 18014 childInfo.uid = childPs.appId; 18015 } 18016 } 18017 } 18018 } 18019 18020 // Delete package data from internal structures and also remove data if flag is set 18021 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 18022 18023 // Delete the child packages data 18024 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 18025 for (int i = 0; i < childCount; i++) { 18026 PackageSetting childPs; 18027 synchronized (mPackages) { 18028 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 18029 } 18030 if (childPs != null) { 18031 PackageRemovedInfo childOutInfo = (outInfo != null 18032 && outInfo.removedChildPackages != null) 18033 ? outInfo.removedChildPackages.get(childPs.name) : null; 18034 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 18035 && (replacingPackage != null 18036 && !replacingPackage.hasChildPackage(childPs.name)) 18037 ? flags & ~DELETE_KEEP_DATA : flags; 18038 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 18039 deleteFlags, writeSettings); 18040 } 18041 } 18042 18043 // Delete application code and resources only for parent packages 18044 if (ps.parentPackageName == null) { 18045 if (deleteCodeAndResources && (outInfo != null)) { 18046 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 18047 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 18048 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 18049 } 18050 } 18051 18052 return true; 18053 } 18054 18055 @Override 18056 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 18057 int userId) { 18058 mContext.enforceCallingOrSelfPermission( 18059 android.Manifest.permission.DELETE_PACKAGES, null); 18060 synchronized (mPackages) { 18061 PackageSetting ps = mSettings.mPackages.get(packageName); 18062 if (ps == null) { 18063 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 18064 return false; 18065 } 18066 // Cannot block uninstall of static shared libs as they are 18067 // considered a part of the using app (emulating static linking). 18068 // Also static libs are installed always on internal storage. 18069 PackageParser.Package pkg = mPackages.get(packageName); 18070 if (pkg != null && pkg.staticSharedLibName != null) { 18071 Slog.w(TAG, "Cannot block uninstall of package: " + packageName 18072 + " providing static shared library: " + pkg.staticSharedLibName); 18073 return false; 18074 } 18075 if (!ps.getInstalled(userId)) { 18076 // Can't block uninstall for an app that is not installed or enabled. 18077 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 18078 return false; 18079 } 18080 ps.setBlockUninstall(blockUninstall, userId); 18081 mSettings.writePackageRestrictionsLPr(userId); 18082 } 18083 return true; 18084 } 18085 18086 @Override 18087 public boolean getBlockUninstallForUser(String packageName, int userId) { 18088 synchronized (mPackages) { 18089 PackageSetting ps = mSettings.mPackages.get(packageName); 18090 if (ps == null) { 18091 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 18092 return false; 18093 } 18094 return ps.getBlockUninstall(userId); 18095 } 18096 } 18097 18098 @Override 18099 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 18100 int callingUid = Binder.getCallingUid(); 18101 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 18102 throw new SecurityException( 18103 "setRequiredForSystemUser can only be run by the system or root"); 18104 } 18105 synchronized (mPackages) { 18106 PackageSetting ps = mSettings.mPackages.get(packageName); 18107 if (ps == null) { 18108 Log.w(TAG, "Package doesn't exist: " + packageName); 18109 return false; 18110 } 18111 if (systemUserApp) { 18112 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 18113 } else { 18114 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 18115 } 18116 mSettings.writeLPr(); 18117 } 18118 return true; 18119 } 18120 18121 /* 18122 * This method handles package deletion in general 18123 */ 18124 private boolean deletePackageLIF(String packageName, UserHandle user, 18125 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 18126 PackageRemovedInfo outInfo, boolean writeSettings, 18127 PackageParser.Package replacingPackage) { 18128 if (packageName == null) { 18129 Slog.w(TAG, "Attempt to delete null packageName."); 18130 return false; 18131 } 18132 18133 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 18134 18135 PackageSetting ps; 18136 synchronized (mPackages) { 18137 ps = mSettings.mPackages.get(packageName); 18138 if (ps == null) { 18139 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 18140 return false; 18141 } 18142 18143 if (ps.parentPackageName != null && (!isSystemApp(ps) 18144 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 18145 if (DEBUG_REMOVE) { 18146 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 18147 + ((user == null) ? UserHandle.USER_ALL : user)); 18148 } 18149 final int removedUserId = (user != null) ? user.getIdentifier() 18150 : UserHandle.USER_ALL; 18151 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 18152 return false; 18153 } 18154 markPackageUninstalledForUserLPw(ps, user); 18155 scheduleWritePackageRestrictionsLocked(user); 18156 return true; 18157 } 18158 } 18159 18160 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 18161 && user.getIdentifier() != UserHandle.USER_ALL)) { 18162 // The caller is asking that the package only be deleted for a single 18163 // user. To do this, we just mark its uninstalled state and delete 18164 // its data. If this is a system app, we only allow this to happen if 18165 // they have set the special DELETE_SYSTEM_APP which requests different 18166 // semantics than normal for uninstalling system apps. 18167 markPackageUninstalledForUserLPw(ps, user); 18168 18169 if (!isSystemApp(ps)) { 18170 // Do not uninstall the APK if an app should be cached 18171 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 18172 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 18173 // Other user still have this package installed, so all 18174 // we need to do is clear this user's data and save that 18175 // it is uninstalled. 18176 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 18177 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 18178 return false; 18179 } 18180 scheduleWritePackageRestrictionsLocked(user); 18181 return true; 18182 } else { 18183 // We need to set it back to 'installed' so the uninstall 18184 // broadcasts will be sent correctly. 18185 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 18186 ps.setInstalled(true, user.getIdentifier()); 18187 mSettings.writeKernelMappingLPr(ps); 18188 } 18189 } else { 18190 // This is a system app, so we assume that the 18191 // other users still have this package installed, so all 18192 // we need to do is clear this user's data and save that 18193 // it is uninstalled. 18194 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 18195 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 18196 return false; 18197 } 18198 scheduleWritePackageRestrictionsLocked(user); 18199 return true; 18200 } 18201 } 18202 18203 // If we are deleting a composite package for all users, keep track 18204 // of result for each child. 18205 if (ps.childPackageNames != null && outInfo != null) { 18206 synchronized (mPackages) { 18207 final int childCount = ps.childPackageNames.size(); 18208 outInfo.removedChildPackages = new ArrayMap<>(childCount); 18209 for (int i = 0; i < childCount; i++) { 18210 String childPackageName = ps.childPackageNames.get(i); 18211 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 18212 childInfo.removedPackage = childPackageName; 18213 outInfo.removedChildPackages.put(childPackageName, childInfo); 18214 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 18215 if (childPs != null) { 18216 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 18217 } 18218 } 18219 } 18220 } 18221 18222 boolean ret = false; 18223 if (isSystemApp(ps)) { 18224 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 18225 // When an updated system application is deleted we delete the existing resources 18226 // as well and fall back to existing code in system partition 18227 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 18228 } else { 18229 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 18230 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 18231 outInfo, writeSettings, replacingPackage); 18232 } 18233 18234 // Take a note whether we deleted the package for all users 18235 if (outInfo != null) { 18236 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 18237 if (outInfo.removedChildPackages != null) { 18238 synchronized (mPackages) { 18239 final int childCount = outInfo.removedChildPackages.size(); 18240 for (int i = 0; i < childCount; i++) { 18241 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 18242 if (childInfo != null) { 18243 childInfo.removedForAllUsers = mPackages.get( 18244 childInfo.removedPackage) == null; 18245 } 18246 } 18247 } 18248 } 18249 // If we uninstalled an update to a system app there may be some 18250 // child packages that appeared as they are declared in the system 18251 // app but were not declared in the update. 18252 if (isSystemApp(ps)) { 18253 synchronized (mPackages) { 18254 PackageSetting updatedPs = mSettings.getPackageLPr(ps.name); 18255 final int childCount = (updatedPs.childPackageNames != null) 18256 ? updatedPs.childPackageNames.size() : 0; 18257 for (int i = 0; i < childCount; i++) { 18258 String childPackageName = updatedPs.childPackageNames.get(i); 18259 if (outInfo.removedChildPackages == null 18260 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 18261 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 18262 if (childPs == null) { 18263 continue; 18264 } 18265 PackageInstalledInfo installRes = new PackageInstalledInfo(); 18266 installRes.name = childPackageName; 18267 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 18268 installRes.pkg = mPackages.get(childPackageName); 18269 installRes.uid = childPs.pkg.applicationInfo.uid; 18270 if (outInfo.appearedChildPackages == null) { 18271 outInfo.appearedChildPackages = new ArrayMap<>(); 18272 } 18273 outInfo.appearedChildPackages.put(childPackageName, installRes); 18274 } 18275 } 18276 } 18277 } 18278 } 18279 18280 return ret; 18281 } 18282 18283 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 18284 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 18285 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 18286 for (int nextUserId : userIds) { 18287 if (DEBUG_REMOVE) { 18288 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 18289 } 18290 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 18291 false /*installed*/, 18292 true /*stopped*/, 18293 true /*notLaunched*/, 18294 false /*hidden*/, 18295 false /*suspended*/, 18296 false /*instantApp*/, 18297 null /*lastDisableAppCaller*/, 18298 null /*enabledComponents*/, 18299 null /*disabledComponents*/, 18300 false /*blockUninstall*/, 18301 ps.readUserState(nextUserId).domainVerificationStatus, 18302 0, PackageManager.INSTALL_REASON_UNKNOWN); 18303 } 18304 mSettings.writeKernelMappingLPr(ps); 18305 } 18306 18307 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 18308 PackageRemovedInfo outInfo) { 18309 final PackageParser.Package pkg; 18310 synchronized (mPackages) { 18311 pkg = mPackages.get(ps.name); 18312 } 18313 18314 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 18315 : new int[] {userId}; 18316 for (int nextUserId : userIds) { 18317 if (DEBUG_REMOVE) { 18318 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 18319 + nextUserId); 18320 } 18321 18322 destroyAppDataLIF(pkg, userId, 18323 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18324 destroyAppProfilesLIF(pkg, userId); 18325 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 18326 schedulePackageCleaning(ps.name, nextUserId, false); 18327 synchronized (mPackages) { 18328 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 18329 scheduleWritePackageRestrictionsLocked(nextUserId); 18330 } 18331 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 18332 } 18333 } 18334 18335 if (outInfo != null) { 18336 outInfo.removedPackage = ps.name; 18337 outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null; 18338 outInfo.removedAppId = ps.appId; 18339 outInfo.removedUsers = userIds; 18340 } 18341 18342 return true; 18343 } 18344 18345 private final class ClearStorageConnection implements ServiceConnection { 18346 IMediaContainerService mContainerService; 18347 18348 @Override 18349 public void onServiceConnected(ComponentName name, IBinder service) { 18350 synchronized (this) { 18351 mContainerService = IMediaContainerService.Stub 18352 .asInterface(Binder.allowBlocking(service)); 18353 notifyAll(); 18354 } 18355 } 18356 18357 @Override 18358 public void onServiceDisconnected(ComponentName name) { 18359 } 18360 } 18361 18362 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 18363 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 18364 18365 final boolean mounted; 18366 if (Environment.isExternalStorageEmulated()) { 18367 mounted = true; 18368 } else { 18369 final String status = Environment.getExternalStorageState(); 18370 18371 mounted = status.equals(Environment.MEDIA_MOUNTED) 18372 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 18373 } 18374 18375 if (!mounted) { 18376 return; 18377 } 18378 18379 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 18380 int[] users; 18381 if (userId == UserHandle.USER_ALL) { 18382 users = sUserManager.getUserIds(); 18383 } else { 18384 users = new int[] { userId }; 18385 } 18386 final ClearStorageConnection conn = new ClearStorageConnection(); 18387 if (mContext.bindServiceAsUser( 18388 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 18389 try { 18390 for (int curUser : users) { 18391 long timeout = SystemClock.uptimeMillis() + 5000; 18392 synchronized (conn) { 18393 long now; 18394 while (conn.mContainerService == null && 18395 (now = SystemClock.uptimeMillis()) < timeout) { 18396 try { 18397 conn.wait(timeout - now); 18398 } catch (InterruptedException e) { 18399 } 18400 } 18401 } 18402 if (conn.mContainerService == null) { 18403 return; 18404 } 18405 18406 final UserEnvironment userEnv = new UserEnvironment(curUser); 18407 clearDirectory(conn.mContainerService, 18408 userEnv.buildExternalStorageAppCacheDirs(packageName)); 18409 if (allData) { 18410 clearDirectory(conn.mContainerService, 18411 userEnv.buildExternalStorageAppDataDirs(packageName)); 18412 clearDirectory(conn.mContainerService, 18413 userEnv.buildExternalStorageAppMediaDirs(packageName)); 18414 } 18415 } 18416 } finally { 18417 mContext.unbindService(conn); 18418 } 18419 } 18420 } 18421 18422 @Override 18423 public void clearApplicationProfileData(String packageName) { 18424 enforceSystemOrRoot("Only the system can clear all profile data"); 18425 18426 final PackageParser.Package pkg; 18427 synchronized (mPackages) { 18428 pkg = mPackages.get(packageName); 18429 } 18430 18431 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 18432 synchronized (mInstallLock) { 18433 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 18434 destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL, 18435 true /* removeBaseMarker */); 18436 } 18437 } 18438 } 18439 18440 @Override 18441 public void clearApplicationUserData(final String packageName, 18442 final IPackageDataObserver observer, final int userId) { 18443 mContext.enforceCallingOrSelfPermission( 18444 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 18445 18446 enforceCrossUserPermission(Binder.getCallingUid(), userId, 18447 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 18448 18449 if (mProtectedPackages.isPackageDataProtected(userId, packageName)) { 18450 throw new SecurityException("Cannot clear data for a protected package: " 18451 + packageName); 18452 } 18453 // Queue up an async operation since the package deletion may take a little while. 18454 mHandler.post(new Runnable() { 18455 public void run() { 18456 mHandler.removeCallbacks(this); 18457 final boolean succeeded; 18458 try (PackageFreezer freezer = freezePackage(packageName, 18459 "clearApplicationUserData")) { 18460 synchronized (mInstallLock) { 18461 succeeded = clearApplicationUserDataLIF(packageName, userId); 18462 } 18463 clearExternalStorageDataSync(packageName, userId, true); 18464 synchronized (mPackages) { 18465 mInstantAppRegistry.deleteInstantApplicationMetadataLPw( 18466 packageName, userId); 18467 } 18468 } 18469 if (succeeded) { 18470 // invoke DeviceStorageMonitor's update method to clear any notifications 18471 DeviceStorageMonitorInternal dsm = LocalServices 18472 .getService(DeviceStorageMonitorInternal.class); 18473 if (dsm != null) { 18474 dsm.checkMemory(); 18475 } 18476 } 18477 if(observer != null) { 18478 try { 18479 observer.onRemoveCompleted(packageName, succeeded); 18480 } catch (RemoteException e) { 18481 Log.i(TAG, "Observer no longer exists."); 18482 } 18483 } //end if observer 18484 } //end run 18485 }); 18486 } 18487 18488 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 18489 if (packageName == null) { 18490 Slog.w(TAG, "Attempt to delete null packageName."); 18491 return false; 18492 } 18493 18494 // Try finding details about the requested package 18495 PackageParser.Package pkg; 18496 synchronized (mPackages) { 18497 pkg = mPackages.get(packageName); 18498 if (pkg == null) { 18499 final PackageSetting ps = mSettings.mPackages.get(packageName); 18500 if (ps != null) { 18501 pkg = ps.pkg; 18502 } 18503 } 18504 18505 if (pkg == null) { 18506 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 18507 return false; 18508 } 18509 18510 PackageSetting ps = (PackageSetting) pkg.mExtras; 18511 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 18512 } 18513 18514 clearAppDataLIF(pkg, userId, 18515 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18516 18517 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 18518 removeKeystoreDataIfNeeded(userId, appId); 18519 18520 UserManagerInternal umInternal = getUserManagerInternal(); 18521 final int flags; 18522 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 18523 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18524 } else if (umInternal.isUserRunning(userId)) { 18525 flags = StorageManager.FLAG_STORAGE_DE; 18526 } else { 18527 flags = 0; 18528 } 18529 prepareAppDataContentsLIF(pkg, userId, flags); 18530 18531 return true; 18532 } 18533 18534 /** 18535 * Reverts user permission state changes (permissions and flags) in 18536 * all packages for a given user. 18537 * 18538 * @param userId The device user for which to do a reset. 18539 */ 18540 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 18541 final int packageCount = mPackages.size(); 18542 for (int i = 0; i < packageCount; i++) { 18543 PackageParser.Package pkg = mPackages.valueAt(i); 18544 PackageSetting ps = (PackageSetting) pkg.mExtras; 18545 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 18546 } 18547 } 18548 18549 private void resetNetworkPolicies(int userId) { 18550 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 18551 } 18552 18553 /** 18554 * Reverts user permission state changes (permissions and flags). 18555 * 18556 * @param ps The package for which to reset. 18557 * @param userId The device user for which to do a reset. 18558 */ 18559 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 18560 final PackageSetting ps, final int userId) { 18561 if (ps.pkg == null) { 18562 return; 18563 } 18564 18565 // These are flags that can change base on user actions. 18566 final int userSettableMask = FLAG_PERMISSION_USER_SET 18567 | FLAG_PERMISSION_USER_FIXED 18568 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 18569 | FLAG_PERMISSION_REVIEW_REQUIRED; 18570 18571 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 18572 | FLAG_PERMISSION_POLICY_FIXED; 18573 18574 boolean writeInstallPermissions = false; 18575 boolean writeRuntimePermissions = false; 18576 18577 final int permissionCount = ps.pkg.requestedPermissions.size(); 18578 for (int i = 0; i < permissionCount; i++) { 18579 String permission = ps.pkg.requestedPermissions.get(i); 18580 18581 BasePermission bp = mSettings.mPermissions.get(permission); 18582 if (bp == null) { 18583 continue; 18584 } 18585 18586 // If shared user we just reset the state to which only this app contributed. 18587 if (ps.sharedUser != null) { 18588 boolean used = false; 18589 final int packageCount = ps.sharedUser.packages.size(); 18590 for (int j = 0; j < packageCount; j++) { 18591 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 18592 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 18593 && pkg.pkg.requestedPermissions.contains(permission)) { 18594 used = true; 18595 break; 18596 } 18597 } 18598 if (used) { 18599 continue; 18600 } 18601 } 18602 18603 PermissionsState permissionsState = ps.getPermissionsState(); 18604 18605 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 18606 18607 // Always clear the user settable flags. 18608 final boolean hasInstallState = permissionsState.getInstallPermissionState( 18609 bp.name) != null; 18610 // If permission review is enabled and this is a legacy app, mark the 18611 // permission as requiring a review as this is the initial state. 18612 int flags = 0; 18613 if (mPermissionReviewRequired 18614 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 18615 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 18616 } 18617 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 18618 if (hasInstallState) { 18619 writeInstallPermissions = true; 18620 } else { 18621 writeRuntimePermissions = true; 18622 } 18623 } 18624 18625 // Below is only runtime permission handling. 18626 if (!bp.isRuntime()) { 18627 continue; 18628 } 18629 18630 // Never clobber system or policy. 18631 if ((oldFlags & policyOrSystemFlags) != 0) { 18632 continue; 18633 } 18634 18635 // If this permission was granted by default, make sure it is. 18636 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 18637 if (permissionsState.grantRuntimePermission(bp, userId) 18638 != PERMISSION_OPERATION_FAILURE) { 18639 writeRuntimePermissions = true; 18640 } 18641 // If permission review is enabled the permissions for a legacy apps 18642 // are represented as constantly granted runtime ones, so don't revoke. 18643 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 18644 // Otherwise, reset the permission. 18645 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 18646 switch (revokeResult) { 18647 case PERMISSION_OPERATION_SUCCESS: 18648 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 18649 writeRuntimePermissions = true; 18650 final int appId = ps.appId; 18651 mHandler.post(new Runnable() { 18652 @Override 18653 public void run() { 18654 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 18655 } 18656 }); 18657 } break; 18658 } 18659 } 18660 } 18661 18662 // Synchronously write as we are taking permissions away. 18663 if (writeRuntimePermissions) { 18664 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 18665 } 18666 18667 // Synchronously write as we are taking permissions away. 18668 if (writeInstallPermissions) { 18669 mSettings.writeLPr(); 18670 } 18671 } 18672 18673 /** 18674 * Remove entries from the keystore daemon. Will only remove it if the 18675 * {@code appId} is valid. 18676 */ 18677 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 18678 if (appId < 0) { 18679 return; 18680 } 18681 18682 final KeyStore keyStore = KeyStore.getInstance(); 18683 if (keyStore != null) { 18684 if (userId == UserHandle.USER_ALL) { 18685 for (final int individual : sUserManager.getUserIds()) { 18686 keyStore.clearUid(UserHandle.getUid(individual, appId)); 18687 } 18688 } else { 18689 keyStore.clearUid(UserHandle.getUid(userId, appId)); 18690 } 18691 } else { 18692 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 18693 } 18694 } 18695 18696 @Override 18697 public void deleteApplicationCacheFiles(final String packageName, 18698 final IPackageDataObserver observer) { 18699 final int userId = UserHandle.getCallingUserId(); 18700 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 18701 } 18702 18703 @Override 18704 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 18705 final IPackageDataObserver observer) { 18706 mContext.enforceCallingOrSelfPermission( 18707 android.Manifest.permission.DELETE_CACHE_FILES, null); 18708 enforceCrossUserPermission(Binder.getCallingUid(), userId, 18709 /* requireFullPermission= */ true, /* checkShell= */ false, 18710 "delete application cache files"); 18711 18712 final PackageParser.Package pkg; 18713 synchronized (mPackages) { 18714 pkg = mPackages.get(packageName); 18715 } 18716 18717 // Queue up an async operation since the package deletion may take a little while. 18718 mHandler.post(new Runnable() { 18719 public void run() { 18720 synchronized (mInstallLock) { 18721 final int flags = StorageManager.FLAG_STORAGE_DE 18722 | StorageManager.FLAG_STORAGE_CE; 18723 // We're only clearing cache files, so we don't care if the 18724 // app is unfrozen and still able to run 18725 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 18726 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 18727 } 18728 clearExternalStorageDataSync(packageName, userId, false); 18729 if (observer != null) { 18730 try { 18731 observer.onRemoveCompleted(packageName, true); 18732 } catch (RemoteException e) { 18733 Log.i(TAG, "Observer no longer exists."); 18734 } 18735 } 18736 } 18737 }); 18738 } 18739 18740 @Override 18741 public void getPackageSizeInfo(final String packageName, int userHandle, 18742 final IPackageStatsObserver observer) { 18743 mContext.enforceCallingOrSelfPermission( 18744 android.Manifest.permission.GET_PACKAGE_SIZE, null); 18745 if (packageName == null) { 18746 throw new IllegalArgumentException("Attempt to get size of null packageName"); 18747 } 18748 18749 PackageStats stats = new PackageStats(packageName, userHandle); 18750 18751 /* 18752 * Queue up an async operation since the package measurement may take a 18753 * little while. 18754 */ 18755 Message msg = mHandler.obtainMessage(INIT_COPY); 18756 msg.obj = new MeasureParams(stats, observer); 18757 mHandler.sendMessage(msg); 18758 } 18759 18760 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 18761 final PackageSetting ps; 18762 synchronized (mPackages) { 18763 ps = mSettings.mPackages.get(packageName); 18764 if (ps == null) { 18765 Slog.w(TAG, "Failed to find settings for " + packageName); 18766 return false; 18767 } 18768 } 18769 18770 final String[] packageNames = { packageName }; 18771 final long[] ceDataInodes = { ps.getCeDataInode(userId) }; 18772 final String[] codePaths = { ps.codePathString }; 18773 18774 try { 18775 mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0, 18776 ps.appId, ceDataInodes, codePaths, stats); 18777 18778 // For now, ignore code size of packages on system partition 18779 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 18780 stats.codeSize = 0; 18781 } 18782 18783 // External clients expect these to be tracked separately 18784 stats.dataSize -= stats.cacheSize; 18785 18786 } catch (InstallerException e) { 18787 Slog.w(TAG, String.valueOf(e)); 18788 return false; 18789 } 18790 18791 return true; 18792 } 18793 18794 private int getUidTargetSdkVersionLockedLPr(int uid) { 18795 Object obj = mSettings.getUserIdLPr(uid); 18796 if (obj instanceof SharedUserSetting) { 18797 final SharedUserSetting sus = (SharedUserSetting) obj; 18798 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 18799 final Iterator<PackageSetting> it = sus.packages.iterator(); 18800 while (it.hasNext()) { 18801 final PackageSetting ps = it.next(); 18802 if (ps.pkg != null) { 18803 int v = ps.pkg.applicationInfo.targetSdkVersion; 18804 if (v < vers) vers = v; 18805 } 18806 } 18807 return vers; 18808 } else if (obj instanceof PackageSetting) { 18809 final PackageSetting ps = (PackageSetting) obj; 18810 if (ps.pkg != null) { 18811 return ps.pkg.applicationInfo.targetSdkVersion; 18812 } 18813 } 18814 return Build.VERSION_CODES.CUR_DEVELOPMENT; 18815 } 18816 18817 @Override 18818 public void addPreferredActivity(IntentFilter filter, int match, 18819 ComponentName[] set, ComponentName activity, int userId) { 18820 addPreferredActivityInternal(filter, match, set, activity, true, userId, 18821 "Adding preferred"); 18822 } 18823 18824 private void addPreferredActivityInternal(IntentFilter filter, int match, 18825 ComponentName[] set, ComponentName activity, boolean always, int userId, 18826 String opname) { 18827 // writer 18828 int callingUid = Binder.getCallingUid(); 18829 enforceCrossUserPermission(callingUid, userId, 18830 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 18831 if (filter.countActions() == 0) { 18832 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 18833 return; 18834 } 18835 synchronized (mPackages) { 18836 if (mContext.checkCallingOrSelfPermission( 18837 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 18838 != PackageManager.PERMISSION_GRANTED) { 18839 if (getUidTargetSdkVersionLockedLPr(callingUid) 18840 < Build.VERSION_CODES.FROYO) { 18841 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 18842 + callingUid); 18843 return; 18844 } 18845 mContext.enforceCallingOrSelfPermission( 18846 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 18847 } 18848 18849 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 18850 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 18851 + userId + ":"); 18852 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18853 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 18854 scheduleWritePackageRestrictionsLocked(userId); 18855 postPreferredActivityChangedBroadcast(userId); 18856 } 18857 } 18858 18859 private void postPreferredActivityChangedBroadcast(int userId) { 18860 mHandler.post(() -> { 18861 final IActivityManager am = ActivityManager.getService(); 18862 if (am == null) { 18863 return; 18864 } 18865 18866 final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED); 18867 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 18868 try { 18869 am.broadcastIntent(null, intent, null, null, 18870 0, null, null, null, android.app.AppOpsManager.OP_NONE, 18871 null, false, false, userId); 18872 } catch (RemoteException e) { 18873 } 18874 }); 18875 } 18876 18877 @Override 18878 public void replacePreferredActivity(IntentFilter filter, int match, 18879 ComponentName[] set, ComponentName activity, int userId) { 18880 if (filter.countActions() != 1) { 18881 throw new IllegalArgumentException( 18882 "replacePreferredActivity expects filter to have only 1 action."); 18883 } 18884 if (filter.countDataAuthorities() != 0 18885 || filter.countDataPaths() != 0 18886 || filter.countDataSchemes() > 1 18887 || filter.countDataTypes() != 0) { 18888 throw new IllegalArgumentException( 18889 "replacePreferredActivity expects filter to have no data authorities, " + 18890 "paths, or types; and at most one scheme."); 18891 } 18892 18893 final int callingUid = Binder.getCallingUid(); 18894 enforceCrossUserPermission(callingUid, userId, 18895 true /* requireFullPermission */, false /* checkShell */, 18896 "replace preferred activity"); 18897 synchronized (mPackages) { 18898 if (mContext.checkCallingOrSelfPermission( 18899 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 18900 != PackageManager.PERMISSION_GRANTED) { 18901 if (getUidTargetSdkVersionLockedLPr(callingUid) 18902 < Build.VERSION_CODES.FROYO) { 18903 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 18904 + Binder.getCallingUid()); 18905 return; 18906 } 18907 mContext.enforceCallingOrSelfPermission( 18908 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 18909 } 18910 18911 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 18912 if (pir != null) { 18913 // Get all of the existing entries that exactly match this filter. 18914 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 18915 if (existing != null && existing.size() == 1) { 18916 PreferredActivity cur = existing.get(0); 18917 if (DEBUG_PREFERRED) { 18918 Slog.i(TAG, "Checking replace of preferred:"); 18919 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18920 if (!cur.mPref.mAlways) { 18921 Slog.i(TAG, " -- CUR; not mAlways!"); 18922 } else { 18923 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 18924 Slog.i(TAG, " -- CUR: mSet=" 18925 + Arrays.toString(cur.mPref.mSetComponents)); 18926 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 18927 Slog.i(TAG, " -- NEW: mMatch=" 18928 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 18929 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 18930 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 18931 } 18932 } 18933 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 18934 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 18935 && cur.mPref.sameSet(set)) { 18936 // Setting the preferred activity to what it happens to be already 18937 if (DEBUG_PREFERRED) { 18938 Slog.i(TAG, "Replacing with same preferred activity " 18939 + cur.mPref.mShortComponent + " for user " 18940 + userId + ":"); 18941 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18942 } 18943 return; 18944 } 18945 } 18946 18947 if (existing != null) { 18948 if (DEBUG_PREFERRED) { 18949 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 18950 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18951 } 18952 for (int i = 0; i < existing.size(); i++) { 18953 PreferredActivity pa = existing.get(i); 18954 if (DEBUG_PREFERRED) { 18955 Slog.i(TAG, "Removing existing preferred activity " 18956 + pa.mPref.mComponent + ":"); 18957 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 18958 } 18959 pir.removeFilter(pa); 18960 } 18961 } 18962 } 18963 addPreferredActivityInternal(filter, match, set, activity, true, userId, 18964 "Replacing preferred"); 18965 } 18966 } 18967 18968 @Override 18969 public void clearPackagePreferredActivities(String packageName) { 18970 final int uid = Binder.getCallingUid(); 18971 // writer 18972 synchronized (mPackages) { 18973 PackageParser.Package pkg = mPackages.get(packageName); 18974 if (pkg == null || pkg.applicationInfo.uid != uid) { 18975 if (mContext.checkCallingOrSelfPermission( 18976 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 18977 != PackageManager.PERMISSION_GRANTED) { 18978 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 18979 < Build.VERSION_CODES.FROYO) { 18980 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 18981 + Binder.getCallingUid()); 18982 return; 18983 } 18984 mContext.enforceCallingOrSelfPermission( 18985 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 18986 } 18987 } 18988 18989 int user = UserHandle.getCallingUserId(); 18990 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 18991 scheduleWritePackageRestrictionsLocked(user); 18992 } 18993 } 18994 } 18995 18996 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 18997 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 18998 ArrayList<PreferredActivity> removed = null; 18999 boolean changed = false; 19000 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 19001 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 19002 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 19003 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 19004 continue; 19005 } 19006 Iterator<PreferredActivity> it = pir.filterIterator(); 19007 while (it.hasNext()) { 19008 PreferredActivity pa = it.next(); 19009 // Mark entry for removal only if it matches the package name 19010 // and the entry is of type "always". 19011 if (packageName == null || 19012 (pa.mPref.mComponent.getPackageName().equals(packageName) 19013 && pa.mPref.mAlways)) { 19014 if (removed == null) { 19015 removed = new ArrayList<PreferredActivity>(); 19016 } 19017 removed.add(pa); 19018 } 19019 } 19020 if (removed != null) { 19021 for (int j=0; j<removed.size(); j++) { 19022 PreferredActivity pa = removed.get(j); 19023 pir.removeFilter(pa); 19024 } 19025 changed = true; 19026 } 19027 } 19028 if (changed) { 19029 postPreferredActivityChangedBroadcast(userId); 19030 } 19031 return changed; 19032 } 19033 19034 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 19035 private void clearIntentFilterVerificationsLPw(int userId) { 19036 final int packageCount = mPackages.size(); 19037 for (int i = 0; i < packageCount; i++) { 19038 PackageParser.Package pkg = mPackages.valueAt(i); 19039 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 19040 } 19041 } 19042 19043 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 19044 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 19045 if (userId == UserHandle.USER_ALL) { 19046 if (mSettings.removeIntentFilterVerificationLPw(packageName, 19047 sUserManager.getUserIds())) { 19048 for (int oneUserId : sUserManager.getUserIds()) { 19049 scheduleWritePackageRestrictionsLocked(oneUserId); 19050 } 19051 } 19052 } else { 19053 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 19054 scheduleWritePackageRestrictionsLocked(userId); 19055 } 19056 } 19057 } 19058 19059 void clearDefaultBrowserIfNeeded(String packageName) { 19060 for (int oneUserId : sUserManager.getUserIds()) { 19061 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 19062 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 19063 if (packageName.equals(defaultBrowserPackageName)) { 19064 setDefaultBrowserPackageName(null, oneUserId); 19065 } 19066 } 19067 } 19068 19069 @Override 19070 public void resetApplicationPreferences(int userId) { 19071 mContext.enforceCallingOrSelfPermission( 19072 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 19073 final long identity = Binder.clearCallingIdentity(); 19074 // writer 19075 try { 19076 synchronized (mPackages) { 19077 clearPackagePreferredActivitiesLPw(null, userId); 19078 mSettings.applyDefaultPreferredAppsLPw(this, userId); 19079 // TODO: We have to reset the default SMS and Phone. This requires 19080 // significant refactoring to keep all default apps in the package 19081 // manager (cleaner but more work) or have the services provide 19082 // callbacks to the package manager to request a default app reset. 19083 applyFactoryDefaultBrowserLPw(userId); 19084 clearIntentFilterVerificationsLPw(userId); 19085 primeDomainVerificationsLPw(userId); 19086 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 19087 scheduleWritePackageRestrictionsLocked(userId); 19088 } 19089 resetNetworkPolicies(userId); 19090 } finally { 19091 Binder.restoreCallingIdentity(identity); 19092 } 19093 } 19094 19095 @Override 19096 public int getPreferredActivities(List<IntentFilter> outFilters, 19097 List<ComponentName> outActivities, String packageName) { 19098 19099 int num = 0; 19100 final int userId = UserHandle.getCallingUserId(); 19101 // reader 19102 synchronized (mPackages) { 19103 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 19104 if (pir != null) { 19105 final Iterator<PreferredActivity> it = pir.filterIterator(); 19106 while (it.hasNext()) { 19107 final PreferredActivity pa = it.next(); 19108 if (packageName == null 19109 || (pa.mPref.mComponent.getPackageName().equals(packageName) 19110 && pa.mPref.mAlways)) { 19111 if (outFilters != null) { 19112 outFilters.add(new IntentFilter(pa)); 19113 } 19114 if (outActivities != null) { 19115 outActivities.add(pa.mPref.mComponent); 19116 } 19117 } 19118 } 19119 } 19120 } 19121 19122 return num; 19123 } 19124 19125 @Override 19126 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 19127 int userId) { 19128 int callingUid = Binder.getCallingUid(); 19129 if (callingUid != Process.SYSTEM_UID) { 19130 throw new SecurityException( 19131 "addPersistentPreferredActivity can only be run by the system"); 19132 } 19133 if (filter.countActions() == 0) { 19134 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 19135 return; 19136 } 19137 synchronized (mPackages) { 19138 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 19139 ":"); 19140 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19141 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 19142 new PersistentPreferredActivity(filter, activity)); 19143 scheduleWritePackageRestrictionsLocked(userId); 19144 postPreferredActivityChangedBroadcast(userId); 19145 } 19146 } 19147 19148 @Override 19149 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 19150 int callingUid = Binder.getCallingUid(); 19151 if (callingUid != Process.SYSTEM_UID) { 19152 throw new SecurityException( 19153 "clearPackagePersistentPreferredActivities can only be run by the system"); 19154 } 19155 ArrayList<PersistentPreferredActivity> removed = null; 19156 boolean changed = false; 19157 synchronized (mPackages) { 19158 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 19159 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 19160 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 19161 .valueAt(i); 19162 if (userId != thisUserId) { 19163 continue; 19164 } 19165 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 19166 while (it.hasNext()) { 19167 PersistentPreferredActivity ppa = it.next(); 19168 // Mark entry for removal only if it matches the package name. 19169 if (ppa.mComponent.getPackageName().equals(packageName)) { 19170 if (removed == null) { 19171 removed = new ArrayList<PersistentPreferredActivity>(); 19172 } 19173 removed.add(ppa); 19174 } 19175 } 19176 if (removed != null) { 19177 for (int j=0; j<removed.size(); j++) { 19178 PersistentPreferredActivity ppa = removed.get(j); 19179 ppir.removeFilter(ppa); 19180 } 19181 changed = true; 19182 } 19183 } 19184 19185 if (changed) { 19186 scheduleWritePackageRestrictionsLocked(userId); 19187 postPreferredActivityChangedBroadcast(userId); 19188 } 19189 } 19190 } 19191 19192 /** 19193 * Common machinery for picking apart a restored XML blob and passing 19194 * it to a caller-supplied functor to be applied to the running system. 19195 */ 19196 private void restoreFromXml(XmlPullParser parser, int userId, 19197 String expectedStartTag, BlobXmlRestorer functor) 19198 throws IOException, XmlPullParserException { 19199 int type; 19200 while ((type = parser.next()) != XmlPullParser.START_TAG 19201 && type != XmlPullParser.END_DOCUMENT) { 19202 } 19203 if (type != XmlPullParser.START_TAG) { 19204 // oops didn't find a start tag?! 19205 if (DEBUG_BACKUP) { 19206 Slog.e(TAG, "Didn't find start tag during restore"); 19207 } 19208 return; 19209 } 19210Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 19211 // this is supposed to be TAG_PREFERRED_BACKUP 19212 if (!expectedStartTag.equals(parser.getName())) { 19213 if (DEBUG_BACKUP) { 19214 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 19215 } 19216 return; 19217 } 19218 19219 // skip interfering stuff, then we're aligned with the backing implementation 19220 while ((type = parser.next()) == XmlPullParser.TEXT) { } 19221Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 19222 functor.apply(parser, userId); 19223 } 19224 19225 private interface BlobXmlRestorer { 19226 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 19227 } 19228 19229 /** 19230 * Non-Binder method, support for the backup/restore mechanism: write the 19231 * full set of preferred activities in its canonical XML format. Returns the 19232 * XML output as a byte array, or null if there is none. 19233 */ 19234 @Override 19235 public byte[] getPreferredActivityBackup(int userId) { 19236 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19237 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 19238 } 19239 19240 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19241 try { 19242 final XmlSerializer serializer = new FastXmlSerializer(); 19243 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19244 serializer.startDocument(null, true); 19245 serializer.startTag(null, TAG_PREFERRED_BACKUP); 19246 19247 synchronized (mPackages) { 19248 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 19249 } 19250 19251 serializer.endTag(null, TAG_PREFERRED_BACKUP); 19252 serializer.endDocument(); 19253 serializer.flush(); 19254 } catch (Exception e) { 19255 if (DEBUG_BACKUP) { 19256 Slog.e(TAG, "Unable to write preferred activities for backup", e); 19257 } 19258 return null; 19259 } 19260 19261 return dataStream.toByteArray(); 19262 } 19263 19264 @Override 19265 public void restorePreferredActivities(byte[] backup, int userId) { 19266 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19267 throw new SecurityException("Only the system may call restorePreferredActivities()"); 19268 } 19269 19270 try { 19271 final XmlPullParser parser = Xml.newPullParser(); 19272 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19273 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 19274 new BlobXmlRestorer() { 19275 @Override 19276 public void apply(XmlPullParser parser, int userId) 19277 throws XmlPullParserException, IOException { 19278 synchronized (mPackages) { 19279 mSettings.readPreferredActivitiesLPw(parser, userId); 19280 } 19281 } 19282 } ); 19283 } catch (Exception e) { 19284 if (DEBUG_BACKUP) { 19285 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19286 } 19287 } 19288 } 19289 19290 /** 19291 * Non-Binder method, support for the backup/restore mechanism: write the 19292 * default browser (etc) settings in its canonical XML format. Returns the default 19293 * browser XML representation as a byte array, or null if there is none. 19294 */ 19295 @Override 19296 public byte[] getDefaultAppsBackup(int userId) { 19297 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19298 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 19299 } 19300 19301 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19302 try { 19303 final XmlSerializer serializer = new FastXmlSerializer(); 19304 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19305 serializer.startDocument(null, true); 19306 serializer.startTag(null, TAG_DEFAULT_APPS); 19307 19308 synchronized (mPackages) { 19309 mSettings.writeDefaultAppsLPr(serializer, userId); 19310 } 19311 19312 serializer.endTag(null, TAG_DEFAULT_APPS); 19313 serializer.endDocument(); 19314 serializer.flush(); 19315 } catch (Exception e) { 19316 if (DEBUG_BACKUP) { 19317 Slog.e(TAG, "Unable to write default apps for backup", e); 19318 } 19319 return null; 19320 } 19321 19322 return dataStream.toByteArray(); 19323 } 19324 19325 @Override 19326 public void restoreDefaultApps(byte[] backup, int userId) { 19327 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19328 throw new SecurityException("Only the system may call restoreDefaultApps()"); 19329 } 19330 19331 try { 19332 final XmlPullParser parser = Xml.newPullParser(); 19333 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19334 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 19335 new BlobXmlRestorer() { 19336 @Override 19337 public void apply(XmlPullParser parser, int userId) 19338 throws XmlPullParserException, IOException { 19339 synchronized (mPackages) { 19340 mSettings.readDefaultAppsLPw(parser, userId); 19341 } 19342 } 19343 } ); 19344 } catch (Exception e) { 19345 if (DEBUG_BACKUP) { 19346 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 19347 } 19348 } 19349 } 19350 19351 @Override 19352 public byte[] getIntentFilterVerificationBackup(int userId) { 19353 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19354 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 19355 } 19356 19357 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19358 try { 19359 final XmlSerializer serializer = new FastXmlSerializer(); 19360 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19361 serializer.startDocument(null, true); 19362 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 19363 19364 synchronized (mPackages) { 19365 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 19366 } 19367 19368 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 19369 serializer.endDocument(); 19370 serializer.flush(); 19371 } catch (Exception e) { 19372 if (DEBUG_BACKUP) { 19373 Slog.e(TAG, "Unable to write default apps for backup", e); 19374 } 19375 return null; 19376 } 19377 19378 return dataStream.toByteArray(); 19379 } 19380 19381 @Override 19382 public void restoreIntentFilterVerification(byte[] backup, int userId) { 19383 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19384 throw new SecurityException("Only the system may call restorePreferredActivities()"); 19385 } 19386 19387 try { 19388 final XmlPullParser parser = Xml.newPullParser(); 19389 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19390 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 19391 new BlobXmlRestorer() { 19392 @Override 19393 public void apply(XmlPullParser parser, int userId) 19394 throws XmlPullParserException, IOException { 19395 synchronized (mPackages) { 19396 mSettings.readAllDomainVerificationsLPr(parser, userId); 19397 mSettings.writeLPr(); 19398 } 19399 } 19400 } ); 19401 } catch (Exception e) { 19402 if (DEBUG_BACKUP) { 19403 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19404 } 19405 } 19406 } 19407 19408 @Override 19409 public byte[] getPermissionGrantBackup(int userId) { 19410 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19411 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 19412 } 19413 19414 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19415 try { 19416 final XmlSerializer serializer = new FastXmlSerializer(); 19417 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19418 serializer.startDocument(null, true); 19419 serializer.startTag(null, TAG_PERMISSION_BACKUP); 19420 19421 synchronized (mPackages) { 19422 serializeRuntimePermissionGrantsLPr(serializer, userId); 19423 } 19424 19425 serializer.endTag(null, TAG_PERMISSION_BACKUP); 19426 serializer.endDocument(); 19427 serializer.flush(); 19428 } catch (Exception e) { 19429 if (DEBUG_BACKUP) { 19430 Slog.e(TAG, "Unable to write default apps for backup", e); 19431 } 19432 return null; 19433 } 19434 19435 return dataStream.toByteArray(); 19436 } 19437 19438 @Override 19439 public void restorePermissionGrants(byte[] backup, int userId) { 19440 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19441 throw new SecurityException("Only the system may call restorePermissionGrants()"); 19442 } 19443 19444 try { 19445 final XmlPullParser parser = Xml.newPullParser(); 19446 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19447 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 19448 new BlobXmlRestorer() { 19449 @Override 19450 public void apply(XmlPullParser parser, int userId) 19451 throws XmlPullParserException, IOException { 19452 synchronized (mPackages) { 19453 processRestoredPermissionGrantsLPr(parser, userId); 19454 } 19455 } 19456 } ); 19457 } catch (Exception e) { 19458 if (DEBUG_BACKUP) { 19459 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19460 } 19461 } 19462 } 19463 19464 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 19465 throws IOException { 19466 serializer.startTag(null, TAG_ALL_GRANTS); 19467 19468 final int N = mSettings.mPackages.size(); 19469 for (int i = 0; i < N; i++) { 19470 final PackageSetting ps = mSettings.mPackages.valueAt(i); 19471 boolean pkgGrantsKnown = false; 19472 19473 PermissionsState packagePerms = ps.getPermissionsState(); 19474 19475 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 19476 final int grantFlags = state.getFlags(); 19477 // only look at grants that are not system/policy fixed 19478 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 19479 final boolean isGranted = state.isGranted(); 19480 // And only back up the user-twiddled state bits 19481 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 19482 final String packageName = mSettings.mPackages.keyAt(i); 19483 if (!pkgGrantsKnown) { 19484 serializer.startTag(null, TAG_GRANT); 19485 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 19486 pkgGrantsKnown = true; 19487 } 19488 19489 final boolean userSet = 19490 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 19491 final boolean userFixed = 19492 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 19493 final boolean revoke = 19494 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 19495 19496 serializer.startTag(null, TAG_PERMISSION); 19497 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 19498 if (isGranted) { 19499 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 19500 } 19501 if (userSet) { 19502 serializer.attribute(null, ATTR_USER_SET, "true"); 19503 } 19504 if (userFixed) { 19505 serializer.attribute(null, ATTR_USER_FIXED, "true"); 19506 } 19507 if (revoke) { 19508 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 19509 } 19510 serializer.endTag(null, TAG_PERMISSION); 19511 } 19512 } 19513 } 19514 19515 if (pkgGrantsKnown) { 19516 serializer.endTag(null, TAG_GRANT); 19517 } 19518 } 19519 19520 serializer.endTag(null, TAG_ALL_GRANTS); 19521 } 19522 19523 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 19524 throws XmlPullParserException, IOException { 19525 String pkgName = null; 19526 int outerDepth = parser.getDepth(); 19527 int type; 19528 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 19529 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 19530 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 19531 continue; 19532 } 19533 19534 final String tagName = parser.getName(); 19535 if (tagName.equals(TAG_GRANT)) { 19536 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 19537 if (DEBUG_BACKUP) { 19538 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 19539 } 19540 } else if (tagName.equals(TAG_PERMISSION)) { 19541 19542 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 19543 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 19544 19545 int newFlagSet = 0; 19546 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 19547 newFlagSet |= FLAG_PERMISSION_USER_SET; 19548 } 19549 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 19550 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 19551 } 19552 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 19553 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 19554 } 19555 if (DEBUG_BACKUP) { 19556 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 19557 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 19558 } 19559 final PackageSetting ps = mSettings.mPackages.get(pkgName); 19560 if (ps != null) { 19561 // Already installed so we apply the grant immediately 19562 if (DEBUG_BACKUP) { 19563 Slog.v(TAG, " + already installed; applying"); 19564 } 19565 PermissionsState perms = ps.getPermissionsState(); 19566 BasePermission bp = mSettings.mPermissions.get(permName); 19567 if (bp != null) { 19568 if (isGranted) { 19569 perms.grantRuntimePermission(bp, userId); 19570 } 19571 if (newFlagSet != 0) { 19572 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 19573 } 19574 } 19575 } else { 19576 // Need to wait for post-restore install to apply the grant 19577 if (DEBUG_BACKUP) { 19578 Slog.v(TAG, " - not yet installed; saving for later"); 19579 } 19580 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 19581 isGranted, newFlagSet, userId); 19582 } 19583 } else { 19584 PackageManagerService.reportSettingsProblem(Log.WARN, 19585 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 19586 XmlUtils.skipCurrentTag(parser); 19587 } 19588 } 19589 19590 scheduleWriteSettingsLocked(); 19591 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 19592 } 19593 19594 @Override 19595 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 19596 int sourceUserId, int targetUserId, int flags) { 19597 mContext.enforceCallingOrSelfPermission( 19598 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 19599 int callingUid = Binder.getCallingUid(); 19600 enforceOwnerRights(ownerPackage, callingUid); 19601 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 19602 if (intentFilter.countActions() == 0) { 19603 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 19604 return; 19605 } 19606 synchronized (mPackages) { 19607 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 19608 ownerPackage, targetUserId, flags); 19609 CrossProfileIntentResolver resolver = 19610 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 19611 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 19612 // We have all those whose filter is equal. Now checking if the rest is equal as well. 19613 if (existing != null) { 19614 int size = existing.size(); 19615 for (int i = 0; i < size; i++) { 19616 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 19617 return; 19618 } 19619 } 19620 } 19621 resolver.addFilter(newFilter); 19622 scheduleWritePackageRestrictionsLocked(sourceUserId); 19623 } 19624 } 19625 19626 @Override 19627 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 19628 mContext.enforceCallingOrSelfPermission( 19629 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 19630 int callingUid = Binder.getCallingUid(); 19631 enforceOwnerRights(ownerPackage, callingUid); 19632 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 19633 synchronized (mPackages) { 19634 CrossProfileIntentResolver resolver = 19635 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 19636 ArraySet<CrossProfileIntentFilter> set = 19637 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 19638 for (CrossProfileIntentFilter filter : set) { 19639 if (filter.getOwnerPackage().equals(ownerPackage)) { 19640 resolver.removeFilter(filter); 19641 } 19642 } 19643 scheduleWritePackageRestrictionsLocked(sourceUserId); 19644 } 19645 } 19646 19647 // Enforcing that callingUid is owning pkg on userId 19648 private void enforceOwnerRights(String pkg, int callingUid) { 19649 // The system owns everything. 19650 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 19651 return; 19652 } 19653 int callingUserId = UserHandle.getUserId(callingUid); 19654 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 19655 if (pi == null) { 19656 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 19657 + callingUserId); 19658 } 19659 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 19660 throw new SecurityException("Calling uid " + callingUid 19661 + " does not own package " + pkg); 19662 } 19663 } 19664 19665 @Override 19666 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 19667 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 19668 } 19669 19670 private Intent getHomeIntent() { 19671 Intent intent = new Intent(Intent.ACTION_MAIN); 19672 intent.addCategory(Intent.CATEGORY_HOME); 19673 intent.addCategory(Intent.CATEGORY_DEFAULT); 19674 return intent; 19675 } 19676 19677 private IntentFilter getHomeFilter() { 19678 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 19679 filter.addCategory(Intent.CATEGORY_HOME); 19680 filter.addCategory(Intent.CATEGORY_DEFAULT); 19681 return filter; 19682 } 19683 19684 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 19685 int userId) { 19686 Intent intent = getHomeIntent(); 19687 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 19688 PackageManager.GET_META_DATA, userId); 19689 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 19690 true, false, false, userId); 19691 19692 allHomeCandidates.clear(); 19693 if (list != null) { 19694 for (ResolveInfo ri : list) { 19695 allHomeCandidates.add(ri); 19696 } 19697 } 19698 return (preferred == null || preferred.activityInfo == null) 19699 ? null 19700 : new ComponentName(preferred.activityInfo.packageName, 19701 preferred.activityInfo.name); 19702 } 19703 19704 @Override 19705 public void setHomeActivity(ComponentName comp, int userId) { 19706 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 19707 getHomeActivitiesAsUser(homeActivities, userId); 19708 19709 boolean found = false; 19710 19711 final int size = homeActivities.size(); 19712 final ComponentName[] set = new ComponentName[size]; 19713 for (int i = 0; i < size; i++) { 19714 final ResolveInfo candidate = homeActivities.get(i); 19715 final ActivityInfo info = candidate.activityInfo; 19716 final ComponentName activityName = new ComponentName(info.packageName, info.name); 19717 set[i] = activityName; 19718 if (!found && activityName.equals(comp)) { 19719 found = true; 19720 } 19721 } 19722 if (!found) { 19723 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 19724 + userId); 19725 } 19726 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 19727 set, comp, userId); 19728 } 19729 19730 private @Nullable String getSetupWizardPackageName() { 19731 final Intent intent = new Intent(Intent.ACTION_MAIN); 19732 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 19733 19734 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 19735 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 19736 | MATCH_DISABLED_COMPONENTS, 19737 UserHandle.myUserId()); 19738 if (matches.size() == 1) { 19739 return matches.get(0).getComponentInfo().packageName; 19740 } else { 19741 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 19742 + ": matches=" + matches); 19743 return null; 19744 } 19745 } 19746 19747 private @Nullable String getStorageManagerPackageName() { 19748 final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE); 19749 19750 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 19751 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 19752 | MATCH_DISABLED_COMPONENTS, 19753 UserHandle.myUserId()); 19754 if (matches.size() == 1) { 19755 return matches.get(0).getComponentInfo().packageName; 19756 } else { 19757 Slog.e(TAG, "There should probably be exactly one storage manager; found " 19758 + matches.size() + ": matches=" + matches); 19759 return null; 19760 } 19761 } 19762 19763 @Override 19764 public void setApplicationEnabledSetting(String appPackageName, 19765 int newState, int flags, int userId, String callingPackage) { 19766 if (!sUserManager.exists(userId)) return; 19767 if (callingPackage == null) { 19768 callingPackage = Integer.toString(Binder.getCallingUid()); 19769 } 19770 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 19771 } 19772 19773 @Override 19774 public void setComponentEnabledSetting(ComponentName componentName, 19775 int newState, int flags, int userId) { 19776 if (!sUserManager.exists(userId)) return; 19777 setEnabledSetting(componentName.getPackageName(), 19778 componentName.getClassName(), newState, flags, userId, null); 19779 } 19780 19781 private void setEnabledSetting(final String packageName, String className, int newState, 19782 final int flags, int userId, String callingPackage) { 19783 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 19784 || newState == COMPONENT_ENABLED_STATE_ENABLED 19785 || newState == COMPONENT_ENABLED_STATE_DISABLED 19786 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 19787 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 19788 throw new IllegalArgumentException("Invalid new component state: " 19789 + newState); 19790 } 19791 PackageSetting pkgSetting; 19792 final int uid = Binder.getCallingUid(); 19793 final int permission; 19794 if (uid == Process.SYSTEM_UID) { 19795 permission = PackageManager.PERMISSION_GRANTED; 19796 } else { 19797 permission = mContext.checkCallingOrSelfPermission( 19798 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 19799 } 19800 enforceCrossUserPermission(uid, userId, 19801 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 19802 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 19803 boolean sendNow = false; 19804 boolean isApp = (className == null); 19805 String componentName = isApp ? packageName : className; 19806 int packageUid = -1; 19807 ArrayList<String> components; 19808 19809 // writer 19810 synchronized (mPackages) { 19811 pkgSetting = mSettings.mPackages.get(packageName); 19812 if (pkgSetting == null) { 19813 if (className == null) { 19814 throw new IllegalArgumentException("Unknown package: " + packageName); 19815 } 19816 throw new IllegalArgumentException( 19817 "Unknown component: " + packageName + "/" + className); 19818 } 19819 } 19820 19821 // Limit who can change which apps 19822 if (!UserHandle.isSameApp(uid, pkgSetting.appId)) { 19823 // Don't allow apps that don't have permission to modify other apps 19824 if (!allowedByPermission) { 19825 throw new SecurityException( 19826 "Permission Denial: attempt to change component state from pid=" 19827 + Binder.getCallingPid() 19828 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 19829 } 19830 // Don't allow changing protected packages. 19831 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 19832 throw new SecurityException("Cannot disable a protected package: " + packageName); 19833 } 19834 } 19835 19836 synchronized (mPackages) { 19837 if (uid == Process.SHELL_UID 19838 && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) { 19839 // Shell can only change whole packages between ENABLED and DISABLED_USER states 19840 // unless it is a test package. 19841 int oldState = pkgSetting.getEnabled(userId); 19842 if (className == null 19843 && 19844 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 19845 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 19846 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 19847 && 19848 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 19849 || newState == COMPONENT_ENABLED_STATE_DEFAULT 19850 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 19851 // ok 19852 } else { 19853 throw new SecurityException( 19854 "Shell cannot change component state for " + packageName + "/" 19855 + className + " to " + newState); 19856 } 19857 } 19858 if (className == null) { 19859 // We're dealing with an application/package level state change 19860 if (pkgSetting.getEnabled(userId) == newState) { 19861 // Nothing to do 19862 return; 19863 } 19864 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 19865 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 19866 // Don't care about who enables an app. 19867 callingPackage = null; 19868 } 19869 pkgSetting.setEnabled(newState, userId, callingPackage); 19870 // pkgSetting.pkg.mSetEnabled = newState; 19871 } else { 19872 // We're dealing with a component level state change 19873 // First, verify that this is a valid class name. 19874 PackageParser.Package pkg = pkgSetting.pkg; 19875 if (pkg == null || !pkg.hasComponentClassName(className)) { 19876 if (pkg != null && 19877 pkg.applicationInfo.targetSdkVersion >= 19878 Build.VERSION_CODES.JELLY_BEAN) { 19879 throw new IllegalArgumentException("Component class " + className 19880 + " does not exist in " + packageName); 19881 } else { 19882 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 19883 + className + " does not exist in " + packageName); 19884 } 19885 } 19886 switch (newState) { 19887 case COMPONENT_ENABLED_STATE_ENABLED: 19888 if (!pkgSetting.enableComponentLPw(className, userId)) { 19889 return; 19890 } 19891 break; 19892 case COMPONENT_ENABLED_STATE_DISABLED: 19893 if (!pkgSetting.disableComponentLPw(className, userId)) { 19894 return; 19895 } 19896 break; 19897 case COMPONENT_ENABLED_STATE_DEFAULT: 19898 if (!pkgSetting.restoreComponentLPw(className, userId)) { 19899 return; 19900 } 19901 break; 19902 default: 19903 Slog.e(TAG, "Invalid new component state: " + newState); 19904 return; 19905 } 19906 } 19907 scheduleWritePackageRestrictionsLocked(userId); 19908 updateSequenceNumberLP(packageName, new int[] { userId }); 19909 components = mPendingBroadcasts.get(userId, packageName); 19910 final boolean newPackage = components == null; 19911 if (newPackage) { 19912 components = new ArrayList<String>(); 19913 } 19914 if (!components.contains(componentName)) { 19915 components.add(componentName); 19916 } 19917 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 19918 sendNow = true; 19919 // Purge entry from pending broadcast list if another one exists already 19920 // since we are sending one right away. 19921 mPendingBroadcasts.remove(userId, packageName); 19922 } else { 19923 if (newPackage) { 19924 mPendingBroadcasts.put(userId, packageName, components); 19925 } 19926 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 19927 // Schedule a message 19928 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 19929 } 19930 } 19931 } 19932 19933 long callingId = Binder.clearCallingIdentity(); 19934 try { 19935 if (sendNow) { 19936 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 19937 sendPackageChangedBroadcast(packageName, 19938 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 19939 } 19940 } finally { 19941 Binder.restoreCallingIdentity(callingId); 19942 } 19943 } 19944 19945 @Override 19946 public void flushPackageRestrictionsAsUser(int userId) { 19947 if (!sUserManager.exists(userId)) { 19948 return; 19949 } 19950 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 19951 false /* checkShell */, "flushPackageRestrictions"); 19952 synchronized (mPackages) { 19953 mSettings.writePackageRestrictionsLPr(userId); 19954 mDirtyUsers.remove(userId); 19955 if (mDirtyUsers.isEmpty()) { 19956 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 19957 } 19958 } 19959 } 19960 19961 private void sendPackageChangedBroadcast(String packageName, 19962 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 19963 if (DEBUG_INSTALL) 19964 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 19965 + componentNames); 19966 Bundle extras = new Bundle(4); 19967 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 19968 String nameList[] = new String[componentNames.size()]; 19969 componentNames.toArray(nameList); 19970 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 19971 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 19972 extras.putInt(Intent.EXTRA_UID, packageUid); 19973 // If this is not reporting a change of the overall package, then only send it 19974 // to registered receivers. We don't want to launch a swath of apps for every 19975 // little component state change. 19976 final int flags = !componentNames.contains(packageName) 19977 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 19978 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 19979 new int[] {UserHandle.getUserId(packageUid)}); 19980 } 19981 19982 @Override 19983 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 19984 if (!sUserManager.exists(userId)) return; 19985 final int uid = Binder.getCallingUid(); 19986 final int permission = mContext.checkCallingOrSelfPermission( 19987 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 19988 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 19989 enforceCrossUserPermission(uid, userId, 19990 true /* requireFullPermission */, true /* checkShell */, "stop package"); 19991 // writer 19992 synchronized (mPackages) { 19993 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 19994 allowedByPermission, uid, userId)) { 19995 scheduleWritePackageRestrictionsLocked(userId); 19996 } 19997 } 19998 } 19999 20000 @Override 20001 public String getInstallerPackageName(String packageName) { 20002 // reader 20003 synchronized (mPackages) { 20004 return mSettings.getInstallerPackageNameLPr(packageName); 20005 } 20006 } 20007 20008 public boolean isOrphaned(String packageName) { 20009 // reader 20010 synchronized (mPackages) { 20011 return mSettings.isOrphaned(packageName); 20012 } 20013 } 20014 20015 @Override 20016 public int getApplicationEnabledSetting(String packageName, int userId) { 20017 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 20018 int uid = Binder.getCallingUid(); 20019 enforceCrossUserPermission(uid, userId, 20020 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 20021 // reader 20022 synchronized (mPackages) { 20023 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 20024 } 20025 } 20026 20027 @Override 20028 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 20029 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 20030 int uid = Binder.getCallingUid(); 20031 enforceCrossUserPermission(uid, userId, 20032 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 20033 // reader 20034 synchronized (mPackages) { 20035 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 20036 } 20037 } 20038 20039 @Override 20040 public void enterSafeMode() { 20041 enforceSystemOrRoot("Only the system can request entering safe mode"); 20042 20043 if (!mSystemReady) { 20044 mSafeMode = true; 20045 } 20046 } 20047 20048 @Override 20049 public void systemReady() { 20050 mSystemReady = true; 20051 20052 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 20053 // disabled after already being started. 20054 CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this, 20055 mContext.getContentResolver(), UserHandle.USER_SYSTEM); 20056 20057 // Read the compatibilty setting when the system is ready. 20058 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 20059 mContext.getContentResolver(), 20060 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 20061 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 20062 if (DEBUG_SETTINGS) { 20063 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 20064 } 20065 20066 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 20067 20068 synchronized (mPackages) { 20069 // Verify that all of the preferred activity components actually 20070 // exist. It is possible for applications to be updated and at 20071 // that point remove a previously declared activity component that 20072 // had been set as a preferred activity. We try to clean this up 20073 // the next time we encounter that preferred activity, but it is 20074 // possible for the user flow to never be able to return to that 20075 // situation so here we do a sanity check to make sure we haven't 20076 // left any junk around. 20077 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 20078 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 20079 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 20080 removed.clear(); 20081 for (PreferredActivity pa : pir.filterSet()) { 20082 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 20083 removed.add(pa); 20084 } 20085 } 20086 if (removed.size() > 0) { 20087 for (int r=0; r<removed.size(); r++) { 20088 PreferredActivity pa = removed.get(r); 20089 Slog.w(TAG, "Removing dangling preferred activity: " 20090 + pa.mPref.mComponent); 20091 pir.removeFilter(pa); 20092 } 20093 mSettings.writePackageRestrictionsLPr( 20094 mSettings.mPreferredActivities.keyAt(i)); 20095 } 20096 } 20097 20098 for (int userId : UserManagerService.getInstance().getUserIds()) { 20099 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 20100 grantPermissionsUserIds = ArrayUtils.appendInt( 20101 grantPermissionsUserIds, userId); 20102 } 20103 } 20104 } 20105 sUserManager.systemReady(); 20106 20107 // If we upgraded grant all default permissions before kicking off. 20108 for (int userId : grantPermissionsUserIds) { 20109 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 20110 } 20111 20112 // If we did not grant default permissions, we preload from this the 20113 // default permission exceptions lazily to ensure we don't hit the 20114 // disk on a new user creation. 20115 if (grantPermissionsUserIds == EMPTY_INT_ARRAY) { 20116 mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions(); 20117 } 20118 20119 // Kick off any messages waiting for system ready 20120 if (mPostSystemReadyMessages != null) { 20121 for (Message msg : mPostSystemReadyMessages) { 20122 msg.sendToTarget(); 20123 } 20124 mPostSystemReadyMessages = null; 20125 } 20126 20127 // Watch for external volumes that come and go over time 20128 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20129 storage.registerListener(mStorageListener); 20130 20131 mInstallerService.systemReady(); 20132 mPackageDexOptimizer.systemReady(); 20133 20134 StorageManagerInternal StorageManagerInternal = LocalServices.getService( 20135 StorageManagerInternal.class); 20136 StorageManagerInternal.addExternalStoragePolicy( 20137 new StorageManagerInternal.ExternalStorageMountPolicy() { 20138 @Override 20139 public int getMountMode(int uid, String packageName) { 20140 if (Process.isIsolated(uid)) { 20141 return Zygote.MOUNT_EXTERNAL_NONE; 20142 } 20143 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 20144 return Zygote.MOUNT_EXTERNAL_DEFAULT; 20145 } 20146 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 20147 return Zygote.MOUNT_EXTERNAL_DEFAULT; 20148 } 20149 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 20150 return Zygote.MOUNT_EXTERNAL_READ; 20151 } 20152 return Zygote.MOUNT_EXTERNAL_WRITE; 20153 } 20154 20155 @Override 20156 public boolean hasExternalStorage(int uid, String packageName) { 20157 return true; 20158 } 20159 }); 20160 20161 // Now that we're mostly running, clean up stale users and apps 20162 sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 20163 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 20164 20165 if (mPrivappPermissionsViolations != null) { 20166 Slog.wtf(TAG,"Signature|privileged permissions not in " 20167 + "privapp-permissions whitelist: " + mPrivappPermissionsViolations); 20168 mPrivappPermissionsViolations = null; 20169 } 20170 } 20171 20172 public void waitForAppDataPrepared() { 20173 if (mPrepareAppDataFuture == null) { 20174 return; 20175 } 20176 ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData"); 20177 mPrepareAppDataFuture = null; 20178 } 20179 20180 @Override 20181 public boolean isSafeMode() { 20182 return mSafeMode; 20183 } 20184 20185 @Override 20186 public boolean hasSystemUidErrors() { 20187 return mHasSystemUidErrors; 20188 } 20189 20190 static String arrayToString(int[] array) { 20191 StringBuffer buf = new StringBuffer(128); 20192 buf.append('['); 20193 if (array != null) { 20194 for (int i=0; i<array.length; i++) { 20195 if (i > 0) buf.append(", "); 20196 buf.append(array[i]); 20197 } 20198 } 20199 buf.append(']'); 20200 return buf.toString(); 20201 } 20202 20203 static class DumpState { 20204 public static final int DUMP_LIBS = 1 << 0; 20205 public static final int DUMP_FEATURES = 1 << 1; 20206 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 20207 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 20208 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 20209 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 20210 public static final int DUMP_PERMISSIONS = 1 << 6; 20211 public static final int DUMP_PACKAGES = 1 << 7; 20212 public static final int DUMP_SHARED_USERS = 1 << 8; 20213 public static final int DUMP_MESSAGES = 1 << 9; 20214 public static final int DUMP_PROVIDERS = 1 << 10; 20215 public static final int DUMP_VERIFIERS = 1 << 11; 20216 public static final int DUMP_PREFERRED = 1 << 12; 20217 public static final int DUMP_PREFERRED_XML = 1 << 13; 20218 public static final int DUMP_KEYSETS = 1 << 14; 20219 public static final int DUMP_VERSION = 1 << 15; 20220 public static final int DUMP_INSTALLS = 1 << 16; 20221 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 20222 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 20223 public static final int DUMP_FROZEN = 1 << 19; 20224 public static final int DUMP_DEXOPT = 1 << 20; 20225 public static final int DUMP_COMPILER_STATS = 1 << 21; 20226 20227 public static final int OPTION_SHOW_FILTERS = 1 << 0; 20228 20229 private int mTypes; 20230 20231 private int mOptions; 20232 20233 private boolean mTitlePrinted; 20234 20235 private SharedUserSetting mSharedUser; 20236 20237 public boolean isDumping(int type) { 20238 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 20239 return true; 20240 } 20241 20242 return (mTypes & type) != 0; 20243 } 20244 20245 public void setDump(int type) { 20246 mTypes |= type; 20247 } 20248 20249 public boolean isOptionEnabled(int option) { 20250 return (mOptions & option) != 0; 20251 } 20252 20253 public void setOptionEnabled(int option) { 20254 mOptions |= option; 20255 } 20256 20257 public boolean onTitlePrinted() { 20258 final boolean printed = mTitlePrinted; 20259 mTitlePrinted = true; 20260 return printed; 20261 } 20262 20263 public boolean getTitlePrinted() { 20264 return mTitlePrinted; 20265 } 20266 20267 public void setTitlePrinted(boolean enabled) { 20268 mTitlePrinted = enabled; 20269 } 20270 20271 public SharedUserSetting getSharedUser() { 20272 return mSharedUser; 20273 } 20274 20275 public void setSharedUser(SharedUserSetting user) { 20276 mSharedUser = user; 20277 } 20278 } 20279 20280 @Override 20281 public void onShellCommand(FileDescriptor in, FileDescriptor out, 20282 FileDescriptor err, String[] args, ShellCallback callback, 20283 ResultReceiver resultReceiver) { 20284 (new PackageManagerShellCommand(this)).exec( 20285 this, in, out, err, args, callback, resultReceiver); 20286 } 20287 20288 @Override 20289 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 20290 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 20291 != PackageManager.PERMISSION_GRANTED) { 20292 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 20293 + Binder.getCallingPid() 20294 + ", uid=" + Binder.getCallingUid() 20295 + " without permission " 20296 + android.Manifest.permission.DUMP); 20297 return; 20298 } 20299 20300 DumpState dumpState = new DumpState(); 20301 boolean fullPreferred = false; 20302 boolean checkin = false; 20303 20304 String packageName = null; 20305 ArraySet<String> permissionNames = null; 20306 20307 int opti = 0; 20308 while (opti < args.length) { 20309 String opt = args[opti]; 20310 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 20311 break; 20312 } 20313 opti++; 20314 20315 if ("-a".equals(opt)) { 20316 // Right now we only know how to print all. 20317 } else if ("-h".equals(opt)) { 20318 pw.println("Package manager dump options:"); 20319 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 20320 pw.println(" --checkin: dump for a checkin"); 20321 pw.println(" -f: print details of intent filters"); 20322 pw.println(" -h: print this help"); 20323 pw.println(" cmd may be one of:"); 20324 pw.println(" l[ibraries]: list known shared libraries"); 20325 pw.println(" f[eatures]: list device features"); 20326 pw.println(" k[eysets]: print known keysets"); 20327 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 20328 pw.println(" perm[issions]: dump permissions"); 20329 pw.println(" permission [name ...]: dump declaration and use of given permission"); 20330 pw.println(" pref[erred]: print preferred package settings"); 20331 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 20332 pw.println(" prov[iders]: dump content providers"); 20333 pw.println(" p[ackages]: dump installed packages"); 20334 pw.println(" s[hared-users]: dump shared user IDs"); 20335 pw.println(" m[essages]: print collected runtime messages"); 20336 pw.println(" v[erifiers]: print package verifier info"); 20337 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 20338 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 20339 pw.println(" version: print database version info"); 20340 pw.println(" write: write current settings now"); 20341 pw.println(" installs: details about install sessions"); 20342 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 20343 pw.println(" dexopt: dump dexopt state"); 20344 pw.println(" compiler-stats: dump compiler statistics"); 20345 pw.println(" <package.name>: info about given package"); 20346 return; 20347 } else if ("--checkin".equals(opt)) { 20348 checkin = true; 20349 } else if ("-f".equals(opt)) { 20350 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 20351 } else { 20352 pw.println("Unknown argument: " + opt + "; use -h for help"); 20353 } 20354 } 20355 20356 // Is the caller requesting to dump a particular piece of data? 20357 if (opti < args.length) { 20358 String cmd = args[opti]; 20359 opti++; 20360 // Is this a package name? 20361 if ("android".equals(cmd) || cmd.contains(".")) { 20362 packageName = cmd; 20363 // When dumping a single package, we always dump all of its 20364 // filter information since the amount of data will be reasonable. 20365 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 20366 } else if ("check-permission".equals(cmd)) { 20367 if (opti >= args.length) { 20368 pw.println("Error: check-permission missing permission argument"); 20369 return; 20370 } 20371 String perm = args[opti]; 20372 opti++; 20373 if (opti >= args.length) { 20374 pw.println("Error: check-permission missing package argument"); 20375 return; 20376 } 20377 20378 String pkg = args[opti]; 20379 opti++; 20380 int user = UserHandle.getUserId(Binder.getCallingUid()); 20381 if (opti < args.length) { 20382 try { 20383 user = Integer.parseInt(args[opti]); 20384 } catch (NumberFormatException e) { 20385 pw.println("Error: check-permission user argument is not a number: " 20386 + args[opti]); 20387 return; 20388 } 20389 } 20390 20391 // Normalize package name to handle renamed packages and static libs 20392 pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST); 20393 20394 pw.println(checkPermission(perm, pkg, user)); 20395 return; 20396 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 20397 dumpState.setDump(DumpState.DUMP_LIBS); 20398 } else if ("f".equals(cmd) || "features".equals(cmd)) { 20399 dumpState.setDump(DumpState.DUMP_FEATURES); 20400 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 20401 if (opti >= args.length) { 20402 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 20403 | DumpState.DUMP_SERVICE_RESOLVERS 20404 | DumpState.DUMP_RECEIVER_RESOLVERS 20405 | DumpState.DUMP_CONTENT_RESOLVERS); 20406 } else { 20407 while (opti < args.length) { 20408 String name = args[opti]; 20409 if ("a".equals(name) || "activity".equals(name)) { 20410 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 20411 } else if ("s".equals(name) || "service".equals(name)) { 20412 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 20413 } else if ("r".equals(name) || "receiver".equals(name)) { 20414 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 20415 } else if ("c".equals(name) || "content".equals(name)) { 20416 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 20417 } else { 20418 pw.println("Error: unknown resolver table type: " + name); 20419 return; 20420 } 20421 opti++; 20422 } 20423 } 20424 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 20425 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 20426 } else if ("permission".equals(cmd)) { 20427 if (opti >= args.length) { 20428 pw.println("Error: permission requires permission name"); 20429 return; 20430 } 20431 permissionNames = new ArraySet<>(); 20432 while (opti < args.length) { 20433 permissionNames.add(args[opti]); 20434 opti++; 20435 } 20436 dumpState.setDump(DumpState.DUMP_PERMISSIONS 20437 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 20438 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 20439 dumpState.setDump(DumpState.DUMP_PREFERRED); 20440 } else if ("preferred-xml".equals(cmd)) { 20441 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 20442 if (opti < args.length && "--full".equals(args[opti])) { 20443 fullPreferred = true; 20444 opti++; 20445 } 20446 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 20447 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 20448 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 20449 dumpState.setDump(DumpState.DUMP_PACKAGES); 20450 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 20451 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 20452 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 20453 dumpState.setDump(DumpState.DUMP_PROVIDERS); 20454 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 20455 dumpState.setDump(DumpState.DUMP_MESSAGES); 20456 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 20457 dumpState.setDump(DumpState.DUMP_VERIFIERS); 20458 } else if ("i".equals(cmd) || "ifv".equals(cmd) 20459 || "intent-filter-verifiers".equals(cmd)) { 20460 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 20461 } else if ("version".equals(cmd)) { 20462 dumpState.setDump(DumpState.DUMP_VERSION); 20463 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 20464 dumpState.setDump(DumpState.DUMP_KEYSETS); 20465 } else if ("installs".equals(cmd)) { 20466 dumpState.setDump(DumpState.DUMP_INSTALLS); 20467 } else if ("frozen".equals(cmd)) { 20468 dumpState.setDump(DumpState.DUMP_FROZEN); 20469 } else if ("dexopt".equals(cmd)) { 20470 dumpState.setDump(DumpState.DUMP_DEXOPT); 20471 } else if ("compiler-stats".equals(cmd)) { 20472 dumpState.setDump(DumpState.DUMP_COMPILER_STATS); 20473 } else if ("write".equals(cmd)) { 20474 synchronized (mPackages) { 20475 mSettings.writeLPr(); 20476 pw.println("Settings written."); 20477 return; 20478 } 20479 } 20480 } 20481 20482 if (checkin) { 20483 pw.println("vers,1"); 20484 } 20485 20486 // reader 20487 synchronized (mPackages) { 20488 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 20489 if (!checkin) { 20490 if (dumpState.onTitlePrinted()) 20491 pw.println(); 20492 pw.println("Database versions:"); 20493 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 20494 } 20495 } 20496 20497 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 20498 if (!checkin) { 20499 if (dumpState.onTitlePrinted()) 20500 pw.println(); 20501 pw.println("Verifiers:"); 20502 pw.print(" Required: "); 20503 pw.print(mRequiredVerifierPackage); 20504 pw.print(" (uid="); 20505 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 20506 UserHandle.USER_SYSTEM)); 20507 pw.println(")"); 20508 } else if (mRequiredVerifierPackage != null) { 20509 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 20510 pw.print(","); 20511 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 20512 UserHandle.USER_SYSTEM)); 20513 } 20514 } 20515 20516 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 20517 packageName == null) { 20518 if (mIntentFilterVerifierComponent != null) { 20519 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 20520 if (!checkin) { 20521 if (dumpState.onTitlePrinted()) 20522 pw.println(); 20523 pw.println("Intent Filter Verifier:"); 20524 pw.print(" Using: "); 20525 pw.print(verifierPackageName); 20526 pw.print(" (uid="); 20527 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 20528 UserHandle.USER_SYSTEM)); 20529 pw.println(")"); 20530 } else if (verifierPackageName != null) { 20531 pw.print("ifv,"); pw.print(verifierPackageName); 20532 pw.print(","); 20533 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 20534 UserHandle.USER_SYSTEM)); 20535 } 20536 } else { 20537 pw.println(); 20538 pw.println("No Intent Filter Verifier available!"); 20539 } 20540 } 20541 20542 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 20543 boolean printedHeader = false; 20544 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 20545 while (it.hasNext()) { 20546 String libName = it.next(); 20547 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName); 20548 if (versionedLib == null) { 20549 continue; 20550 } 20551 final int versionCount = versionedLib.size(); 20552 for (int i = 0; i < versionCount; i++) { 20553 SharedLibraryEntry libEntry = versionedLib.valueAt(i); 20554 if (!checkin) { 20555 if (!printedHeader) { 20556 if (dumpState.onTitlePrinted()) 20557 pw.println(); 20558 pw.println("Libraries:"); 20559 printedHeader = true; 20560 } 20561 pw.print(" "); 20562 } else { 20563 pw.print("lib,"); 20564 } 20565 pw.print(libEntry.info.getName()); 20566 if (libEntry.info.isStatic()) { 20567 pw.print(" version=" + libEntry.info.getVersion()); 20568 } 20569 if (!checkin) { 20570 pw.print(" -> "); 20571 } 20572 if (libEntry.path != null) { 20573 pw.print(" (jar) "); 20574 pw.print(libEntry.path); 20575 } else { 20576 pw.print(" (apk) "); 20577 pw.print(libEntry.apk); 20578 } 20579 pw.println(); 20580 } 20581 } 20582 } 20583 20584 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 20585 if (dumpState.onTitlePrinted()) 20586 pw.println(); 20587 if (!checkin) { 20588 pw.println("Features:"); 20589 } 20590 20591 synchronized (mAvailableFeatures) { 20592 for (FeatureInfo feat : mAvailableFeatures.values()) { 20593 if (checkin) { 20594 pw.print("feat,"); 20595 pw.print(feat.name); 20596 pw.print(","); 20597 pw.println(feat.version); 20598 } else { 20599 pw.print(" "); 20600 pw.print(feat.name); 20601 if (feat.version > 0) { 20602 pw.print(" version="); 20603 pw.print(feat.version); 20604 } 20605 pw.println(); 20606 } 20607 } 20608 } 20609 } 20610 20611 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 20612 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 20613 : "Activity Resolver Table:", " ", packageName, 20614 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20615 dumpState.setTitlePrinted(true); 20616 } 20617 } 20618 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 20619 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 20620 : "Receiver Resolver Table:", " ", packageName, 20621 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20622 dumpState.setTitlePrinted(true); 20623 } 20624 } 20625 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 20626 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 20627 : "Service Resolver Table:", " ", packageName, 20628 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20629 dumpState.setTitlePrinted(true); 20630 } 20631 } 20632 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 20633 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 20634 : "Provider Resolver Table:", " ", packageName, 20635 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20636 dumpState.setTitlePrinted(true); 20637 } 20638 } 20639 20640 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 20641 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 20642 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 20643 int user = mSettings.mPreferredActivities.keyAt(i); 20644 if (pir.dump(pw, 20645 dumpState.getTitlePrinted() 20646 ? "\nPreferred Activities User " + user + ":" 20647 : "Preferred Activities User " + user + ":", " ", 20648 packageName, true, false)) { 20649 dumpState.setTitlePrinted(true); 20650 } 20651 } 20652 } 20653 20654 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 20655 pw.flush(); 20656 FileOutputStream fout = new FileOutputStream(fd); 20657 BufferedOutputStream str = new BufferedOutputStream(fout); 20658 XmlSerializer serializer = new FastXmlSerializer(); 20659 try { 20660 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 20661 serializer.startDocument(null, true); 20662 serializer.setFeature( 20663 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 20664 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 20665 serializer.endDocument(); 20666 serializer.flush(); 20667 } catch (IllegalArgumentException e) { 20668 pw.println("Failed writing: " + e); 20669 } catch (IllegalStateException e) { 20670 pw.println("Failed writing: " + e); 20671 } catch (IOException e) { 20672 pw.println("Failed writing: " + e); 20673 } 20674 } 20675 20676 if (!checkin 20677 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 20678 && packageName == null) { 20679 pw.println(); 20680 int count = mSettings.mPackages.size(); 20681 if (count == 0) { 20682 pw.println("No applications!"); 20683 pw.println(); 20684 } else { 20685 final String prefix = " "; 20686 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 20687 if (allPackageSettings.size() == 0) { 20688 pw.println("No domain preferred apps!"); 20689 pw.println(); 20690 } else { 20691 pw.println("App verification status:"); 20692 pw.println(); 20693 count = 0; 20694 for (PackageSetting ps : allPackageSettings) { 20695 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 20696 if (ivi == null || ivi.getPackageName() == null) continue; 20697 pw.println(prefix + "Package: " + ivi.getPackageName()); 20698 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 20699 pw.println(prefix + "Status: " + ivi.getStatusString()); 20700 pw.println(); 20701 count++; 20702 } 20703 if (count == 0) { 20704 pw.println(prefix + "No app verification established."); 20705 pw.println(); 20706 } 20707 for (int userId : sUserManager.getUserIds()) { 20708 pw.println("App linkages for user " + userId + ":"); 20709 pw.println(); 20710 count = 0; 20711 for (PackageSetting ps : allPackageSettings) { 20712 final long status = ps.getDomainVerificationStatusForUser(userId); 20713 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 20714 && !DEBUG_DOMAIN_VERIFICATION) { 20715 continue; 20716 } 20717 pw.println(prefix + "Package: " + ps.name); 20718 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 20719 String statusStr = IntentFilterVerificationInfo. 20720 getStatusStringFromValue(status); 20721 pw.println(prefix + "Status: " + statusStr); 20722 pw.println(); 20723 count++; 20724 } 20725 if (count == 0) { 20726 pw.println(prefix + "No configured app linkages."); 20727 pw.println(); 20728 } 20729 } 20730 } 20731 } 20732 } 20733 20734 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 20735 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 20736 if (packageName == null && permissionNames == null) { 20737 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 20738 if (iperm == 0) { 20739 if (dumpState.onTitlePrinted()) 20740 pw.println(); 20741 pw.println("AppOp Permissions:"); 20742 } 20743 pw.print(" AppOp Permission "); 20744 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 20745 pw.println(":"); 20746 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 20747 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 20748 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 20749 } 20750 } 20751 } 20752 } 20753 20754 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 20755 boolean printedSomething = false; 20756 for (PackageParser.Provider p : mProviders.mProviders.values()) { 20757 if (packageName != null && !packageName.equals(p.info.packageName)) { 20758 continue; 20759 } 20760 if (!printedSomething) { 20761 if (dumpState.onTitlePrinted()) 20762 pw.println(); 20763 pw.println("Registered ContentProviders:"); 20764 printedSomething = true; 20765 } 20766 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 20767 pw.print(" "); pw.println(p.toString()); 20768 } 20769 printedSomething = false; 20770 for (Map.Entry<String, PackageParser.Provider> entry : 20771 mProvidersByAuthority.entrySet()) { 20772 PackageParser.Provider p = entry.getValue(); 20773 if (packageName != null && !packageName.equals(p.info.packageName)) { 20774 continue; 20775 } 20776 if (!printedSomething) { 20777 if (dumpState.onTitlePrinted()) 20778 pw.println(); 20779 pw.println("ContentProvider Authorities:"); 20780 printedSomething = true; 20781 } 20782 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 20783 pw.print(" "); pw.println(p.toString()); 20784 if (p.info != null && p.info.applicationInfo != null) { 20785 final String appInfo = p.info.applicationInfo.toString(); 20786 pw.print(" applicationInfo="); pw.println(appInfo); 20787 } 20788 } 20789 } 20790 20791 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 20792 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 20793 } 20794 20795 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 20796 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 20797 } 20798 20799 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 20800 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 20801 } 20802 20803 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 20804 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 20805 } 20806 20807 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 20808 // XXX should handle packageName != null by dumping only install data that 20809 // the given package is involved with. 20810 if (dumpState.onTitlePrinted()) pw.println(); 20811 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 20812 } 20813 20814 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 20815 // XXX should handle packageName != null by dumping only install data that 20816 // the given package is involved with. 20817 if (dumpState.onTitlePrinted()) pw.println(); 20818 20819 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 20820 ipw.println(); 20821 ipw.println("Frozen packages:"); 20822 ipw.increaseIndent(); 20823 if (mFrozenPackages.size() == 0) { 20824 ipw.println("(none)"); 20825 } else { 20826 for (int i = 0; i < mFrozenPackages.size(); i++) { 20827 ipw.println(mFrozenPackages.valueAt(i)); 20828 } 20829 } 20830 ipw.decreaseIndent(); 20831 } 20832 20833 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 20834 if (dumpState.onTitlePrinted()) pw.println(); 20835 dumpDexoptStateLPr(pw, packageName); 20836 } 20837 20838 if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) { 20839 if (dumpState.onTitlePrinted()) pw.println(); 20840 dumpCompilerStatsLPr(pw, packageName); 20841 } 20842 20843 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 20844 if (dumpState.onTitlePrinted()) pw.println(); 20845 mSettings.dumpReadMessagesLPr(pw, dumpState); 20846 20847 pw.println(); 20848 pw.println("Package warning messages:"); 20849 BufferedReader in = null; 20850 String line = null; 20851 try { 20852 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 20853 while ((line = in.readLine()) != null) { 20854 if (line.contains("ignored: updated version")) continue; 20855 pw.println(line); 20856 } 20857 } catch (IOException ignored) { 20858 } finally { 20859 IoUtils.closeQuietly(in); 20860 } 20861 } 20862 20863 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 20864 BufferedReader in = null; 20865 String line = null; 20866 try { 20867 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 20868 while ((line = in.readLine()) != null) { 20869 if (line.contains("ignored: updated version")) continue; 20870 pw.print("msg,"); 20871 pw.println(line); 20872 } 20873 } catch (IOException ignored) { 20874 } finally { 20875 IoUtils.closeQuietly(in); 20876 } 20877 } 20878 } 20879 } 20880 20881 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 20882 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 20883 ipw.println(); 20884 ipw.println("Dexopt state:"); 20885 ipw.increaseIndent(); 20886 Collection<PackageParser.Package> packages = null; 20887 if (packageName != null) { 20888 PackageParser.Package targetPackage = mPackages.get(packageName); 20889 if (targetPackage != null) { 20890 packages = Collections.singletonList(targetPackage); 20891 } else { 20892 ipw.println("Unable to find package: " + packageName); 20893 return; 20894 } 20895 } else { 20896 packages = mPackages.values(); 20897 } 20898 20899 for (PackageParser.Package pkg : packages) { 20900 ipw.println("[" + pkg.packageName + "]"); 20901 ipw.increaseIndent(); 20902 mPackageDexOptimizer.dumpDexoptState(ipw, pkg); 20903 ipw.decreaseIndent(); 20904 } 20905 } 20906 20907 private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) { 20908 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 20909 ipw.println(); 20910 ipw.println("Compiler stats:"); 20911 ipw.increaseIndent(); 20912 Collection<PackageParser.Package> packages = null; 20913 if (packageName != null) { 20914 PackageParser.Package targetPackage = mPackages.get(packageName); 20915 if (targetPackage != null) { 20916 packages = Collections.singletonList(targetPackage); 20917 } else { 20918 ipw.println("Unable to find package: " + packageName); 20919 return; 20920 } 20921 } else { 20922 packages = mPackages.values(); 20923 } 20924 20925 for (PackageParser.Package pkg : packages) { 20926 ipw.println("[" + pkg.packageName + "]"); 20927 ipw.increaseIndent(); 20928 20929 CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName); 20930 if (stats == null) { 20931 ipw.println("(No recorded stats)"); 20932 } else { 20933 stats.dump(ipw); 20934 } 20935 ipw.decreaseIndent(); 20936 } 20937 } 20938 20939 private String dumpDomainString(String packageName) { 20940 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 20941 .getList(); 20942 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 20943 20944 ArraySet<String> result = new ArraySet<>(); 20945 if (iviList.size() > 0) { 20946 for (IntentFilterVerificationInfo ivi : iviList) { 20947 for (String host : ivi.getDomains()) { 20948 result.add(host); 20949 } 20950 } 20951 } 20952 if (filters != null && filters.size() > 0) { 20953 for (IntentFilter filter : filters) { 20954 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 20955 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 20956 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 20957 result.addAll(filter.getHostsList()); 20958 } 20959 } 20960 } 20961 20962 StringBuilder sb = new StringBuilder(result.size() * 16); 20963 for (String domain : result) { 20964 if (sb.length() > 0) sb.append(" "); 20965 sb.append(domain); 20966 } 20967 return sb.toString(); 20968 } 20969 20970 // ------- apps on sdcard specific code ------- 20971 static final boolean DEBUG_SD_INSTALL = false; 20972 20973 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 20974 20975 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 20976 20977 private boolean mMediaMounted = false; 20978 20979 static String getEncryptKey() { 20980 try { 20981 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 20982 SD_ENCRYPTION_KEYSTORE_NAME); 20983 if (sdEncKey == null) { 20984 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 20985 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 20986 if (sdEncKey == null) { 20987 Slog.e(TAG, "Failed to create encryption keys"); 20988 return null; 20989 } 20990 } 20991 return sdEncKey; 20992 } catch (NoSuchAlgorithmException nsae) { 20993 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 20994 return null; 20995 } catch (IOException ioe) { 20996 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 20997 return null; 20998 } 20999 } 21000 21001 /* 21002 * Update media status on PackageManager. 21003 */ 21004 @Override 21005 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 21006 int callingUid = Binder.getCallingUid(); 21007 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 21008 throw new SecurityException("Media status can only be updated by the system"); 21009 } 21010 // reader; this apparently protects mMediaMounted, but should probably 21011 // be a different lock in that case. 21012 synchronized (mPackages) { 21013 Log.i(TAG, "Updating external media status from " 21014 + (mMediaMounted ? "mounted" : "unmounted") + " to " 21015 + (mediaStatus ? "mounted" : "unmounted")); 21016 if (DEBUG_SD_INSTALL) 21017 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 21018 + ", mMediaMounted=" + mMediaMounted); 21019 if (mediaStatus == mMediaMounted) { 21020 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 21021 : 0, -1); 21022 mHandler.sendMessage(msg); 21023 return; 21024 } 21025 mMediaMounted = mediaStatus; 21026 } 21027 // Queue up an async operation since the package installation may take a 21028 // little while. 21029 mHandler.post(new Runnable() { 21030 public void run() { 21031 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 21032 } 21033 }); 21034 } 21035 21036 /** 21037 * Called by StorageManagerService when the initial ASECs to scan are available. 21038 * Should block until all the ASEC containers are finished being scanned. 21039 */ 21040 public void scanAvailableAsecs() { 21041 updateExternalMediaStatusInner(true, false, false); 21042 } 21043 21044 /* 21045 * Collect information of applications on external media, map them against 21046 * existing containers and update information based on current mount status. 21047 * Please note that we always have to report status if reportStatus has been 21048 * set to true especially when unloading packages. 21049 */ 21050 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 21051 boolean externalStorage) { 21052 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 21053 int[] uidArr = EmptyArray.INT; 21054 21055 final String[] list = PackageHelper.getSecureContainerList(); 21056 if (ArrayUtils.isEmpty(list)) { 21057 Log.i(TAG, "No secure containers found"); 21058 } else { 21059 // Process list of secure containers and categorize them 21060 // as active or stale based on their package internal state. 21061 21062 // reader 21063 synchronized (mPackages) { 21064 for (String cid : list) { 21065 // Leave stages untouched for now; installer service owns them 21066 if (PackageInstallerService.isStageName(cid)) continue; 21067 21068 if (DEBUG_SD_INSTALL) 21069 Log.i(TAG, "Processing container " + cid); 21070 String pkgName = getAsecPackageName(cid); 21071 if (pkgName == null) { 21072 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 21073 continue; 21074 } 21075 if (DEBUG_SD_INSTALL) 21076 Log.i(TAG, "Looking for pkg : " + pkgName); 21077 21078 final PackageSetting ps = mSettings.mPackages.get(pkgName); 21079 if (ps == null) { 21080 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 21081 continue; 21082 } 21083 21084 /* 21085 * Skip packages that are not external if we're unmounting 21086 * external storage. 21087 */ 21088 if (externalStorage && !isMounted && !isExternal(ps)) { 21089 continue; 21090 } 21091 21092 final AsecInstallArgs args = new AsecInstallArgs(cid, 21093 getAppDexInstructionSets(ps), ps.isForwardLocked()); 21094 // The package status is changed only if the code path 21095 // matches between settings and the container id. 21096 if (ps.codePathString != null 21097 && ps.codePathString.startsWith(args.getCodePath())) { 21098 if (DEBUG_SD_INSTALL) { 21099 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 21100 + " at code path: " + ps.codePathString); 21101 } 21102 21103 // We do have a valid package installed on sdcard 21104 processCids.put(args, ps.codePathString); 21105 final int uid = ps.appId; 21106 if (uid != -1) { 21107 uidArr = ArrayUtils.appendInt(uidArr, uid); 21108 } 21109 } else { 21110 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 21111 + ps.codePathString); 21112 } 21113 } 21114 } 21115 21116 Arrays.sort(uidArr); 21117 } 21118 21119 // Process packages with valid entries. 21120 if (isMounted) { 21121 if (DEBUG_SD_INSTALL) 21122 Log.i(TAG, "Loading packages"); 21123 loadMediaPackages(processCids, uidArr, externalStorage); 21124 startCleaningPackages(); 21125 mInstallerService.onSecureContainersAvailable(); 21126 } else { 21127 if (DEBUG_SD_INSTALL) 21128 Log.i(TAG, "Unloading packages"); 21129 unloadMediaPackages(processCids, uidArr, reportStatus); 21130 } 21131 } 21132 21133 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21134 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 21135 final int size = infos.size(); 21136 final String[] packageNames = new String[size]; 21137 final int[] packageUids = new int[size]; 21138 for (int i = 0; i < size; i++) { 21139 final ApplicationInfo info = infos.get(i); 21140 packageNames[i] = info.packageName; 21141 packageUids[i] = info.uid; 21142 } 21143 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 21144 finishedReceiver); 21145 } 21146 21147 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21148 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 21149 sendResourcesChangedBroadcast(mediaStatus, replacing, 21150 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 21151 } 21152 21153 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21154 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 21155 int size = pkgList.length; 21156 if (size > 0) { 21157 // Send broadcasts here 21158 Bundle extras = new Bundle(); 21159 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 21160 if (uidArr != null) { 21161 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 21162 } 21163 if (replacing) { 21164 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 21165 } 21166 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 21167 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 21168 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 21169 } 21170 } 21171 21172 /* 21173 * Look at potentially valid container ids from processCids If package 21174 * information doesn't match the one on record or package scanning fails, 21175 * the cid is added to list of removeCids. We currently don't delete stale 21176 * containers. 21177 */ 21178 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 21179 boolean externalStorage) { 21180 ArrayList<String> pkgList = new ArrayList<String>(); 21181 Set<AsecInstallArgs> keys = processCids.keySet(); 21182 21183 for (AsecInstallArgs args : keys) { 21184 String codePath = processCids.get(args); 21185 if (DEBUG_SD_INSTALL) 21186 Log.i(TAG, "Loading container : " + args.cid); 21187 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 21188 try { 21189 // Make sure there are no container errors first. 21190 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 21191 Slog.e(TAG, "Failed to mount cid : " + args.cid 21192 + " when installing from sdcard"); 21193 continue; 21194 } 21195 // Check code path here. 21196 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 21197 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 21198 + " does not match one in settings " + codePath); 21199 continue; 21200 } 21201 // Parse package 21202 int parseFlags = mDefParseFlags; 21203 if (args.isExternalAsec()) { 21204 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 21205 } 21206 if (args.isFwdLocked()) { 21207 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 21208 } 21209 21210 synchronized (mInstallLock) { 21211 PackageParser.Package pkg = null; 21212 try { 21213 // Sadly we don't know the package name yet to freeze it 21214 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 21215 SCAN_IGNORE_FROZEN, 0, null); 21216 } catch (PackageManagerException e) { 21217 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 21218 } 21219 // Scan the package 21220 if (pkg != null) { 21221 /* 21222 * TODO why is the lock being held? doPostInstall is 21223 * called in other places without the lock. This needs 21224 * to be straightened out. 21225 */ 21226 // writer 21227 synchronized (mPackages) { 21228 retCode = PackageManager.INSTALL_SUCCEEDED; 21229 pkgList.add(pkg.packageName); 21230 // Post process args 21231 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 21232 pkg.applicationInfo.uid); 21233 } 21234 } else { 21235 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 21236 } 21237 } 21238 21239 } finally { 21240 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 21241 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 21242 } 21243 } 21244 } 21245 // writer 21246 synchronized (mPackages) { 21247 // If the platform SDK has changed since the last time we booted, 21248 // we need to re-grant app permission to catch any new ones that 21249 // appear. This is really a hack, and means that apps can in some 21250 // cases get permissions that the user didn't initially explicitly 21251 // allow... it would be nice to have some better way to handle 21252 // this situation. 21253 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 21254 : mSettings.getInternalVersion(); 21255 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 21256 : StorageManager.UUID_PRIVATE_INTERNAL; 21257 21258 int updateFlags = UPDATE_PERMISSIONS_ALL; 21259 if (ver.sdkVersion != mSdkVersion) { 21260 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 21261 + mSdkVersion + "; regranting permissions for external"); 21262 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 21263 } 21264 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 21265 21266 // Yay, everything is now upgraded 21267 ver.forceCurrent(); 21268 21269 // can downgrade to reader 21270 // Persist settings 21271 mSettings.writeLPr(); 21272 } 21273 // Send a broadcast to let everyone know we are done processing 21274 if (pkgList.size() > 0) { 21275 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 21276 } 21277 } 21278 21279 /* 21280 * Utility method to unload a list of specified containers 21281 */ 21282 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 21283 // Just unmount all valid containers. 21284 for (AsecInstallArgs arg : cidArgs) { 21285 synchronized (mInstallLock) { 21286 arg.doPostDeleteLI(false); 21287 } 21288 } 21289 } 21290 21291 /* 21292 * Unload packages mounted on external media. This involves deleting package 21293 * data from internal structures, sending broadcasts about disabled packages, 21294 * gc'ing to free up references, unmounting all secure containers 21295 * corresponding to packages on external media, and posting a 21296 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 21297 * that we always have to post this message if status has been requested no 21298 * matter what. 21299 */ 21300 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 21301 final boolean reportStatus) { 21302 if (DEBUG_SD_INSTALL) 21303 Log.i(TAG, "unloading media packages"); 21304 ArrayList<String> pkgList = new ArrayList<String>(); 21305 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 21306 final Set<AsecInstallArgs> keys = processCids.keySet(); 21307 for (AsecInstallArgs args : keys) { 21308 String pkgName = args.getPackageName(); 21309 if (DEBUG_SD_INSTALL) 21310 Log.i(TAG, "Trying to unload pkg : " + pkgName); 21311 // Delete package internally 21312 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 21313 synchronized (mInstallLock) { 21314 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 21315 final boolean res; 21316 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 21317 "unloadMediaPackages")) { 21318 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 21319 null); 21320 } 21321 if (res) { 21322 pkgList.add(pkgName); 21323 } else { 21324 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 21325 failedList.add(args); 21326 } 21327 } 21328 } 21329 21330 // reader 21331 synchronized (mPackages) { 21332 // We didn't update the settings after removing each package; 21333 // write them now for all packages. 21334 mSettings.writeLPr(); 21335 } 21336 21337 // We have to absolutely send UPDATED_MEDIA_STATUS only 21338 // after confirming that all the receivers processed the ordered 21339 // broadcast when packages get disabled, force a gc to clean things up. 21340 // and unload all the containers. 21341 if (pkgList.size() > 0) { 21342 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 21343 new IIntentReceiver.Stub() { 21344 public void performReceive(Intent intent, int resultCode, String data, 21345 Bundle extras, boolean ordered, boolean sticky, 21346 int sendingUser) throws RemoteException { 21347 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 21348 reportStatus ? 1 : 0, 1, keys); 21349 mHandler.sendMessage(msg); 21350 } 21351 }); 21352 } else { 21353 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 21354 keys); 21355 mHandler.sendMessage(msg); 21356 } 21357 } 21358 21359 private void loadPrivatePackages(final VolumeInfo vol) { 21360 mHandler.post(new Runnable() { 21361 @Override 21362 public void run() { 21363 loadPrivatePackagesInner(vol); 21364 } 21365 }); 21366 } 21367 21368 private void loadPrivatePackagesInner(VolumeInfo vol) { 21369 final String volumeUuid = vol.fsUuid; 21370 if (TextUtils.isEmpty(volumeUuid)) { 21371 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 21372 return; 21373 } 21374 21375 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 21376 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 21377 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 21378 21379 final VersionInfo ver; 21380 final List<PackageSetting> packages; 21381 synchronized (mPackages) { 21382 ver = mSettings.findOrCreateVersion(volumeUuid); 21383 packages = mSettings.getVolumePackagesLPr(volumeUuid); 21384 } 21385 21386 for (PackageSetting ps : packages) { 21387 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 21388 synchronized (mInstallLock) { 21389 final PackageParser.Package pkg; 21390 try { 21391 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 21392 loaded.add(pkg.applicationInfo); 21393 21394 } catch (PackageManagerException e) { 21395 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 21396 } 21397 21398 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 21399 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 21400 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 21401 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 21402 } 21403 } 21404 } 21405 21406 // Reconcile app data for all started/unlocked users 21407 final StorageManager sm = mContext.getSystemService(StorageManager.class); 21408 final UserManager um = mContext.getSystemService(UserManager.class); 21409 UserManagerInternal umInternal = getUserManagerInternal(); 21410 for (UserInfo user : um.getUsers()) { 21411 final int flags; 21412 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 21413 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 21414 } else if (umInternal.isUserRunning(user.id)) { 21415 flags = StorageManager.FLAG_STORAGE_DE; 21416 } else { 21417 continue; 21418 } 21419 21420 try { 21421 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 21422 synchronized (mInstallLock) { 21423 reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */); 21424 } 21425 } catch (IllegalStateException e) { 21426 // Device was probably ejected, and we'll process that event momentarily 21427 Slog.w(TAG, "Failed to prepare storage: " + e); 21428 } 21429 } 21430 21431 synchronized (mPackages) { 21432 int updateFlags = UPDATE_PERMISSIONS_ALL; 21433 if (ver.sdkVersion != mSdkVersion) { 21434 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 21435 + mSdkVersion + "; regranting permissions for " + volumeUuid); 21436 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 21437 } 21438 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 21439 21440 // Yay, everything is now upgraded 21441 ver.forceCurrent(); 21442 21443 mSettings.writeLPr(); 21444 } 21445 21446 for (PackageFreezer freezer : freezers) { 21447 freezer.close(); 21448 } 21449 21450 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 21451 sendResourcesChangedBroadcast(true, false, loaded, null); 21452 } 21453 21454 private void unloadPrivatePackages(final VolumeInfo vol) { 21455 mHandler.post(new Runnable() { 21456 @Override 21457 public void run() { 21458 unloadPrivatePackagesInner(vol); 21459 } 21460 }); 21461 } 21462 21463 private void unloadPrivatePackagesInner(VolumeInfo vol) { 21464 final String volumeUuid = vol.fsUuid; 21465 if (TextUtils.isEmpty(volumeUuid)) { 21466 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 21467 return; 21468 } 21469 21470 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 21471 synchronized (mInstallLock) { 21472 synchronized (mPackages) { 21473 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 21474 for (PackageSetting ps : packages) { 21475 if (ps.pkg == null) continue; 21476 21477 final ApplicationInfo info = ps.pkg.applicationInfo; 21478 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 21479 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 21480 21481 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 21482 "unloadPrivatePackagesInner")) { 21483 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 21484 false, null)) { 21485 unloaded.add(info); 21486 } else { 21487 Slog.w(TAG, "Failed to unload " + ps.codePath); 21488 } 21489 } 21490 21491 // Try very hard to release any references to this package 21492 // so we don't risk the system server being killed due to 21493 // open FDs 21494 AttributeCache.instance().removePackage(ps.name); 21495 } 21496 21497 mSettings.writeLPr(); 21498 } 21499 } 21500 21501 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 21502 sendResourcesChangedBroadcast(false, false, unloaded, null); 21503 21504 // Try very hard to release any references to this path so we don't risk 21505 // the system server being killed due to open FDs 21506 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 21507 21508 for (int i = 0; i < 3; i++) { 21509 System.gc(); 21510 System.runFinalization(); 21511 } 21512 } 21513 21514 private void assertPackageKnown(String volumeUuid, String packageName) 21515 throws PackageManagerException { 21516 synchronized (mPackages) { 21517 // Normalize package name to handle renamed packages 21518 packageName = normalizePackageNameLPr(packageName); 21519 21520 final PackageSetting ps = mSettings.mPackages.get(packageName); 21521 if (ps == null) { 21522 throw new PackageManagerException("Package " + packageName + " is unknown"); 21523 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 21524 throw new PackageManagerException( 21525 "Package " + packageName + " found on unknown volume " + volumeUuid 21526 + "; expected volume " + ps.volumeUuid); 21527 } 21528 } 21529 } 21530 21531 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 21532 throws PackageManagerException { 21533 synchronized (mPackages) { 21534 // Normalize package name to handle renamed packages 21535 packageName = normalizePackageNameLPr(packageName); 21536 21537 final PackageSetting ps = mSettings.mPackages.get(packageName); 21538 if (ps == null) { 21539 throw new PackageManagerException("Package " + packageName + " is unknown"); 21540 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 21541 throw new PackageManagerException( 21542 "Package " + packageName + " found on unknown volume " + volumeUuid 21543 + "; expected volume " + ps.volumeUuid); 21544 } else if (!ps.getInstalled(userId)) { 21545 throw new PackageManagerException( 21546 "Package " + packageName + " not installed for user " + userId); 21547 } 21548 } 21549 } 21550 21551 private List<String> collectAbsoluteCodePaths() { 21552 synchronized (mPackages) { 21553 List<String> codePaths = new ArrayList<>(); 21554 final int packageCount = mSettings.mPackages.size(); 21555 for (int i = 0; i < packageCount; i++) { 21556 final PackageSetting ps = mSettings.mPackages.valueAt(i); 21557 codePaths.add(ps.codePath.getAbsolutePath()); 21558 } 21559 return codePaths; 21560 } 21561 } 21562 21563 /** 21564 * Examine all apps present on given mounted volume, and destroy apps that 21565 * aren't expected, either due to uninstallation or reinstallation on 21566 * another volume. 21567 */ 21568 private void reconcileApps(String volumeUuid) { 21569 List<String> absoluteCodePaths = collectAbsoluteCodePaths(); 21570 List<File> filesToDelete = null; 21571 21572 final File[] files = FileUtils.listFilesOrEmpty( 21573 Environment.getDataAppDirectory(volumeUuid)); 21574 for (File file : files) { 21575 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 21576 && !PackageInstallerService.isStageName(file.getName()); 21577 if (!isPackage) { 21578 // Ignore entries which are not packages 21579 continue; 21580 } 21581 21582 String absolutePath = file.getAbsolutePath(); 21583 21584 boolean pathValid = false; 21585 final int absoluteCodePathCount = absoluteCodePaths.size(); 21586 for (int i = 0; i < absoluteCodePathCount; i++) { 21587 String absoluteCodePath = absoluteCodePaths.get(i); 21588 if (absolutePath.startsWith(absoluteCodePath)) { 21589 pathValid = true; 21590 break; 21591 } 21592 } 21593 21594 if (!pathValid) { 21595 if (filesToDelete == null) { 21596 filesToDelete = new ArrayList<>(); 21597 } 21598 filesToDelete.add(file); 21599 } 21600 } 21601 21602 if (filesToDelete != null) { 21603 final int fileToDeleteCount = filesToDelete.size(); 21604 for (int i = 0; i < fileToDeleteCount; i++) { 21605 File fileToDelete = filesToDelete.get(i); 21606 logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete); 21607 synchronized (mInstallLock) { 21608 removeCodePathLI(fileToDelete); 21609 } 21610 } 21611 } 21612 } 21613 21614 /** 21615 * Reconcile all app data for the given user. 21616 * <p> 21617 * Verifies that directories exist and that ownership and labeling is 21618 * correct for all installed apps on all mounted volumes. 21619 */ 21620 void reconcileAppsData(int userId, int flags, boolean migrateAppsData) { 21621 final StorageManager storage = mContext.getSystemService(StorageManager.class); 21622 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 21623 final String volumeUuid = vol.getFsUuid(); 21624 synchronized (mInstallLock) { 21625 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData); 21626 } 21627 } 21628 } 21629 21630 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags, 21631 boolean migrateAppData) { 21632 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */); 21633 } 21634 21635 /** 21636 * Reconcile all app data on given mounted volume. 21637 * <p> 21638 * Destroys app data that isn't expected, either due to uninstallation or 21639 * reinstallation on another volume. 21640 * <p> 21641 * Verifies that directories exist and that ownership and labeling is 21642 * correct for all installed apps. 21643 * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true) 21644 */ 21645 private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags, 21646 boolean migrateAppData, boolean onlyCoreApps) { 21647 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 21648 + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData); 21649 List<String> result = onlyCoreApps ? new ArrayList<>() : null; 21650 21651 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 21652 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 21653 21654 // First look for stale data that doesn't belong, and check if things 21655 // have changed since we did our last restorecon 21656 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 21657 if (StorageManager.isFileEncryptedNativeOrEmulated() 21658 && !StorageManager.isUserKeyUnlocked(userId)) { 21659 throw new RuntimeException( 21660 "Yikes, someone asked us to reconcile CE storage while " + userId 21661 + " was still locked; this would have caused massive data loss!"); 21662 } 21663 21664 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 21665 for (File file : files) { 21666 final String packageName = file.getName(); 21667 try { 21668 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 21669 } catch (PackageManagerException e) { 21670 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 21671 try { 21672 mInstaller.destroyAppData(volumeUuid, packageName, userId, 21673 StorageManager.FLAG_STORAGE_CE, 0); 21674 } catch (InstallerException e2) { 21675 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 21676 } 21677 } 21678 } 21679 } 21680 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 21681 final File[] files = FileUtils.listFilesOrEmpty(deDir); 21682 for (File file : files) { 21683 final String packageName = file.getName(); 21684 try { 21685 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 21686 } catch (PackageManagerException e) { 21687 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 21688 try { 21689 mInstaller.destroyAppData(volumeUuid, packageName, userId, 21690 StorageManager.FLAG_STORAGE_DE, 0); 21691 } catch (InstallerException e2) { 21692 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 21693 } 21694 } 21695 } 21696 } 21697 21698 // Ensure that data directories are ready to roll for all packages 21699 // installed for this volume and user 21700 final List<PackageSetting> packages; 21701 synchronized (mPackages) { 21702 packages = mSettings.getVolumePackagesLPr(volumeUuid); 21703 } 21704 int preparedCount = 0; 21705 for (PackageSetting ps : packages) { 21706 final String packageName = ps.name; 21707 if (ps.pkg == null) { 21708 Slog.w(TAG, "Odd, missing scanned package " + packageName); 21709 // TODO: might be due to legacy ASEC apps; we should circle back 21710 // and reconcile again once they're scanned 21711 continue; 21712 } 21713 // Skip non-core apps if requested 21714 if (onlyCoreApps && !ps.pkg.coreApp) { 21715 result.add(packageName); 21716 continue; 21717 } 21718 21719 if (ps.getInstalled(userId)) { 21720 prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData); 21721 preparedCount++; 21722 } 21723 } 21724 21725 Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages"); 21726 return result; 21727 } 21728 21729 /** 21730 * Prepare app data for the given app just after it was installed or 21731 * upgraded. This method carefully only touches users that it's installed 21732 * for, and it forces a restorecon to handle any seinfo changes. 21733 * <p> 21734 * Verifies that directories exist and that ownership and labeling is 21735 * correct for all installed apps. If there is an ownership mismatch, it 21736 * will try recovering system apps by wiping data; third-party app data is 21737 * left intact. 21738 * <p> 21739 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 21740 */ 21741 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 21742 final PackageSetting ps; 21743 synchronized (mPackages) { 21744 ps = mSettings.mPackages.get(pkg.packageName); 21745 mSettings.writeKernelMappingLPr(ps); 21746 } 21747 21748 final UserManager um = mContext.getSystemService(UserManager.class); 21749 UserManagerInternal umInternal = getUserManagerInternal(); 21750 for (UserInfo user : um.getUsers()) { 21751 final int flags; 21752 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 21753 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 21754 } else if (umInternal.isUserRunning(user.id)) { 21755 flags = StorageManager.FLAG_STORAGE_DE; 21756 } else { 21757 continue; 21758 } 21759 21760 if (ps.getInstalled(user.id)) { 21761 // TODO: when user data is locked, mark that we're still dirty 21762 prepareAppDataLIF(pkg, user.id, flags); 21763 } 21764 } 21765 } 21766 21767 /** 21768 * Prepare app data for the given app. 21769 * <p> 21770 * Verifies that directories exist and that ownership and labeling is 21771 * correct for all installed apps. If there is an ownership mismatch, this 21772 * will try recovering system apps by wiping data; third-party app data is 21773 * left intact. 21774 */ 21775 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 21776 if (pkg == null) { 21777 Slog.wtf(TAG, "Package was null!", new Throwable()); 21778 return; 21779 } 21780 prepareAppDataLeafLIF(pkg, userId, flags); 21781 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 21782 for (int i = 0; i < childCount; i++) { 21783 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 21784 } 21785 } 21786 21787 private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags, 21788 boolean maybeMigrateAppData) { 21789 prepareAppDataLIF(pkg, userId, flags); 21790 21791 if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) { 21792 // We may have just shuffled around app data directories, so 21793 // prepare them one more time 21794 prepareAppDataLIF(pkg, userId, flags); 21795 } 21796 } 21797 21798 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 21799 if (DEBUG_APP_DATA) { 21800 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 21801 + Integer.toHexString(flags)); 21802 } 21803 21804 final String volumeUuid = pkg.volumeUuid; 21805 final String packageName = pkg.packageName; 21806 final ApplicationInfo app = pkg.applicationInfo; 21807 final int appId = UserHandle.getAppId(app.uid); 21808 21809 Preconditions.checkNotNull(app.seInfo); 21810 21811 long ceDataInode = -1; 21812 try { 21813 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 21814 appId, app.seInfo, app.targetSdkVersion); 21815 } catch (InstallerException e) { 21816 if (app.isSystemApp()) { 21817 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 21818 + ", but trying to recover: " + e); 21819 destroyAppDataLeafLIF(pkg, userId, flags); 21820 try { 21821 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 21822 appId, app.seInfo, app.targetSdkVersion); 21823 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 21824 } catch (InstallerException e2) { 21825 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 21826 } 21827 } else { 21828 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 21829 } 21830 } 21831 21832 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) { 21833 // TODO: mark this structure as dirty so we persist it! 21834 synchronized (mPackages) { 21835 final PackageSetting ps = mSettings.mPackages.get(packageName); 21836 if (ps != null) { 21837 ps.setCeDataInode(ceDataInode, userId); 21838 } 21839 } 21840 } 21841 21842 prepareAppDataContentsLeafLIF(pkg, userId, flags); 21843 } 21844 21845 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 21846 if (pkg == null) { 21847 Slog.wtf(TAG, "Package was null!", new Throwable()); 21848 return; 21849 } 21850 prepareAppDataContentsLeafLIF(pkg, userId, flags); 21851 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 21852 for (int i = 0; i < childCount; i++) { 21853 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 21854 } 21855 } 21856 21857 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 21858 final String volumeUuid = pkg.volumeUuid; 21859 final String packageName = pkg.packageName; 21860 final ApplicationInfo app = pkg.applicationInfo; 21861 21862 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 21863 // Create a native library symlink only if we have native libraries 21864 // and if the native libraries are 32 bit libraries. We do not provide 21865 // this symlink for 64 bit libraries. 21866 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 21867 final String nativeLibPath = app.nativeLibraryDir; 21868 try { 21869 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 21870 nativeLibPath, userId); 21871 } catch (InstallerException e) { 21872 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 21873 } 21874 } 21875 } 21876 } 21877 21878 /** 21879 * For system apps on non-FBE devices, this method migrates any existing 21880 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 21881 * requested by the app. 21882 */ 21883 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 21884 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 21885 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 21886 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 21887 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 21888 try { 21889 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 21890 storageTarget); 21891 } catch (InstallerException e) { 21892 logCriticalInfo(Log.WARN, 21893 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 21894 } 21895 return true; 21896 } else { 21897 return false; 21898 } 21899 } 21900 21901 public PackageFreezer freezePackage(String packageName, String killReason) { 21902 return freezePackage(packageName, UserHandle.USER_ALL, killReason); 21903 } 21904 21905 public PackageFreezer freezePackage(String packageName, int userId, String killReason) { 21906 return new PackageFreezer(packageName, userId, killReason); 21907 } 21908 21909 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 21910 String killReason) { 21911 return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason); 21912 } 21913 21914 public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags, 21915 String killReason) { 21916 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 21917 return new PackageFreezer(); 21918 } else { 21919 return freezePackage(packageName, userId, killReason); 21920 } 21921 } 21922 21923 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 21924 String killReason) { 21925 return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason); 21926 } 21927 21928 public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags, 21929 String killReason) { 21930 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 21931 return new PackageFreezer(); 21932 } else { 21933 return freezePackage(packageName, userId, killReason); 21934 } 21935 } 21936 21937 /** 21938 * Class that freezes and kills the given package upon creation, and 21939 * unfreezes it upon closing. This is typically used when doing surgery on 21940 * app code/data to prevent the app from running while you're working. 21941 */ 21942 private class PackageFreezer implements AutoCloseable { 21943 private final String mPackageName; 21944 private final PackageFreezer[] mChildren; 21945 21946 private final boolean mWeFroze; 21947 21948 private final AtomicBoolean mClosed = new AtomicBoolean(); 21949 private final CloseGuard mCloseGuard = CloseGuard.get(); 21950 21951 /** 21952 * Create and return a stub freezer that doesn't actually do anything, 21953 * typically used when someone requested 21954 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 21955 * {@link PackageManager#DELETE_DONT_KILL_APP}. 21956 */ 21957 public PackageFreezer() { 21958 mPackageName = null; 21959 mChildren = null; 21960 mWeFroze = false; 21961 mCloseGuard.open("close"); 21962 } 21963 21964 public PackageFreezer(String packageName, int userId, String killReason) { 21965 synchronized (mPackages) { 21966 mPackageName = packageName; 21967 mWeFroze = mFrozenPackages.add(mPackageName); 21968 21969 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 21970 if (ps != null) { 21971 killApplication(ps.name, ps.appId, userId, killReason); 21972 } 21973 21974 final PackageParser.Package p = mPackages.get(packageName); 21975 if (p != null && p.childPackages != null) { 21976 final int N = p.childPackages.size(); 21977 mChildren = new PackageFreezer[N]; 21978 for (int i = 0; i < N; i++) { 21979 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 21980 userId, killReason); 21981 } 21982 } else { 21983 mChildren = null; 21984 } 21985 } 21986 mCloseGuard.open("close"); 21987 } 21988 21989 @Override 21990 protected void finalize() throws Throwable { 21991 try { 21992 mCloseGuard.warnIfOpen(); 21993 close(); 21994 } finally { 21995 super.finalize(); 21996 } 21997 } 21998 21999 @Override 22000 public void close() { 22001 mCloseGuard.close(); 22002 if (mClosed.compareAndSet(false, true)) { 22003 synchronized (mPackages) { 22004 if (mWeFroze) { 22005 mFrozenPackages.remove(mPackageName); 22006 } 22007 22008 if (mChildren != null) { 22009 for (PackageFreezer freezer : mChildren) { 22010 freezer.close(); 22011 } 22012 } 22013 } 22014 } 22015 } 22016 } 22017 22018 /** 22019 * Verify that given package is currently frozen. 22020 */ 22021 private void checkPackageFrozen(String packageName) { 22022 synchronized (mPackages) { 22023 if (!mFrozenPackages.contains(packageName)) { 22024 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 22025 } 22026 } 22027 } 22028 22029 @Override 22030 public int movePackage(final String packageName, final String volumeUuid) { 22031 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 22032 22033 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 22034 final int moveId = mNextMoveId.getAndIncrement(); 22035 mHandler.post(new Runnable() { 22036 @Override 22037 public void run() { 22038 try { 22039 movePackageInternal(packageName, volumeUuid, moveId, user); 22040 } catch (PackageManagerException e) { 22041 Slog.w(TAG, "Failed to move " + packageName, e); 22042 mMoveCallbacks.notifyStatusChanged(moveId, 22043 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 22044 } 22045 } 22046 }); 22047 return moveId; 22048 } 22049 22050 private void movePackageInternal(final String packageName, final String volumeUuid, 22051 final int moveId, UserHandle user) throws PackageManagerException { 22052 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22053 final PackageManager pm = mContext.getPackageManager(); 22054 22055 final boolean currentAsec; 22056 final String currentVolumeUuid; 22057 final File codeFile; 22058 final String installerPackageName; 22059 final String packageAbiOverride; 22060 final int appId; 22061 final String seinfo; 22062 final String label; 22063 final int targetSdkVersion; 22064 final PackageFreezer freezer; 22065 final int[] installedUserIds; 22066 22067 // reader 22068 synchronized (mPackages) { 22069 final PackageParser.Package pkg = mPackages.get(packageName); 22070 final PackageSetting ps = mSettings.mPackages.get(packageName); 22071 if (pkg == null || ps == null) { 22072 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 22073 } 22074 22075 if (pkg.applicationInfo.isSystemApp()) { 22076 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 22077 "Cannot move system application"); 22078 } 22079 22080 final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid); 22081 final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean( 22082 com.android.internal.R.bool.config_allow3rdPartyAppOnInternal); 22083 if (isInternalStorage && !allow3rdPartyOnInternal) { 22084 throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL, 22085 "3rd party apps are not allowed on internal storage"); 22086 } 22087 22088 if (pkg.applicationInfo.isExternalAsec()) { 22089 currentAsec = true; 22090 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 22091 } else if (pkg.applicationInfo.isForwardLocked()) { 22092 currentAsec = true; 22093 currentVolumeUuid = "forward_locked"; 22094 } else { 22095 currentAsec = false; 22096 currentVolumeUuid = ps.volumeUuid; 22097 22098 final File probe = new File(pkg.codePath); 22099 final File probeOat = new File(probe, "oat"); 22100 if (!probe.isDirectory() || !probeOat.isDirectory()) { 22101 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22102 "Move only supported for modern cluster style installs"); 22103 } 22104 } 22105 22106 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 22107 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22108 "Package already moved to " + volumeUuid); 22109 } 22110 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 22111 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 22112 "Device admin cannot be moved"); 22113 } 22114 22115 if (mFrozenPackages.contains(packageName)) { 22116 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 22117 "Failed to move already frozen package"); 22118 } 22119 22120 codeFile = new File(pkg.codePath); 22121 installerPackageName = ps.installerPackageName; 22122 packageAbiOverride = ps.cpuAbiOverrideString; 22123 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 22124 seinfo = pkg.applicationInfo.seInfo; 22125 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 22126 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 22127 freezer = freezePackage(packageName, "movePackageInternal"); 22128 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 22129 } 22130 22131 final Bundle extras = new Bundle(); 22132 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 22133 extras.putString(Intent.EXTRA_TITLE, label); 22134 mMoveCallbacks.notifyCreated(moveId, extras); 22135 22136 int installFlags; 22137 final boolean moveCompleteApp; 22138 final File measurePath; 22139 22140 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 22141 installFlags = INSTALL_INTERNAL; 22142 moveCompleteApp = !currentAsec; 22143 measurePath = Environment.getDataAppDirectory(volumeUuid); 22144 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 22145 installFlags = INSTALL_EXTERNAL; 22146 moveCompleteApp = false; 22147 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 22148 } else { 22149 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 22150 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 22151 || !volume.isMountedWritable()) { 22152 freezer.close(); 22153 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22154 "Move location not mounted private volume"); 22155 } 22156 22157 Preconditions.checkState(!currentAsec); 22158 22159 installFlags = INSTALL_INTERNAL; 22160 moveCompleteApp = true; 22161 measurePath = Environment.getDataAppDirectory(volumeUuid); 22162 } 22163 22164 final PackageStats stats = new PackageStats(null, -1); 22165 synchronized (mInstaller) { 22166 for (int userId : installedUserIds) { 22167 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 22168 freezer.close(); 22169 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22170 "Failed to measure package size"); 22171 } 22172 } 22173 } 22174 22175 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 22176 + stats.dataSize); 22177 22178 final long startFreeBytes = measurePath.getFreeSpace(); 22179 final long sizeBytes; 22180 if (moveCompleteApp) { 22181 sizeBytes = stats.codeSize + stats.dataSize; 22182 } else { 22183 sizeBytes = stats.codeSize; 22184 } 22185 22186 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 22187 freezer.close(); 22188 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22189 "Not enough free space to move"); 22190 } 22191 22192 mMoveCallbacks.notifyStatusChanged(moveId, 10); 22193 22194 final CountDownLatch installedLatch = new CountDownLatch(1); 22195 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 22196 @Override 22197 public void onUserActionRequired(Intent intent) throws RemoteException { 22198 throw new IllegalStateException(); 22199 } 22200 22201 @Override 22202 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 22203 Bundle extras) throws RemoteException { 22204 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 22205 + PackageManager.installStatusToString(returnCode, msg)); 22206 22207 installedLatch.countDown(); 22208 freezer.close(); 22209 22210 final int status = PackageManager.installStatusToPublicStatus(returnCode); 22211 switch (status) { 22212 case PackageInstaller.STATUS_SUCCESS: 22213 mMoveCallbacks.notifyStatusChanged(moveId, 22214 PackageManager.MOVE_SUCCEEDED); 22215 break; 22216 case PackageInstaller.STATUS_FAILURE_STORAGE: 22217 mMoveCallbacks.notifyStatusChanged(moveId, 22218 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 22219 break; 22220 default: 22221 mMoveCallbacks.notifyStatusChanged(moveId, 22222 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 22223 break; 22224 } 22225 } 22226 }; 22227 22228 final MoveInfo move; 22229 if (moveCompleteApp) { 22230 // Kick off a thread to report progress estimates 22231 new Thread() { 22232 @Override 22233 public void run() { 22234 while (true) { 22235 try { 22236 if (installedLatch.await(1, TimeUnit.SECONDS)) { 22237 break; 22238 } 22239 } catch (InterruptedException ignored) { 22240 } 22241 22242 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 22243 final int progress = 10 + (int) MathUtils.constrain( 22244 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 22245 mMoveCallbacks.notifyStatusChanged(moveId, progress); 22246 } 22247 } 22248 }.start(); 22249 22250 final String dataAppName = codeFile.getName(); 22251 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 22252 dataAppName, appId, seinfo, targetSdkVersion); 22253 } else { 22254 move = null; 22255 } 22256 22257 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 22258 22259 final Message msg = mHandler.obtainMessage(INIT_COPY); 22260 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 22261 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 22262 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 22263 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/, 22264 PackageManager.INSTALL_REASON_UNKNOWN); 22265 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 22266 msg.obj = params; 22267 22268 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 22269 System.identityHashCode(msg.obj)); 22270 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 22271 System.identityHashCode(msg.obj)); 22272 22273 mHandler.sendMessage(msg); 22274 } 22275 22276 @Override 22277 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 22278 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 22279 22280 final int realMoveId = mNextMoveId.getAndIncrement(); 22281 final Bundle extras = new Bundle(); 22282 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 22283 mMoveCallbacks.notifyCreated(realMoveId, extras); 22284 22285 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 22286 @Override 22287 public void onCreated(int moveId, Bundle extras) { 22288 // Ignored 22289 } 22290 22291 @Override 22292 public void onStatusChanged(int moveId, int status, long estMillis) { 22293 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 22294 } 22295 }; 22296 22297 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22298 storage.setPrimaryStorageUuid(volumeUuid, callback); 22299 return realMoveId; 22300 } 22301 22302 @Override 22303 public int getMoveStatus(int moveId) { 22304 mContext.enforceCallingOrSelfPermission( 22305 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22306 return mMoveCallbacks.mLastStatus.get(moveId); 22307 } 22308 22309 @Override 22310 public void registerMoveCallback(IPackageMoveObserver callback) { 22311 mContext.enforceCallingOrSelfPermission( 22312 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22313 mMoveCallbacks.register(callback); 22314 } 22315 22316 @Override 22317 public void unregisterMoveCallback(IPackageMoveObserver callback) { 22318 mContext.enforceCallingOrSelfPermission( 22319 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22320 mMoveCallbacks.unregister(callback); 22321 } 22322 22323 @Override 22324 public boolean setInstallLocation(int loc) { 22325 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 22326 null); 22327 if (getInstallLocation() == loc) { 22328 return true; 22329 } 22330 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 22331 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 22332 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 22333 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 22334 return true; 22335 } 22336 return false; 22337 } 22338 22339 @Override 22340 public int getInstallLocation() { 22341 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 22342 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 22343 PackageHelper.APP_INSTALL_AUTO); 22344 } 22345 22346 /** Called by UserManagerService */ 22347 void cleanUpUser(UserManagerService userManager, int userHandle) { 22348 synchronized (mPackages) { 22349 mDirtyUsers.remove(userHandle); 22350 mUserNeedsBadging.delete(userHandle); 22351 mSettings.removeUserLPw(userHandle); 22352 mPendingBroadcasts.remove(userHandle); 22353 mInstantAppRegistry.onUserRemovedLPw(userHandle); 22354 removeUnusedPackagesLPw(userManager, userHandle); 22355 } 22356 } 22357 22358 /** 22359 * We're removing userHandle and would like to remove any downloaded packages 22360 * that are no longer in use by any other user. 22361 * @param userHandle the user being removed 22362 */ 22363 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 22364 final boolean DEBUG_CLEAN_APKS = false; 22365 int [] users = userManager.getUserIds(); 22366 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 22367 while (psit.hasNext()) { 22368 PackageSetting ps = psit.next(); 22369 if (ps.pkg == null) { 22370 continue; 22371 } 22372 final String packageName = ps.pkg.packageName; 22373 // Skip over if system app 22374 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 22375 continue; 22376 } 22377 if (DEBUG_CLEAN_APKS) { 22378 Slog.i(TAG, "Checking package " + packageName); 22379 } 22380 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 22381 if (keep) { 22382 if (DEBUG_CLEAN_APKS) { 22383 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 22384 } 22385 } else { 22386 for (int i = 0; i < users.length; i++) { 22387 if (users[i] != userHandle && ps.getInstalled(users[i])) { 22388 keep = true; 22389 if (DEBUG_CLEAN_APKS) { 22390 Slog.i(TAG, " Keeping package " + packageName + " for user " 22391 + users[i]); 22392 } 22393 break; 22394 } 22395 } 22396 } 22397 if (!keep) { 22398 if (DEBUG_CLEAN_APKS) { 22399 Slog.i(TAG, " Removing package " + packageName); 22400 } 22401 mHandler.post(new Runnable() { 22402 public void run() { 22403 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 22404 userHandle, 0); 22405 } //end run 22406 }); 22407 } 22408 } 22409 } 22410 22411 /** Called by UserManagerService */ 22412 void createNewUser(int userId, String[] disallowedPackages) { 22413 synchronized (mInstallLock) { 22414 mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages); 22415 } 22416 synchronized (mPackages) { 22417 scheduleWritePackageRestrictionsLocked(userId); 22418 scheduleWritePackageListLocked(userId); 22419 applyFactoryDefaultBrowserLPw(userId); 22420 primeDomainVerificationsLPw(userId); 22421 } 22422 } 22423 22424 void onNewUserCreated(final int userId) { 22425 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 22426 // If permission review for legacy apps is required, we represent 22427 // dagerous permissions for such apps as always granted runtime 22428 // permissions to keep per user flag state whether review is needed. 22429 // Hence, if a new user is added we have to propagate dangerous 22430 // permission grants for these legacy apps. 22431 if (mPermissionReviewRequired) { 22432 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 22433 | UPDATE_PERMISSIONS_REPLACE_ALL); 22434 } 22435 } 22436 22437 @Override 22438 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 22439 mContext.enforceCallingOrSelfPermission( 22440 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 22441 "Only package verification agents can read the verifier device identity"); 22442 22443 synchronized (mPackages) { 22444 return mSettings.getVerifierDeviceIdentityLPw(); 22445 } 22446 } 22447 22448 @Override 22449 public void setPermissionEnforced(String permission, boolean enforced) { 22450 // TODO: Now that we no longer change GID for storage, this should to away. 22451 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 22452 "setPermissionEnforced"); 22453 if (READ_EXTERNAL_STORAGE.equals(permission)) { 22454 synchronized (mPackages) { 22455 if (mSettings.mReadExternalStorageEnforced == null 22456 || mSettings.mReadExternalStorageEnforced != enforced) { 22457 mSettings.mReadExternalStorageEnforced = enforced; 22458 mSettings.writeLPr(); 22459 } 22460 } 22461 // kill any non-foreground processes so we restart them and 22462 // grant/revoke the GID. 22463 final IActivityManager am = ActivityManager.getService(); 22464 if (am != null) { 22465 final long token = Binder.clearCallingIdentity(); 22466 try { 22467 am.killProcessesBelowForeground("setPermissionEnforcement"); 22468 } catch (RemoteException e) { 22469 } finally { 22470 Binder.restoreCallingIdentity(token); 22471 } 22472 } 22473 } else { 22474 throw new IllegalArgumentException("No selective enforcement for " + permission); 22475 } 22476 } 22477 22478 @Override 22479 @Deprecated 22480 public boolean isPermissionEnforced(String permission) { 22481 return true; 22482 } 22483 22484 @Override 22485 public boolean isStorageLow() { 22486 final long token = Binder.clearCallingIdentity(); 22487 try { 22488 final DeviceStorageMonitorInternal 22489 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 22490 if (dsm != null) { 22491 return dsm.isMemoryLow(); 22492 } else { 22493 return false; 22494 } 22495 } finally { 22496 Binder.restoreCallingIdentity(token); 22497 } 22498 } 22499 22500 @Override 22501 public IPackageInstaller getPackageInstaller() { 22502 return mInstallerService; 22503 } 22504 22505 private boolean userNeedsBadging(int userId) { 22506 int index = mUserNeedsBadging.indexOfKey(userId); 22507 if (index < 0) { 22508 final UserInfo userInfo; 22509 final long token = Binder.clearCallingIdentity(); 22510 try { 22511 userInfo = sUserManager.getUserInfo(userId); 22512 } finally { 22513 Binder.restoreCallingIdentity(token); 22514 } 22515 final boolean b; 22516 if (userInfo != null && userInfo.isManagedProfile()) { 22517 b = true; 22518 } else { 22519 b = false; 22520 } 22521 mUserNeedsBadging.put(userId, b); 22522 return b; 22523 } 22524 return mUserNeedsBadging.valueAt(index); 22525 } 22526 22527 @Override 22528 public KeySet getKeySetByAlias(String packageName, String alias) { 22529 if (packageName == null || alias == null) { 22530 return null; 22531 } 22532 synchronized(mPackages) { 22533 final PackageParser.Package pkg = mPackages.get(packageName); 22534 if (pkg == null) { 22535 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22536 throw new IllegalArgumentException("Unknown package: " + packageName); 22537 } 22538 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22539 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 22540 } 22541 } 22542 22543 @Override 22544 public KeySet getSigningKeySet(String packageName) { 22545 if (packageName == null) { 22546 return null; 22547 } 22548 synchronized(mPackages) { 22549 final PackageParser.Package pkg = mPackages.get(packageName); 22550 if (pkg == null) { 22551 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22552 throw new IllegalArgumentException("Unknown package: " + packageName); 22553 } 22554 if (pkg.applicationInfo.uid != Binder.getCallingUid() 22555 && Process.SYSTEM_UID != Binder.getCallingUid()) { 22556 throw new SecurityException("May not access signing KeySet of other apps."); 22557 } 22558 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22559 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 22560 } 22561 } 22562 22563 @Override 22564 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 22565 if (packageName == null || ks == null) { 22566 return false; 22567 } 22568 synchronized(mPackages) { 22569 final PackageParser.Package pkg = mPackages.get(packageName); 22570 if (pkg == null) { 22571 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22572 throw new IllegalArgumentException("Unknown package: " + packageName); 22573 } 22574 IBinder ksh = ks.getToken(); 22575 if (ksh instanceof KeySetHandle) { 22576 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22577 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 22578 } 22579 return false; 22580 } 22581 } 22582 22583 @Override 22584 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 22585 if (packageName == null || ks == null) { 22586 return false; 22587 } 22588 synchronized(mPackages) { 22589 final PackageParser.Package pkg = mPackages.get(packageName); 22590 if (pkg == null) { 22591 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22592 throw new IllegalArgumentException("Unknown package: " + packageName); 22593 } 22594 IBinder ksh = ks.getToken(); 22595 if (ksh instanceof KeySetHandle) { 22596 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22597 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 22598 } 22599 return false; 22600 } 22601 } 22602 22603 private void deletePackageIfUnusedLPr(final String packageName) { 22604 PackageSetting ps = mSettings.mPackages.get(packageName); 22605 if (ps == null) { 22606 return; 22607 } 22608 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 22609 // TODO Implement atomic delete if package is unused 22610 // It is currently possible that the package will be deleted even if it is installed 22611 // after this method returns. 22612 mHandler.post(new Runnable() { 22613 public void run() { 22614 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 22615 0, PackageManager.DELETE_ALL_USERS); 22616 } 22617 }); 22618 } 22619 } 22620 22621 /** 22622 * Check and throw if the given before/after packages would be considered a 22623 * downgrade. 22624 */ 22625 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 22626 throws PackageManagerException { 22627 if (after.versionCode < before.mVersionCode) { 22628 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 22629 "Update version code " + after.versionCode + " is older than current " 22630 + before.mVersionCode); 22631 } else if (after.versionCode == before.mVersionCode) { 22632 if (after.baseRevisionCode < before.baseRevisionCode) { 22633 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 22634 "Update base revision code " + after.baseRevisionCode 22635 + " is older than current " + before.baseRevisionCode); 22636 } 22637 22638 if (!ArrayUtils.isEmpty(after.splitNames)) { 22639 for (int i = 0; i < after.splitNames.length; i++) { 22640 final String splitName = after.splitNames[i]; 22641 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 22642 if (j != -1) { 22643 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 22644 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 22645 "Update split " + splitName + " revision code " 22646 + after.splitRevisionCodes[i] + " is older than current " 22647 + before.splitRevisionCodes[j]); 22648 } 22649 } 22650 } 22651 } 22652 } 22653 } 22654 22655 private static class MoveCallbacks extends Handler { 22656 private static final int MSG_CREATED = 1; 22657 private static final int MSG_STATUS_CHANGED = 2; 22658 22659 private final RemoteCallbackList<IPackageMoveObserver> 22660 mCallbacks = new RemoteCallbackList<>(); 22661 22662 private final SparseIntArray mLastStatus = new SparseIntArray(); 22663 22664 public MoveCallbacks(Looper looper) { 22665 super(looper); 22666 } 22667 22668 public void register(IPackageMoveObserver callback) { 22669 mCallbacks.register(callback); 22670 } 22671 22672 public void unregister(IPackageMoveObserver callback) { 22673 mCallbacks.unregister(callback); 22674 } 22675 22676 @Override 22677 public void handleMessage(Message msg) { 22678 final SomeArgs args = (SomeArgs) msg.obj; 22679 final int n = mCallbacks.beginBroadcast(); 22680 for (int i = 0; i < n; i++) { 22681 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 22682 try { 22683 invokeCallback(callback, msg.what, args); 22684 } catch (RemoteException ignored) { 22685 } 22686 } 22687 mCallbacks.finishBroadcast(); 22688 args.recycle(); 22689 } 22690 22691 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 22692 throws RemoteException { 22693 switch (what) { 22694 case MSG_CREATED: { 22695 callback.onCreated(args.argi1, (Bundle) args.arg2); 22696 break; 22697 } 22698 case MSG_STATUS_CHANGED: { 22699 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 22700 break; 22701 } 22702 } 22703 } 22704 22705 private void notifyCreated(int moveId, Bundle extras) { 22706 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 22707 22708 final SomeArgs args = SomeArgs.obtain(); 22709 args.argi1 = moveId; 22710 args.arg2 = extras; 22711 obtainMessage(MSG_CREATED, args).sendToTarget(); 22712 } 22713 22714 private void notifyStatusChanged(int moveId, int status) { 22715 notifyStatusChanged(moveId, status, -1); 22716 } 22717 22718 private void notifyStatusChanged(int moveId, int status, long estMillis) { 22719 Slog.v(TAG, "Move " + moveId + " status " + status); 22720 22721 final SomeArgs args = SomeArgs.obtain(); 22722 args.argi1 = moveId; 22723 args.argi2 = status; 22724 args.arg3 = estMillis; 22725 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 22726 22727 synchronized (mLastStatus) { 22728 mLastStatus.put(moveId, status); 22729 } 22730 } 22731 } 22732 22733 private final static class OnPermissionChangeListeners extends Handler { 22734 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 22735 22736 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 22737 new RemoteCallbackList<>(); 22738 22739 public OnPermissionChangeListeners(Looper looper) { 22740 super(looper); 22741 } 22742 22743 @Override 22744 public void handleMessage(Message msg) { 22745 switch (msg.what) { 22746 case MSG_ON_PERMISSIONS_CHANGED: { 22747 final int uid = msg.arg1; 22748 handleOnPermissionsChanged(uid); 22749 } break; 22750 } 22751 } 22752 22753 public void addListenerLocked(IOnPermissionsChangeListener listener) { 22754 mPermissionListeners.register(listener); 22755 22756 } 22757 22758 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 22759 mPermissionListeners.unregister(listener); 22760 } 22761 22762 public void onPermissionsChanged(int uid) { 22763 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 22764 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 22765 } 22766 } 22767 22768 private void handleOnPermissionsChanged(int uid) { 22769 final int count = mPermissionListeners.beginBroadcast(); 22770 try { 22771 for (int i = 0; i < count; i++) { 22772 IOnPermissionsChangeListener callback = mPermissionListeners 22773 .getBroadcastItem(i); 22774 try { 22775 callback.onPermissionsChanged(uid); 22776 } catch (RemoteException e) { 22777 Log.e(TAG, "Permission listener is dead", e); 22778 } 22779 } 22780 } finally { 22781 mPermissionListeners.finishBroadcast(); 22782 } 22783 } 22784 } 22785 22786 private class PackageManagerInternalImpl extends PackageManagerInternal { 22787 @Override 22788 public void setLocationPackagesProvider(PackagesProvider provider) { 22789 synchronized (mPackages) { 22790 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 22791 } 22792 } 22793 22794 @Override 22795 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 22796 synchronized (mPackages) { 22797 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 22798 } 22799 } 22800 22801 @Override 22802 public void setSmsAppPackagesProvider(PackagesProvider provider) { 22803 synchronized (mPackages) { 22804 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 22805 } 22806 } 22807 22808 @Override 22809 public void setDialerAppPackagesProvider(PackagesProvider provider) { 22810 synchronized (mPackages) { 22811 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 22812 } 22813 } 22814 22815 @Override 22816 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 22817 synchronized (mPackages) { 22818 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 22819 } 22820 } 22821 22822 @Override 22823 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 22824 synchronized (mPackages) { 22825 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 22826 } 22827 } 22828 22829 @Override 22830 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 22831 synchronized (mPackages) { 22832 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 22833 packageName, userId); 22834 } 22835 } 22836 22837 @Override 22838 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 22839 synchronized (mPackages) { 22840 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 22841 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 22842 packageName, userId); 22843 } 22844 } 22845 22846 @Override 22847 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 22848 synchronized (mPackages) { 22849 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 22850 packageName, userId); 22851 } 22852 } 22853 22854 @Override 22855 public void setKeepUninstalledPackages(final List<String> packageList) { 22856 Preconditions.checkNotNull(packageList); 22857 List<String> removedFromList = null; 22858 synchronized (mPackages) { 22859 if (mKeepUninstalledPackages != null) { 22860 final int packagesCount = mKeepUninstalledPackages.size(); 22861 for (int i = 0; i < packagesCount; i++) { 22862 String oldPackage = mKeepUninstalledPackages.get(i); 22863 if (packageList != null && packageList.contains(oldPackage)) { 22864 continue; 22865 } 22866 if (removedFromList == null) { 22867 removedFromList = new ArrayList<>(); 22868 } 22869 removedFromList.add(oldPackage); 22870 } 22871 } 22872 mKeepUninstalledPackages = new ArrayList<>(packageList); 22873 if (removedFromList != null) { 22874 final int removedCount = removedFromList.size(); 22875 for (int i = 0; i < removedCount; i++) { 22876 deletePackageIfUnusedLPr(removedFromList.get(i)); 22877 } 22878 } 22879 } 22880 } 22881 22882 @Override 22883 public boolean isPermissionsReviewRequired(String packageName, int userId) { 22884 synchronized (mPackages) { 22885 // If we do not support permission review, done. 22886 if (!mPermissionReviewRequired) { 22887 return false; 22888 } 22889 22890 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 22891 if (packageSetting == null) { 22892 return false; 22893 } 22894 22895 // Permission review applies only to apps not supporting the new permission model. 22896 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 22897 return false; 22898 } 22899 22900 // Legacy apps have the permission and get user consent on launch. 22901 PermissionsState permissionsState = packageSetting.getPermissionsState(); 22902 return permissionsState.isPermissionReviewRequired(userId); 22903 } 22904 } 22905 22906 @Override 22907 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 22908 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 22909 } 22910 22911 @Override 22912 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 22913 int userId) { 22914 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 22915 } 22916 22917 @Override 22918 public void setDeviceAndProfileOwnerPackages( 22919 int deviceOwnerUserId, String deviceOwnerPackage, 22920 SparseArray<String> profileOwnerPackages) { 22921 mProtectedPackages.setDeviceAndProfileOwnerPackages( 22922 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages); 22923 } 22924 22925 @Override 22926 public boolean isPackageDataProtected(int userId, String packageName) { 22927 return mProtectedPackages.isPackageDataProtected(userId, packageName); 22928 } 22929 22930 @Override 22931 public boolean isPackageEphemeral(int userId, String packageName) { 22932 synchronized (mPackages) { 22933 final PackageSetting ps = mSettings.mPackages.get(packageName); 22934 return ps != null ? ps.getInstantApp(userId) : false; 22935 } 22936 } 22937 22938 @Override 22939 public boolean wasPackageEverLaunched(String packageName, int userId) { 22940 synchronized (mPackages) { 22941 return mSettings.wasPackageEverLaunchedLPr(packageName, userId); 22942 } 22943 } 22944 22945 @Override 22946 public void grantRuntimePermission(String packageName, String name, int userId, 22947 boolean overridePolicy) { 22948 PackageManagerService.this.grantRuntimePermission(packageName, name, userId, 22949 overridePolicy); 22950 } 22951 22952 @Override 22953 public void revokeRuntimePermission(String packageName, String name, int userId, 22954 boolean overridePolicy) { 22955 PackageManagerService.this.revokeRuntimePermission(packageName, name, userId, 22956 overridePolicy); 22957 } 22958 22959 @Override 22960 public String getNameForUid(int uid) { 22961 return PackageManagerService.this.getNameForUid(uid); 22962 } 22963 22964 @Override 22965 public void requestEphemeralResolutionPhaseTwo(EphemeralResponse responseObj, 22966 Intent origIntent, String resolvedType, Intent launchIntent, 22967 String callingPackage, int userId) { 22968 PackageManagerService.this.requestEphemeralResolutionPhaseTwo( 22969 responseObj, origIntent, resolvedType, launchIntent, callingPackage, userId); 22970 } 22971 22972 @Override 22973 public void grantEphemeralAccess(int userId, Intent intent, 22974 int targetAppId, int ephemeralAppId) { 22975 synchronized (mPackages) { 22976 mInstantAppRegistry.grantInstantAccessLPw(userId, intent, 22977 targetAppId, ephemeralAppId); 22978 } 22979 } 22980 22981 @Override 22982 public void pruneInstantApps() { 22983 synchronized (mPackages) { 22984 mInstantAppRegistry.pruneInstantAppsLPw(); 22985 } 22986 } 22987 22988 @Override 22989 public String getSetupWizardPackageName() { 22990 return mSetupWizardPackage; 22991 } 22992 22993 public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) { 22994 if (policy != null) { 22995 mExternalSourcesPolicy = policy; 22996 } 22997 } 22998 22999 @Override 23000 public boolean isPackagePersistent(String packageName) { 23001 synchronized (mPackages) { 23002 PackageParser.Package pkg = mPackages.get(packageName); 23003 return pkg != null 23004 ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM 23005 | ApplicationInfo.FLAG_PERSISTENT)) == 23006 (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT)) 23007 : false; 23008 } 23009 } 23010 23011 @Override 23012 public List<PackageInfo> getOverlayPackages(int userId) { 23013 final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>(); 23014 synchronized (mPackages) { 23015 for (PackageParser.Package p : mPackages.values()) { 23016 if (p.mOverlayTarget != null) { 23017 PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId); 23018 if (pkg != null) { 23019 overlayPackages.add(pkg); 23020 } 23021 } 23022 } 23023 } 23024 return overlayPackages; 23025 } 23026 23027 @Override 23028 public List<String> getTargetPackageNames(int userId) { 23029 List<String> targetPackages = new ArrayList<>(); 23030 synchronized (mPackages) { 23031 for (PackageParser.Package p : mPackages.values()) { 23032 if (p.mOverlayTarget == null) { 23033 targetPackages.add(p.packageName); 23034 } 23035 } 23036 } 23037 return targetPackages; 23038 } 23039 23040 23041 @Override 23042 public boolean setEnabledOverlayPackages(int userId, String targetPackageName, 23043 List<String> overlayPackageNames) { 23044 // TODO: implement when we integrate OMS properly 23045 return false; 23046 } 23047 } 23048 23049 @Override 23050 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 23051 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 23052 synchronized (mPackages) { 23053 final long identity = Binder.clearCallingIdentity(); 23054 try { 23055 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 23056 packageNames, userId); 23057 } finally { 23058 Binder.restoreCallingIdentity(identity); 23059 } 23060 } 23061 } 23062 23063 @Override 23064 public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) { 23065 enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices"); 23066 synchronized (mPackages) { 23067 final long identity = Binder.clearCallingIdentity(); 23068 try { 23069 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr( 23070 packageNames, userId); 23071 } finally { 23072 Binder.restoreCallingIdentity(identity); 23073 } 23074 } 23075 } 23076 23077 private static void enforceSystemOrPhoneCaller(String tag) { 23078 int callingUid = Binder.getCallingUid(); 23079 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 23080 throw new SecurityException( 23081 "Cannot call " + tag + " from UID " + callingUid); 23082 } 23083 } 23084 23085 boolean isHistoricalPackageUsageAvailable() { 23086 return mPackageUsage.isHistoricalPackageUsageAvailable(); 23087 } 23088 23089 /** 23090 * Return a <b>copy</b> of the collection of packages known to the package manager. 23091 * @return A copy of the values of mPackages. 23092 */ 23093 Collection<PackageParser.Package> getPackages() { 23094 synchronized (mPackages) { 23095 return new ArrayList<>(mPackages.values()); 23096 } 23097 } 23098 23099 /** 23100 * Logs process start information (including base APK hash) to the security log. 23101 * @hide 23102 */ 23103 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 23104 String apkFile, int pid) { 23105 if (!SecurityLog.isLoggingEnabled()) { 23106 return; 23107 } 23108 Bundle data = new Bundle(); 23109 data.putLong("startTimestamp", System.currentTimeMillis()); 23110 data.putString("processName", processName); 23111 data.putInt("uid", uid); 23112 data.putString("seinfo", seinfo); 23113 data.putString("apkFile", apkFile); 23114 data.putInt("pid", pid); 23115 Message msg = mProcessLoggingHandler.obtainMessage( 23116 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 23117 msg.setData(data); 23118 mProcessLoggingHandler.sendMessage(msg); 23119 } 23120 23121 public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) { 23122 return mCompilerStats.getPackageStats(pkgName); 23123 } 23124 23125 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) { 23126 return getOrCreateCompilerPackageStats(pkg.packageName); 23127 } 23128 23129 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) { 23130 return mCompilerStats.getOrCreatePackageStats(pkgName); 23131 } 23132 23133 public void deleteCompilerPackageStats(String pkgName) { 23134 mCompilerStats.deletePackageStats(pkgName); 23135 } 23136 23137 @Override 23138 public int getInstallReason(String packageName, int userId) { 23139 enforceCrossUserPermission(Binder.getCallingUid(), userId, 23140 true /* requireFullPermission */, false /* checkShell */, 23141 "get install reason"); 23142 synchronized (mPackages) { 23143 final PackageSetting ps = mSettings.mPackages.get(packageName); 23144 if (ps != null) { 23145 return ps.getInstallReason(userId); 23146 } 23147 } 23148 return PackageManager.INSTALL_REASON_UNKNOWN; 23149 } 23150 23151 @Override 23152 public boolean canRequestPackageInstalls(String packageName, int userId) { 23153 int callingUid = Binder.getCallingUid(); 23154 int uid = getPackageUid(packageName, 0, userId); 23155 if (callingUid != uid && callingUid != Process.ROOT_UID 23156 && callingUid != Process.SYSTEM_UID) { 23157 throw new SecurityException( 23158 "Caller uid " + callingUid + " does not own package " + packageName); 23159 } 23160 ApplicationInfo info = getApplicationInfo(packageName, 0, userId); 23161 if (info == null) { 23162 return false; 23163 } 23164 if (info.targetSdkVersion < Build.VERSION_CODES.O) { 23165 throw new UnsupportedOperationException( 23166 "Operation only supported on apps targeting Android O or higher"); 23167 } 23168 String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES; 23169 String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission); 23170 if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) { 23171 throw new SecurityException("Need to declare " + appOpPermission + " to call this api"); 23172 } 23173 if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) { 23174 return false; 23175 } 23176 if (mExternalSourcesPolicy != null) { 23177 int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid); 23178 if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) { 23179 return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED; 23180 } 23181 } 23182 return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED; 23183 } 23184} 23185