PackageManagerService.java revision 5e2714ea7ae7bd162ee8c8ae60233e47bbdf7075
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_EPHEMERAL_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.ServiceInfo; 168import android.content.pm.SharedLibraryInfo; 169import android.content.pm.Signature; 170import android.content.pm.UserInfo; 171import android.content.pm.VerifierDeviceIdentity; 172import android.content.pm.VerifierInfo; 173import android.content.pm.VersionedPackage; 174import android.content.res.Resources; 175import android.graphics.Bitmap; 176import android.hardware.display.DisplayManager; 177import android.net.Uri; 178import android.os.Binder; 179import android.os.Build; 180import android.os.Bundle; 181import android.os.Debug; 182import android.os.Environment; 183import android.os.Environment.UserEnvironment; 184import android.os.FileUtils; 185import android.os.Handler; 186import android.os.IBinder; 187import android.os.Looper; 188import android.os.Message; 189import android.os.Parcel; 190import android.os.ParcelFileDescriptor; 191import android.os.PatternMatcher; 192import android.os.Process; 193import android.os.RemoteCallbackList; 194import android.os.RemoteException; 195import android.os.ResultReceiver; 196import android.os.SELinux; 197import android.os.ServiceManager; 198import android.os.ShellCallback; 199import android.os.SystemClock; 200import android.os.SystemProperties; 201import android.os.Trace; 202import android.os.UserHandle; 203import android.os.UserManager; 204import android.os.UserManagerInternal; 205import android.os.storage.IStorageManager; 206import android.os.storage.StorageManagerInternal; 207import android.os.storage.StorageEventListener; 208import android.os.storage.StorageManager; 209import android.os.storage.VolumeInfo; 210import android.os.storage.VolumeRecord; 211import android.provider.Settings.Global; 212import android.provider.Settings.Secure; 213import android.security.KeyStore; 214import android.security.SystemKeyStore; 215import android.system.ErrnoException; 216import android.system.Os; 217import android.text.TextUtils; 218import android.text.format.DateUtils; 219import android.util.ArrayMap; 220import android.util.ArraySet; 221import android.util.Base64; 222import android.util.DisplayMetrics; 223import android.util.EventLog; 224import android.util.ExceptionUtils; 225import android.util.Log; 226import android.util.LogPrinter; 227import android.util.MathUtils; 228import android.util.PackageUtils; 229import android.util.Pair; 230import android.util.PrintStreamPrinter; 231import android.util.Slog; 232import android.util.SparseArray; 233import android.util.SparseBooleanArray; 234import android.util.SparseIntArray; 235import android.util.Xml; 236import android.util.jar.StrictJarFile; 237import android.view.Display; 238 239import com.android.internal.R; 240import com.android.internal.annotations.GuardedBy; 241import com.android.internal.app.IMediaContainerService; 242import com.android.internal.app.ResolverActivity; 243import com.android.internal.content.NativeLibraryHelper; 244import com.android.internal.content.PackageHelper; 245import com.android.internal.logging.MetricsLogger; 246import com.android.internal.logging.nano.MetricsProto.MetricsEvent; 247import com.android.internal.os.IParcelFileDescriptorFactory; 248import com.android.internal.os.RoSystemProperties; 249import com.android.internal.os.SomeArgs; 250import com.android.internal.os.Zygote; 251import com.android.internal.telephony.CarrierAppUtils; 252import com.android.internal.util.ArrayUtils; 253import com.android.internal.util.FastPrintWriter; 254import com.android.internal.util.FastXmlSerializer; 255import com.android.internal.util.IndentingPrintWriter; 256import com.android.internal.util.Preconditions; 257import com.android.internal.util.XmlUtils; 258import com.android.server.AttributeCache; 259import com.android.server.BackgroundDexOptJobService; 260import com.android.server.EventLogTags; 261import com.android.server.FgThread; 262import com.android.server.IntentResolver; 263import com.android.server.LocalServices; 264import com.android.server.ServiceThread; 265import com.android.server.SystemConfig; 266import com.android.server.Watchdog; 267import com.android.server.net.NetworkPolicyManagerInternal; 268import com.android.server.pm.Installer.InstallerException; 269import com.android.server.pm.PermissionsState.PermissionState; 270import com.android.server.pm.Settings.DatabaseVersion; 271import com.android.server.pm.Settings.VersionInfo; 272import com.android.server.pm.dex.DexManager; 273import com.android.server.storage.DeviceStorageMonitorInternal; 274 275import dalvik.system.CloseGuard; 276import dalvik.system.DexFile; 277import dalvik.system.VMRuntime; 278 279import libcore.io.IoUtils; 280import libcore.util.EmptyArray; 281 282import org.xmlpull.v1.XmlPullParser; 283import org.xmlpull.v1.XmlPullParserException; 284import org.xmlpull.v1.XmlSerializer; 285 286import java.io.BufferedOutputStream; 287import java.io.BufferedReader; 288import java.io.ByteArrayInputStream; 289import java.io.ByteArrayOutputStream; 290import java.io.File; 291import java.io.FileDescriptor; 292import java.io.FileInputStream; 293import java.io.FileNotFoundException; 294import java.io.FileOutputStream; 295import java.io.FileReader; 296import java.io.FilenameFilter; 297import java.io.IOException; 298import java.io.PrintWriter; 299import java.nio.charset.StandardCharsets; 300import java.security.DigestInputStream; 301import java.security.MessageDigest; 302import java.security.NoSuchAlgorithmException; 303import java.security.PublicKey; 304import java.security.SecureRandom; 305import java.security.cert.Certificate; 306import java.security.cert.CertificateEncodingException; 307import java.security.cert.CertificateException; 308import java.text.SimpleDateFormat; 309import java.util.ArrayList; 310import java.util.Arrays; 311import java.util.Collection; 312import java.util.Collections; 313import java.util.Comparator; 314import java.util.Date; 315import java.util.HashSet; 316import java.util.HashMap; 317import java.util.Iterator; 318import java.util.List; 319import java.util.Map; 320import java.util.Objects; 321import java.util.Set; 322import java.util.concurrent.CountDownLatch; 323import java.util.concurrent.TimeUnit; 324import java.util.concurrent.atomic.AtomicBoolean; 325import java.util.concurrent.atomic.AtomicInteger; 326 327/** 328 * Keep track of all those APKs everywhere. 329 * <p> 330 * Internally there are two important locks: 331 * <ul> 332 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 333 * and other related state. It is a fine-grained lock that should only be held 334 * momentarily, as it's one of the most contended locks in the system. 335 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 336 * operations typically involve heavy lifting of application data on disk. Since 337 * {@code installd} is single-threaded, and it's operations can often be slow, 338 * this lock should never be acquired while already holding {@link #mPackages}. 339 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 340 * holding {@link #mInstallLock}. 341 * </ul> 342 * Many internal methods rely on the caller to hold the appropriate locks, and 343 * this contract is expressed through method name suffixes: 344 * <ul> 345 * <li>fooLI(): the caller must hold {@link #mInstallLock} 346 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 347 * being modified must be frozen 348 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 349 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 350 * </ul> 351 * <p> 352 * Because this class is very central to the platform's security; please run all 353 * CTS and unit tests whenever making modifications: 354 * 355 * <pre> 356 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 357 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases 358 * </pre> 359 */ 360public class PackageManagerService extends IPackageManager.Stub { 361 static final String TAG = "PackageManager"; 362 static final boolean DEBUG_SETTINGS = false; 363 static final boolean DEBUG_PREFERRED = false; 364 static final boolean DEBUG_UPGRADE = false; 365 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 366 private static final boolean DEBUG_BACKUP = false; 367 private static final boolean DEBUG_INSTALL = false; 368 private static final boolean DEBUG_REMOVE = false; 369 private static final boolean DEBUG_BROADCASTS = false; 370 private static final boolean DEBUG_SHOW_INFO = false; 371 private static final boolean DEBUG_PACKAGE_INFO = false; 372 private static final boolean DEBUG_INTENT_MATCHING = false; 373 private static final boolean DEBUG_PACKAGE_SCANNING = false; 374 private static final boolean DEBUG_VERIFY = false; 375 private static final boolean DEBUG_FILTERS = false; 376 377 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 378 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 379 // user, but by default initialize to this. 380 public static final boolean DEBUG_DEXOPT = false; 381 382 private static final boolean DEBUG_ABI_SELECTION = false; 383 private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE; 384 private static final boolean DEBUG_TRIAGED_MISSING = false; 385 private static final boolean DEBUG_APP_DATA = false; 386 387 /** REMOVE. According to Svet, this was only used to reset permissions during development. */ 388 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 389 390 private static final boolean DISABLE_EPHEMERAL_APPS = false; 391 private static final boolean HIDE_EPHEMERAL_APIS = false; 392 393 private static final boolean ENABLE_QUOTA = 394 SystemProperties.getBoolean("persist.fw.quota", false); 395 396 private static final int RADIO_UID = Process.PHONE_UID; 397 private static final int LOG_UID = Process.LOG_UID; 398 private static final int NFC_UID = Process.NFC_UID; 399 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 400 private static final int SHELL_UID = Process.SHELL_UID; 401 402 // Cap the size of permission trees that 3rd party apps can define 403 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 404 405 // Suffix used during package installation when copying/moving 406 // package apks to install directory. 407 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 408 409 static final int SCAN_NO_DEX = 1<<1; 410 static final int SCAN_FORCE_DEX = 1<<2; 411 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 412 static final int SCAN_NEW_INSTALL = 1<<4; 413 static final int SCAN_UPDATE_TIME = 1<<5; 414 static final int SCAN_BOOTING = 1<<6; 415 static final int SCAN_TRUSTED_OVERLAY = 1<<7; 416 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8; 417 static final int SCAN_REPLACING = 1<<9; 418 static final int SCAN_REQUIRE_KNOWN = 1<<10; 419 static final int SCAN_MOVE = 1<<11; 420 static final int SCAN_INITIAL = 1<<12; 421 static final int SCAN_CHECK_ONLY = 1<<13; 422 static final int SCAN_DONT_KILL_APP = 1<<14; 423 static final int SCAN_IGNORE_FROZEN = 1<<15; 424 static final int REMOVE_CHATTY = 1<<16; 425 static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<17; 426 427 private static final String STATIC_SHARED_LIB_DELIMITER = "_"; 428 429 private static final int[] EMPTY_INT_ARRAY = new int[0]; 430 431 /** 432 * Timeout (in milliseconds) after which the watchdog should declare that 433 * our handler thread is wedged. The usual default for such things is one 434 * minute but we sometimes do very lengthy I/O operations on this thread, 435 * such as installing multi-gigabyte applications, so ours needs to be longer. 436 */ 437 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 438 439 /** 440 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 441 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 442 * settings entry if available, otherwise we use the hardcoded default. If it's been 443 * more than this long since the last fstrim, we force one during the boot sequence. 444 * 445 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 446 * one gets run at the next available charging+idle time. This final mandatory 447 * no-fstrim check kicks in only of the other scheduling criteria is never met. 448 */ 449 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 450 451 /** 452 * Whether verification is enabled by default. 453 */ 454 private static final boolean DEFAULT_VERIFY_ENABLE = true; 455 456 /** 457 * The default maximum time to wait for the verification agent to return in 458 * milliseconds. 459 */ 460 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 461 462 /** 463 * The default response for package verification timeout. 464 * 465 * This can be either PackageManager.VERIFICATION_ALLOW or 466 * PackageManager.VERIFICATION_REJECT. 467 */ 468 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 469 470 static final String PLATFORM_PACKAGE_NAME = "android"; 471 472 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 473 474 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 475 DEFAULT_CONTAINER_PACKAGE, 476 "com.android.defcontainer.DefaultContainerService"); 477 478 private static final String KILL_APP_REASON_GIDS_CHANGED = 479 "permission grant or revoke changed gids"; 480 481 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 482 "permissions revoked"; 483 484 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 485 486 private static final String PACKAGE_SCHEME = "package"; 487 488 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 489 /** 490 * If VENDOR_OVERLAY_THEME_PROPERTY is set, search for runtime resource overlay APKs also in 491 * VENDOR_OVERLAY_DIR/<value of VENDOR_OVERLAY_THEME_PROPERTY> in addition to 492 * VENDOR_OVERLAY_DIR. 493 */ 494 private static final String VENDOR_OVERLAY_THEME_PROPERTY = "ro.boot.vendor.overlay.theme"; 495 /** 496 * Same as VENDOR_OVERLAY_THEME_PROPERTY, except persistent. If set will override whatever 497 * is in VENDOR_OVERLAY_THEME_PROPERTY. 498 */ 499 private static final String VENDOR_OVERLAY_THEME_PERSIST_PROPERTY 500 = "persist.vendor.overlay.theme"; 501 502 /** Permission grant: not grant the permission. */ 503 private static final int GRANT_DENIED = 1; 504 505 /** Permission grant: grant the permission as an install permission. */ 506 private static final int GRANT_INSTALL = 2; 507 508 /** Permission grant: grant the permission as a runtime one. */ 509 private static final int GRANT_RUNTIME = 3; 510 511 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 512 private static final int GRANT_UPGRADE = 4; 513 514 /** Canonical intent used to identify what counts as a "web browser" app */ 515 private static final Intent sBrowserIntent; 516 static { 517 sBrowserIntent = new Intent(); 518 sBrowserIntent.setAction(Intent.ACTION_VIEW); 519 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 520 sBrowserIntent.setData(Uri.parse("http:")); 521 } 522 523 /** 524 * The set of all protected actions [i.e. those actions for which a high priority 525 * intent filter is disallowed]. 526 */ 527 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 528 static { 529 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 530 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 531 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 532 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 533 } 534 535 // Compilation reasons. 536 public static final int REASON_FIRST_BOOT = 0; 537 public static final int REASON_BOOT = 1; 538 public static final int REASON_INSTALL = 2; 539 public static final int REASON_BACKGROUND_DEXOPT = 3; 540 public static final int REASON_AB_OTA = 4; 541 public static final int REASON_NON_SYSTEM_LIBRARY = 5; 542 public static final int REASON_SHARED_APK = 6; 543 public static final int REASON_FORCED_DEXOPT = 7; 544 public static final int REASON_CORE_APP = 8; 545 546 public static final int REASON_LAST = REASON_CORE_APP; 547 548 /** Special library name that skips shared libraries check during compilation. */ 549 private static final String SKIP_SHARED_LIBRARY_CHECK = "&"; 550 551 /** All dangerous permission names in the same order as the events in MetricsEvent */ 552 private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList( 553 Manifest.permission.READ_CALENDAR, 554 Manifest.permission.WRITE_CALENDAR, 555 Manifest.permission.CAMERA, 556 Manifest.permission.READ_CONTACTS, 557 Manifest.permission.WRITE_CONTACTS, 558 Manifest.permission.GET_ACCOUNTS, 559 Manifest.permission.ACCESS_FINE_LOCATION, 560 Manifest.permission.ACCESS_COARSE_LOCATION, 561 Manifest.permission.RECORD_AUDIO, 562 Manifest.permission.READ_PHONE_STATE, 563 Manifest.permission.CALL_PHONE, 564 Manifest.permission.READ_CALL_LOG, 565 Manifest.permission.WRITE_CALL_LOG, 566 Manifest.permission.ADD_VOICEMAIL, 567 Manifest.permission.USE_SIP, 568 Manifest.permission.PROCESS_OUTGOING_CALLS, 569 Manifest.permission.READ_CELL_BROADCASTS, 570 Manifest.permission.BODY_SENSORS, 571 Manifest.permission.SEND_SMS, 572 Manifest.permission.RECEIVE_SMS, 573 Manifest.permission.READ_SMS, 574 Manifest.permission.RECEIVE_WAP_PUSH, 575 Manifest.permission.RECEIVE_MMS, 576 Manifest.permission.READ_EXTERNAL_STORAGE, 577 Manifest.permission.WRITE_EXTERNAL_STORAGE, 578 Manifest.permission.READ_PHONE_NUMBER); 579 580 581 /** 582 * Version number for the package parser cache. Increment this whenever the format or 583 * extent of cached data changes. See {@code PackageParser#setCacheDir}. 584 */ 585 private static final String PACKAGE_PARSER_CACHE_VERSION = "1"; 586 587 /** 588 * Whether the package parser cache is enabled. 589 */ 590 private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true; 591 592 final ServiceThread mHandlerThread; 593 594 final PackageHandler mHandler; 595 596 private final ProcessLoggingHandler mProcessLoggingHandler; 597 598 /** 599 * Messages for {@link #mHandler} that need to wait for system ready before 600 * being dispatched. 601 */ 602 private ArrayList<Message> mPostSystemReadyMessages; 603 604 final int mSdkVersion = Build.VERSION.SDK_INT; 605 606 final Context mContext; 607 final boolean mFactoryTest; 608 final boolean mOnlyCore; 609 final DisplayMetrics mMetrics; 610 final int mDefParseFlags; 611 final String[] mSeparateProcesses; 612 final boolean mIsUpgrade; 613 final boolean mIsPreNUpgrade; 614 final boolean mIsPreNMR1Upgrade; 615 616 @GuardedBy("mPackages") 617 private boolean mDexOptDialogShown; 618 619 /** The location for ASEC container files on internal storage. */ 620 final String mAsecInternalPath; 621 622 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 623 // LOCK HELD. Can be called with mInstallLock held. 624 @GuardedBy("mInstallLock") 625 final Installer mInstaller; 626 627 /** Directory where installed third-party apps stored */ 628 final File mAppInstallDir; 629 final File mEphemeralInstallDir; 630 631 /** 632 * Directory to which applications installed internally have their 633 * 32 bit native libraries copied. 634 */ 635 private File mAppLib32InstallDir; 636 637 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 638 // apps. 639 final File mDrmAppPrivateInstallDir; 640 641 // ---------------------------------------------------------------- 642 643 // Lock for state used when installing and doing other long running 644 // operations. Methods that must be called with this lock held have 645 // the suffix "LI". 646 final Object mInstallLock = new Object(); 647 648 // ---------------------------------------------------------------- 649 650 // Keys are String (package name), values are Package. This also serves 651 // as the lock for the global state. Methods that must be called with 652 // this lock held have the prefix "LP". 653 @GuardedBy("mPackages") 654 final ArrayMap<String, PackageParser.Package> mPackages = 655 new ArrayMap<String, PackageParser.Package>(); 656 657 final ArrayMap<String, Set<String>> mKnownCodebase = 658 new ArrayMap<String, Set<String>>(); 659 660 // Tracks available target package names -> overlay package paths. 661 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 662 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 663 664 /** 665 * Tracks new system packages [received in an OTA] that we expect to 666 * find updated user-installed versions. Keys are package name, values 667 * are package location. 668 */ 669 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 670 /** 671 * Tracks high priority intent filters for protected actions. During boot, certain 672 * filter actions are protected and should never be allowed to have a high priority 673 * intent filter for them. However, there is one, and only one exception -- the 674 * setup wizard. It must be able to define a high priority intent filter for these 675 * actions to ensure there are no escapes from the wizard. We need to delay processing 676 * of these during boot as we need to look at all of the system packages in order 677 * to know which component is the setup wizard. 678 */ 679 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 680 /** 681 * Whether or not processing protected filters should be deferred. 682 */ 683 private boolean mDeferProtectedFilters = true; 684 685 /** 686 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 687 */ 688 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 689 /** 690 * Whether or not system app permissions should be promoted from install to runtime. 691 */ 692 boolean mPromoteSystemApps; 693 694 @GuardedBy("mPackages") 695 final Settings mSettings; 696 697 /** 698 * Set of package names that are currently "frozen", which means active 699 * surgery is being done on the code/data for that package. The platform 700 * will refuse to launch frozen packages to avoid race conditions. 701 * 702 * @see PackageFreezer 703 */ 704 @GuardedBy("mPackages") 705 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 706 707 final ProtectedPackages mProtectedPackages; 708 709 boolean mFirstBoot; 710 711 PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy; 712 713 // System configuration read by SystemConfig. 714 final int[] mGlobalGids; 715 final SparseArray<ArraySet<String>> mSystemPermissions; 716 @GuardedBy("mAvailableFeatures") 717 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 718 719 // If mac_permissions.xml was found for seinfo labeling. 720 boolean mFoundPolicyFile; 721 722 private final InstantAppRegistry mInstantAppRegistry; 723 724 @GuardedBy("mPackages") 725 int mChangedPackagesSequenceNumber; 726 /** 727 * List of changed [installed, removed or updated] packages. 728 * mapping from user id -> sequence number -> package name 729 */ 730 @GuardedBy("mPackages") 731 final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>(); 732 /** 733 * The sequence number of the last change to a package. 734 * mapping from user id -> package name -> sequence number 735 */ 736 @GuardedBy("mPackages") 737 final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>(); 738 739 public static final class SharedLibraryEntry { 740 public final String path; 741 public final String apk; 742 public final SharedLibraryInfo info; 743 744 SharedLibraryEntry(String _path, String _apk, String name, int version, int type, 745 String declaringPackageName, int declaringPackageVersionCode) { 746 path = _path; 747 apk = _apk; 748 info = new SharedLibraryInfo(name, version, type, new VersionedPackage( 749 declaringPackageName, declaringPackageVersionCode), null); 750 } 751 } 752 753 // Currently known shared libraries. 754 final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>(); 755 final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage = 756 new ArrayMap<>(); 757 758 // All available activities, for your resolving pleasure. 759 final ActivityIntentResolver mActivities = 760 new ActivityIntentResolver(); 761 762 // All available receivers, for your resolving pleasure. 763 final ActivityIntentResolver mReceivers = 764 new ActivityIntentResolver(); 765 766 // All available services, for your resolving pleasure. 767 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 768 769 // All available providers, for your resolving pleasure. 770 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 771 772 // Mapping from provider base names (first directory in content URI codePath) 773 // to the provider information. 774 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 775 new ArrayMap<String, PackageParser.Provider>(); 776 777 // Mapping from instrumentation class names to info about them. 778 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 779 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 780 781 // Mapping from permission names to info about them. 782 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 783 new ArrayMap<String, PackageParser.PermissionGroup>(); 784 785 // Packages whose data we have transfered into another package, thus 786 // should no longer exist. 787 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 788 789 // Broadcast actions that are only available to the system. 790 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 791 792 /** List of packages waiting for verification. */ 793 final SparseArray<PackageVerificationState> mPendingVerification 794 = new SparseArray<PackageVerificationState>(); 795 796 /** Set of packages associated with each app op permission. */ 797 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 798 799 final PackageInstallerService mInstallerService; 800 801 private final PackageDexOptimizer mPackageDexOptimizer; 802 // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package 803 // is used by other apps). 804 private final DexManager mDexManager; 805 806 private AtomicInteger mNextMoveId = new AtomicInteger(); 807 private final MoveCallbacks mMoveCallbacks; 808 809 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 810 811 // Cache of users who need badging. 812 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 813 814 /** Token for keys in mPendingVerification. */ 815 private int mPendingVerificationToken = 0; 816 817 volatile boolean mSystemReady; 818 volatile boolean mSafeMode; 819 volatile boolean mHasSystemUidErrors; 820 821 ApplicationInfo mAndroidApplication; 822 final ActivityInfo mResolveActivity = new ActivityInfo(); 823 final ResolveInfo mResolveInfo = new ResolveInfo(); 824 ComponentName mResolveComponentName; 825 PackageParser.Package mPlatformPackage; 826 ComponentName mCustomResolverComponentName; 827 828 boolean mResolverReplaced = false; 829 830 private final @Nullable ComponentName mIntentFilterVerifierComponent; 831 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 832 833 private int mIntentFilterVerificationToken = 0; 834 835 /** The service connection to the ephemeral resolver */ 836 final EphemeralResolverConnection mEphemeralResolverConnection; 837 838 /** Component used to install ephemeral applications */ 839 ComponentName mEphemeralInstallerComponent; 840 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 841 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 842 843 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 844 = new SparseArray<IntentFilterVerificationState>(); 845 846 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy; 847 848 // List of packages names to keep cached, even if they are uninstalled for all users 849 private List<String> mKeepUninstalledPackages; 850 851 private UserManagerInternal mUserManagerInternal; 852 853 private File mCacheDir; 854 855 private ArraySet<String> mPrivappPermissionsViolations; 856 857 private static class IFVerificationParams { 858 PackageParser.Package pkg; 859 boolean replacing; 860 int userId; 861 int verifierUid; 862 863 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 864 int _userId, int _verifierUid) { 865 pkg = _pkg; 866 replacing = _replacing; 867 userId = _userId; 868 replacing = _replacing; 869 verifierUid = _verifierUid; 870 } 871 } 872 873 private interface IntentFilterVerifier<T extends IntentFilter> { 874 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 875 T filter, String packageName); 876 void startVerifications(int userId); 877 void receiveVerificationResponse(int verificationId); 878 } 879 880 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 881 private Context mContext; 882 private ComponentName mIntentFilterVerifierComponent; 883 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 884 885 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 886 mContext = context; 887 mIntentFilterVerifierComponent = verifierComponent; 888 } 889 890 private String getDefaultScheme() { 891 return IntentFilter.SCHEME_HTTPS; 892 } 893 894 @Override 895 public void startVerifications(int userId) { 896 // Launch verifications requests 897 int count = mCurrentIntentFilterVerifications.size(); 898 for (int n=0; n<count; n++) { 899 int verificationId = mCurrentIntentFilterVerifications.get(n); 900 final IntentFilterVerificationState ivs = 901 mIntentFilterVerificationStates.get(verificationId); 902 903 String packageName = ivs.getPackageName(); 904 905 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 906 final int filterCount = filters.size(); 907 ArraySet<String> domainsSet = new ArraySet<>(); 908 for (int m=0; m<filterCount; m++) { 909 PackageParser.ActivityIntentInfo filter = filters.get(m); 910 domainsSet.addAll(filter.getHostsList()); 911 } 912 synchronized (mPackages) { 913 if (mSettings.createIntentFilterVerificationIfNeededLPw( 914 packageName, domainsSet) != null) { 915 scheduleWriteSettingsLocked(); 916 } 917 } 918 sendVerificationRequest(userId, verificationId, ivs); 919 } 920 mCurrentIntentFilterVerifications.clear(); 921 } 922 923 private void sendVerificationRequest(int userId, int verificationId, 924 IntentFilterVerificationState ivs) { 925 926 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 927 verificationIntent.putExtra( 928 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 929 verificationId); 930 verificationIntent.putExtra( 931 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 932 getDefaultScheme()); 933 verificationIntent.putExtra( 934 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 935 ivs.getHostsString()); 936 verificationIntent.putExtra( 937 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 938 ivs.getPackageName()); 939 verificationIntent.setComponent(mIntentFilterVerifierComponent); 940 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 941 942 UserHandle user = new UserHandle(userId); 943 mContext.sendBroadcastAsUser(verificationIntent, user); 944 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 945 "Sending IntentFilter verification broadcast"); 946 } 947 948 public void receiveVerificationResponse(int verificationId) { 949 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 950 951 final boolean verified = ivs.isVerified(); 952 953 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 954 final int count = filters.size(); 955 if (DEBUG_DOMAIN_VERIFICATION) { 956 Slog.i(TAG, "Received verification response " + verificationId 957 + " for " + count + " filters, verified=" + verified); 958 } 959 for (int n=0; n<count; n++) { 960 PackageParser.ActivityIntentInfo filter = filters.get(n); 961 filter.setVerified(verified); 962 963 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 964 + " verified with result:" + verified + " and hosts:" 965 + ivs.getHostsString()); 966 } 967 968 mIntentFilterVerificationStates.remove(verificationId); 969 970 final String packageName = ivs.getPackageName(); 971 IntentFilterVerificationInfo ivi = null; 972 973 synchronized (mPackages) { 974 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 975 } 976 if (ivi == null) { 977 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 978 + verificationId + " packageName:" + packageName); 979 return; 980 } 981 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 982 "Updating IntentFilterVerificationInfo for package " + packageName 983 +" verificationId:" + verificationId); 984 985 synchronized (mPackages) { 986 if (verified) { 987 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 988 } else { 989 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 990 } 991 scheduleWriteSettingsLocked(); 992 993 final int userId = ivs.getUserId(); 994 if (userId != UserHandle.USER_ALL) { 995 final int userStatus = 996 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 997 998 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 999 boolean needUpdate = false; 1000 1001 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 1002 // already been set by the User thru the Disambiguation dialog 1003 switch (userStatus) { 1004 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 1005 if (verified) { 1006 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 1007 } else { 1008 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 1009 } 1010 needUpdate = true; 1011 break; 1012 1013 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 1014 if (verified) { 1015 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 1016 needUpdate = true; 1017 } 1018 break; 1019 1020 default: 1021 // Nothing to do 1022 } 1023 1024 if (needUpdate) { 1025 mSettings.updateIntentFilterVerificationStatusLPw( 1026 packageName, updatedStatus, userId); 1027 scheduleWritePackageRestrictionsLocked(userId); 1028 } 1029 } 1030 } 1031 } 1032 1033 @Override 1034 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 1035 ActivityIntentInfo filter, String packageName) { 1036 if (!hasValidDomains(filter)) { 1037 return false; 1038 } 1039 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 1040 if (ivs == null) { 1041 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 1042 packageName); 1043 } 1044 if (DEBUG_DOMAIN_VERIFICATION) { 1045 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 1046 } 1047 ivs.addFilter(filter); 1048 return true; 1049 } 1050 1051 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 1052 int userId, int verificationId, String packageName) { 1053 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 1054 verifierUid, userId, packageName); 1055 ivs.setPendingState(); 1056 synchronized (mPackages) { 1057 mIntentFilterVerificationStates.append(verificationId, ivs); 1058 mCurrentIntentFilterVerifications.add(verificationId); 1059 } 1060 return ivs; 1061 } 1062 } 1063 1064 private static boolean hasValidDomains(ActivityIntentInfo filter) { 1065 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 1066 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 1067 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 1068 } 1069 1070 // Set of pending broadcasts for aggregating enable/disable of components. 1071 static class PendingPackageBroadcasts { 1072 // for each user id, a map of <package name -> components within that package> 1073 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 1074 1075 public PendingPackageBroadcasts() { 1076 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 1077 } 1078 1079 public ArrayList<String> get(int userId, String packageName) { 1080 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1081 return packages.get(packageName); 1082 } 1083 1084 public void put(int userId, String packageName, ArrayList<String> components) { 1085 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1086 packages.put(packageName, components); 1087 } 1088 1089 public void remove(int userId, String packageName) { 1090 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 1091 if (packages != null) { 1092 packages.remove(packageName); 1093 } 1094 } 1095 1096 public void remove(int userId) { 1097 mUidMap.remove(userId); 1098 } 1099 1100 public int userIdCount() { 1101 return mUidMap.size(); 1102 } 1103 1104 public int userIdAt(int n) { 1105 return mUidMap.keyAt(n); 1106 } 1107 1108 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 1109 return mUidMap.get(userId); 1110 } 1111 1112 public int size() { 1113 // total number of pending broadcast entries across all userIds 1114 int num = 0; 1115 for (int i = 0; i< mUidMap.size(); i++) { 1116 num += mUidMap.valueAt(i).size(); 1117 } 1118 return num; 1119 } 1120 1121 public void clear() { 1122 mUidMap.clear(); 1123 } 1124 1125 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1126 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1127 if (map == null) { 1128 map = new ArrayMap<String, ArrayList<String>>(); 1129 mUidMap.put(userId, map); 1130 } 1131 return map; 1132 } 1133 } 1134 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1135 1136 // Service Connection to remote media container service to copy 1137 // package uri's from external media onto secure containers 1138 // or internal storage. 1139 private IMediaContainerService mContainerService = null; 1140 1141 static final int SEND_PENDING_BROADCAST = 1; 1142 static final int MCS_BOUND = 3; 1143 static final int END_COPY = 4; 1144 static final int INIT_COPY = 5; 1145 static final int MCS_UNBIND = 6; 1146 static final int START_CLEANING_PACKAGE = 7; 1147 static final int FIND_INSTALL_LOC = 8; 1148 static final int POST_INSTALL = 9; 1149 static final int MCS_RECONNECT = 10; 1150 static final int MCS_GIVE_UP = 11; 1151 static final int UPDATED_MEDIA_STATUS = 12; 1152 static final int WRITE_SETTINGS = 13; 1153 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1154 static final int PACKAGE_VERIFIED = 15; 1155 static final int CHECK_PENDING_VERIFICATION = 16; 1156 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1157 static final int INTENT_FILTER_VERIFIED = 18; 1158 static final int WRITE_PACKAGE_LIST = 19; 1159 static final int EPHEMERAL_RESOLUTION_PHASE_TWO = 20; 1160 1161 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1162 1163 // Delay time in millisecs 1164 static final int BROADCAST_DELAY = 10 * 1000; 1165 1166 static UserManagerService sUserManager; 1167 1168 // Stores a list of users whose package restrictions file needs to be updated 1169 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1170 1171 final private DefaultContainerConnection mDefContainerConn = 1172 new DefaultContainerConnection(); 1173 class DefaultContainerConnection implements ServiceConnection { 1174 public void onServiceConnected(ComponentName name, IBinder service) { 1175 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1176 final IMediaContainerService imcs = IMediaContainerService.Stub 1177 .asInterface(Binder.allowBlocking(service)); 1178 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1179 } 1180 1181 public void onServiceDisconnected(ComponentName name) { 1182 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1183 } 1184 } 1185 1186 // Recordkeeping of restore-after-install operations that are currently in flight 1187 // between the Package Manager and the Backup Manager 1188 static class PostInstallData { 1189 public InstallArgs args; 1190 public PackageInstalledInfo res; 1191 1192 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1193 args = _a; 1194 res = _r; 1195 } 1196 } 1197 1198 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1199 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1200 1201 // XML tags for backup/restore of various bits of state 1202 private static final String TAG_PREFERRED_BACKUP = "pa"; 1203 private static final String TAG_DEFAULT_APPS = "da"; 1204 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1205 1206 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1207 private static final String TAG_ALL_GRANTS = "rt-grants"; 1208 private static final String TAG_GRANT = "grant"; 1209 private static final String ATTR_PACKAGE_NAME = "pkg"; 1210 1211 private static final String TAG_PERMISSION = "perm"; 1212 private static final String ATTR_PERMISSION_NAME = "name"; 1213 private static final String ATTR_IS_GRANTED = "g"; 1214 private static final String ATTR_USER_SET = "set"; 1215 private static final String ATTR_USER_FIXED = "fixed"; 1216 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1217 1218 // System/policy permission grants are not backed up 1219 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1220 FLAG_PERMISSION_POLICY_FIXED 1221 | FLAG_PERMISSION_SYSTEM_FIXED 1222 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1223 1224 // And we back up these user-adjusted states 1225 private static final int USER_RUNTIME_GRANT_MASK = 1226 FLAG_PERMISSION_USER_SET 1227 | FLAG_PERMISSION_USER_FIXED 1228 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1229 1230 final @Nullable String mRequiredVerifierPackage; 1231 final @NonNull String mRequiredInstallerPackage; 1232 final @NonNull String mRequiredUninstallerPackage; 1233 final @Nullable String mSetupWizardPackage; 1234 final @Nullable String mStorageManagerPackage; 1235 final @NonNull String mServicesSystemSharedLibraryPackageName; 1236 final @NonNull String mSharedSystemSharedLibraryPackageName; 1237 1238 final boolean mPermissionReviewRequired; 1239 1240 private final PackageUsage mPackageUsage = new PackageUsage(); 1241 private final CompilerStats mCompilerStats = new CompilerStats(); 1242 1243 class PackageHandler extends Handler { 1244 private boolean mBound = false; 1245 final ArrayList<HandlerParams> mPendingInstalls = 1246 new ArrayList<HandlerParams>(); 1247 1248 private boolean connectToService() { 1249 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1250 " DefaultContainerService"); 1251 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1252 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1253 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1254 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1255 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1256 mBound = true; 1257 return true; 1258 } 1259 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1260 return false; 1261 } 1262 1263 private void disconnectService() { 1264 mContainerService = null; 1265 mBound = false; 1266 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1267 mContext.unbindService(mDefContainerConn); 1268 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1269 } 1270 1271 PackageHandler(Looper looper) { 1272 super(looper); 1273 } 1274 1275 public void handleMessage(Message msg) { 1276 try { 1277 doHandleMessage(msg); 1278 } finally { 1279 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1280 } 1281 } 1282 1283 void doHandleMessage(Message msg) { 1284 switch (msg.what) { 1285 case INIT_COPY: { 1286 HandlerParams params = (HandlerParams) msg.obj; 1287 int idx = mPendingInstalls.size(); 1288 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1289 // If a bind was already initiated we dont really 1290 // need to do anything. The pending install 1291 // will be processed later on. 1292 if (!mBound) { 1293 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1294 System.identityHashCode(mHandler)); 1295 // If this is the only one pending we might 1296 // have to bind to the service again. 1297 if (!connectToService()) { 1298 Slog.e(TAG, "Failed to bind to media container service"); 1299 params.serviceError(); 1300 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1301 System.identityHashCode(mHandler)); 1302 if (params.traceMethod != null) { 1303 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1304 params.traceCookie); 1305 } 1306 return; 1307 } else { 1308 // Once we bind to the service, the first 1309 // pending request will be processed. 1310 mPendingInstalls.add(idx, params); 1311 } 1312 } else { 1313 mPendingInstalls.add(idx, params); 1314 // Already bound to the service. Just make 1315 // sure we trigger off processing the first request. 1316 if (idx == 0) { 1317 mHandler.sendEmptyMessage(MCS_BOUND); 1318 } 1319 } 1320 break; 1321 } 1322 case MCS_BOUND: { 1323 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1324 if (msg.obj != null) { 1325 mContainerService = (IMediaContainerService) msg.obj; 1326 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1327 System.identityHashCode(mHandler)); 1328 } 1329 if (mContainerService == null) { 1330 if (!mBound) { 1331 // Something seriously wrong since we are not bound and we are not 1332 // waiting for connection. Bail out. 1333 Slog.e(TAG, "Cannot bind to media container service"); 1334 for (HandlerParams params : mPendingInstalls) { 1335 // Indicate service bind error 1336 params.serviceError(); 1337 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1338 System.identityHashCode(params)); 1339 if (params.traceMethod != null) { 1340 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1341 params.traceMethod, params.traceCookie); 1342 } 1343 return; 1344 } 1345 mPendingInstalls.clear(); 1346 } else { 1347 Slog.w(TAG, "Waiting to connect to media container service"); 1348 } 1349 } else if (mPendingInstalls.size() > 0) { 1350 HandlerParams params = mPendingInstalls.get(0); 1351 if (params != null) { 1352 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1353 System.identityHashCode(params)); 1354 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1355 if (params.startCopy()) { 1356 // We are done... look for more work or to 1357 // go idle. 1358 if (DEBUG_SD_INSTALL) Log.i(TAG, 1359 "Checking for more work or unbind..."); 1360 // Delete pending install 1361 if (mPendingInstalls.size() > 0) { 1362 mPendingInstalls.remove(0); 1363 } 1364 if (mPendingInstalls.size() == 0) { 1365 if (mBound) { 1366 if (DEBUG_SD_INSTALL) Log.i(TAG, 1367 "Posting delayed MCS_UNBIND"); 1368 removeMessages(MCS_UNBIND); 1369 Message ubmsg = obtainMessage(MCS_UNBIND); 1370 // Unbind after a little delay, to avoid 1371 // continual thrashing. 1372 sendMessageDelayed(ubmsg, 10000); 1373 } 1374 } else { 1375 // There are more pending requests in queue. 1376 // Just post MCS_BOUND message to trigger processing 1377 // of next pending install. 1378 if (DEBUG_SD_INSTALL) Log.i(TAG, 1379 "Posting MCS_BOUND for next work"); 1380 mHandler.sendEmptyMessage(MCS_BOUND); 1381 } 1382 } 1383 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1384 } 1385 } else { 1386 // Should never happen ideally. 1387 Slog.w(TAG, "Empty queue"); 1388 } 1389 break; 1390 } 1391 case MCS_RECONNECT: { 1392 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1393 if (mPendingInstalls.size() > 0) { 1394 if (mBound) { 1395 disconnectService(); 1396 } 1397 if (!connectToService()) { 1398 Slog.e(TAG, "Failed to bind to media container service"); 1399 for (HandlerParams params : mPendingInstalls) { 1400 // Indicate service bind error 1401 params.serviceError(); 1402 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1403 System.identityHashCode(params)); 1404 } 1405 mPendingInstalls.clear(); 1406 } 1407 } 1408 break; 1409 } 1410 case MCS_UNBIND: { 1411 // If there is no actual work left, then time to unbind. 1412 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1413 1414 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1415 if (mBound) { 1416 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1417 1418 disconnectService(); 1419 } 1420 } else if (mPendingInstalls.size() > 0) { 1421 // There are more pending requests in queue. 1422 // Just post MCS_BOUND message to trigger processing 1423 // of next pending install. 1424 mHandler.sendEmptyMessage(MCS_BOUND); 1425 } 1426 1427 break; 1428 } 1429 case MCS_GIVE_UP: { 1430 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1431 HandlerParams params = mPendingInstalls.remove(0); 1432 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1433 System.identityHashCode(params)); 1434 break; 1435 } 1436 case SEND_PENDING_BROADCAST: { 1437 String packages[]; 1438 ArrayList<String> components[]; 1439 int size = 0; 1440 int uids[]; 1441 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1442 synchronized (mPackages) { 1443 if (mPendingBroadcasts == null) { 1444 return; 1445 } 1446 size = mPendingBroadcasts.size(); 1447 if (size <= 0) { 1448 // Nothing to be done. Just return 1449 return; 1450 } 1451 packages = new String[size]; 1452 components = new ArrayList[size]; 1453 uids = new int[size]; 1454 int i = 0; // filling out the above arrays 1455 1456 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1457 int packageUserId = mPendingBroadcasts.userIdAt(n); 1458 Iterator<Map.Entry<String, ArrayList<String>>> it 1459 = mPendingBroadcasts.packagesForUserId(packageUserId) 1460 .entrySet().iterator(); 1461 while (it.hasNext() && i < size) { 1462 Map.Entry<String, ArrayList<String>> ent = it.next(); 1463 packages[i] = ent.getKey(); 1464 components[i] = ent.getValue(); 1465 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1466 uids[i] = (ps != null) 1467 ? UserHandle.getUid(packageUserId, ps.appId) 1468 : -1; 1469 i++; 1470 } 1471 } 1472 size = i; 1473 mPendingBroadcasts.clear(); 1474 } 1475 // Send broadcasts 1476 for (int i = 0; i < size; i++) { 1477 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1478 } 1479 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1480 break; 1481 } 1482 case START_CLEANING_PACKAGE: { 1483 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1484 final String packageName = (String)msg.obj; 1485 final int userId = msg.arg1; 1486 final boolean andCode = msg.arg2 != 0; 1487 synchronized (mPackages) { 1488 if (userId == UserHandle.USER_ALL) { 1489 int[] users = sUserManager.getUserIds(); 1490 for (int user : users) { 1491 mSettings.addPackageToCleanLPw( 1492 new PackageCleanItem(user, packageName, andCode)); 1493 } 1494 } else { 1495 mSettings.addPackageToCleanLPw( 1496 new PackageCleanItem(userId, packageName, andCode)); 1497 } 1498 } 1499 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1500 startCleaningPackages(); 1501 } break; 1502 case POST_INSTALL: { 1503 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1504 1505 PostInstallData data = mRunningInstalls.get(msg.arg1); 1506 final boolean didRestore = (msg.arg2 != 0); 1507 mRunningInstalls.delete(msg.arg1); 1508 1509 if (data != null) { 1510 InstallArgs args = data.args; 1511 PackageInstalledInfo parentRes = data.res; 1512 1513 final boolean grantPermissions = (args.installFlags 1514 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1515 final boolean killApp = (args.installFlags 1516 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1517 final String[] grantedPermissions = args.installGrantPermissions; 1518 1519 // Handle the parent package 1520 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1521 grantedPermissions, didRestore, args.installerPackageName, 1522 args.observer); 1523 1524 // Handle the child packages 1525 final int childCount = (parentRes.addedChildPackages != null) 1526 ? parentRes.addedChildPackages.size() : 0; 1527 for (int i = 0; i < childCount; i++) { 1528 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1529 handlePackagePostInstall(childRes, grantPermissions, killApp, 1530 grantedPermissions, false, args.installerPackageName, 1531 args.observer); 1532 } 1533 1534 // Log tracing if needed 1535 if (args.traceMethod != null) { 1536 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1537 args.traceCookie); 1538 } 1539 } else { 1540 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1541 } 1542 1543 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1544 } break; 1545 case UPDATED_MEDIA_STATUS: { 1546 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1547 boolean reportStatus = msg.arg1 == 1; 1548 boolean doGc = msg.arg2 == 1; 1549 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1550 if (doGc) { 1551 // Force a gc to clear up stale containers. 1552 Runtime.getRuntime().gc(); 1553 } 1554 if (msg.obj != null) { 1555 @SuppressWarnings("unchecked") 1556 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1557 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1558 // Unload containers 1559 unloadAllContainers(args); 1560 } 1561 if (reportStatus) { 1562 try { 1563 if (DEBUG_SD_INSTALL) Log.i(TAG, 1564 "Invoking StorageManagerService call back"); 1565 PackageHelper.getStorageManager().finishMediaUpdate(); 1566 } catch (RemoteException e) { 1567 Log.e(TAG, "StorageManagerService not running?"); 1568 } 1569 } 1570 } break; 1571 case WRITE_SETTINGS: { 1572 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1573 synchronized (mPackages) { 1574 removeMessages(WRITE_SETTINGS); 1575 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1576 mSettings.writeLPr(); 1577 mDirtyUsers.clear(); 1578 } 1579 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1580 } break; 1581 case WRITE_PACKAGE_RESTRICTIONS: { 1582 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1583 synchronized (mPackages) { 1584 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1585 for (int userId : mDirtyUsers) { 1586 mSettings.writePackageRestrictionsLPr(userId); 1587 } 1588 mDirtyUsers.clear(); 1589 } 1590 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1591 } break; 1592 case WRITE_PACKAGE_LIST: { 1593 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1594 synchronized (mPackages) { 1595 removeMessages(WRITE_PACKAGE_LIST); 1596 mSettings.writePackageListLPr(msg.arg1); 1597 } 1598 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1599 } break; 1600 case CHECK_PENDING_VERIFICATION: { 1601 final int verificationId = msg.arg1; 1602 final PackageVerificationState state = mPendingVerification.get(verificationId); 1603 1604 if ((state != null) && !state.timeoutExtended()) { 1605 final InstallArgs args = state.getInstallArgs(); 1606 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1607 1608 Slog.i(TAG, "Verification timed out for " + originUri); 1609 mPendingVerification.remove(verificationId); 1610 1611 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1612 1613 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1614 Slog.i(TAG, "Continuing with installation of " + originUri); 1615 state.setVerifierResponse(Binder.getCallingUid(), 1616 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1617 broadcastPackageVerified(verificationId, originUri, 1618 PackageManager.VERIFICATION_ALLOW, 1619 state.getInstallArgs().getUser()); 1620 try { 1621 ret = args.copyApk(mContainerService, true); 1622 } catch (RemoteException e) { 1623 Slog.e(TAG, "Could not contact the ContainerService"); 1624 } 1625 } else { 1626 broadcastPackageVerified(verificationId, originUri, 1627 PackageManager.VERIFICATION_REJECT, 1628 state.getInstallArgs().getUser()); 1629 } 1630 1631 Trace.asyncTraceEnd( 1632 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1633 1634 processPendingInstall(args, ret); 1635 mHandler.sendEmptyMessage(MCS_UNBIND); 1636 } 1637 break; 1638 } 1639 case PACKAGE_VERIFIED: { 1640 final int verificationId = msg.arg1; 1641 1642 final PackageVerificationState state = mPendingVerification.get(verificationId); 1643 if (state == null) { 1644 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1645 break; 1646 } 1647 1648 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1649 1650 state.setVerifierResponse(response.callerUid, response.code); 1651 1652 if (state.isVerificationComplete()) { 1653 mPendingVerification.remove(verificationId); 1654 1655 final InstallArgs args = state.getInstallArgs(); 1656 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1657 1658 int ret; 1659 if (state.isInstallAllowed()) { 1660 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1661 broadcastPackageVerified(verificationId, originUri, 1662 response.code, state.getInstallArgs().getUser()); 1663 try { 1664 ret = args.copyApk(mContainerService, true); 1665 } catch (RemoteException e) { 1666 Slog.e(TAG, "Could not contact the ContainerService"); 1667 } 1668 } else { 1669 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1670 } 1671 1672 Trace.asyncTraceEnd( 1673 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1674 1675 processPendingInstall(args, ret); 1676 mHandler.sendEmptyMessage(MCS_UNBIND); 1677 } 1678 1679 break; 1680 } 1681 case START_INTENT_FILTER_VERIFICATIONS: { 1682 IFVerificationParams params = (IFVerificationParams) msg.obj; 1683 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1684 params.replacing, params.pkg); 1685 break; 1686 } 1687 case INTENT_FILTER_VERIFIED: { 1688 final int verificationId = msg.arg1; 1689 1690 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1691 verificationId); 1692 if (state == null) { 1693 Slog.w(TAG, "Invalid IntentFilter verification token " 1694 + verificationId + " received"); 1695 break; 1696 } 1697 1698 final int userId = state.getUserId(); 1699 1700 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1701 "Processing IntentFilter verification with token:" 1702 + verificationId + " and userId:" + userId); 1703 1704 final IntentFilterVerificationResponse response = 1705 (IntentFilterVerificationResponse) msg.obj; 1706 1707 state.setVerifierResponse(response.callerUid, response.code); 1708 1709 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1710 "IntentFilter verification with token:" + verificationId 1711 + " and userId:" + userId 1712 + " is settings verifier response with response code:" 1713 + response.code); 1714 1715 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1716 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1717 + response.getFailedDomainsString()); 1718 } 1719 1720 if (state.isVerificationComplete()) { 1721 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1722 } else { 1723 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1724 "IntentFilter verification with token:" + verificationId 1725 + " was not said to be complete"); 1726 } 1727 1728 break; 1729 } 1730 case EPHEMERAL_RESOLUTION_PHASE_TWO: { 1731 EphemeralResolver.doEphemeralResolutionPhaseTwo(mContext, 1732 mEphemeralResolverConnection, 1733 (EphemeralRequest) msg.obj, 1734 mEphemeralInstallerActivity, 1735 mHandler); 1736 } 1737 } 1738 } 1739 } 1740 1741 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1742 boolean killApp, String[] grantedPermissions, 1743 boolean launchedForRestore, String installerPackage, 1744 IPackageInstallObserver2 installObserver) { 1745 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1746 // Send the removed broadcasts 1747 if (res.removedInfo != null) { 1748 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1749 } 1750 1751 // Now that we successfully installed the package, grant runtime 1752 // permissions if requested before broadcasting the install. Also 1753 // for legacy apps in permission review mode we clear the permission 1754 // review flag which is used to emulate runtime permissions for 1755 // legacy apps. 1756 if (grantPermissions) { 1757 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1758 } 1759 1760 final boolean update = res.removedInfo != null 1761 && res.removedInfo.removedPackage != null; 1762 1763 // If this is the first time we have child packages for a disabled privileged 1764 // app that had no children, we grant requested runtime permissions to the new 1765 // children if the parent on the system image had them already granted. 1766 if (res.pkg.parentPackage != null) { 1767 synchronized (mPackages) { 1768 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1769 } 1770 } 1771 1772 synchronized (mPackages) { 1773 mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers); 1774 } 1775 1776 final String packageName = res.pkg.applicationInfo.packageName; 1777 1778 // Determine the set of users who are adding this package for 1779 // the first time vs. those who are seeing an update. 1780 int[] firstUsers = EMPTY_INT_ARRAY; 1781 int[] updateUsers = EMPTY_INT_ARRAY; 1782 if (res.origUsers == null || res.origUsers.length == 0) { 1783 firstUsers = res.newUsers; 1784 } else { 1785 for (int newUser : res.newUsers) { 1786 boolean isNew = true; 1787 for (int origUser : res.origUsers) { 1788 if (origUser == newUser) { 1789 isNew = false; 1790 break; 1791 } 1792 } 1793 if (isNew) { 1794 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1795 } else { 1796 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1797 } 1798 } 1799 } 1800 1801 // Send installed broadcasts if the install/update is not ephemeral 1802 // and the package is not a static shared lib. 1803 if (!isEphemeral(res.pkg) && res.pkg.staticSharedLibName == null) { 1804 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1805 1806 // Send added for users that see the package for the first time 1807 // sendPackageAddedForNewUsers also deals with system apps 1808 int appId = UserHandle.getAppId(res.uid); 1809 boolean isSystem = res.pkg.applicationInfo.isSystemApp(); 1810 sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers); 1811 1812 // Send added for users that don't see the package for the first time 1813 Bundle extras = new Bundle(1); 1814 extras.putInt(Intent.EXTRA_UID, res.uid); 1815 if (update) { 1816 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1817 } 1818 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1819 extras, 0 /*flags*/, null /*targetPackage*/, 1820 null /*finishedReceiver*/, updateUsers); 1821 1822 // Send replaced for users that don't see the package for the first time 1823 if (update) { 1824 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1825 packageName, extras, 0 /*flags*/, 1826 null /*targetPackage*/, null /*finishedReceiver*/, 1827 updateUsers); 1828 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1829 null /*package*/, null /*extras*/, 0 /*flags*/, 1830 packageName /*targetPackage*/, 1831 null /*finishedReceiver*/, updateUsers); 1832 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 1833 // First-install and we did a restore, so we're responsible for the 1834 // first-launch broadcast. 1835 if (DEBUG_BACKUP) { 1836 Slog.i(TAG, "Post-restore of " + packageName 1837 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers)); 1838 } 1839 sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers); 1840 } 1841 1842 // Send broadcast package appeared if forward locked/external for all users 1843 // treat asec-hosted packages like removable media on upgrade 1844 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1845 if (DEBUG_INSTALL) { 1846 Slog.i(TAG, "upgrading pkg " + res.pkg 1847 + " is ASEC-hosted -> AVAILABLE"); 1848 } 1849 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1850 ArrayList<String> pkgList = new ArrayList<>(1); 1851 pkgList.add(packageName); 1852 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1853 } 1854 } 1855 1856 // Work that needs to happen on first install within each user 1857 if (firstUsers != null && firstUsers.length > 0) { 1858 synchronized (mPackages) { 1859 for (int userId : firstUsers) { 1860 // If this app is a browser and it's newly-installed for some 1861 // users, clear any default-browser state in those users. The 1862 // app's nature doesn't depend on the user, so we can just check 1863 // its browser nature in any user and generalize. 1864 if (packageIsBrowser(packageName, userId)) { 1865 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1866 } 1867 1868 // We may also need to apply pending (restored) runtime 1869 // permission grants within these users. 1870 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1871 } 1872 } 1873 } 1874 1875 // Log current value of "unknown sources" setting 1876 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1877 getUnknownSourcesSettings()); 1878 1879 // Force a gc to clear up things 1880 Runtime.getRuntime().gc(); 1881 1882 // Remove the replaced package's older resources safely now 1883 // We delete after a gc for applications on sdcard. 1884 if (res.removedInfo != null && res.removedInfo.args != null) { 1885 synchronized (mInstallLock) { 1886 res.removedInfo.args.doPostDeleteLI(true); 1887 } 1888 } 1889 1890 if (!isEphemeral(res.pkg)) { 1891 // Notify DexManager that the package was installed for new users. 1892 // The updated users should already be indexed and the package code paths 1893 // should not change. 1894 // Don't notify the manager for ephemeral apps as they are not expected to 1895 // survive long enough to benefit of background optimizations. 1896 for (int userId : firstUsers) { 1897 PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId); 1898 mDexManager.notifyPackageInstalled(info, userId); 1899 } 1900 } 1901 } 1902 1903 // If someone is watching installs - notify them 1904 if (installObserver != null) { 1905 try { 1906 Bundle extras = extrasForInstallResult(res); 1907 installObserver.onPackageInstalled(res.name, res.returnCode, 1908 res.returnMsg, extras); 1909 } catch (RemoteException e) { 1910 Slog.i(TAG, "Observer no longer exists."); 1911 } 1912 } 1913 } 1914 1915 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1916 PackageParser.Package pkg) { 1917 if (pkg.parentPackage == null) { 1918 return; 1919 } 1920 if (pkg.requestedPermissions == null) { 1921 return; 1922 } 1923 final PackageSetting disabledSysParentPs = mSettings 1924 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1925 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1926 || !disabledSysParentPs.isPrivileged() 1927 || (disabledSysParentPs.childPackageNames != null 1928 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1929 return; 1930 } 1931 final int[] allUserIds = sUserManager.getUserIds(); 1932 final int permCount = pkg.requestedPermissions.size(); 1933 for (int i = 0; i < permCount; i++) { 1934 String permission = pkg.requestedPermissions.get(i); 1935 BasePermission bp = mSettings.mPermissions.get(permission); 1936 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1937 continue; 1938 } 1939 for (int userId : allUserIds) { 1940 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1941 permission, userId)) { 1942 grantRuntimePermission(pkg.packageName, permission, userId); 1943 } 1944 } 1945 } 1946 } 1947 1948 private StorageEventListener mStorageListener = new StorageEventListener() { 1949 @Override 1950 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1951 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1952 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1953 final String volumeUuid = vol.getFsUuid(); 1954 1955 // Clean up any users or apps that were removed or recreated 1956 // while this volume was missing 1957 sUserManager.reconcileUsers(volumeUuid); 1958 reconcileApps(volumeUuid); 1959 1960 // Clean up any install sessions that expired or were 1961 // cancelled while this volume was missing 1962 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1963 1964 loadPrivatePackages(vol); 1965 1966 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1967 unloadPrivatePackages(vol); 1968 } 1969 } 1970 1971 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1972 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1973 updateExternalMediaStatus(true, false); 1974 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1975 updateExternalMediaStatus(false, false); 1976 } 1977 } 1978 } 1979 1980 @Override 1981 public void onVolumeForgotten(String fsUuid) { 1982 if (TextUtils.isEmpty(fsUuid)) { 1983 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1984 return; 1985 } 1986 1987 // Remove any apps installed on the forgotten volume 1988 synchronized (mPackages) { 1989 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1990 for (PackageSetting ps : packages) { 1991 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1992 deletePackageVersioned(new VersionedPackage(ps.name, 1993 PackageManager.VERSION_CODE_HIGHEST), 1994 new LegacyPackageDeleteObserver(null).getBinder(), 1995 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 1996 // Try very hard to release any references to this package 1997 // so we don't risk the system server being killed due to 1998 // open FDs 1999 AttributeCache.instance().removePackage(ps.name); 2000 } 2001 2002 mSettings.onVolumeForgotten(fsUuid); 2003 mSettings.writeLPr(); 2004 } 2005 } 2006 }; 2007 2008 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 2009 String[] grantedPermissions) { 2010 for (int userId : userIds) { 2011 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 2012 } 2013 } 2014 2015 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 2016 String[] grantedPermissions) { 2017 SettingBase sb = (SettingBase) pkg.mExtras; 2018 if (sb == null) { 2019 return; 2020 } 2021 2022 PermissionsState permissionsState = sb.getPermissionsState(); 2023 2024 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 2025 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 2026 2027 final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 2028 >= Build.VERSION_CODES.M; 2029 2030 for (String permission : pkg.requestedPermissions) { 2031 final BasePermission bp; 2032 synchronized (mPackages) { 2033 bp = mSettings.mPermissions.get(permission); 2034 } 2035 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 2036 && (grantedPermissions == null 2037 || ArrayUtils.contains(grantedPermissions, permission))) { 2038 final int flags = permissionsState.getPermissionFlags(permission, userId); 2039 if (supportsRuntimePermissions) { 2040 // Installer cannot change immutable permissions. 2041 if ((flags & immutableFlags) == 0) { 2042 grantRuntimePermission(pkg.packageName, permission, userId); 2043 } 2044 } else if (mPermissionReviewRequired) { 2045 // In permission review mode we clear the review flag when we 2046 // are asked to install the app with all permissions granted. 2047 if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 2048 updatePermissionFlags(permission, pkg.packageName, 2049 PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId); 2050 } 2051 } 2052 } 2053 } 2054 } 2055 2056 Bundle extrasForInstallResult(PackageInstalledInfo res) { 2057 Bundle extras = null; 2058 switch (res.returnCode) { 2059 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 2060 extras = new Bundle(); 2061 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 2062 res.origPermission); 2063 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 2064 res.origPackage); 2065 break; 2066 } 2067 case PackageManager.INSTALL_SUCCEEDED: { 2068 extras = new Bundle(); 2069 extras.putBoolean(Intent.EXTRA_REPLACING, 2070 res.removedInfo != null && res.removedInfo.removedPackage != null); 2071 break; 2072 } 2073 } 2074 return extras; 2075 } 2076 2077 void scheduleWriteSettingsLocked() { 2078 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2079 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2080 } 2081 } 2082 2083 void scheduleWritePackageListLocked(int userId) { 2084 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) { 2085 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST); 2086 msg.arg1 = userId; 2087 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY); 2088 } 2089 } 2090 2091 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2092 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2093 scheduleWritePackageRestrictionsLocked(userId); 2094 } 2095 2096 void scheduleWritePackageRestrictionsLocked(int userId) { 2097 final int[] userIds = (userId == UserHandle.USER_ALL) 2098 ? sUserManager.getUserIds() : new int[]{userId}; 2099 for (int nextUserId : userIds) { 2100 if (!sUserManager.exists(nextUserId)) return; 2101 mDirtyUsers.add(nextUserId); 2102 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2103 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2104 } 2105 } 2106 } 2107 2108 public static PackageManagerService main(Context context, Installer installer, 2109 boolean factoryTest, boolean onlyCore) { 2110 // Self-check for initial settings. 2111 PackageManagerServiceCompilerMapping.checkProperties(); 2112 2113 PackageManagerService m = new PackageManagerService(context, installer, 2114 factoryTest, onlyCore); 2115 m.enableSystemUserPackages(); 2116 ServiceManager.addService("package", m); 2117 return m; 2118 } 2119 2120 private void enableSystemUserPackages() { 2121 if (!UserManager.isSplitSystemUser()) { 2122 return; 2123 } 2124 // For system user, enable apps based on the following conditions: 2125 // - app is whitelisted or belong to one of these groups: 2126 // -- system app which has no launcher icons 2127 // -- system app which has INTERACT_ACROSS_USERS permission 2128 // -- system IME app 2129 // - app is not in the blacklist 2130 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2131 Set<String> enableApps = new ArraySet<>(); 2132 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2133 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2134 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2135 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2136 enableApps.addAll(wlApps); 2137 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2138 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2139 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2140 enableApps.removeAll(blApps); 2141 Log.i(TAG, "Applications installed for system user: " + enableApps); 2142 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2143 UserHandle.SYSTEM); 2144 final int allAppsSize = allAps.size(); 2145 synchronized (mPackages) { 2146 for (int i = 0; i < allAppsSize; i++) { 2147 String pName = allAps.get(i); 2148 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2149 // Should not happen, but we shouldn't be failing if it does 2150 if (pkgSetting == null) { 2151 continue; 2152 } 2153 boolean install = enableApps.contains(pName); 2154 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2155 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2156 + " for system user"); 2157 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2158 } 2159 } 2160 scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM); 2161 } 2162 } 2163 2164 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2165 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2166 Context.DISPLAY_SERVICE); 2167 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2168 } 2169 2170 /** 2171 * Requests that files preopted on a secondary system partition be copied to the data partition 2172 * if possible. Note that the actual copying of the files is accomplished by init for security 2173 * reasons. This simply requests that the copy takes place and awaits confirmation of its 2174 * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy. 2175 */ 2176 private static void requestCopyPreoptedFiles() { 2177 final int WAIT_TIME_MS = 100; 2178 final String CP_PREOPT_PROPERTY = "sys.cppreopt"; 2179 if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) { 2180 SystemProperties.set(CP_PREOPT_PROPERTY, "requested"); 2181 // We will wait for up to 100 seconds. 2182 final long timeStart = SystemClock.uptimeMillis(); 2183 final long timeEnd = timeStart + 100 * 1000; 2184 long timeNow = timeStart; 2185 while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) { 2186 try { 2187 Thread.sleep(WAIT_TIME_MS); 2188 } catch (InterruptedException e) { 2189 // Do nothing 2190 } 2191 timeNow = SystemClock.uptimeMillis(); 2192 if (timeNow > timeEnd) { 2193 SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out"); 2194 Slog.wtf(TAG, "cppreopt did not finish!"); 2195 break; 2196 } 2197 } 2198 2199 Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms"); 2200 } 2201 } 2202 2203 public PackageManagerService(Context context, Installer installer, 2204 boolean factoryTest, boolean onlyCore) { 2205 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager"); 2206 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2207 SystemClock.uptimeMillis()); 2208 2209 if (mSdkVersion <= 0) { 2210 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2211 } 2212 2213 mContext = context; 2214 2215 mPermissionReviewRequired = context.getResources().getBoolean( 2216 R.bool.config_permissionReviewRequired); 2217 2218 mFactoryTest = factoryTest; 2219 mOnlyCore = onlyCore; 2220 mMetrics = new DisplayMetrics(); 2221 mSettings = new Settings(mPackages); 2222 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2223 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2224 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2225 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2226 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2227 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2228 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2229 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2230 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2231 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2232 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2233 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2234 2235 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2236 if (separateProcesses != null && separateProcesses.length() > 0) { 2237 if ("*".equals(separateProcesses)) { 2238 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2239 mSeparateProcesses = null; 2240 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2241 } else { 2242 mDefParseFlags = 0; 2243 mSeparateProcesses = separateProcesses.split(","); 2244 Slog.w(TAG, "Running with debug.separate_processes: " 2245 + separateProcesses); 2246 } 2247 } else { 2248 mDefParseFlags = 0; 2249 mSeparateProcesses = null; 2250 } 2251 2252 mInstaller = installer; 2253 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2254 "*dexopt*"); 2255 mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock); 2256 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2257 2258 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2259 FgThread.get().getLooper()); 2260 2261 getDefaultDisplayMetrics(context, mMetrics); 2262 2263 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config"); 2264 SystemConfig systemConfig = SystemConfig.getInstance(); 2265 mGlobalGids = systemConfig.getGlobalGids(); 2266 mSystemPermissions = systemConfig.getSystemPermissions(); 2267 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2268 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2269 2270 mProtectedPackages = new ProtectedPackages(mContext); 2271 2272 synchronized (mInstallLock) { 2273 // writer 2274 synchronized (mPackages) { 2275 mHandlerThread = new ServiceThread(TAG, 2276 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2277 mHandlerThread.start(); 2278 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2279 mProcessLoggingHandler = new ProcessLoggingHandler(); 2280 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2281 2282 mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this); 2283 mInstantAppRegistry = new InstantAppRegistry(this); 2284 2285 File dataDir = Environment.getDataDirectory(); 2286 mAppInstallDir = new File(dataDir, "app"); 2287 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2288 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2289 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2290 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2291 sUserManager = new UserManagerService(context, this, 2292 new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages); 2293 2294 // Propagate permission configuration in to package manager. 2295 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2296 = systemConfig.getPermissions(); 2297 for (int i=0; i<permConfig.size(); i++) { 2298 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2299 BasePermission bp = mSettings.mPermissions.get(perm.name); 2300 if (bp == null) { 2301 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2302 mSettings.mPermissions.put(perm.name, bp); 2303 } 2304 if (perm.gids != null) { 2305 bp.setGids(perm.gids, perm.perUser); 2306 } 2307 } 2308 2309 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2310 final int builtInLibCount = libConfig.size(); 2311 for (int i = 0; i < builtInLibCount; i++) { 2312 String name = libConfig.keyAt(i); 2313 String path = libConfig.valueAt(i); 2314 addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED, 2315 SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0); 2316 } 2317 2318 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2319 2320 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings"); 2321 mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false)); 2322 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2323 2324 // Clean up orphaned packages for which the code path doesn't exist 2325 // and they are an update to a system app - caused by bug/32321269 2326 final int packageSettingCount = mSettings.mPackages.size(); 2327 for (int i = packageSettingCount - 1; i >= 0; i--) { 2328 PackageSetting ps = mSettings.mPackages.valueAt(i); 2329 if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists()) 2330 && mSettings.getDisabledSystemPkgLPr(ps.name) != null) { 2331 mSettings.mPackages.removeAt(i); 2332 mSettings.enableSystemPackageLPw(ps.name); 2333 } 2334 } 2335 2336 if (mFirstBoot) { 2337 requestCopyPreoptedFiles(); 2338 } 2339 2340 String customResolverActivity = Resources.getSystem().getString( 2341 R.string.config_customResolverActivity); 2342 if (TextUtils.isEmpty(customResolverActivity)) { 2343 customResolverActivity = null; 2344 } else { 2345 mCustomResolverComponentName = ComponentName.unflattenFromString( 2346 customResolverActivity); 2347 } 2348 2349 long startTime = SystemClock.uptimeMillis(); 2350 2351 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2352 startTime); 2353 2354 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2355 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2356 2357 if (bootClassPath == null) { 2358 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2359 } 2360 2361 if (systemServerClassPath == null) { 2362 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2363 } 2364 2365 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2366 final String[] dexCodeInstructionSets = 2367 getDexCodeInstructionSets( 2368 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2369 2370 /** 2371 * Ensure all external libraries have had dexopt run on them. 2372 */ 2373 if (mSharedLibraries.size() > 0) { 2374 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 2375 // NOTE: For now, we're compiling these system "shared libraries" 2376 // (and framework jars) into all available architectures. It's possible 2377 // to compile them only when we come across an app that uses them (there's 2378 // already logic for that in scanPackageLI) but that adds some complexity. 2379 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2380 final int libCount = mSharedLibraries.size(); 2381 for (int i = 0; i < libCount; i++) { 2382 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 2383 final int versionCount = versionedLib.size(); 2384 for (int j = 0; j < versionCount; j++) { 2385 SharedLibraryEntry libEntry = versionedLib.valueAt(j); 2386 final String libPath = libEntry.path != null 2387 ? libEntry.path : libEntry.apk; 2388 if (libPath == null) { 2389 continue; 2390 } 2391 try { 2392 // Shared libraries do not have profiles so we perform a full 2393 // AOT compilation (if needed). 2394 int dexoptNeeded = DexFile.getDexOptNeeded( 2395 libPath, dexCodeInstructionSet, 2396 getCompilerFilterForReason(REASON_SHARED_APK), 2397 false /* newProfile */); 2398 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2399 mInstaller.dexopt(libPath, Process.SYSTEM_UID, "*", 2400 dexCodeInstructionSet, dexoptNeeded, null, 2401 DEXOPT_PUBLIC, 2402 getCompilerFilterForReason(REASON_SHARED_APK), 2403 StorageManager.UUID_PRIVATE_INTERNAL, 2404 SKIP_SHARED_LIBRARY_CHECK); 2405 } 2406 } catch (FileNotFoundException e) { 2407 Slog.w(TAG, "Library not found: " + libPath); 2408 } catch (IOException | InstallerException e) { 2409 Slog.w(TAG, "Cannot dexopt " + libPath + "; is it an APK or JAR? " 2410 + e.getMessage()); 2411 } 2412 } 2413 } 2414 } 2415 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2416 } 2417 2418 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2419 2420 final VersionInfo ver = mSettings.getInternalVersion(); 2421 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2422 2423 // when upgrading from pre-M, promote system app permissions from install to runtime 2424 mPromoteSystemApps = 2425 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2426 2427 // When upgrading from pre-N, we need to handle package extraction like first boot, 2428 // as there is no profiling data available. 2429 mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N; 2430 2431 mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1; 2432 2433 // save off the names of pre-existing system packages prior to scanning; we don't 2434 // want to automatically grant runtime permissions for new system apps 2435 if (mPromoteSystemApps) { 2436 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2437 while (pkgSettingIter.hasNext()) { 2438 PackageSetting ps = pkgSettingIter.next(); 2439 if (isSystemApp(ps)) { 2440 mExistingSystemPackages.add(ps.name); 2441 } 2442 } 2443 } 2444 2445 mCacheDir = preparePackageParserCache(mIsUpgrade); 2446 2447 // Set flag to monitor and not change apk file paths when 2448 // scanning install directories. 2449 int scanFlags = SCAN_BOOTING | SCAN_INITIAL; 2450 2451 if (mIsUpgrade || mFirstBoot) { 2452 scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE; 2453 } 2454 2455 // Collect vendor overlay packages. (Do this before scanning any apps.) 2456 // For security and version matching reason, only consider 2457 // overlay packages if they reside in the right directory. 2458 String overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PERSIST_PROPERTY); 2459 if (overlayThemeDir.isEmpty()) { 2460 overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PROPERTY); 2461 } 2462 if (!overlayThemeDir.isEmpty()) { 2463 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR, overlayThemeDir), mDefParseFlags 2464 | PackageParser.PARSE_IS_SYSTEM 2465 | PackageParser.PARSE_IS_SYSTEM_DIR 2466 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2467 } 2468 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags 2469 | PackageParser.PARSE_IS_SYSTEM 2470 | PackageParser.PARSE_IS_SYSTEM_DIR 2471 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2472 2473 // Find base frameworks (resource packages without code). 2474 scanDirTracedLI(frameworkDir, mDefParseFlags 2475 | PackageParser.PARSE_IS_SYSTEM 2476 | PackageParser.PARSE_IS_SYSTEM_DIR 2477 | PackageParser.PARSE_IS_PRIVILEGED, 2478 scanFlags | SCAN_NO_DEX, 0); 2479 2480 // Collected privileged system packages. 2481 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2482 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2483 | PackageParser.PARSE_IS_SYSTEM 2484 | PackageParser.PARSE_IS_SYSTEM_DIR 2485 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2486 2487 // Collect ordinary system packages. 2488 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2489 scanDirTracedLI(systemAppDir, mDefParseFlags 2490 | PackageParser.PARSE_IS_SYSTEM 2491 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2492 2493 // Collect all vendor packages. 2494 File vendorAppDir = new File("/vendor/app"); 2495 try { 2496 vendorAppDir = vendorAppDir.getCanonicalFile(); 2497 } catch (IOException e) { 2498 // failed to look up canonical path, continue with original one 2499 } 2500 scanDirTracedLI(vendorAppDir, mDefParseFlags 2501 | PackageParser.PARSE_IS_SYSTEM 2502 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2503 2504 // Collect all OEM packages. 2505 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2506 scanDirTracedLI(oemAppDir, mDefParseFlags 2507 | PackageParser.PARSE_IS_SYSTEM 2508 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2509 2510 // Prune any system packages that no longer exist. 2511 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2512 if (!mOnlyCore) { 2513 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2514 while (psit.hasNext()) { 2515 PackageSetting ps = psit.next(); 2516 2517 /* 2518 * If this is not a system app, it can't be a 2519 * disable system app. 2520 */ 2521 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2522 continue; 2523 } 2524 2525 /* 2526 * If the package is scanned, it's not erased. 2527 */ 2528 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2529 if (scannedPkg != null) { 2530 /* 2531 * If the system app is both scanned and in the 2532 * disabled packages list, then it must have been 2533 * added via OTA. Remove it from the currently 2534 * scanned package so the previously user-installed 2535 * application can be scanned. 2536 */ 2537 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2538 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2539 + ps.name + "; removing system app. Last known codePath=" 2540 + ps.codePathString + ", installStatus=" + ps.installStatus 2541 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2542 + scannedPkg.mVersionCode); 2543 removePackageLI(scannedPkg, true); 2544 mExpectingBetter.put(ps.name, ps.codePath); 2545 } 2546 2547 continue; 2548 } 2549 2550 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2551 psit.remove(); 2552 logCriticalInfo(Log.WARN, "System package " + ps.name 2553 + " no longer exists; it's data will be wiped"); 2554 // Actual deletion of code and data will be handled by later 2555 // reconciliation step 2556 } else { 2557 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2558 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2559 possiblyDeletedUpdatedSystemApps.add(ps.name); 2560 } 2561 } 2562 } 2563 } 2564 2565 //look for any incomplete package installations 2566 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2567 for (int i = 0; i < deletePkgsList.size(); i++) { 2568 // Actual deletion of code and data will be handled by later 2569 // reconciliation step 2570 final String packageName = deletePkgsList.get(i).name; 2571 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2572 synchronized (mPackages) { 2573 mSettings.removePackageLPw(packageName); 2574 } 2575 } 2576 2577 //delete tmp files 2578 deleteTempPackageFiles(); 2579 2580 // Remove any shared userIDs that have no associated packages 2581 mSettings.pruneSharedUsersLPw(); 2582 2583 if (!mOnlyCore) { 2584 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2585 SystemClock.uptimeMillis()); 2586 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2587 2588 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2589 | PackageParser.PARSE_FORWARD_LOCK, 2590 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2591 2592 scanDirLI(mEphemeralInstallDir, mDefParseFlags 2593 | PackageParser.PARSE_IS_EPHEMERAL, 2594 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2595 2596 /** 2597 * Remove disable package settings for any updated system 2598 * apps that were removed via an OTA. If they're not a 2599 * previously-updated app, remove them completely. 2600 * Otherwise, just revoke their system-level permissions. 2601 */ 2602 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2603 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2604 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2605 2606 String msg; 2607 if (deletedPkg == null) { 2608 msg = "Updated system package " + deletedAppName 2609 + " no longer exists; it's data will be wiped"; 2610 // Actual deletion of code and data will be handled by later 2611 // reconciliation step 2612 } else { 2613 msg = "Updated system app + " + deletedAppName 2614 + " no longer present; removing system privileges for " 2615 + deletedAppName; 2616 2617 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2618 2619 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2620 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2621 } 2622 logCriticalInfo(Log.WARN, msg); 2623 } 2624 2625 /** 2626 * Make sure all system apps that we expected to appear on 2627 * the userdata partition actually showed up. If they never 2628 * appeared, crawl back and revive the system version. 2629 */ 2630 for (int i = 0; i < mExpectingBetter.size(); i++) { 2631 final String packageName = mExpectingBetter.keyAt(i); 2632 if (!mPackages.containsKey(packageName)) { 2633 final File scanFile = mExpectingBetter.valueAt(i); 2634 2635 logCriticalInfo(Log.WARN, "Expected better " + packageName 2636 + " but never showed up; reverting to system"); 2637 2638 int reparseFlags = mDefParseFlags; 2639 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2640 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2641 | PackageParser.PARSE_IS_SYSTEM_DIR 2642 | PackageParser.PARSE_IS_PRIVILEGED; 2643 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2644 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2645 | PackageParser.PARSE_IS_SYSTEM_DIR; 2646 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2647 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2648 | PackageParser.PARSE_IS_SYSTEM_DIR; 2649 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2650 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2651 | PackageParser.PARSE_IS_SYSTEM_DIR; 2652 } else { 2653 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2654 continue; 2655 } 2656 2657 mSettings.enableSystemPackageLPw(packageName); 2658 2659 try { 2660 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2661 } catch (PackageManagerException e) { 2662 Slog.e(TAG, "Failed to parse original system package: " 2663 + e.getMessage()); 2664 } 2665 } 2666 } 2667 } 2668 mExpectingBetter.clear(); 2669 2670 // Resolve the storage manager. 2671 mStorageManagerPackage = getStorageManagerPackageName(); 2672 2673 // Resolve protected action filters. Only the setup wizard is allowed to 2674 // have a high priority filter for these actions. 2675 mSetupWizardPackage = getSetupWizardPackageName(); 2676 if (mProtectedFilters.size() > 0) { 2677 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2678 Slog.i(TAG, "No setup wizard;" 2679 + " All protected intents capped to priority 0"); 2680 } 2681 for (ActivityIntentInfo filter : mProtectedFilters) { 2682 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2683 if (DEBUG_FILTERS) { 2684 Slog.i(TAG, "Found setup wizard;" 2685 + " allow priority " + filter.getPriority() + ";" 2686 + " package: " + filter.activity.info.packageName 2687 + " activity: " + filter.activity.className 2688 + " priority: " + filter.getPriority()); 2689 } 2690 // skip setup wizard; allow it to keep the high priority filter 2691 continue; 2692 } 2693 Slog.w(TAG, "Protected action; cap priority to 0;" 2694 + " package: " + filter.activity.info.packageName 2695 + " activity: " + filter.activity.className 2696 + " origPrio: " + filter.getPriority()); 2697 filter.setPriority(0); 2698 } 2699 } 2700 mDeferProtectedFilters = false; 2701 mProtectedFilters.clear(); 2702 2703 // Now that we know all of the shared libraries, update all clients to have 2704 // the correct library paths. 2705 updateAllSharedLibrariesLPw(null); 2706 2707 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2708 // NOTE: We ignore potential failures here during a system scan (like 2709 // the rest of the commands above) because there's precious little we 2710 // can do about it. A settings error is reported, though. 2711 adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/); 2712 } 2713 2714 // Now that we know all the packages we are keeping, 2715 // read and update their last usage times. 2716 mPackageUsage.read(mPackages); 2717 mCompilerStats.read(); 2718 2719 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2720 SystemClock.uptimeMillis()); 2721 Slog.i(TAG, "Time to scan packages: " 2722 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2723 + " seconds"); 2724 2725 // If the platform SDK has changed since the last time we booted, 2726 // we need to re-grant app permission to catch any new ones that 2727 // appear. This is really a hack, and means that apps can in some 2728 // cases get permissions that the user didn't initially explicitly 2729 // allow... it would be nice to have some better way to handle 2730 // this situation. 2731 int updateFlags = UPDATE_PERMISSIONS_ALL; 2732 if (ver.sdkVersion != mSdkVersion) { 2733 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2734 + mSdkVersion + "; regranting permissions for internal storage"); 2735 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2736 } 2737 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2738 ver.sdkVersion = mSdkVersion; 2739 2740 // If this is the first boot or an update from pre-M, and it is a normal 2741 // boot, then we need to initialize the default preferred apps across 2742 // all defined users. 2743 if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) { 2744 for (UserInfo user : sUserManager.getUsers(true)) { 2745 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2746 applyFactoryDefaultBrowserLPw(user.id); 2747 primeDomainVerificationsLPw(user.id); 2748 } 2749 } 2750 2751 // Prepare storage for system user really early during boot, 2752 // since core system apps like SettingsProvider and SystemUI 2753 // can't wait for user to start 2754 final int storageFlags; 2755 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2756 storageFlags = StorageManager.FLAG_STORAGE_DE; 2757 } else { 2758 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2759 } 2760 reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2761 storageFlags, true /* migrateAppData */); 2762 2763 // If this is first boot after an OTA, and a normal boot, then 2764 // we need to clear code cache directories. 2765 // Note that we do *not* clear the application profiles. These remain valid 2766 // across OTAs and are used to drive profile verification (post OTA) and 2767 // profile compilation (without waiting to collect a fresh set of profiles). 2768 if (mIsUpgrade && !onlyCore) { 2769 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2770 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2771 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2772 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2773 // No apps are running this early, so no need to freeze 2774 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2775 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2776 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2777 } 2778 } 2779 ver.fingerprint = Build.FINGERPRINT; 2780 } 2781 2782 checkDefaultBrowser(); 2783 2784 // clear only after permissions and other defaults have been updated 2785 mExistingSystemPackages.clear(); 2786 mPromoteSystemApps = false; 2787 2788 // All the changes are done during package scanning. 2789 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2790 2791 // can downgrade to reader 2792 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings"); 2793 mSettings.writeLPr(); 2794 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2795 2796 // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty 2797 // early on (before the package manager declares itself as early) because other 2798 // components in the system server might ask for package contexts for these apps. 2799 // 2800 // Note that "onlyCore" in this context means the system is encrypted or encrypting 2801 // (i.e, that the data partition is unavailable). 2802 if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) { 2803 long start = System.nanoTime(); 2804 List<PackageParser.Package> coreApps = new ArrayList<>(); 2805 for (PackageParser.Package pkg : mPackages.values()) { 2806 if (pkg.coreApp) { 2807 coreApps.add(pkg); 2808 } 2809 } 2810 2811 int[] stats = performDexOptUpgrade(coreApps, false, 2812 getCompilerFilterForReason(REASON_CORE_APP)); 2813 2814 final int elapsedTimeSeconds = 2815 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start); 2816 MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds); 2817 2818 if (DEBUG_DEXOPT) { 2819 Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" + 2820 stats[0] + ", " + stats[1] + ", " + stats[2] + ")"); 2821 } 2822 2823 2824 // TODO: Should we log these stats to tron too ? 2825 // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]); 2826 // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]); 2827 // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]); 2828 // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size()); 2829 } 2830 2831 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2832 SystemClock.uptimeMillis()); 2833 2834 if (!mOnlyCore) { 2835 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2836 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2837 mRequiredUninstallerPackage = getRequiredUninstallerLPr(); 2838 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2839 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2840 mIntentFilterVerifierComponent); 2841 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2842 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES, 2843 SharedLibraryInfo.VERSION_UNDEFINED); 2844 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2845 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED, 2846 SharedLibraryInfo.VERSION_UNDEFINED); 2847 } else { 2848 mRequiredVerifierPackage = null; 2849 mRequiredInstallerPackage = null; 2850 mRequiredUninstallerPackage = null; 2851 mIntentFilterVerifierComponent = null; 2852 mIntentFilterVerifier = null; 2853 mServicesSystemSharedLibraryPackageName = null; 2854 mSharedSystemSharedLibraryPackageName = null; 2855 } 2856 2857 mInstallerService = new PackageInstallerService(context, this); 2858 2859 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2860 if (ephemeralResolverComponent != null) { 2861 if (DEBUG_EPHEMERAL) { 2862 Slog.i(TAG, "Ephemeral resolver: " + ephemeralResolverComponent); 2863 } 2864 mEphemeralResolverConnection = 2865 new EphemeralResolverConnection(mContext, ephemeralResolverComponent); 2866 } else { 2867 mEphemeralResolverConnection = null; 2868 } 2869 mEphemeralInstallerComponent = getEphemeralInstallerLPr(); 2870 if (mEphemeralInstallerComponent != null) { 2871 if (DEBUG_EPHEMERAL) { 2872 Slog.i(TAG, "Ephemeral installer: " + mEphemeralInstallerComponent); 2873 } 2874 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2875 } 2876 2877 // Read and update the usage of dex files. 2878 // Do this at the end of PM init so that all the packages have their 2879 // data directory reconciled. 2880 // At this point we know the code paths of the packages, so we can validate 2881 // the disk file and build the internal cache. 2882 // The usage file is expected to be small so loading and verifying it 2883 // should take a fairly small time compare to the other activities (e.g. package 2884 // scanning). 2885 final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>(); 2886 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 2887 for (int userId : currentUserIds) { 2888 userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList()); 2889 } 2890 mDexManager.load(userPackages); 2891 } // synchronized (mPackages) 2892 } // synchronized (mInstallLock) 2893 2894 // Now after opening every single application zip, make sure they 2895 // are all flushed. Not really needed, but keeps things nice and 2896 // tidy. 2897 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC"); 2898 Runtime.getRuntime().gc(); 2899 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2900 2901 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks"); 2902 FallbackCategoryProvider.loadFallbacks(); 2903 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2904 2905 // The initial scanning above does many calls into installd while 2906 // holding the mPackages lock, but we're mostly interested in yelling 2907 // once we have a booted system. 2908 mInstaller.setWarnIfHeld(mPackages); 2909 2910 // Expose private service for system components to use. 2911 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2912 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2913 } 2914 2915 private static File preparePackageParserCache(boolean isUpgrade) { 2916 if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) { 2917 return null; 2918 } 2919 2920 // Disable package parsing on eng builds to allow for faster incremental development. 2921 if ("eng".equals(Build.TYPE)) { 2922 return null; 2923 } 2924 2925 if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) { 2926 Slog.i(TAG, "Disabling package parser cache due to system property."); 2927 return null; 2928 } 2929 2930 // The base directory for the package parser cache lives under /data/system/. 2931 final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(), 2932 "package_cache"); 2933 if (cacheBaseDir == null) { 2934 return null; 2935 } 2936 2937 // If this is a system upgrade scenario, delete the contents of the package cache dir. 2938 // This also serves to "GC" unused entries when the package cache version changes (which 2939 // can only happen during upgrades). 2940 if (isUpgrade) { 2941 FileUtils.deleteContents(cacheBaseDir); 2942 } 2943 2944 2945 // Return the versioned package cache directory. This is something like 2946 // "/data/system/package_cache/1" 2947 File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION); 2948 2949 // The following is a workaround to aid development on non-numbered userdebug 2950 // builds or cases where "adb sync" is used on userdebug builds. If we detect that 2951 // the system partition is newer. 2952 // 2953 // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build 2954 // that starts with "eng." to signify that this is an engineering build and not 2955 // destined for release. 2956 if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) { 2957 Slog.w(TAG, "Wiping cache directory because the system partition changed."); 2958 2959 // Heuristic: If the /system directory has been modified recently due to an "adb sync" 2960 // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable 2961 // in general and should not be used for production changes. In this specific case, 2962 // we know that they will work. 2963 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2964 if (cacheDir.lastModified() < frameworkDir.lastModified()) { 2965 FileUtils.deleteContents(cacheBaseDir); 2966 cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION); 2967 } 2968 } 2969 2970 return cacheDir; 2971 } 2972 2973 @Override 2974 public boolean isFirstBoot() { 2975 return mFirstBoot; 2976 } 2977 2978 @Override 2979 public boolean isOnlyCoreApps() { 2980 return mOnlyCore; 2981 } 2982 2983 @Override 2984 public boolean isUpgrade() { 2985 return mIsUpgrade; 2986 } 2987 2988 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2989 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2990 2991 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2992 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2993 UserHandle.USER_SYSTEM); 2994 if (matches.size() == 1) { 2995 return matches.get(0).getComponentInfo().packageName; 2996 } else if (matches.size() == 0) { 2997 Log.e(TAG, "There should probably be a verifier, but, none were found"); 2998 return null; 2999 } 3000 throw new RuntimeException("There must be exactly one verifier; found " + matches); 3001 } 3002 3003 private @NonNull String getRequiredSharedLibraryLPr(String name, int version) { 3004 synchronized (mPackages) { 3005 SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version); 3006 if (libraryEntry == null) { 3007 throw new IllegalStateException("Missing required shared library:" + name); 3008 } 3009 return libraryEntry.apk; 3010 } 3011 } 3012 3013 private @NonNull String getRequiredInstallerLPr() { 3014 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 3015 intent.addCategory(Intent.CATEGORY_DEFAULT); 3016 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 3017 3018 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3019 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3020 UserHandle.USER_SYSTEM); 3021 if (matches.size() == 1) { 3022 ResolveInfo resolveInfo = matches.get(0); 3023 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 3024 throw new RuntimeException("The installer must be a privileged app"); 3025 } 3026 return matches.get(0).getComponentInfo().packageName; 3027 } else { 3028 throw new RuntimeException("There must be exactly one installer; found " + matches); 3029 } 3030 } 3031 3032 private @NonNull String getRequiredUninstallerLPr() { 3033 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 3034 intent.addCategory(Intent.CATEGORY_DEFAULT); 3035 intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null)); 3036 3037 final ResolveInfo resolveInfo = resolveIntent(intent, null, 3038 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3039 UserHandle.USER_SYSTEM); 3040 if (resolveInfo == null || 3041 mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) { 3042 throw new RuntimeException("There must be exactly one uninstaller; found " 3043 + resolveInfo); 3044 } 3045 return resolveInfo.getComponentInfo().packageName; 3046 } 3047 3048 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 3049 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 3050 3051 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 3052 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3053 UserHandle.USER_SYSTEM); 3054 ResolveInfo best = null; 3055 final int N = matches.size(); 3056 for (int i = 0; i < N; i++) { 3057 final ResolveInfo cur = matches.get(i); 3058 final String packageName = cur.getComponentInfo().packageName; 3059 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 3060 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 3061 continue; 3062 } 3063 3064 if (best == null || cur.priority > best.priority) { 3065 best = cur; 3066 } 3067 } 3068 3069 if (best != null) { 3070 return best.getComponentInfo().getComponentName(); 3071 } else { 3072 throw new RuntimeException("There must be at least one intent filter verifier"); 3073 } 3074 } 3075 3076 private @Nullable ComponentName getEphemeralResolverLPr() { 3077 final String[] packageArray = 3078 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 3079 if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) { 3080 if (DEBUG_EPHEMERAL) { 3081 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 3082 } 3083 return null; 3084 } 3085 3086 final int resolveFlags = 3087 MATCH_DIRECT_BOOT_AWARE 3088 | MATCH_DIRECT_BOOT_UNAWARE 3089 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3090 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 3091 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 3092 resolveFlags, UserHandle.USER_SYSTEM); 3093 3094 final int N = resolvers.size(); 3095 if (N == 0) { 3096 if (DEBUG_EPHEMERAL) { 3097 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 3098 } 3099 return null; 3100 } 3101 3102 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 3103 for (int i = 0; i < N; i++) { 3104 final ResolveInfo info = resolvers.get(i); 3105 3106 if (info.serviceInfo == null) { 3107 continue; 3108 } 3109 3110 final String packageName = info.serviceInfo.packageName; 3111 if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) { 3112 if (DEBUG_EPHEMERAL) { 3113 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 3114 + " pkg: " + packageName + ", info:" + info); 3115 } 3116 continue; 3117 } 3118 3119 if (DEBUG_EPHEMERAL) { 3120 Slog.v(TAG, "Ephemeral resolver found;" 3121 + " pkg: " + packageName + ", info:" + info); 3122 } 3123 return new ComponentName(packageName, info.serviceInfo.name); 3124 } 3125 if (DEBUG_EPHEMERAL) { 3126 Slog.v(TAG, "Ephemeral resolver NOT found"); 3127 } 3128 return null; 3129 } 3130 3131 private @Nullable ComponentName getEphemeralInstallerLPr() { 3132 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 3133 intent.addCategory(Intent.CATEGORY_DEFAULT); 3134 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 3135 3136 final int resolveFlags = 3137 MATCH_DIRECT_BOOT_AWARE 3138 | MATCH_DIRECT_BOOT_UNAWARE 3139 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3140 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3141 resolveFlags, UserHandle.USER_SYSTEM); 3142 Iterator<ResolveInfo> iter = matches.iterator(); 3143 while (iter.hasNext()) { 3144 final ResolveInfo rInfo = iter.next(); 3145 final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName); 3146 if (ps != null) { 3147 final PermissionsState permissionsState = ps.getPermissionsState(); 3148 if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) { 3149 continue; 3150 } 3151 } 3152 iter.remove(); 3153 } 3154 if (matches.size() == 0) { 3155 return null; 3156 } else if (matches.size() == 1) { 3157 return matches.get(0).getComponentInfo().getComponentName(); 3158 } else { 3159 throw new RuntimeException( 3160 "There must be at most one ephemeral installer; found " + matches); 3161 } 3162 } 3163 3164 private void primeDomainVerificationsLPw(int userId) { 3165 if (DEBUG_DOMAIN_VERIFICATION) { 3166 Slog.d(TAG, "Priming domain verifications in user " + userId); 3167 } 3168 3169 SystemConfig systemConfig = SystemConfig.getInstance(); 3170 ArraySet<String> packages = systemConfig.getLinkedApps(); 3171 3172 for (String packageName : packages) { 3173 PackageParser.Package pkg = mPackages.get(packageName); 3174 if (pkg != null) { 3175 if (!pkg.isSystemApp()) { 3176 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 3177 continue; 3178 } 3179 3180 ArraySet<String> domains = null; 3181 for (PackageParser.Activity a : pkg.activities) { 3182 for (ActivityIntentInfo filter : a.intents) { 3183 if (hasValidDomains(filter)) { 3184 if (domains == null) { 3185 domains = new ArraySet<String>(); 3186 } 3187 domains.addAll(filter.getHostsList()); 3188 } 3189 } 3190 } 3191 3192 if (domains != null && domains.size() > 0) { 3193 if (DEBUG_DOMAIN_VERIFICATION) { 3194 Slog.v(TAG, " + " + packageName); 3195 } 3196 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 3197 // state w.r.t. the formal app-linkage "no verification attempted" state; 3198 // and then 'always' in the per-user state actually used for intent resolution. 3199 final IntentFilterVerificationInfo ivi; 3200 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains); 3201 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 3202 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 3203 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 3204 } else { 3205 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 3206 + "' does not handle web links"); 3207 } 3208 } else { 3209 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 3210 } 3211 } 3212 3213 scheduleWritePackageRestrictionsLocked(userId); 3214 scheduleWriteSettingsLocked(); 3215 } 3216 3217 private void applyFactoryDefaultBrowserLPw(int userId) { 3218 // The default browser app's package name is stored in a string resource, 3219 // with a product-specific overlay used for vendor customization. 3220 String browserPkg = mContext.getResources().getString( 3221 com.android.internal.R.string.default_browser); 3222 if (!TextUtils.isEmpty(browserPkg)) { 3223 // non-empty string => required to be a known package 3224 PackageSetting ps = mSettings.mPackages.get(browserPkg); 3225 if (ps == null) { 3226 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 3227 browserPkg = null; 3228 } else { 3229 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3230 } 3231 } 3232 3233 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3234 // default. If there's more than one, just leave everything alone. 3235 if (browserPkg == null) { 3236 calculateDefaultBrowserLPw(userId); 3237 } 3238 } 3239 3240 private void calculateDefaultBrowserLPw(int userId) { 3241 List<String> allBrowsers = resolveAllBrowserApps(userId); 3242 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3243 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3244 } 3245 3246 private List<String> resolveAllBrowserApps(int userId) { 3247 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3248 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3249 PackageManager.MATCH_ALL, userId); 3250 3251 final int count = list.size(); 3252 List<String> result = new ArrayList<String>(count); 3253 for (int i=0; i<count; i++) { 3254 ResolveInfo info = list.get(i); 3255 if (info.activityInfo == null 3256 || !info.handleAllWebDataURI 3257 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3258 || result.contains(info.activityInfo.packageName)) { 3259 continue; 3260 } 3261 result.add(info.activityInfo.packageName); 3262 } 3263 3264 return result; 3265 } 3266 3267 private boolean packageIsBrowser(String packageName, int userId) { 3268 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3269 PackageManager.MATCH_ALL, userId); 3270 final int N = list.size(); 3271 for (int i = 0; i < N; i++) { 3272 ResolveInfo info = list.get(i); 3273 if (packageName.equals(info.activityInfo.packageName)) { 3274 return true; 3275 } 3276 } 3277 return false; 3278 } 3279 3280 private void checkDefaultBrowser() { 3281 final int myUserId = UserHandle.myUserId(); 3282 final String packageName = getDefaultBrowserPackageName(myUserId); 3283 if (packageName != null) { 3284 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3285 if (info == null) { 3286 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3287 synchronized (mPackages) { 3288 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3289 } 3290 } 3291 } 3292 } 3293 3294 @Override 3295 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3296 throws RemoteException { 3297 try { 3298 return super.onTransact(code, data, reply, flags); 3299 } catch (RuntimeException e) { 3300 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3301 Slog.wtf(TAG, "Package Manager Crash", e); 3302 } 3303 throw e; 3304 } 3305 } 3306 3307 static int[] appendInts(int[] cur, int[] add) { 3308 if (add == null) return cur; 3309 if (cur == null) return add; 3310 final int N = add.length; 3311 for (int i=0; i<N; i++) { 3312 cur = appendInt(cur, add[i]); 3313 } 3314 return cur; 3315 } 3316 3317 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3318 if (!sUserManager.exists(userId)) return null; 3319 if (ps == null) { 3320 return null; 3321 } 3322 final PackageParser.Package p = ps.pkg; 3323 if (p == null) { 3324 return null; 3325 } 3326 // Filter out ephemeral app metadata: 3327 // * The system/shell/root can see metadata for any app 3328 // * An installed app can see metadata for 1) other installed apps 3329 // and 2) ephemeral apps that have explicitly interacted with it 3330 // * Ephemeral apps can only see their own metadata 3331 // * Holding a signature permission allows seeing instant apps 3332 final int callingAppId = UserHandle.getAppId(Binder.getCallingUid()); 3333 if (callingAppId != Process.SYSTEM_UID 3334 && callingAppId != Process.SHELL_UID 3335 && callingAppId != Process.ROOT_UID 3336 && checkUidPermission(Manifest.permission.ACCESS_INSTANT_APPS, 3337 Binder.getCallingUid()) != PackageManager.PERMISSION_GRANTED) { 3338 final String ephemeralPackageName = getEphemeralPackageName(Binder.getCallingUid()); 3339 if (ephemeralPackageName != null) { 3340 // ephemeral apps can only get information on themselves 3341 if (!ephemeralPackageName.equals(p.packageName)) { 3342 return null; 3343 } 3344 } else { 3345 if (p.applicationInfo.isInstantApp()) { 3346 // only get access to the ephemeral app if we've been granted access 3347 if (!mInstantAppRegistry.isInstantAccessGranted( 3348 userId, callingAppId, ps.appId)) { 3349 return null; 3350 } 3351 } 3352 } 3353 } 3354 3355 final PermissionsState permissionsState = ps.getPermissionsState(); 3356 3357 // Compute GIDs only if requested 3358 final int[] gids = (flags & PackageManager.GET_GIDS) == 0 3359 ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId); 3360 // Compute granted permissions only if package has requested permissions 3361 final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions) 3362 ? Collections.<String>emptySet() : permissionsState.getPermissions(userId); 3363 final PackageUserState state = ps.readUserState(userId); 3364 3365 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0 3366 && ps.isSystem()) { 3367 flags |= MATCH_ANY_USER; 3368 } 3369 3370 PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags, 3371 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3372 3373 if (packageInfo == null) { 3374 return null; 3375 } 3376 3377 packageInfo.packageName = packageInfo.applicationInfo.packageName = 3378 resolveExternalPackageNameLPr(p); 3379 3380 return packageInfo; 3381 } 3382 3383 @Override 3384 public void checkPackageStartable(String packageName, int userId) { 3385 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3386 3387 synchronized (mPackages) { 3388 final PackageSetting ps = mSettings.mPackages.get(packageName); 3389 if (ps == null) { 3390 throw new SecurityException("Package " + packageName + " was not found!"); 3391 } 3392 3393 if (!ps.getInstalled(userId)) { 3394 throw new SecurityException( 3395 "Package " + packageName + " was not installed for user " + userId + "!"); 3396 } 3397 3398 if (mSafeMode && !ps.isSystem()) { 3399 throw new SecurityException("Package " + packageName + " not a system app!"); 3400 } 3401 3402 if (mFrozenPackages.contains(packageName)) { 3403 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3404 } 3405 3406 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3407 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3408 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3409 } 3410 } 3411 } 3412 3413 @Override 3414 public boolean isPackageAvailable(String packageName, int userId) { 3415 if (!sUserManager.exists(userId)) return false; 3416 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3417 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3418 synchronized (mPackages) { 3419 PackageParser.Package p = mPackages.get(packageName); 3420 if (p != null) { 3421 final PackageSetting ps = (PackageSetting) p.mExtras; 3422 if (ps != null) { 3423 final PackageUserState state = ps.readUserState(userId); 3424 if (state != null) { 3425 return PackageParser.isAvailable(state); 3426 } 3427 } 3428 } 3429 } 3430 return false; 3431 } 3432 3433 @Override 3434 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3435 return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST, 3436 flags, userId); 3437 } 3438 3439 @Override 3440 public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage, 3441 int flags, int userId) { 3442 return getPackageInfoInternal(versionedPackage.getPackageName(), 3443 // TODO: We will change version code to long, so in the new API it is long 3444 (int) versionedPackage.getVersionCode(), flags, userId); 3445 } 3446 3447 private PackageInfo getPackageInfoInternal(String packageName, int versionCode, 3448 int flags, int userId) { 3449 if (!sUserManager.exists(userId)) return null; 3450 flags = updateFlagsForPackage(flags, userId, packageName); 3451 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3452 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3453 3454 // reader 3455 synchronized (mPackages) { 3456 // Normalize package name to handle renamed packages and static libs 3457 packageName = resolveInternalPackageNameLPr(packageName, versionCode); 3458 3459 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3460 if (matchFactoryOnly) { 3461 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3462 if (ps != null) { 3463 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 3464 return null; 3465 } 3466 return generatePackageInfo(ps, flags, userId); 3467 } 3468 } 3469 3470 PackageParser.Package p = mPackages.get(packageName); 3471 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3472 return null; 3473 } 3474 if (DEBUG_PACKAGE_INFO) 3475 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3476 if (p != null) { 3477 if (filterSharedLibPackageLPr((PackageSetting) p.mExtras, 3478 Binder.getCallingUid(), userId)) { 3479 return null; 3480 } 3481 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3482 } 3483 if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) { 3484 final PackageSetting ps = mSettings.mPackages.get(packageName); 3485 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 3486 return null; 3487 } 3488 return generatePackageInfo(ps, flags, userId); 3489 } 3490 } 3491 return null; 3492 } 3493 3494 3495 private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId) { 3496 // System/shell/root get to see all static libs 3497 final int appId = UserHandle.getAppId(uid); 3498 if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID 3499 || appId == Process.ROOT_UID) { 3500 return false; 3501 } 3502 3503 // No package means no static lib as it is always on internal storage 3504 if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) { 3505 return false; 3506 } 3507 3508 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName, 3509 ps.pkg.staticSharedLibVersion); 3510 if (libEntry == null) { 3511 return false; 3512 } 3513 3514 final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid)); 3515 final String[] uidPackageNames = getPackagesForUid(resolvedUid); 3516 if (uidPackageNames == null) { 3517 return true; 3518 } 3519 3520 for (String uidPackageName : uidPackageNames) { 3521 if (ps.name.equals(uidPackageName)) { 3522 return false; 3523 } 3524 PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName); 3525 if (uidPs != null) { 3526 final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries, 3527 libEntry.info.getName()); 3528 if (index < 0) { 3529 continue; 3530 } 3531 if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) { 3532 return false; 3533 } 3534 } 3535 } 3536 return true; 3537 } 3538 3539 @Override 3540 public String[] currentToCanonicalPackageNames(String[] names) { 3541 String[] out = new String[names.length]; 3542 // reader 3543 synchronized (mPackages) { 3544 for (int i=names.length-1; i>=0; i--) { 3545 PackageSetting ps = mSettings.mPackages.get(names[i]); 3546 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3547 } 3548 } 3549 return out; 3550 } 3551 3552 @Override 3553 public String[] canonicalToCurrentPackageNames(String[] names) { 3554 String[] out = new String[names.length]; 3555 // reader 3556 synchronized (mPackages) { 3557 for (int i=names.length-1; i>=0; i--) { 3558 String cur = mSettings.getRenamedPackageLPr(names[i]); 3559 out[i] = cur != null ? cur : names[i]; 3560 } 3561 } 3562 return out; 3563 } 3564 3565 @Override 3566 public int getPackageUid(String packageName, int flags, int userId) { 3567 if (!sUserManager.exists(userId)) return -1; 3568 flags = updateFlagsForPackage(flags, userId, packageName); 3569 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3570 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3571 3572 // reader 3573 synchronized (mPackages) { 3574 final PackageParser.Package p = mPackages.get(packageName); 3575 if (p != null && p.isMatch(flags)) { 3576 return UserHandle.getUid(userId, p.applicationInfo.uid); 3577 } 3578 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3579 final PackageSetting ps = mSettings.mPackages.get(packageName); 3580 if (ps != null && ps.isMatch(flags)) { 3581 return UserHandle.getUid(userId, ps.appId); 3582 } 3583 } 3584 } 3585 3586 return -1; 3587 } 3588 3589 @Override 3590 public int[] getPackageGids(String packageName, int flags, int userId) { 3591 if (!sUserManager.exists(userId)) return null; 3592 flags = updateFlagsForPackage(flags, userId, packageName); 3593 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3594 false /* requireFullPermission */, false /* checkShell */, 3595 "getPackageGids"); 3596 3597 // reader 3598 synchronized (mPackages) { 3599 final PackageParser.Package p = mPackages.get(packageName); 3600 if (p != null && p.isMatch(flags)) { 3601 PackageSetting ps = (PackageSetting) p.mExtras; 3602 // TODO: Shouldn't this be checking for package installed state for userId and 3603 // return null? 3604 return ps.getPermissionsState().computeGids(userId); 3605 } 3606 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3607 final PackageSetting ps = mSettings.mPackages.get(packageName); 3608 if (ps != null && ps.isMatch(flags)) { 3609 return ps.getPermissionsState().computeGids(userId); 3610 } 3611 } 3612 } 3613 3614 return null; 3615 } 3616 3617 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3618 if (bp.perm != null) { 3619 return PackageParser.generatePermissionInfo(bp.perm, flags); 3620 } 3621 PermissionInfo pi = new PermissionInfo(); 3622 pi.name = bp.name; 3623 pi.packageName = bp.sourcePackage; 3624 pi.nonLocalizedLabel = bp.name; 3625 pi.protectionLevel = bp.protectionLevel; 3626 return pi; 3627 } 3628 3629 @Override 3630 public PermissionInfo getPermissionInfo(String name, int flags) { 3631 // reader 3632 synchronized (mPackages) { 3633 final BasePermission p = mSettings.mPermissions.get(name); 3634 if (p != null) { 3635 return generatePermissionInfo(p, flags); 3636 } 3637 return null; 3638 } 3639 } 3640 3641 @Override 3642 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3643 int flags) { 3644 // reader 3645 synchronized (mPackages) { 3646 if (group != null && !mPermissionGroups.containsKey(group)) { 3647 // This is thrown as NameNotFoundException 3648 return null; 3649 } 3650 3651 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3652 for (BasePermission p : mSettings.mPermissions.values()) { 3653 if (group == null) { 3654 if (p.perm == null || p.perm.info.group == null) { 3655 out.add(generatePermissionInfo(p, flags)); 3656 } 3657 } else { 3658 if (p.perm != null && group.equals(p.perm.info.group)) { 3659 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3660 } 3661 } 3662 } 3663 return new ParceledListSlice<>(out); 3664 } 3665 } 3666 3667 @Override 3668 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3669 // reader 3670 synchronized (mPackages) { 3671 return PackageParser.generatePermissionGroupInfo( 3672 mPermissionGroups.get(name), flags); 3673 } 3674 } 3675 3676 @Override 3677 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3678 // reader 3679 synchronized (mPackages) { 3680 final int N = mPermissionGroups.size(); 3681 ArrayList<PermissionGroupInfo> out 3682 = new ArrayList<PermissionGroupInfo>(N); 3683 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3684 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3685 } 3686 return new ParceledListSlice<>(out); 3687 } 3688 } 3689 3690 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3691 int uid, int userId) { 3692 if (!sUserManager.exists(userId)) return null; 3693 PackageSetting ps = mSettings.mPackages.get(packageName); 3694 if (ps != null) { 3695 if (filterSharedLibPackageLPr(ps, uid, userId)) { 3696 return null; 3697 } 3698 if (ps.pkg == null) { 3699 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3700 if (pInfo != null) { 3701 return pInfo.applicationInfo; 3702 } 3703 return null; 3704 } 3705 ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 3706 ps.readUserState(userId), userId); 3707 if (ai != null) { 3708 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 3709 } 3710 return ai; 3711 } 3712 return null; 3713 } 3714 3715 @Override 3716 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3717 if (!sUserManager.exists(userId)) return null; 3718 flags = updateFlagsForApplication(flags, userId, packageName); 3719 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3720 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3721 3722 // writer 3723 synchronized (mPackages) { 3724 // Normalize package name to handle renamed packages and static libs 3725 packageName = resolveInternalPackageNameLPr(packageName, 3726 PackageManager.VERSION_CODE_HIGHEST); 3727 3728 PackageParser.Package p = mPackages.get(packageName); 3729 if (DEBUG_PACKAGE_INFO) Log.v( 3730 TAG, "getApplicationInfo " + packageName 3731 + ": " + p); 3732 if (p != null) { 3733 PackageSetting ps = mSettings.mPackages.get(packageName); 3734 if (ps == null) return null; 3735 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 3736 return null; 3737 } 3738 // Note: isEnabledLP() does not apply here - always return info 3739 ApplicationInfo ai = PackageParser.generateApplicationInfo( 3740 p, flags, ps.readUserState(userId), userId); 3741 if (ai != null) { 3742 ai.packageName = resolveExternalPackageNameLPr(p); 3743 } 3744 return ai; 3745 } 3746 if ("android".equals(packageName)||"system".equals(packageName)) { 3747 return mAndroidApplication; 3748 } 3749 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3750 // Already generates the external package name 3751 return generateApplicationInfoFromSettingsLPw(packageName, 3752 Binder.getCallingUid(), flags, userId); 3753 } 3754 } 3755 return null; 3756 } 3757 3758 private String normalizePackageNameLPr(String packageName) { 3759 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 3760 return normalizedPackageName != null ? normalizedPackageName : packageName; 3761 } 3762 3763 @Override 3764 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3765 final IPackageDataObserver observer) { 3766 mContext.enforceCallingOrSelfPermission( 3767 android.Manifest.permission.CLEAR_APP_CACHE, null); 3768 // Queue up an async operation since clearing cache may take a little while. 3769 mHandler.post(new Runnable() { 3770 public void run() { 3771 mHandler.removeCallbacks(this); 3772 boolean success = true; 3773 synchronized (mInstallLock) { 3774 try { 3775 mInstaller.freeCache(volumeUuid, freeStorageSize, 0); 3776 } catch (InstallerException e) { 3777 Slog.w(TAG, "Couldn't clear application caches: " + e); 3778 success = false; 3779 } 3780 } 3781 if (observer != null) { 3782 try { 3783 observer.onRemoveCompleted(null, success); 3784 } catch (RemoteException e) { 3785 Slog.w(TAG, "RemoveException when invoking call back"); 3786 } 3787 } 3788 } 3789 }); 3790 } 3791 3792 @Override 3793 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3794 final IntentSender pi) { 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(pi != null) { 3811 try { 3812 // Callback via pending intent 3813 int code = success ? 1 : 0; 3814 pi.sendIntent(null, code, null, 3815 null, null); 3816 } catch (SendIntentException e1) { 3817 Slog.i(TAG, "Failed to send pending intent"); 3818 } 3819 } 3820 } 3821 }); 3822 } 3823 3824 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3825 synchronized (mInstallLock) { 3826 try { 3827 mInstaller.freeCache(volumeUuid, freeStorageSize, 0); 3828 } catch (InstallerException e) { 3829 throw new IOException("Failed to free enough space", e); 3830 } 3831 } 3832 } 3833 3834 /** 3835 * Update given flags based on encryption status of current user. 3836 */ 3837 private int updateFlags(int flags, int userId) { 3838 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3839 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3840 // Caller expressed an explicit opinion about what encryption 3841 // aware/unaware components they want to see, so fall through and 3842 // give them what they want 3843 } else { 3844 // Caller expressed no opinion, so match based on user state 3845 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 3846 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3847 } else { 3848 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3849 } 3850 } 3851 return flags; 3852 } 3853 3854 private UserManagerInternal getUserManagerInternal() { 3855 if (mUserManagerInternal == null) { 3856 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 3857 } 3858 return mUserManagerInternal; 3859 } 3860 3861 /** 3862 * Update given flags when being used to request {@link PackageInfo}. 3863 */ 3864 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3865 final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM; 3866 boolean triaged = true; 3867 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3868 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3869 // Caller is asking for component details, so they'd better be 3870 // asking for specific encryption matching behavior, or be triaged 3871 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3872 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3873 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3874 triaged = false; 3875 } 3876 } 3877 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3878 | PackageManager.MATCH_SYSTEM_ONLY 3879 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3880 triaged = false; 3881 } 3882 if ((flags & PackageManager.MATCH_ANY_USER) != 0) { 3883 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 3884 "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at " 3885 + Debug.getCallers(5)); 3886 } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser 3887 && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) { 3888 // If the caller wants all packages and has a restricted profile associated with it, 3889 // then match all users. This is to make sure that launchers that need to access work 3890 // profile apps don't start breaking. TODO: Remove this hack when launchers stop using 3891 // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380 3892 flags |= PackageManager.MATCH_ANY_USER; 3893 } 3894 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3895 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3896 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3897 } 3898 return updateFlags(flags, userId); 3899 } 3900 3901 /** 3902 * Update given flags when being used to request {@link ApplicationInfo}. 3903 */ 3904 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3905 return updateFlagsForPackage(flags, userId, cookie); 3906 } 3907 3908 /** 3909 * Update given flags when being used to request {@link ComponentInfo}. 3910 */ 3911 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3912 if (cookie instanceof Intent) { 3913 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3914 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3915 } 3916 } 3917 3918 boolean triaged = true; 3919 // Caller is asking for component details, so they'd better be 3920 // asking for specific encryption matching behavior, or be triaged 3921 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3922 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3923 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3924 triaged = false; 3925 } 3926 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3927 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3928 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3929 } 3930 3931 return updateFlags(flags, userId); 3932 } 3933 3934 /** 3935 * Update given intent when being used to request {@link ResolveInfo}. 3936 */ 3937 private Intent updateIntentForResolve(Intent intent) { 3938 if (intent.getSelector() != null) { 3939 intent = intent.getSelector(); 3940 } 3941 if (DEBUG_PREFERRED) { 3942 intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3943 } 3944 return intent; 3945 } 3946 3947 /** 3948 * Update given flags when being used to request {@link ResolveInfo}. 3949 */ 3950 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3951 // Safe mode means we shouldn't match any third-party components 3952 if (mSafeMode) { 3953 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3954 } 3955 final int callingUid = Binder.getCallingUid(); 3956 if (callingUid == Process.SYSTEM_UID || callingUid == 0) { 3957 // The system sees all components 3958 flags |= PackageManager.MATCH_EPHEMERAL; 3959 } else if (getEphemeralPackageName(callingUid) != null) { 3960 // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components 3961 flags |= PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY; 3962 flags |= PackageManager.MATCH_EPHEMERAL; 3963 } else { 3964 // Otherwise, prevent leaking ephemeral components 3965 flags &= ~PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY; 3966 flags &= ~PackageManager.MATCH_EPHEMERAL; 3967 } 3968 return updateFlagsForComponent(flags, userId, cookie); 3969 } 3970 3971 @Override 3972 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3973 if (!sUserManager.exists(userId)) return null; 3974 flags = updateFlagsForComponent(flags, userId, component); 3975 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3976 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 3977 synchronized (mPackages) { 3978 PackageParser.Activity a = mActivities.mActivities.get(component); 3979 3980 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3981 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3982 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3983 if (ps == null) return null; 3984 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3985 userId); 3986 } 3987 if (mResolveComponentName.equals(component)) { 3988 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3989 new PackageUserState(), userId); 3990 } 3991 } 3992 return null; 3993 } 3994 3995 @Override 3996 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3997 String resolvedType) { 3998 synchronized (mPackages) { 3999 if (component.equals(mResolveComponentName)) { 4000 // The resolver supports EVERYTHING! 4001 return true; 4002 } 4003 PackageParser.Activity a = mActivities.mActivities.get(component); 4004 if (a == null) { 4005 return false; 4006 } 4007 for (int i=0; i<a.intents.size(); i++) { 4008 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 4009 intent.getData(), intent.getCategories(), TAG) >= 0) { 4010 return true; 4011 } 4012 } 4013 return false; 4014 } 4015 } 4016 4017 @Override 4018 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 4019 if (!sUserManager.exists(userId)) return null; 4020 flags = updateFlagsForComponent(flags, userId, component); 4021 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4022 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 4023 synchronized (mPackages) { 4024 PackageParser.Activity a = mReceivers.mActivities.get(component); 4025 if (DEBUG_PACKAGE_INFO) Log.v( 4026 TAG, "getReceiverInfo " + component + ": " + a); 4027 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 4028 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4029 if (ps == null) return null; 4030 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 4031 userId); 4032 } 4033 } 4034 return null; 4035 } 4036 4037 @Override 4038 public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(int flags, int userId) { 4039 if (!sUserManager.exists(userId)) return null; 4040 Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0"); 4041 4042 flags = updateFlagsForPackage(flags, userId, null); 4043 4044 final boolean canSeeStaticLibraries = 4045 mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES) 4046 == PERMISSION_GRANTED 4047 || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES) 4048 == PERMISSION_GRANTED 4049 || mContext.checkCallingOrSelfPermission(REQUEST_INSTALL_PACKAGES) 4050 == PERMISSION_GRANTED 4051 || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES) 4052 == PERMISSION_GRANTED; 4053 4054 synchronized (mPackages) { 4055 List<SharedLibraryInfo> result = null; 4056 4057 final int libCount = mSharedLibraries.size(); 4058 for (int i = 0; i < libCount; i++) { 4059 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 4060 if (versionedLib == null) { 4061 continue; 4062 } 4063 4064 final int versionCount = versionedLib.size(); 4065 for (int j = 0; j < versionCount; j++) { 4066 SharedLibraryInfo libInfo = versionedLib.valueAt(j).info; 4067 if (!canSeeStaticLibraries && libInfo.isStatic()) { 4068 break; 4069 } 4070 final long identity = Binder.clearCallingIdentity(); 4071 try { 4072 // TODO: We will change version code to long, so in the new API it is long 4073 PackageInfo packageInfo = getPackageInfoVersioned( 4074 libInfo.getDeclaringPackage(), flags, userId); 4075 if (packageInfo == null) { 4076 continue; 4077 } 4078 } finally { 4079 Binder.restoreCallingIdentity(identity); 4080 } 4081 4082 SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(), 4083 libInfo.getVersion(), libInfo.getType(), libInfo.getDeclaringPackage(), 4084 getPackagesUsingSharedLibraryLPr(libInfo, flags, userId)); 4085 4086 if (result == null) { 4087 result = new ArrayList<>(); 4088 } 4089 result.add(resLibInfo); 4090 } 4091 } 4092 4093 return result != null ? new ParceledListSlice<>(result) : null; 4094 } 4095 } 4096 4097 private List<VersionedPackage> getPackagesUsingSharedLibraryLPr( 4098 SharedLibraryInfo libInfo, int flags, int userId) { 4099 List<VersionedPackage> versionedPackages = null; 4100 final int packageCount = mSettings.mPackages.size(); 4101 for (int i = 0; i < packageCount; i++) { 4102 PackageSetting ps = mSettings.mPackages.valueAt(i); 4103 4104 if (ps == null) { 4105 continue; 4106 } 4107 4108 if (!ps.getUserState().get(userId).isAvailable(flags)) { 4109 continue; 4110 } 4111 4112 final String libName = libInfo.getName(); 4113 if (libInfo.isStatic()) { 4114 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 4115 if (libIdx < 0) { 4116 continue; 4117 } 4118 if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) { 4119 continue; 4120 } 4121 if (versionedPackages == null) { 4122 versionedPackages = new ArrayList<>(); 4123 } 4124 // If the dependent is a static shared lib, use the public package name 4125 String dependentPackageName = ps.name; 4126 if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) { 4127 dependentPackageName = ps.pkg.manifestPackageName; 4128 } 4129 versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode)); 4130 } else if (ps.pkg != null) { 4131 if (ArrayUtils.contains(ps.pkg.usesLibraries, libName) 4132 || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) { 4133 if (versionedPackages == null) { 4134 versionedPackages = new ArrayList<>(); 4135 } 4136 versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode)); 4137 } 4138 } 4139 } 4140 4141 return versionedPackages; 4142 } 4143 4144 @Override 4145 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 4146 if (!sUserManager.exists(userId)) return null; 4147 flags = updateFlagsForComponent(flags, userId, component); 4148 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4149 false /* requireFullPermission */, false /* checkShell */, "get service info"); 4150 synchronized (mPackages) { 4151 PackageParser.Service s = mServices.mServices.get(component); 4152 if (DEBUG_PACKAGE_INFO) Log.v( 4153 TAG, "getServiceInfo " + component + ": " + s); 4154 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 4155 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4156 if (ps == null) return null; 4157 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 4158 userId); 4159 } 4160 } 4161 return null; 4162 } 4163 4164 @Override 4165 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 4166 if (!sUserManager.exists(userId)) return null; 4167 flags = updateFlagsForComponent(flags, userId, component); 4168 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4169 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 4170 synchronized (mPackages) { 4171 PackageParser.Provider p = mProviders.mProviders.get(component); 4172 if (DEBUG_PACKAGE_INFO) Log.v( 4173 TAG, "getProviderInfo " + component + ": " + p); 4174 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 4175 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4176 if (ps == null) return null; 4177 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 4178 userId); 4179 } 4180 } 4181 return null; 4182 } 4183 4184 @Override 4185 public String[] getSystemSharedLibraryNames() { 4186 synchronized (mPackages) { 4187 Set<String> libs = null; 4188 final int libCount = mSharedLibraries.size(); 4189 for (int i = 0; i < libCount; i++) { 4190 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 4191 if (versionedLib == null) { 4192 continue; 4193 } 4194 final int versionCount = versionedLib.size(); 4195 for (int j = 0; j < versionCount; j++) { 4196 SharedLibraryEntry libEntry = versionedLib.valueAt(j); 4197 if (!libEntry.info.isStatic()) { 4198 if (libs == null) { 4199 libs = new ArraySet<>(); 4200 } 4201 libs.add(libEntry.info.getName()); 4202 break; 4203 } 4204 PackageSetting ps = mSettings.getPackageLPr(libEntry.apk); 4205 if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(), 4206 UserHandle.getUserId(Binder.getCallingUid()))) { 4207 if (libs == null) { 4208 libs = new ArraySet<>(); 4209 } 4210 libs.add(libEntry.info.getName()); 4211 break; 4212 } 4213 } 4214 } 4215 4216 if (libs != null) { 4217 String[] libsArray = new String[libs.size()]; 4218 libs.toArray(libsArray); 4219 return libsArray; 4220 } 4221 4222 return null; 4223 } 4224 } 4225 4226 @Override 4227 public @NonNull String getServicesSystemSharedLibraryPackageName() { 4228 synchronized (mPackages) { 4229 return mServicesSystemSharedLibraryPackageName; 4230 } 4231 } 4232 4233 @Override 4234 public @NonNull String getSharedSystemSharedLibraryPackageName() { 4235 synchronized (mPackages) { 4236 return mSharedSystemSharedLibraryPackageName; 4237 } 4238 } 4239 4240 private void updateSequenceNumberLP(String packageName, int[] userList) { 4241 for (int i = userList.length - 1; i >= 0; --i) { 4242 final int userId = userList[i]; 4243 SparseArray<String> changedPackages = mChangedPackages.get(userId); 4244 if (changedPackages == null) { 4245 changedPackages = new SparseArray<>(); 4246 mChangedPackages.put(userId, changedPackages); 4247 } 4248 Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId); 4249 if (sequenceNumbers == null) { 4250 sequenceNumbers = new HashMap<>(); 4251 mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers); 4252 } 4253 final Integer sequenceNumber = sequenceNumbers.get(packageName); 4254 if (sequenceNumber != null) { 4255 changedPackages.remove(sequenceNumber); 4256 } 4257 changedPackages.put(mChangedPackagesSequenceNumber, packageName); 4258 sequenceNumbers.put(packageName, mChangedPackagesSequenceNumber); 4259 } 4260 mChangedPackagesSequenceNumber++; 4261 } 4262 4263 @Override 4264 public ChangedPackages getChangedPackages(int sequenceNumber, int userId) { 4265 synchronized (mPackages) { 4266 if (sequenceNumber >= mChangedPackagesSequenceNumber) { 4267 return null; 4268 } 4269 final SparseArray<String> changedPackages = mChangedPackages.get(userId); 4270 if (changedPackages == null) { 4271 return null; 4272 } 4273 final List<String> packageNames = 4274 new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber); 4275 for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) { 4276 final String packageName = changedPackages.get(i); 4277 if (packageName != null) { 4278 packageNames.add(packageName); 4279 } 4280 } 4281 return packageNames.isEmpty() 4282 ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames); 4283 } 4284 } 4285 4286 @Override 4287 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 4288 ArrayList<FeatureInfo> res; 4289 synchronized (mAvailableFeatures) { 4290 res = new ArrayList<>(mAvailableFeatures.size() + 1); 4291 res.addAll(mAvailableFeatures.values()); 4292 } 4293 final FeatureInfo fi = new FeatureInfo(); 4294 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 4295 FeatureInfo.GL_ES_VERSION_UNDEFINED); 4296 res.add(fi); 4297 4298 return new ParceledListSlice<>(res); 4299 } 4300 4301 @Override 4302 public boolean hasSystemFeature(String name, int version) { 4303 synchronized (mAvailableFeatures) { 4304 final FeatureInfo feat = mAvailableFeatures.get(name); 4305 if (feat == null) { 4306 return false; 4307 } else { 4308 return feat.version >= version; 4309 } 4310 } 4311 } 4312 4313 @Override 4314 public int checkPermission(String permName, String pkgName, int userId) { 4315 if (!sUserManager.exists(userId)) { 4316 return PackageManager.PERMISSION_DENIED; 4317 } 4318 4319 synchronized (mPackages) { 4320 final PackageParser.Package p = mPackages.get(pkgName); 4321 if (p != null && p.mExtras != null) { 4322 final PackageSetting ps = (PackageSetting) p.mExtras; 4323 final PermissionsState permissionsState = ps.getPermissionsState(); 4324 if (permissionsState.hasPermission(permName, userId)) { 4325 return PackageManager.PERMISSION_GRANTED; 4326 } 4327 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 4328 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 4329 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 4330 return PackageManager.PERMISSION_GRANTED; 4331 } 4332 } 4333 } 4334 4335 return PackageManager.PERMISSION_DENIED; 4336 } 4337 4338 @Override 4339 public int checkUidPermission(String permName, int uid) { 4340 final int userId = UserHandle.getUserId(uid); 4341 4342 if (!sUserManager.exists(userId)) { 4343 return PackageManager.PERMISSION_DENIED; 4344 } 4345 4346 synchronized (mPackages) { 4347 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4348 if (obj != null) { 4349 final SettingBase ps = (SettingBase) obj; 4350 final PermissionsState permissionsState = ps.getPermissionsState(); 4351 if (permissionsState.hasPermission(permName, userId)) { 4352 return PackageManager.PERMISSION_GRANTED; 4353 } 4354 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 4355 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 4356 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 4357 return PackageManager.PERMISSION_GRANTED; 4358 } 4359 } else { 4360 ArraySet<String> perms = mSystemPermissions.get(uid); 4361 if (perms != null) { 4362 if (perms.contains(permName)) { 4363 return PackageManager.PERMISSION_GRANTED; 4364 } 4365 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 4366 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 4367 return PackageManager.PERMISSION_GRANTED; 4368 } 4369 } 4370 } 4371 } 4372 4373 return PackageManager.PERMISSION_DENIED; 4374 } 4375 4376 @Override 4377 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 4378 if (UserHandle.getCallingUserId() != userId) { 4379 mContext.enforceCallingPermission( 4380 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4381 "isPermissionRevokedByPolicy for user " + userId); 4382 } 4383 4384 if (checkPermission(permission, packageName, userId) 4385 == PackageManager.PERMISSION_GRANTED) { 4386 return false; 4387 } 4388 4389 final long identity = Binder.clearCallingIdentity(); 4390 try { 4391 final int flags = getPermissionFlags(permission, packageName, userId); 4392 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 4393 } finally { 4394 Binder.restoreCallingIdentity(identity); 4395 } 4396 } 4397 4398 @Override 4399 public String getPermissionControllerPackageName() { 4400 synchronized (mPackages) { 4401 return mRequiredInstallerPackage; 4402 } 4403 } 4404 4405 /** 4406 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 4407 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 4408 * @param checkShell whether to prevent shell from access if there's a debugging restriction 4409 * @param message the message to log on security exception 4410 */ 4411 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 4412 boolean checkShell, String message) { 4413 if (userId < 0) { 4414 throw new IllegalArgumentException("Invalid userId " + userId); 4415 } 4416 if (checkShell) { 4417 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 4418 } 4419 if (userId == UserHandle.getUserId(callingUid)) return; 4420 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4421 if (requireFullPermission) { 4422 mContext.enforceCallingOrSelfPermission( 4423 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 4424 } else { 4425 try { 4426 mContext.enforceCallingOrSelfPermission( 4427 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 4428 } catch (SecurityException se) { 4429 mContext.enforceCallingOrSelfPermission( 4430 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 4431 } 4432 } 4433 } 4434 } 4435 4436 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 4437 if (callingUid == Process.SHELL_UID) { 4438 if (userHandle >= 0 4439 && sUserManager.hasUserRestriction(restriction, userHandle)) { 4440 throw new SecurityException("Shell does not have permission to access user " 4441 + userHandle); 4442 } else if (userHandle < 0) { 4443 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 4444 + Debug.getCallers(3)); 4445 } 4446 } 4447 } 4448 4449 private BasePermission findPermissionTreeLP(String permName) { 4450 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 4451 if (permName.startsWith(bp.name) && 4452 permName.length() > bp.name.length() && 4453 permName.charAt(bp.name.length()) == '.') { 4454 return bp; 4455 } 4456 } 4457 return null; 4458 } 4459 4460 private BasePermission checkPermissionTreeLP(String permName) { 4461 if (permName != null) { 4462 BasePermission bp = findPermissionTreeLP(permName); 4463 if (bp != null) { 4464 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 4465 return bp; 4466 } 4467 throw new SecurityException("Calling uid " 4468 + Binder.getCallingUid() 4469 + " is not allowed to add to permission tree " 4470 + bp.name + " owned by uid " + bp.uid); 4471 } 4472 } 4473 throw new SecurityException("No permission tree found for " + permName); 4474 } 4475 4476 static boolean compareStrings(CharSequence s1, CharSequence s2) { 4477 if (s1 == null) { 4478 return s2 == null; 4479 } 4480 if (s2 == null) { 4481 return false; 4482 } 4483 if (s1.getClass() != s2.getClass()) { 4484 return false; 4485 } 4486 return s1.equals(s2); 4487 } 4488 4489 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 4490 if (pi1.icon != pi2.icon) return false; 4491 if (pi1.logo != pi2.logo) return false; 4492 if (pi1.protectionLevel != pi2.protectionLevel) return false; 4493 if (!compareStrings(pi1.name, pi2.name)) return false; 4494 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 4495 // We'll take care of setting this one. 4496 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 4497 // These are not currently stored in settings. 4498 //if (!compareStrings(pi1.group, pi2.group)) return false; 4499 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 4500 //if (pi1.labelRes != pi2.labelRes) return false; 4501 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 4502 return true; 4503 } 4504 4505 int permissionInfoFootprint(PermissionInfo info) { 4506 int size = info.name.length(); 4507 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 4508 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 4509 return size; 4510 } 4511 4512 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 4513 int size = 0; 4514 for (BasePermission perm : mSettings.mPermissions.values()) { 4515 if (perm.uid == tree.uid) { 4516 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 4517 } 4518 } 4519 return size; 4520 } 4521 4522 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 4523 // We calculate the max size of permissions defined by this uid and throw 4524 // if that plus the size of 'info' would exceed our stated maximum. 4525 if (tree.uid != Process.SYSTEM_UID) { 4526 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 4527 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 4528 throw new SecurityException("Permission tree size cap exceeded"); 4529 } 4530 } 4531 } 4532 4533 boolean addPermissionLocked(PermissionInfo info, boolean async) { 4534 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 4535 throw new SecurityException("Label must be specified in permission"); 4536 } 4537 BasePermission tree = checkPermissionTreeLP(info.name); 4538 BasePermission bp = mSettings.mPermissions.get(info.name); 4539 boolean added = bp == null; 4540 boolean changed = true; 4541 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 4542 if (added) { 4543 enforcePermissionCapLocked(info, tree); 4544 bp = new BasePermission(info.name, tree.sourcePackage, 4545 BasePermission.TYPE_DYNAMIC); 4546 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 4547 throw new SecurityException( 4548 "Not allowed to modify non-dynamic permission " 4549 + info.name); 4550 } else { 4551 if (bp.protectionLevel == fixedLevel 4552 && bp.perm.owner.equals(tree.perm.owner) 4553 && bp.uid == tree.uid 4554 && comparePermissionInfos(bp.perm.info, info)) { 4555 changed = false; 4556 } 4557 } 4558 bp.protectionLevel = fixedLevel; 4559 info = new PermissionInfo(info); 4560 info.protectionLevel = fixedLevel; 4561 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 4562 bp.perm.info.packageName = tree.perm.info.packageName; 4563 bp.uid = tree.uid; 4564 if (added) { 4565 mSettings.mPermissions.put(info.name, bp); 4566 } 4567 if (changed) { 4568 if (!async) { 4569 mSettings.writeLPr(); 4570 } else { 4571 scheduleWriteSettingsLocked(); 4572 } 4573 } 4574 return added; 4575 } 4576 4577 @Override 4578 public boolean addPermission(PermissionInfo info) { 4579 synchronized (mPackages) { 4580 return addPermissionLocked(info, false); 4581 } 4582 } 4583 4584 @Override 4585 public boolean addPermissionAsync(PermissionInfo info) { 4586 synchronized (mPackages) { 4587 return addPermissionLocked(info, true); 4588 } 4589 } 4590 4591 @Override 4592 public void removePermission(String name) { 4593 synchronized (mPackages) { 4594 checkPermissionTreeLP(name); 4595 BasePermission bp = mSettings.mPermissions.get(name); 4596 if (bp != null) { 4597 if (bp.type != BasePermission.TYPE_DYNAMIC) { 4598 throw new SecurityException( 4599 "Not allowed to modify non-dynamic permission " 4600 + name); 4601 } 4602 mSettings.mPermissions.remove(name); 4603 mSettings.writeLPr(); 4604 } 4605 } 4606 } 4607 4608 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 4609 BasePermission bp) { 4610 int index = pkg.requestedPermissions.indexOf(bp.name); 4611 if (index == -1) { 4612 throw new SecurityException("Package " + pkg.packageName 4613 + " has not requested permission " + bp.name); 4614 } 4615 if (!bp.isRuntime() && !bp.isDevelopment()) { 4616 throw new SecurityException("Permission " + bp.name 4617 + " is not a changeable permission type"); 4618 } 4619 } 4620 4621 @Override 4622 public void grantRuntimePermission(String packageName, String name, final int userId) { 4623 grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */); 4624 } 4625 4626 private void grantRuntimePermission(String packageName, String name, final int userId, 4627 boolean overridePolicy) { 4628 if (!sUserManager.exists(userId)) { 4629 Log.e(TAG, "No such user:" + userId); 4630 return; 4631 } 4632 4633 mContext.enforceCallingOrSelfPermission( 4634 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 4635 "grantRuntimePermission"); 4636 4637 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4638 true /* requireFullPermission */, true /* checkShell */, 4639 "grantRuntimePermission"); 4640 4641 final int uid; 4642 final SettingBase sb; 4643 4644 synchronized (mPackages) { 4645 final PackageParser.Package pkg = mPackages.get(packageName); 4646 if (pkg == null) { 4647 throw new IllegalArgumentException("Unknown package: " + packageName); 4648 } 4649 4650 final BasePermission bp = mSettings.mPermissions.get(name); 4651 if (bp == null) { 4652 throw new IllegalArgumentException("Unknown permission: " + name); 4653 } 4654 4655 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4656 4657 // If a permission review is required for legacy apps we represent 4658 // their permissions as always granted runtime ones since we need 4659 // to keep the review required permission flag per user while an 4660 // install permission's state is shared across all users. 4661 if (mPermissionReviewRequired 4662 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4663 && bp.isRuntime()) { 4664 return; 4665 } 4666 4667 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 4668 sb = (SettingBase) pkg.mExtras; 4669 if (sb == null) { 4670 throw new IllegalArgumentException("Unknown package: " + packageName); 4671 } 4672 4673 final PermissionsState permissionsState = sb.getPermissionsState(); 4674 4675 final int flags = permissionsState.getPermissionFlags(name, userId); 4676 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4677 throw new SecurityException("Cannot grant system fixed permission " 4678 + name + " for package " + packageName); 4679 } 4680 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) { 4681 throw new SecurityException("Cannot grant policy fixed permission " 4682 + name + " for package " + packageName); 4683 } 4684 4685 if (bp.isDevelopment()) { 4686 // Development permissions must be handled specially, since they are not 4687 // normal runtime permissions. For now they apply to all users. 4688 if (permissionsState.grantInstallPermission(bp) != 4689 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4690 scheduleWriteSettingsLocked(); 4691 } 4692 return; 4693 } 4694 4695 if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) { 4696 throw new SecurityException("Cannot grant non-ephemeral permission" 4697 + name + " for package " + packageName); 4698 } 4699 4700 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4701 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4702 return; 4703 } 4704 4705 final int result = permissionsState.grantRuntimePermission(bp, userId); 4706 switch (result) { 4707 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4708 return; 4709 } 4710 4711 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4712 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4713 mHandler.post(new Runnable() { 4714 @Override 4715 public void run() { 4716 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4717 } 4718 }); 4719 } 4720 break; 4721 } 4722 4723 if (bp.isRuntime()) { 4724 logPermissionGranted(mContext, name, packageName); 4725 } 4726 4727 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4728 4729 // Not critical if that is lost - app has to request again. 4730 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4731 } 4732 4733 // Only need to do this if user is initialized. Otherwise it's a new user 4734 // and there are no processes running as the user yet and there's no need 4735 // to make an expensive call to remount processes for the changed permissions. 4736 if (READ_EXTERNAL_STORAGE.equals(name) 4737 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4738 final long token = Binder.clearCallingIdentity(); 4739 try { 4740 if (sUserManager.isInitialized(userId)) { 4741 StorageManagerInternal storageManagerInternal = LocalServices.getService( 4742 StorageManagerInternal.class); 4743 storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName); 4744 } 4745 } finally { 4746 Binder.restoreCallingIdentity(token); 4747 } 4748 } 4749 } 4750 4751 @Override 4752 public void revokeRuntimePermission(String packageName, String name, int userId) { 4753 revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */); 4754 } 4755 4756 private void revokeRuntimePermission(String packageName, String name, int userId, 4757 boolean overridePolicy) { 4758 if (!sUserManager.exists(userId)) { 4759 Log.e(TAG, "No such user:" + userId); 4760 return; 4761 } 4762 4763 mContext.enforceCallingOrSelfPermission( 4764 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4765 "revokeRuntimePermission"); 4766 4767 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4768 true /* requireFullPermission */, true /* checkShell */, 4769 "revokeRuntimePermission"); 4770 4771 final int appId; 4772 4773 synchronized (mPackages) { 4774 final PackageParser.Package pkg = mPackages.get(packageName); 4775 if (pkg == null) { 4776 throw new IllegalArgumentException("Unknown package: " + packageName); 4777 } 4778 4779 final BasePermission bp = mSettings.mPermissions.get(name); 4780 if (bp == null) { 4781 throw new IllegalArgumentException("Unknown permission: " + name); 4782 } 4783 4784 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4785 4786 // If a permission review is required for legacy apps we represent 4787 // their permissions as always granted runtime ones since we need 4788 // to keep the review required permission flag per user while an 4789 // install permission's state is shared across all users. 4790 if (mPermissionReviewRequired 4791 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4792 && bp.isRuntime()) { 4793 return; 4794 } 4795 4796 SettingBase sb = (SettingBase) pkg.mExtras; 4797 if (sb == null) { 4798 throw new IllegalArgumentException("Unknown package: " + packageName); 4799 } 4800 4801 final PermissionsState permissionsState = sb.getPermissionsState(); 4802 4803 final int flags = permissionsState.getPermissionFlags(name, userId); 4804 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4805 throw new SecurityException("Cannot revoke system fixed permission " 4806 + name + " for package " + packageName); 4807 } 4808 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) { 4809 throw new SecurityException("Cannot revoke policy fixed permission " 4810 + name + " for package " + packageName); 4811 } 4812 4813 if (bp.isDevelopment()) { 4814 // Development permissions must be handled specially, since they are not 4815 // normal runtime permissions. For now they apply to all users. 4816 if (permissionsState.revokeInstallPermission(bp) != 4817 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4818 scheduleWriteSettingsLocked(); 4819 } 4820 return; 4821 } 4822 4823 if (permissionsState.revokeRuntimePermission(bp, userId) == 4824 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4825 return; 4826 } 4827 4828 if (bp.isRuntime()) { 4829 logPermissionRevoked(mContext, name, packageName); 4830 } 4831 4832 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4833 4834 // Critical, after this call app should never have the permission. 4835 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4836 4837 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4838 } 4839 4840 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4841 } 4842 4843 /** 4844 * Get the first event id for the permission. 4845 * 4846 * <p>There are four events for each permission: <ul> 4847 * <li>Request permission: first id + 0</li> 4848 * <li>Grant permission: first id + 1</li> 4849 * <li>Request for permission denied: first id + 2</li> 4850 * <li>Revoke permission: first id + 3</li> 4851 * </ul></p> 4852 * 4853 * @param name name of the permission 4854 * 4855 * @return The first event id for the permission 4856 */ 4857 private static int getBaseEventId(@NonNull String name) { 4858 int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name); 4859 4860 if (eventIdIndex == -1) { 4861 if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE 4862 || "user".equals(Build.TYPE)) { 4863 Log.i(TAG, "Unknown permission " + name); 4864 4865 return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN; 4866 } else { 4867 // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated. 4868 // 4869 // Also update 4870 // - EventLogger#ALL_DANGEROUS_PERMISSIONS 4871 // - metrics_constants.proto 4872 throw new IllegalStateException("Unknown permission " + name); 4873 } 4874 } 4875 4876 return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4; 4877 } 4878 4879 /** 4880 * Log that a permission was revoked. 4881 * 4882 * @param context Context of the caller 4883 * @param name name of the permission 4884 * @param packageName package permission if for 4885 */ 4886 private static void logPermissionRevoked(@NonNull Context context, @NonNull String name, 4887 @NonNull String packageName) { 4888 MetricsLogger.action(context, getBaseEventId(name) + 3, packageName); 4889 } 4890 4891 /** 4892 * Log that a permission request was granted. 4893 * 4894 * @param context Context of the caller 4895 * @param name name of the permission 4896 * @param packageName package permission if for 4897 */ 4898 private static void logPermissionGranted(@NonNull Context context, @NonNull String name, 4899 @NonNull String packageName) { 4900 MetricsLogger.action(context, getBaseEventId(name) + 1, packageName); 4901 } 4902 4903 @Override 4904 public void resetRuntimePermissions() { 4905 mContext.enforceCallingOrSelfPermission( 4906 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4907 "revokeRuntimePermission"); 4908 4909 int callingUid = Binder.getCallingUid(); 4910 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4911 mContext.enforceCallingOrSelfPermission( 4912 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4913 "resetRuntimePermissions"); 4914 } 4915 4916 synchronized (mPackages) { 4917 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4918 for (int userId : UserManagerService.getInstance().getUserIds()) { 4919 final int packageCount = mPackages.size(); 4920 for (int i = 0; i < packageCount; i++) { 4921 PackageParser.Package pkg = mPackages.valueAt(i); 4922 if (!(pkg.mExtras instanceof PackageSetting)) { 4923 continue; 4924 } 4925 PackageSetting ps = (PackageSetting) pkg.mExtras; 4926 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4927 } 4928 } 4929 } 4930 } 4931 4932 @Override 4933 public int getPermissionFlags(String name, String packageName, int userId) { 4934 if (!sUserManager.exists(userId)) { 4935 return 0; 4936 } 4937 4938 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4939 4940 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4941 true /* requireFullPermission */, false /* checkShell */, 4942 "getPermissionFlags"); 4943 4944 synchronized (mPackages) { 4945 final PackageParser.Package pkg = mPackages.get(packageName); 4946 if (pkg == null) { 4947 return 0; 4948 } 4949 4950 final BasePermission bp = mSettings.mPermissions.get(name); 4951 if (bp == null) { 4952 return 0; 4953 } 4954 4955 SettingBase sb = (SettingBase) pkg.mExtras; 4956 if (sb == null) { 4957 return 0; 4958 } 4959 4960 PermissionsState permissionsState = sb.getPermissionsState(); 4961 return permissionsState.getPermissionFlags(name, userId); 4962 } 4963 } 4964 4965 @Override 4966 public void updatePermissionFlags(String name, String packageName, int flagMask, 4967 int flagValues, int userId) { 4968 if (!sUserManager.exists(userId)) { 4969 return; 4970 } 4971 4972 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4973 4974 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4975 true /* requireFullPermission */, true /* checkShell */, 4976 "updatePermissionFlags"); 4977 4978 // Only the system can change these flags and nothing else. 4979 if (getCallingUid() != Process.SYSTEM_UID) { 4980 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4981 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4982 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4983 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4984 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4985 } 4986 4987 synchronized (mPackages) { 4988 final PackageParser.Package pkg = mPackages.get(packageName); 4989 if (pkg == null) { 4990 throw new IllegalArgumentException("Unknown package: " + packageName); 4991 } 4992 4993 final BasePermission bp = mSettings.mPermissions.get(name); 4994 if (bp == null) { 4995 throw new IllegalArgumentException("Unknown permission: " + name); 4996 } 4997 4998 SettingBase sb = (SettingBase) pkg.mExtras; 4999 if (sb == null) { 5000 throw new IllegalArgumentException("Unknown package: " + packageName); 5001 } 5002 5003 PermissionsState permissionsState = sb.getPermissionsState(); 5004 5005 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 5006 5007 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 5008 // Install and runtime permissions are stored in different places, 5009 // so figure out what permission changed and persist the change. 5010 if (permissionsState.getInstallPermissionState(name) != null) { 5011 scheduleWriteSettingsLocked(); 5012 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 5013 || hadState) { 5014 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 5015 } 5016 } 5017 } 5018 } 5019 5020 /** 5021 * Update the permission flags for all packages and runtime permissions of a user in order 5022 * to allow device or profile owner to remove POLICY_FIXED. 5023 */ 5024 @Override 5025 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 5026 if (!sUserManager.exists(userId)) { 5027 return; 5028 } 5029 5030 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 5031 5032 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5033 true /* requireFullPermission */, true /* checkShell */, 5034 "updatePermissionFlagsForAllApps"); 5035 5036 // Only the system can change system fixed flags. 5037 if (getCallingUid() != Process.SYSTEM_UID) { 5038 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5039 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5040 } 5041 5042 synchronized (mPackages) { 5043 boolean changed = false; 5044 final int packageCount = mPackages.size(); 5045 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 5046 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 5047 SettingBase sb = (SettingBase) pkg.mExtras; 5048 if (sb == null) { 5049 continue; 5050 } 5051 PermissionsState permissionsState = sb.getPermissionsState(); 5052 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 5053 userId, flagMask, flagValues); 5054 } 5055 if (changed) { 5056 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 5057 } 5058 } 5059 } 5060 5061 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 5062 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 5063 != PackageManager.PERMISSION_GRANTED 5064 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 5065 != PackageManager.PERMISSION_GRANTED) { 5066 throw new SecurityException(message + " requires " 5067 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 5068 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 5069 } 5070 } 5071 5072 @Override 5073 public boolean shouldShowRequestPermissionRationale(String permissionName, 5074 String packageName, int userId) { 5075 if (UserHandle.getCallingUserId() != userId) { 5076 mContext.enforceCallingPermission( 5077 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5078 "canShowRequestPermissionRationale for user " + userId); 5079 } 5080 5081 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 5082 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 5083 return false; 5084 } 5085 5086 if (checkPermission(permissionName, packageName, userId) 5087 == PackageManager.PERMISSION_GRANTED) { 5088 return false; 5089 } 5090 5091 final int flags; 5092 5093 final long identity = Binder.clearCallingIdentity(); 5094 try { 5095 flags = getPermissionFlags(permissionName, 5096 packageName, userId); 5097 } finally { 5098 Binder.restoreCallingIdentity(identity); 5099 } 5100 5101 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 5102 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 5103 | PackageManager.FLAG_PERMISSION_USER_FIXED; 5104 5105 if ((flags & fixedFlags) != 0) { 5106 return false; 5107 } 5108 5109 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 5110 } 5111 5112 @Override 5113 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 5114 mContext.enforceCallingOrSelfPermission( 5115 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 5116 "addOnPermissionsChangeListener"); 5117 5118 synchronized (mPackages) { 5119 mOnPermissionChangeListeners.addListenerLocked(listener); 5120 } 5121 } 5122 5123 @Override 5124 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 5125 synchronized (mPackages) { 5126 mOnPermissionChangeListeners.removeListenerLocked(listener); 5127 } 5128 } 5129 5130 @Override 5131 public boolean isProtectedBroadcast(String actionName) { 5132 synchronized (mPackages) { 5133 if (mProtectedBroadcasts.contains(actionName)) { 5134 return true; 5135 } else if (actionName != null) { 5136 // TODO: remove these terrible hacks 5137 if (actionName.startsWith("android.net.netmon.lingerExpired") 5138 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 5139 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 5140 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 5141 return true; 5142 } 5143 } 5144 } 5145 return false; 5146 } 5147 5148 @Override 5149 public int checkSignatures(String pkg1, String pkg2) { 5150 synchronized (mPackages) { 5151 final PackageParser.Package p1 = mPackages.get(pkg1); 5152 final PackageParser.Package p2 = mPackages.get(pkg2); 5153 if (p1 == null || p1.mExtras == null 5154 || p2 == null || p2.mExtras == null) { 5155 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5156 } 5157 return compareSignatures(p1.mSignatures, p2.mSignatures); 5158 } 5159 } 5160 5161 @Override 5162 public int checkUidSignatures(int uid1, int uid2) { 5163 // Map to base uids. 5164 uid1 = UserHandle.getAppId(uid1); 5165 uid2 = UserHandle.getAppId(uid2); 5166 // reader 5167 synchronized (mPackages) { 5168 Signature[] s1; 5169 Signature[] s2; 5170 Object obj = mSettings.getUserIdLPr(uid1); 5171 if (obj != null) { 5172 if (obj instanceof SharedUserSetting) { 5173 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 5174 } else if (obj instanceof PackageSetting) { 5175 s1 = ((PackageSetting)obj).signatures.mSignatures; 5176 } else { 5177 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5178 } 5179 } else { 5180 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5181 } 5182 obj = mSettings.getUserIdLPr(uid2); 5183 if (obj != null) { 5184 if (obj instanceof SharedUserSetting) { 5185 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 5186 } else if (obj instanceof PackageSetting) { 5187 s2 = ((PackageSetting)obj).signatures.mSignatures; 5188 } else { 5189 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5190 } 5191 } else { 5192 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5193 } 5194 return compareSignatures(s1, s2); 5195 } 5196 } 5197 5198 /** 5199 * This method should typically only be used when granting or revoking 5200 * permissions, since the app may immediately restart after this call. 5201 * <p> 5202 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 5203 * guard your work against the app being relaunched. 5204 */ 5205 private void killUid(int appId, int userId, String reason) { 5206 final long identity = Binder.clearCallingIdentity(); 5207 try { 5208 IActivityManager am = ActivityManager.getService(); 5209 if (am != null) { 5210 try { 5211 am.killUid(appId, userId, reason); 5212 } catch (RemoteException e) { 5213 /* ignore - same process */ 5214 } 5215 } 5216 } finally { 5217 Binder.restoreCallingIdentity(identity); 5218 } 5219 } 5220 5221 /** 5222 * Compares two sets of signatures. Returns: 5223 * <br /> 5224 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 5225 * <br /> 5226 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 5227 * <br /> 5228 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 5229 * <br /> 5230 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 5231 * <br /> 5232 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 5233 */ 5234 static int compareSignatures(Signature[] s1, Signature[] s2) { 5235 if (s1 == null) { 5236 return s2 == null 5237 ? PackageManager.SIGNATURE_NEITHER_SIGNED 5238 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 5239 } 5240 5241 if (s2 == null) { 5242 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 5243 } 5244 5245 if (s1.length != s2.length) { 5246 return PackageManager.SIGNATURE_NO_MATCH; 5247 } 5248 5249 // Since both signature sets are of size 1, we can compare without HashSets. 5250 if (s1.length == 1) { 5251 return s1[0].equals(s2[0]) ? 5252 PackageManager.SIGNATURE_MATCH : 5253 PackageManager.SIGNATURE_NO_MATCH; 5254 } 5255 5256 ArraySet<Signature> set1 = new ArraySet<Signature>(); 5257 for (Signature sig : s1) { 5258 set1.add(sig); 5259 } 5260 ArraySet<Signature> set2 = new ArraySet<Signature>(); 5261 for (Signature sig : s2) { 5262 set2.add(sig); 5263 } 5264 // Make sure s2 contains all signatures in s1. 5265 if (set1.equals(set2)) { 5266 return PackageManager.SIGNATURE_MATCH; 5267 } 5268 return PackageManager.SIGNATURE_NO_MATCH; 5269 } 5270 5271 /** 5272 * If the database version for this type of package (internal storage or 5273 * external storage) is less than the version where package signatures 5274 * were updated, return true. 5275 */ 5276 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 5277 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 5278 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 5279 } 5280 5281 /** 5282 * Used for backward compatibility to make sure any packages with 5283 * certificate chains get upgraded to the new style. {@code existingSigs} 5284 * will be in the old format (since they were stored on disk from before the 5285 * system upgrade) and {@code scannedSigs} will be in the newer format. 5286 */ 5287 private int compareSignaturesCompat(PackageSignatures existingSigs, 5288 PackageParser.Package scannedPkg) { 5289 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 5290 return PackageManager.SIGNATURE_NO_MATCH; 5291 } 5292 5293 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 5294 for (Signature sig : existingSigs.mSignatures) { 5295 existingSet.add(sig); 5296 } 5297 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 5298 for (Signature sig : scannedPkg.mSignatures) { 5299 try { 5300 Signature[] chainSignatures = sig.getChainSignatures(); 5301 for (Signature chainSig : chainSignatures) { 5302 scannedCompatSet.add(chainSig); 5303 } 5304 } catch (CertificateEncodingException e) { 5305 scannedCompatSet.add(sig); 5306 } 5307 } 5308 /* 5309 * Make sure the expanded scanned set contains all signatures in the 5310 * existing one. 5311 */ 5312 if (scannedCompatSet.equals(existingSet)) { 5313 // Migrate the old signatures to the new scheme. 5314 existingSigs.assignSignatures(scannedPkg.mSignatures); 5315 // The new KeySets will be re-added later in the scanning process. 5316 synchronized (mPackages) { 5317 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 5318 } 5319 return PackageManager.SIGNATURE_MATCH; 5320 } 5321 return PackageManager.SIGNATURE_NO_MATCH; 5322 } 5323 5324 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 5325 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 5326 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 5327 } 5328 5329 private int compareSignaturesRecover(PackageSignatures existingSigs, 5330 PackageParser.Package scannedPkg) { 5331 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 5332 return PackageManager.SIGNATURE_NO_MATCH; 5333 } 5334 5335 String msg = null; 5336 try { 5337 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 5338 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 5339 + scannedPkg.packageName); 5340 return PackageManager.SIGNATURE_MATCH; 5341 } 5342 } catch (CertificateException e) { 5343 msg = e.getMessage(); 5344 } 5345 5346 logCriticalInfo(Log.INFO, 5347 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 5348 return PackageManager.SIGNATURE_NO_MATCH; 5349 } 5350 5351 @Override 5352 public List<String> getAllPackages() { 5353 synchronized (mPackages) { 5354 return new ArrayList<String>(mPackages.keySet()); 5355 } 5356 } 5357 5358 @Override 5359 public String[] getPackagesForUid(int uid) { 5360 final int userId = UserHandle.getUserId(uid); 5361 uid = UserHandle.getAppId(uid); 5362 // reader 5363 synchronized (mPackages) { 5364 Object obj = mSettings.getUserIdLPr(uid); 5365 if (obj instanceof SharedUserSetting) { 5366 final SharedUserSetting sus = (SharedUserSetting) obj; 5367 final int N = sus.packages.size(); 5368 String[] res = new String[N]; 5369 final Iterator<PackageSetting> it = sus.packages.iterator(); 5370 int i = 0; 5371 while (it.hasNext()) { 5372 PackageSetting ps = it.next(); 5373 if (ps.getInstalled(userId)) { 5374 res[i++] = ps.name; 5375 } else { 5376 res = ArrayUtils.removeElement(String.class, res, res[i]); 5377 } 5378 } 5379 return res; 5380 } else if (obj instanceof PackageSetting) { 5381 final PackageSetting ps = (PackageSetting) obj; 5382 if (ps.getInstalled(userId)) { 5383 return new String[]{ps.name}; 5384 } 5385 } 5386 } 5387 return null; 5388 } 5389 5390 @Override 5391 public String getNameForUid(int uid) { 5392 // reader 5393 synchronized (mPackages) { 5394 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5395 if (obj instanceof SharedUserSetting) { 5396 final SharedUserSetting sus = (SharedUserSetting) obj; 5397 return sus.name + ":" + sus.userId; 5398 } else if (obj instanceof PackageSetting) { 5399 final PackageSetting ps = (PackageSetting) obj; 5400 return ps.name; 5401 } 5402 } 5403 return null; 5404 } 5405 5406 @Override 5407 public int getUidForSharedUser(String sharedUserName) { 5408 if(sharedUserName == null) { 5409 return -1; 5410 } 5411 // reader 5412 synchronized (mPackages) { 5413 SharedUserSetting suid; 5414 try { 5415 suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 5416 if (suid != null) { 5417 return suid.userId; 5418 } 5419 } catch (PackageManagerException ignore) { 5420 // can't happen, but, still need to catch it 5421 } 5422 return -1; 5423 } 5424 } 5425 5426 @Override 5427 public int getFlagsForUid(int uid) { 5428 synchronized (mPackages) { 5429 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5430 if (obj instanceof SharedUserSetting) { 5431 final SharedUserSetting sus = (SharedUserSetting) obj; 5432 return sus.pkgFlags; 5433 } else if (obj instanceof PackageSetting) { 5434 final PackageSetting ps = (PackageSetting) obj; 5435 return ps.pkgFlags; 5436 } 5437 } 5438 return 0; 5439 } 5440 5441 @Override 5442 public int getPrivateFlagsForUid(int uid) { 5443 synchronized (mPackages) { 5444 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5445 if (obj instanceof SharedUserSetting) { 5446 final SharedUserSetting sus = (SharedUserSetting) obj; 5447 return sus.pkgPrivateFlags; 5448 } else if (obj instanceof PackageSetting) { 5449 final PackageSetting ps = (PackageSetting) obj; 5450 return ps.pkgPrivateFlags; 5451 } 5452 } 5453 return 0; 5454 } 5455 5456 @Override 5457 public boolean isUidPrivileged(int uid) { 5458 uid = UserHandle.getAppId(uid); 5459 // reader 5460 synchronized (mPackages) { 5461 Object obj = mSettings.getUserIdLPr(uid); 5462 if (obj instanceof SharedUserSetting) { 5463 final SharedUserSetting sus = (SharedUserSetting) obj; 5464 final Iterator<PackageSetting> it = sus.packages.iterator(); 5465 while (it.hasNext()) { 5466 if (it.next().isPrivileged()) { 5467 return true; 5468 } 5469 } 5470 } else if (obj instanceof PackageSetting) { 5471 final PackageSetting ps = (PackageSetting) obj; 5472 return ps.isPrivileged(); 5473 } 5474 } 5475 return false; 5476 } 5477 5478 @Override 5479 public String[] getAppOpPermissionPackages(String permissionName) { 5480 synchronized (mPackages) { 5481 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 5482 if (pkgs == null) { 5483 return null; 5484 } 5485 return pkgs.toArray(new String[pkgs.size()]); 5486 } 5487 } 5488 5489 @Override 5490 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 5491 int flags, int userId) { 5492 try { 5493 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 5494 5495 if (!sUserManager.exists(userId)) return null; 5496 flags = updateFlagsForResolve(flags, userId, intent); 5497 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5498 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 5499 5500 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5501 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 5502 flags, userId); 5503 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5504 5505 final ResolveInfo bestChoice = 5506 chooseBestActivity(intent, resolvedType, flags, query, userId); 5507 return bestChoice; 5508 } finally { 5509 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5510 } 5511 } 5512 5513 @Override 5514 public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) { 5515 if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) { 5516 throw new SecurityException( 5517 "findPersistentPreferredActivity can only be run by the system"); 5518 } 5519 if (!sUserManager.exists(userId)) { 5520 return null; 5521 } 5522 intent = updateIntentForResolve(intent); 5523 final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver()); 5524 final int flags = updateFlagsForResolve(0, userId, intent); 5525 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5526 userId); 5527 synchronized (mPackages) { 5528 return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false, 5529 userId); 5530 } 5531 } 5532 5533 @Override 5534 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 5535 IntentFilter filter, int match, ComponentName activity) { 5536 final int userId = UserHandle.getCallingUserId(); 5537 if (DEBUG_PREFERRED) { 5538 Log.v(TAG, "setLastChosenActivity intent=" + intent 5539 + " resolvedType=" + resolvedType 5540 + " flags=" + flags 5541 + " filter=" + filter 5542 + " match=" + match 5543 + " activity=" + activity); 5544 filter.dump(new PrintStreamPrinter(System.out), " "); 5545 } 5546 intent.setComponent(null); 5547 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5548 userId); 5549 // Find any earlier preferred or last chosen entries and nuke them 5550 findPreferredActivity(intent, resolvedType, 5551 flags, query, 0, false, true, false, userId); 5552 // Add the new activity as the last chosen for this filter 5553 addPreferredActivityInternal(filter, match, null, activity, false, userId, 5554 "Setting last chosen"); 5555 } 5556 5557 @Override 5558 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 5559 final int userId = UserHandle.getCallingUserId(); 5560 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 5561 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5562 userId); 5563 return findPreferredActivity(intent, resolvedType, flags, query, 0, 5564 false, false, false, userId); 5565 } 5566 5567 private boolean isEphemeralDisabled() { 5568 // ephemeral apps have been disabled across the board 5569 if (DISABLE_EPHEMERAL_APPS) { 5570 return true; 5571 } 5572 // system isn't up yet; can't read settings, so, assume no ephemeral apps 5573 if (!mSystemReady) { 5574 return true; 5575 } 5576 // we can't get a content resolver until the system is ready; these checks must happen last 5577 final ContentResolver resolver = mContext.getContentResolver(); 5578 if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) { 5579 return true; 5580 } 5581 return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0; 5582 } 5583 5584 private boolean isEphemeralAllowed( 5585 Intent intent, List<ResolveInfo> resolvedActivities, int userId, 5586 boolean skipPackageCheck) { 5587 // Short circuit and return early if possible. 5588 if (isEphemeralDisabled()) { 5589 return false; 5590 } 5591 final int callingUser = UserHandle.getCallingUserId(); 5592 if (callingUser != UserHandle.USER_SYSTEM) { 5593 return false; 5594 } 5595 if (mEphemeralResolverConnection == null) { 5596 return false; 5597 } 5598 if (mEphemeralInstallerComponent == null) { 5599 return false; 5600 } 5601 if (intent.getComponent() != null) { 5602 return false; 5603 } 5604 if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) { 5605 return false; 5606 } 5607 if (!skipPackageCheck && intent.getPackage() != null) { 5608 return false; 5609 } 5610 final boolean isWebUri = hasWebURI(intent); 5611 if (!isWebUri || intent.getData().getHost() == null) { 5612 return false; 5613 } 5614 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 5615 synchronized (mPackages) { 5616 final int count = (resolvedActivities == null ? 0 : resolvedActivities.size()); 5617 for (int n = 0; n < count; n++) { 5618 ResolveInfo info = resolvedActivities.get(n); 5619 String packageName = info.activityInfo.packageName; 5620 PackageSetting ps = mSettings.mPackages.get(packageName); 5621 if (ps != null) { 5622 // Try to get the status from User settings first 5623 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5624 int status = (int) (packedStatus >> 32); 5625 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 5626 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5627 if (DEBUG_EPHEMERAL) { 5628 Slog.v(TAG, "DENY ephemeral apps;" 5629 + " pkg: " + packageName + ", status: " + status); 5630 } 5631 return false; 5632 } 5633 } 5634 } 5635 } 5636 // We've exhausted all ways to deny ephemeral application; let the system look for them. 5637 return true; 5638 } 5639 5640 private void requestEphemeralResolutionPhaseTwo(EphemeralResponse responseObj, 5641 Intent origIntent, String resolvedType, Intent launchIntent, String callingPackage, 5642 int userId) { 5643 final Message msg = mHandler.obtainMessage(EPHEMERAL_RESOLUTION_PHASE_TWO, 5644 new EphemeralRequest(responseObj, origIntent, resolvedType, launchIntent, 5645 callingPackage, userId)); 5646 mHandler.sendMessage(msg); 5647 } 5648 5649 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 5650 int flags, List<ResolveInfo> query, int userId) { 5651 if (query != null) { 5652 final int N = query.size(); 5653 if (N == 1) { 5654 return query.get(0); 5655 } else if (N > 1) { 5656 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 5657 // If there is more than one activity with the same priority, 5658 // then let the user decide between them. 5659 ResolveInfo r0 = query.get(0); 5660 ResolveInfo r1 = query.get(1); 5661 if (DEBUG_INTENT_MATCHING || debug) { 5662 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 5663 + r1.activityInfo.name + "=" + r1.priority); 5664 } 5665 // If the first activity has a higher priority, or a different 5666 // default, then it is always desirable to pick it. 5667 if (r0.priority != r1.priority 5668 || r0.preferredOrder != r1.preferredOrder 5669 || r0.isDefault != r1.isDefault) { 5670 return query.get(0); 5671 } 5672 // If we have saved a preference for a preferred activity for 5673 // this Intent, use that. 5674 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 5675 flags, query, r0.priority, true, false, debug, userId); 5676 if (ri != null) { 5677 return ri; 5678 } 5679 ri = new ResolveInfo(mResolveInfo); 5680 ri.activityInfo = new ActivityInfo(ri.activityInfo); 5681 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 5682 // If all of the options come from the same package, show the application's 5683 // label and icon instead of the generic resolver's. 5684 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 5685 // and then throw away the ResolveInfo itself, meaning that the caller loses 5686 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 5687 // a fallback for this case; we only set the target package's resources on 5688 // the ResolveInfo, not the ActivityInfo. 5689 final String intentPackage = intent.getPackage(); 5690 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 5691 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 5692 ri.resolvePackageName = intentPackage; 5693 if (userNeedsBadging(userId)) { 5694 ri.noResourceId = true; 5695 } else { 5696 ri.icon = appi.icon; 5697 } 5698 ri.iconResourceId = appi.icon; 5699 ri.labelRes = appi.labelRes; 5700 } 5701 ri.activityInfo.applicationInfo = new ApplicationInfo( 5702 ri.activityInfo.applicationInfo); 5703 if (userId != 0) { 5704 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 5705 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 5706 } 5707 // Make sure that the resolver is displayable in car mode 5708 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 5709 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 5710 return ri; 5711 } 5712 } 5713 return null; 5714 } 5715 5716 /** 5717 * Return true if the given list is not empty and all of its contents have 5718 * an activityInfo with the given package name. 5719 */ 5720 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 5721 if (ArrayUtils.isEmpty(list)) { 5722 return false; 5723 } 5724 for (int i = 0, N = list.size(); i < N; i++) { 5725 final ResolveInfo ri = list.get(i); 5726 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 5727 if (ai == null || !packageName.equals(ai.packageName)) { 5728 return false; 5729 } 5730 } 5731 return true; 5732 } 5733 5734 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 5735 int flags, List<ResolveInfo> query, boolean debug, int userId) { 5736 final int N = query.size(); 5737 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 5738 .get(userId); 5739 // Get the list of persistent preferred activities that handle the intent 5740 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 5741 List<PersistentPreferredActivity> pprefs = ppir != null 5742 ? ppir.queryIntent(intent, resolvedType, 5743 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 5744 (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0, 5745 (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId) 5746 : null; 5747 if (pprefs != null && pprefs.size() > 0) { 5748 final int M = pprefs.size(); 5749 for (int i=0; i<M; i++) { 5750 final PersistentPreferredActivity ppa = pprefs.get(i); 5751 if (DEBUG_PREFERRED || debug) { 5752 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 5753 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 5754 + "\n component=" + ppa.mComponent); 5755 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5756 } 5757 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 5758 flags | MATCH_DISABLED_COMPONENTS, userId); 5759 if (DEBUG_PREFERRED || debug) { 5760 Slog.v(TAG, "Found persistent preferred activity:"); 5761 if (ai != null) { 5762 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5763 } else { 5764 Slog.v(TAG, " null"); 5765 } 5766 } 5767 if (ai == null) { 5768 // This previously registered persistent preferred activity 5769 // component is no longer known. Ignore it and do NOT remove it. 5770 continue; 5771 } 5772 for (int j=0; j<N; j++) { 5773 final ResolveInfo ri = query.get(j); 5774 if (!ri.activityInfo.applicationInfo.packageName 5775 .equals(ai.applicationInfo.packageName)) { 5776 continue; 5777 } 5778 if (!ri.activityInfo.name.equals(ai.name)) { 5779 continue; 5780 } 5781 // Found a persistent preference that can handle the intent. 5782 if (DEBUG_PREFERRED || debug) { 5783 Slog.v(TAG, "Returning persistent preferred activity: " + 5784 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5785 } 5786 return ri; 5787 } 5788 } 5789 } 5790 return null; 5791 } 5792 5793 // TODO: handle preferred activities missing while user has amnesia 5794 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5795 List<ResolveInfo> query, int priority, boolean always, 5796 boolean removeMatches, boolean debug, int userId) { 5797 if (!sUserManager.exists(userId)) return null; 5798 flags = updateFlagsForResolve(flags, userId, intent); 5799 intent = updateIntentForResolve(intent); 5800 // writer 5801 synchronized (mPackages) { 5802 // Try to find a matching persistent preferred activity. 5803 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5804 debug, userId); 5805 5806 // If a persistent preferred activity matched, use it. 5807 if (pri != null) { 5808 return pri; 5809 } 5810 5811 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5812 // Get the list of preferred activities that handle the intent 5813 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5814 List<PreferredActivity> prefs = pir != null 5815 ? pir.queryIntent(intent, resolvedType, 5816 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 5817 (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0, 5818 (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId) 5819 : null; 5820 if (prefs != null && prefs.size() > 0) { 5821 boolean changed = false; 5822 try { 5823 // First figure out how good the original match set is. 5824 // We will only allow preferred activities that came 5825 // from the same match quality. 5826 int match = 0; 5827 5828 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5829 5830 final int N = query.size(); 5831 for (int j=0; j<N; j++) { 5832 final ResolveInfo ri = query.get(j); 5833 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5834 + ": 0x" + Integer.toHexString(match)); 5835 if (ri.match > match) { 5836 match = ri.match; 5837 } 5838 } 5839 5840 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5841 + Integer.toHexString(match)); 5842 5843 match &= IntentFilter.MATCH_CATEGORY_MASK; 5844 final int M = prefs.size(); 5845 for (int i=0; i<M; i++) { 5846 final PreferredActivity pa = prefs.get(i); 5847 if (DEBUG_PREFERRED || debug) { 5848 Slog.v(TAG, "Checking PreferredActivity ds=" 5849 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5850 + "\n component=" + pa.mPref.mComponent); 5851 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5852 } 5853 if (pa.mPref.mMatch != match) { 5854 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5855 + Integer.toHexString(pa.mPref.mMatch)); 5856 continue; 5857 } 5858 // If it's not an "always" type preferred activity and that's what we're 5859 // looking for, skip it. 5860 if (always && !pa.mPref.mAlways) { 5861 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5862 continue; 5863 } 5864 final ActivityInfo ai = getActivityInfo( 5865 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5866 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5867 userId); 5868 if (DEBUG_PREFERRED || debug) { 5869 Slog.v(TAG, "Found preferred activity:"); 5870 if (ai != null) { 5871 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5872 } else { 5873 Slog.v(TAG, " null"); 5874 } 5875 } 5876 if (ai == null) { 5877 // This previously registered preferred activity 5878 // component is no longer known. Most likely an update 5879 // to the app was installed and in the new version this 5880 // component no longer exists. Clean it up by removing 5881 // it from the preferred activities list, and skip it. 5882 Slog.w(TAG, "Removing dangling preferred activity: " 5883 + pa.mPref.mComponent); 5884 pir.removeFilter(pa); 5885 changed = true; 5886 continue; 5887 } 5888 for (int j=0; j<N; j++) { 5889 final ResolveInfo ri = query.get(j); 5890 if (!ri.activityInfo.applicationInfo.packageName 5891 .equals(ai.applicationInfo.packageName)) { 5892 continue; 5893 } 5894 if (!ri.activityInfo.name.equals(ai.name)) { 5895 continue; 5896 } 5897 5898 if (removeMatches) { 5899 pir.removeFilter(pa); 5900 changed = true; 5901 if (DEBUG_PREFERRED) { 5902 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 5903 } 5904 break; 5905 } 5906 5907 // Okay we found a previously set preferred or last chosen app. 5908 // If the result set is different from when this 5909 // was created, we need to clear it and re-ask the 5910 // user their preference, if we're looking for an "always" type entry. 5911 if (always && !pa.mPref.sameSet(query)) { 5912 Slog.i(TAG, "Result set changed, dropping preferred activity for " 5913 + intent + " type " + resolvedType); 5914 if (DEBUG_PREFERRED) { 5915 Slog.v(TAG, "Removing preferred activity since set changed " 5916 + pa.mPref.mComponent); 5917 } 5918 pir.removeFilter(pa); 5919 // Re-add the filter as a "last chosen" entry (!always) 5920 PreferredActivity lastChosen = new PreferredActivity( 5921 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 5922 pir.addFilter(lastChosen); 5923 changed = true; 5924 return null; 5925 } 5926 5927 // Yay! Either the set matched or we're looking for the last chosen 5928 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 5929 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5930 return ri; 5931 } 5932 } 5933 } finally { 5934 if (changed) { 5935 if (DEBUG_PREFERRED) { 5936 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 5937 } 5938 scheduleWritePackageRestrictionsLocked(userId); 5939 } 5940 } 5941 } 5942 } 5943 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 5944 return null; 5945 } 5946 5947 /* 5948 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 5949 */ 5950 @Override 5951 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 5952 int targetUserId) { 5953 mContext.enforceCallingOrSelfPermission( 5954 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 5955 List<CrossProfileIntentFilter> matches = 5956 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 5957 if (matches != null) { 5958 int size = matches.size(); 5959 for (int i = 0; i < size; i++) { 5960 if (matches.get(i).getTargetUserId() == targetUserId) return true; 5961 } 5962 } 5963 if (hasWebURI(intent)) { 5964 // cross-profile app linking works only towards the parent. 5965 final UserInfo parent = getProfileParent(sourceUserId); 5966 synchronized(mPackages) { 5967 int flags = updateFlagsForResolve(0, parent.id, intent); 5968 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5969 intent, resolvedType, flags, sourceUserId, parent.id); 5970 return xpDomainInfo != null; 5971 } 5972 } 5973 return false; 5974 } 5975 5976 private UserInfo getProfileParent(int userId) { 5977 final long identity = Binder.clearCallingIdentity(); 5978 try { 5979 return sUserManager.getProfileParent(userId); 5980 } finally { 5981 Binder.restoreCallingIdentity(identity); 5982 } 5983 } 5984 5985 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5986 String resolvedType, int userId) { 5987 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5988 if (resolver != null) { 5989 return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, 5990 false /*visibleToEphemeral*/, false /*isInstant*/, userId); 5991 } 5992 return null; 5993 } 5994 5995 @Override 5996 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 5997 String resolvedType, int flags, int userId) { 5998 try { 5999 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 6000 6001 return new ParceledListSlice<>( 6002 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 6003 } finally { 6004 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6005 } 6006 } 6007 6008 /** 6009 * Returns the package name of the calling Uid if it's an ephemeral app. If it isn't 6010 * ephemeral, returns {@code null}. 6011 */ 6012 private String getEphemeralPackageName(int callingUid) { 6013 final int appId = UserHandle.getAppId(callingUid); 6014 synchronized (mPackages) { 6015 final Object obj = mSettings.getUserIdLPr(appId); 6016 if (obj instanceof PackageSetting) { 6017 final PackageSetting ps = (PackageSetting) obj; 6018 return ps.pkg.applicationInfo.isInstantApp() ? ps.pkg.packageName : null; 6019 } 6020 } 6021 return null; 6022 } 6023 6024 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 6025 String resolvedType, int flags, int userId) { 6026 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6027 final String ephemeralPkgName = getEphemeralPackageName(Binder.getCallingUid()); 6028 flags = updateFlagsForResolve(flags, userId, intent); 6029 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6030 false /* requireFullPermission */, false /* checkShell */, 6031 "query intent activities"); 6032 ComponentName comp = intent.getComponent(); 6033 if (comp == null) { 6034 if (intent.getSelector() != null) { 6035 intent = intent.getSelector(); 6036 comp = intent.getComponent(); 6037 } 6038 } 6039 6040 if (comp != null) { 6041 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6042 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 6043 if (ai != null) { 6044 // When specifying an explicit component, we prevent the activity from being 6045 // used when either 1) the calling package is normal and the activity is within 6046 // an ephemeral application or 2) the calling package is ephemeral and the 6047 // activity is not visible to ephemeral applications. 6048 boolean matchEphemeral = 6049 (flags & PackageManager.MATCH_EPHEMERAL) != 0; 6050 boolean ephemeralVisibleOnly = 6051 (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0; 6052 boolean blockResolution = 6053 (!matchEphemeral && ephemeralPkgName == null 6054 && (ai.applicationInfo.privateFlags 6055 & ApplicationInfo.PRIVATE_FLAG_EPHEMERAL) != 0) 6056 || (ephemeralVisibleOnly && ephemeralPkgName != null 6057 && (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0); 6058 if (!blockResolution) { 6059 final ResolveInfo ri = new ResolveInfo(); 6060 ri.activityInfo = ai; 6061 list.add(ri); 6062 } 6063 } 6064 return list; 6065 } 6066 6067 // reader 6068 boolean sortResult = false; 6069 boolean addEphemeral = false; 6070 List<ResolveInfo> result; 6071 final String pkgName = intent.getPackage(); 6072 synchronized (mPackages) { 6073 if (pkgName == null) { 6074 List<CrossProfileIntentFilter> matchingFilters = 6075 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 6076 // Check for results that need to skip the current profile. 6077 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 6078 resolvedType, flags, userId); 6079 if (xpResolveInfo != null) { 6080 List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1); 6081 xpResult.add(xpResolveInfo); 6082 return filterForEphemeral( 6083 filterIfNotSystemUser(xpResult, userId), ephemeralPkgName); 6084 } 6085 6086 // Check for results in the current profile. 6087 result = filterIfNotSystemUser(mActivities.queryIntent( 6088 intent, resolvedType, flags, userId), userId); 6089 addEphemeral = 6090 isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/); 6091 6092 // Check for cross profile results. 6093 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 6094 xpResolveInfo = queryCrossProfileIntents( 6095 matchingFilters, intent, resolvedType, flags, userId, 6096 hasNonNegativePriorityResult); 6097 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 6098 boolean isVisibleToUser = filterIfNotSystemUser( 6099 Collections.singletonList(xpResolveInfo), userId).size() > 0; 6100 if (isVisibleToUser) { 6101 result.add(xpResolveInfo); 6102 sortResult = true; 6103 } 6104 } 6105 if (hasWebURI(intent)) { 6106 CrossProfileDomainInfo xpDomainInfo = null; 6107 final UserInfo parent = getProfileParent(userId); 6108 if (parent != null) { 6109 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 6110 flags, userId, parent.id); 6111 } 6112 if (xpDomainInfo != null) { 6113 if (xpResolveInfo != null) { 6114 // If we didn't remove it, the cross-profile ResolveInfo would be twice 6115 // in the result. 6116 result.remove(xpResolveInfo); 6117 } 6118 if (result.size() == 0 && !addEphemeral) { 6119 // No result in current profile, but found candidate in parent user. 6120 // And we are not going to add emphemeral app, so we can return the 6121 // result straight away. 6122 result.add(xpDomainInfo.resolveInfo); 6123 return filterForEphemeral(result, ephemeralPkgName); 6124 } 6125 } else if (result.size() <= 1 && !addEphemeral) { 6126 // No result in parent user and <= 1 result in current profile, and we 6127 // are not going to add emphemeral app, so we can return the result without 6128 // further processing. 6129 return filterForEphemeral(result, ephemeralPkgName); 6130 } 6131 // We have more than one candidate (combining results from current and parent 6132 // profile), so we need filtering and sorting. 6133 result = filterCandidatesWithDomainPreferredActivitiesLPr( 6134 intent, flags, result, xpDomainInfo, userId); 6135 sortResult = true; 6136 } 6137 } else { 6138 final PackageParser.Package pkg = mPackages.get(pkgName); 6139 if (pkg != null) { 6140 result = filterForEphemeral(filterIfNotSystemUser( 6141 mActivities.queryIntentForPackage( 6142 intent, resolvedType, flags, pkg.activities, userId), 6143 userId), ephemeralPkgName); 6144 } else { 6145 // the caller wants to resolve for a particular package; however, there 6146 // were no installed results, so, try to find an ephemeral result 6147 addEphemeral = isEphemeralAllowed( 6148 intent, null /*result*/, userId, true /*skipPackageCheck*/); 6149 result = new ArrayList<ResolveInfo>(); 6150 } 6151 } 6152 } 6153 if (addEphemeral) { 6154 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 6155 final EphemeralRequest requestObject = new EphemeralRequest( 6156 null /*responseObj*/, intent /*origIntent*/, resolvedType, 6157 null /*launchIntent*/, null /*callingPackage*/, userId); 6158 final EphemeralResponse intentInfo = EphemeralResolver.doEphemeralResolutionPhaseOne( 6159 mContext, mEphemeralResolverConnection, requestObject); 6160 if (intentInfo != null) { 6161 if (DEBUG_EPHEMERAL) { 6162 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 6163 } 6164 final ResolveInfo ephemeralInstaller = new ResolveInfo(mEphemeralInstallerInfo); 6165 ephemeralInstaller.ephemeralResponse = intentInfo; 6166 // make sure this resolver is the default 6167 ephemeralInstaller.isDefault = true; 6168 ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 6169 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 6170 // add a non-generic filter 6171 ephemeralInstaller.filter = new IntentFilter(intent.getAction()); 6172 ephemeralInstaller.filter.addDataPath( 6173 intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL); 6174 result.add(ephemeralInstaller); 6175 } 6176 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6177 } 6178 if (sortResult) { 6179 Collections.sort(result, mResolvePrioritySorter); 6180 } 6181 return filterForEphemeral(result, ephemeralPkgName); 6182 } 6183 6184 private static class CrossProfileDomainInfo { 6185 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 6186 ResolveInfo resolveInfo; 6187 /* Best domain verification status of the activities found in the other profile */ 6188 int bestDomainVerificationStatus; 6189 } 6190 6191 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 6192 String resolvedType, int flags, int sourceUserId, int parentUserId) { 6193 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 6194 sourceUserId)) { 6195 return null; 6196 } 6197 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 6198 resolvedType, flags, parentUserId); 6199 6200 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 6201 return null; 6202 } 6203 CrossProfileDomainInfo result = null; 6204 int size = resultTargetUser.size(); 6205 for (int i = 0; i < size; i++) { 6206 ResolveInfo riTargetUser = resultTargetUser.get(i); 6207 // Intent filter verification is only for filters that specify a host. So don't return 6208 // those that handle all web uris. 6209 if (riTargetUser.handleAllWebDataURI) { 6210 continue; 6211 } 6212 String packageName = riTargetUser.activityInfo.packageName; 6213 PackageSetting ps = mSettings.mPackages.get(packageName); 6214 if (ps == null) { 6215 continue; 6216 } 6217 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 6218 int status = (int)(verificationState >> 32); 6219 if (result == null) { 6220 result = new CrossProfileDomainInfo(); 6221 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 6222 sourceUserId, parentUserId); 6223 result.bestDomainVerificationStatus = status; 6224 } else { 6225 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 6226 result.bestDomainVerificationStatus); 6227 } 6228 } 6229 // Don't consider matches with status NEVER across profiles. 6230 if (result != null && result.bestDomainVerificationStatus 6231 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6232 return null; 6233 } 6234 return result; 6235 } 6236 6237 /** 6238 * Verification statuses are ordered from the worse to the best, except for 6239 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 6240 */ 6241 private int bestDomainVerificationStatus(int status1, int status2) { 6242 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6243 return status2; 6244 } 6245 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6246 return status1; 6247 } 6248 return (int) MathUtils.max(status1, status2); 6249 } 6250 6251 private boolean isUserEnabled(int userId) { 6252 long callingId = Binder.clearCallingIdentity(); 6253 try { 6254 UserInfo userInfo = sUserManager.getUserInfo(userId); 6255 return userInfo != null && userInfo.isEnabled(); 6256 } finally { 6257 Binder.restoreCallingIdentity(callingId); 6258 } 6259 } 6260 6261 /** 6262 * Filter out activities with systemUserOnly flag set, when current user is not System. 6263 * 6264 * @return filtered list 6265 */ 6266 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 6267 if (userId == UserHandle.USER_SYSTEM) { 6268 return resolveInfos; 6269 } 6270 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 6271 ResolveInfo info = resolveInfos.get(i); 6272 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 6273 resolveInfos.remove(i); 6274 } 6275 } 6276 return resolveInfos; 6277 } 6278 6279 /** 6280 * Filters out ephemeral activities. 6281 * <p>When resolving for an ephemeral app, only activities that 1) are defined in the 6282 * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned. 6283 * 6284 * @param resolveInfos The pre-filtered list of resolved activities 6285 * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering 6286 * is performed. 6287 * @return A filtered list of resolved activities. 6288 */ 6289 private List<ResolveInfo> filterForEphemeral(List<ResolveInfo> resolveInfos, 6290 String ephemeralPkgName) { 6291 if (ephemeralPkgName == null) { 6292 return resolveInfos; 6293 } 6294 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 6295 ResolveInfo info = resolveInfos.get(i); 6296 final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp(); 6297 // allow activities that are defined in the provided package 6298 if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) { 6299 continue; 6300 } 6301 // allow activities that have been explicitly exposed to ephemeral apps 6302 if (!isEphemeralApp 6303 && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) { 6304 continue; 6305 } 6306 resolveInfos.remove(i); 6307 } 6308 return resolveInfos; 6309 } 6310 6311 /** 6312 * @param resolveInfos list of resolve infos in descending priority order 6313 * @return if the list contains a resolve info with non-negative priority 6314 */ 6315 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 6316 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 6317 } 6318 6319 private static boolean hasWebURI(Intent intent) { 6320 if (intent.getData() == null) { 6321 return false; 6322 } 6323 final String scheme = intent.getScheme(); 6324 if (TextUtils.isEmpty(scheme)) { 6325 return false; 6326 } 6327 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 6328 } 6329 6330 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 6331 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 6332 int userId) { 6333 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 6334 6335 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 6336 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 6337 candidates.size()); 6338 } 6339 6340 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 6341 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 6342 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 6343 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 6344 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 6345 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 6346 6347 synchronized (mPackages) { 6348 final int count = candidates.size(); 6349 // First, try to use linked apps. Partition the candidates into four lists: 6350 // one for the final results, one for the "do not use ever", one for "undefined status" 6351 // and finally one for "browser app type". 6352 for (int n=0; n<count; n++) { 6353 ResolveInfo info = candidates.get(n); 6354 String packageName = info.activityInfo.packageName; 6355 PackageSetting ps = mSettings.mPackages.get(packageName); 6356 if (ps != null) { 6357 // Add to the special match all list (Browser use case) 6358 if (info.handleAllWebDataURI) { 6359 matchAllList.add(info); 6360 continue; 6361 } 6362 // Try to get the status from User settings first 6363 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 6364 int status = (int)(packedStatus >> 32); 6365 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 6366 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 6367 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6368 Slog.i(TAG, " + always: " + info.activityInfo.packageName 6369 + " : linkgen=" + linkGeneration); 6370 } 6371 // Use link-enabled generation as preferredOrder, i.e. 6372 // prefer newly-enabled over earlier-enabled. 6373 info.preferredOrder = linkGeneration; 6374 alwaysList.add(info); 6375 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6376 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6377 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 6378 } 6379 neverList.add(info); 6380 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 6381 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6382 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 6383 } 6384 alwaysAskList.add(info); 6385 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 6386 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 6387 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6388 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 6389 } 6390 undefinedList.add(info); 6391 } 6392 } 6393 } 6394 6395 // We'll want to include browser possibilities in a few cases 6396 boolean includeBrowser = false; 6397 6398 // First try to add the "always" resolution(s) for the current user, if any 6399 if (alwaysList.size() > 0) { 6400 result.addAll(alwaysList); 6401 } else { 6402 // Add all undefined apps as we want them to appear in the disambiguation dialog. 6403 result.addAll(undefinedList); 6404 // Maybe add one for the other profile. 6405 if (xpDomainInfo != null && ( 6406 xpDomainInfo.bestDomainVerificationStatus 6407 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 6408 result.add(xpDomainInfo.resolveInfo); 6409 } 6410 includeBrowser = true; 6411 } 6412 6413 // The presence of any 'always ask' alternatives means we'll also offer browsers. 6414 // If there were 'always' entries their preferred order has been set, so we also 6415 // back that off to make the alternatives equivalent 6416 if (alwaysAskList.size() > 0) { 6417 for (ResolveInfo i : result) { 6418 i.preferredOrder = 0; 6419 } 6420 result.addAll(alwaysAskList); 6421 includeBrowser = true; 6422 } 6423 6424 if (includeBrowser) { 6425 // Also add browsers (all of them or only the default one) 6426 if (DEBUG_DOMAIN_VERIFICATION) { 6427 Slog.v(TAG, " ...including browsers in candidate set"); 6428 } 6429 if ((matchFlags & MATCH_ALL) != 0) { 6430 result.addAll(matchAllList); 6431 } else { 6432 // Browser/generic handling case. If there's a default browser, go straight 6433 // to that (but only if there is no other higher-priority match). 6434 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 6435 int maxMatchPrio = 0; 6436 ResolveInfo defaultBrowserMatch = null; 6437 final int numCandidates = matchAllList.size(); 6438 for (int n = 0; n < numCandidates; n++) { 6439 ResolveInfo info = matchAllList.get(n); 6440 // track the highest overall match priority... 6441 if (info.priority > maxMatchPrio) { 6442 maxMatchPrio = info.priority; 6443 } 6444 // ...and the highest-priority default browser match 6445 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 6446 if (defaultBrowserMatch == null 6447 || (defaultBrowserMatch.priority < info.priority)) { 6448 if (debug) { 6449 Slog.v(TAG, "Considering default browser match " + info); 6450 } 6451 defaultBrowserMatch = info; 6452 } 6453 } 6454 } 6455 if (defaultBrowserMatch != null 6456 && defaultBrowserMatch.priority >= maxMatchPrio 6457 && !TextUtils.isEmpty(defaultBrowserPackageName)) 6458 { 6459 if (debug) { 6460 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 6461 } 6462 result.add(defaultBrowserMatch); 6463 } else { 6464 result.addAll(matchAllList); 6465 } 6466 } 6467 6468 // If there is nothing selected, add all candidates and remove the ones that the user 6469 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 6470 if (result.size() == 0) { 6471 result.addAll(candidates); 6472 result.removeAll(neverList); 6473 } 6474 } 6475 } 6476 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 6477 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 6478 result.size()); 6479 for (ResolveInfo info : result) { 6480 Slog.v(TAG, " + " + info.activityInfo); 6481 } 6482 } 6483 return result; 6484 } 6485 6486 // Returns a packed value as a long: 6487 // 6488 // high 'int'-sized word: link status: undefined/ask/never/always. 6489 // low 'int'-sized word: relative priority among 'always' results. 6490 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 6491 long result = ps.getDomainVerificationStatusForUser(userId); 6492 // if none available, get the master status 6493 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 6494 if (ps.getIntentFilterVerificationInfo() != null) { 6495 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 6496 } 6497 } 6498 return result; 6499 } 6500 6501 private ResolveInfo querySkipCurrentProfileIntents( 6502 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 6503 int flags, int sourceUserId) { 6504 if (matchingFilters != null) { 6505 int size = matchingFilters.size(); 6506 for (int i = 0; i < size; i ++) { 6507 CrossProfileIntentFilter filter = matchingFilters.get(i); 6508 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 6509 // Checking if there are activities in the target user that can handle the 6510 // intent. 6511 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 6512 resolvedType, flags, sourceUserId); 6513 if (resolveInfo != null) { 6514 return resolveInfo; 6515 } 6516 } 6517 } 6518 } 6519 return null; 6520 } 6521 6522 // Return matching ResolveInfo in target user if any. 6523 private ResolveInfo queryCrossProfileIntents( 6524 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 6525 int flags, int sourceUserId, boolean matchInCurrentProfile) { 6526 if (matchingFilters != null) { 6527 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 6528 // match the same intent. For performance reasons, it is better not to 6529 // run queryIntent twice for the same userId 6530 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 6531 int size = matchingFilters.size(); 6532 for (int i = 0; i < size; i++) { 6533 CrossProfileIntentFilter filter = matchingFilters.get(i); 6534 int targetUserId = filter.getTargetUserId(); 6535 boolean skipCurrentProfile = 6536 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 6537 boolean skipCurrentProfileIfNoMatchFound = 6538 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 6539 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 6540 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 6541 // Checking if there are activities in the target user that can handle the 6542 // intent. 6543 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 6544 resolvedType, flags, sourceUserId); 6545 if (resolveInfo != null) return resolveInfo; 6546 alreadyTriedUserIds.put(targetUserId, true); 6547 } 6548 } 6549 } 6550 return null; 6551 } 6552 6553 /** 6554 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 6555 * will forward the intent to the filter's target user. 6556 * Otherwise, returns null. 6557 */ 6558 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 6559 String resolvedType, int flags, int sourceUserId) { 6560 int targetUserId = filter.getTargetUserId(); 6561 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 6562 resolvedType, flags, targetUserId); 6563 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 6564 // If all the matches in the target profile are suspended, return null. 6565 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 6566 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 6567 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 6568 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 6569 targetUserId); 6570 } 6571 } 6572 } 6573 return null; 6574 } 6575 6576 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 6577 int sourceUserId, int targetUserId) { 6578 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 6579 long ident = Binder.clearCallingIdentity(); 6580 boolean targetIsProfile; 6581 try { 6582 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 6583 } finally { 6584 Binder.restoreCallingIdentity(ident); 6585 } 6586 String className; 6587 if (targetIsProfile) { 6588 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 6589 } else { 6590 className = FORWARD_INTENT_TO_PARENT; 6591 } 6592 ComponentName forwardingActivityComponentName = new ComponentName( 6593 mAndroidApplication.packageName, className); 6594 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 6595 sourceUserId); 6596 if (!targetIsProfile) { 6597 forwardingActivityInfo.showUserIcon = targetUserId; 6598 forwardingResolveInfo.noResourceId = true; 6599 } 6600 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 6601 forwardingResolveInfo.priority = 0; 6602 forwardingResolveInfo.preferredOrder = 0; 6603 forwardingResolveInfo.match = 0; 6604 forwardingResolveInfo.isDefault = true; 6605 forwardingResolveInfo.filter = filter; 6606 forwardingResolveInfo.targetUserId = targetUserId; 6607 return forwardingResolveInfo; 6608 } 6609 6610 @Override 6611 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 6612 Intent[] specifics, String[] specificTypes, Intent intent, 6613 String resolvedType, int flags, int userId) { 6614 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 6615 specificTypes, intent, resolvedType, flags, userId)); 6616 } 6617 6618 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 6619 Intent[] specifics, String[] specificTypes, Intent intent, 6620 String resolvedType, int flags, int userId) { 6621 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6622 flags = updateFlagsForResolve(flags, userId, intent); 6623 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6624 false /* requireFullPermission */, false /* checkShell */, 6625 "query intent activity options"); 6626 final String resultsAction = intent.getAction(); 6627 6628 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 6629 | PackageManager.GET_RESOLVED_FILTER, userId); 6630 6631 if (DEBUG_INTENT_MATCHING) { 6632 Log.v(TAG, "Query " + intent + ": " + results); 6633 } 6634 6635 int specificsPos = 0; 6636 int N; 6637 6638 // todo: note that the algorithm used here is O(N^2). This 6639 // isn't a problem in our current environment, but if we start running 6640 // into situations where we have more than 5 or 10 matches then this 6641 // should probably be changed to something smarter... 6642 6643 // First we go through and resolve each of the specific items 6644 // that were supplied, taking care of removing any corresponding 6645 // duplicate items in the generic resolve list. 6646 if (specifics != null) { 6647 for (int i=0; i<specifics.length; i++) { 6648 final Intent sintent = specifics[i]; 6649 if (sintent == null) { 6650 continue; 6651 } 6652 6653 if (DEBUG_INTENT_MATCHING) { 6654 Log.v(TAG, "Specific #" + i + ": " + sintent); 6655 } 6656 6657 String action = sintent.getAction(); 6658 if (resultsAction != null && resultsAction.equals(action)) { 6659 // If this action was explicitly requested, then don't 6660 // remove things that have it. 6661 action = null; 6662 } 6663 6664 ResolveInfo ri = null; 6665 ActivityInfo ai = null; 6666 6667 ComponentName comp = sintent.getComponent(); 6668 if (comp == null) { 6669 ri = resolveIntent( 6670 sintent, 6671 specificTypes != null ? specificTypes[i] : null, 6672 flags, userId); 6673 if (ri == null) { 6674 continue; 6675 } 6676 if (ri == mResolveInfo) { 6677 // ACK! Must do something better with this. 6678 } 6679 ai = ri.activityInfo; 6680 comp = new ComponentName(ai.applicationInfo.packageName, 6681 ai.name); 6682 } else { 6683 ai = getActivityInfo(comp, flags, userId); 6684 if (ai == null) { 6685 continue; 6686 } 6687 } 6688 6689 // Look for any generic query activities that are duplicates 6690 // of this specific one, and remove them from the results. 6691 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 6692 N = results.size(); 6693 int j; 6694 for (j=specificsPos; j<N; j++) { 6695 ResolveInfo sri = results.get(j); 6696 if ((sri.activityInfo.name.equals(comp.getClassName()) 6697 && sri.activityInfo.applicationInfo.packageName.equals( 6698 comp.getPackageName())) 6699 || (action != null && sri.filter.matchAction(action))) { 6700 results.remove(j); 6701 if (DEBUG_INTENT_MATCHING) Log.v( 6702 TAG, "Removing duplicate item from " + j 6703 + " due to specific " + specificsPos); 6704 if (ri == null) { 6705 ri = sri; 6706 } 6707 j--; 6708 N--; 6709 } 6710 } 6711 6712 // Add this specific item to its proper place. 6713 if (ri == null) { 6714 ri = new ResolveInfo(); 6715 ri.activityInfo = ai; 6716 } 6717 results.add(specificsPos, ri); 6718 ri.specificIndex = i; 6719 specificsPos++; 6720 } 6721 } 6722 6723 // Now we go through the remaining generic results and remove any 6724 // duplicate actions that are found here. 6725 N = results.size(); 6726 for (int i=specificsPos; i<N-1; i++) { 6727 final ResolveInfo rii = results.get(i); 6728 if (rii.filter == null) { 6729 continue; 6730 } 6731 6732 // Iterate over all of the actions of this result's intent 6733 // filter... typically this should be just one. 6734 final Iterator<String> it = rii.filter.actionsIterator(); 6735 if (it == null) { 6736 continue; 6737 } 6738 while (it.hasNext()) { 6739 final String action = it.next(); 6740 if (resultsAction != null && resultsAction.equals(action)) { 6741 // If this action was explicitly requested, then don't 6742 // remove things that have it. 6743 continue; 6744 } 6745 for (int j=i+1; j<N; j++) { 6746 final ResolveInfo rij = results.get(j); 6747 if (rij.filter != null && rij.filter.hasAction(action)) { 6748 results.remove(j); 6749 if (DEBUG_INTENT_MATCHING) Log.v( 6750 TAG, "Removing duplicate item from " + j 6751 + " due to action " + action + " at " + i); 6752 j--; 6753 N--; 6754 } 6755 } 6756 } 6757 6758 // If the caller didn't request filter information, drop it now 6759 // so we don't have to marshall/unmarshall it. 6760 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6761 rii.filter = null; 6762 } 6763 } 6764 6765 // Filter out the caller activity if so requested. 6766 if (caller != null) { 6767 N = results.size(); 6768 for (int i=0; i<N; i++) { 6769 ActivityInfo ainfo = results.get(i).activityInfo; 6770 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 6771 && caller.getClassName().equals(ainfo.name)) { 6772 results.remove(i); 6773 break; 6774 } 6775 } 6776 } 6777 6778 // If the caller didn't request filter information, 6779 // drop them now so we don't have to 6780 // marshall/unmarshall it. 6781 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6782 N = results.size(); 6783 for (int i=0; i<N; i++) { 6784 results.get(i).filter = null; 6785 } 6786 } 6787 6788 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 6789 return results; 6790 } 6791 6792 @Override 6793 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 6794 String resolvedType, int flags, int userId) { 6795 return new ParceledListSlice<>( 6796 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 6797 } 6798 6799 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 6800 String resolvedType, int flags, int userId) { 6801 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6802 flags = updateFlagsForResolve(flags, userId, intent); 6803 ComponentName comp = intent.getComponent(); 6804 if (comp == null) { 6805 if (intent.getSelector() != null) { 6806 intent = intent.getSelector(); 6807 comp = intent.getComponent(); 6808 } 6809 } 6810 if (comp != null) { 6811 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6812 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 6813 if (ai != null) { 6814 ResolveInfo ri = new ResolveInfo(); 6815 ri.activityInfo = ai; 6816 list.add(ri); 6817 } 6818 return list; 6819 } 6820 6821 // reader 6822 synchronized (mPackages) { 6823 String pkgName = intent.getPackage(); 6824 if (pkgName == null) { 6825 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 6826 } 6827 final PackageParser.Package pkg = mPackages.get(pkgName); 6828 if (pkg != null) { 6829 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 6830 userId); 6831 } 6832 return Collections.emptyList(); 6833 } 6834 } 6835 6836 @Override 6837 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 6838 if (!sUserManager.exists(userId)) return null; 6839 flags = updateFlagsForResolve(flags, userId, intent); 6840 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 6841 if (query != null) { 6842 if (query.size() >= 1) { 6843 // If there is more than one service with the same priority, 6844 // just arbitrarily pick the first one. 6845 return query.get(0); 6846 } 6847 } 6848 return null; 6849 } 6850 6851 @Override 6852 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 6853 String resolvedType, int flags, int userId) { 6854 return new ParceledListSlice<>( 6855 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 6856 } 6857 6858 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 6859 String resolvedType, int flags, int userId) { 6860 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6861 flags = updateFlagsForResolve(flags, userId, intent); 6862 ComponentName comp = intent.getComponent(); 6863 if (comp == null) { 6864 if (intent.getSelector() != null) { 6865 intent = intent.getSelector(); 6866 comp = intent.getComponent(); 6867 } 6868 } 6869 if (comp != null) { 6870 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6871 final ServiceInfo si = getServiceInfo(comp, flags, userId); 6872 if (si != null) { 6873 final ResolveInfo ri = new ResolveInfo(); 6874 ri.serviceInfo = si; 6875 list.add(ri); 6876 } 6877 return list; 6878 } 6879 6880 // reader 6881 synchronized (mPackages) { 6882 String pkgName = intent.getPackage(); 6883 if (pkgName == null) { 6884 return mServices.queryIntent(intent, resolvedType, flags, userId); 6885 } 6886 final PackageParser.Package pkg = mPackages.get(pkgName); 6887 if (pkg != null) { 6888 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 6889 userId); 6890 } 6891 return Collections.emptyList(); 6892 } 6893 } 6894 6895 @Override 6896 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 6897 String resolvedType, int flags, int userId) { 6898 return new ParceledListSlice<>( 6899 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 6900 } 6901 6902 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 6903 Intent intent, String resolvedType, int flags, int userId) { 6904 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6905 flags = updateFlagsForResolve(flags, userId, intent); 6906 ComponentName comp = intent.getComponent(); 6907 if (comp == null) { 6908 if (intent.getSelector() != null) { 6909 intent = intent.getSelector(); 6910 comp = intent.getComponent(); 6911 } 6912 } 6913 if (comp != null) { 6914 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6915 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 6916 if (pi != null) { 6917 final ResolveInfo ri = new ResolveInfo(); 6918 ri.providerInfo = pi; 6919 list.add(ri); 6920 } 6921 return list; 6922 } 6923 6924 // reader 6925 synchronized (mPackages) { 6926 String pkgName = intent.getPackage(); 6927 if (pkgName == null) { 6928 return mProviders.queryIntent(intent, resolvedType, flags, userId); 6929 } 6930 final PackageParser.Package pkg = mPackages.get(pkgName); 6931 if (pkg != null) { 6932 return mProviders.queryIntentForPackage( 6933 intent, resolvedType, flags, pkg.providers, userId); 6934 } 6935 return Collections.emptyList(); 6936 } 6937 } 6938 6939 @Override 6940 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 6941 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6942 flags = updateFlagsForPackage(flags, userId, null); 6943 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 6944 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6945 true /* requireFullPermission */, false /* checkShell */, 6946 "get installed packages"); 6947 6948 // writer 6949 synchronized (mPackages) { 6950 ArrayList<PackageInfo> list; 6951 if (listUninstalled) { 6952 list = new ArrayList<>(mSettings.mPackages.size()); 6953 for (PackageSetting ps : mSettings.mPackages.values()) { 6954 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 6955 continue; 6956 } 6957 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 6958 if (pi != null) { 6959 list.add(pi); 6960 } 6961 } 6962 } else { 6963 list = new ArrayList<>(mPackages.size()); 6964 for (PackageParser.Package p : mPackages.values()) { 6965 if (filterSharedLibPackageLPr((PackageSetting) p.mExtras, 6966 Binder.getCallingUid(), userId)) { 6967 continue; 6968 } 6969 final PackageInfo pi = generatePackageInfo((PackageSetting) 6970 p.mExtras, flags, userId); 6971 if (pi != null) { 6972 list.add(pi); 6973 } 6974 } 6975 } 6976 6977 return new ParceledListSlice<>(list); 6978 } 6979 } 6980 6981 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 6982 String[] permissions, boolean[] tmp, int flags, int userId) { 6983 int numMatch = 0; 6984 final PermissionsState permissionsState = ps.getPermissionsState(); 6985 for (int i=0; i<permissions.length; i++) { 6986 final String permission = permissions[i]; 6987 if (permissionsState.hasPermission(permission, userId)) { 6988 tmp[i] = true; 6989 numMatch++; 6990 } else { 6991 tmp[i] = false; 6992 } 6993 } 6994 if (numMatch == 0) { 6995 return; 6996 } 6997 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 6998 6999 // The above might return null in cases of uninstalled apps or install-state 7000 // skew across users/profiles. 7001 if (pi != null) { 7002 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 7003 if (numMatch == permissions.length) { 7004 pi.requestedPermissions = permissions; 7005 } else { 7006 pi.requestedPermissions = new String[numMatch]; 7007 numMatch = 0; 7008 for (int i=0; i<permissions.length; i++) { 7009 if (tmp[i]) { 7010 pi.requestedPermissions[numMatch] = permissions[i]; 7011 numMatch++; 7012 } 7013 } 7014 } 7015 } 7016 list.add(pi); 7017 } 7018 } 7019 7020 @Override 7021 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 7022 String[] permissions, int flags, int userId) { 7023 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7024 flags = updateFlagsForPackage(flags, userId, permissions); 7025 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7026 true /* requireFullPermission */, false /* checkShell */, 7027 "get packages holding permissions"); 7028 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7029 7030 // writer 7031 synchronized (mPackages) { 7032 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 7033 boolean[] tmpBools = new boolean[permissions.length]; 7034 if (listUninstalled) { 7035 for (PackageSetting ps : mSettings.mPackages.values()) { 7036 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 7037 userId); 7038 } 7039 } else { 7040 for (PackageParser.Package pkg : mPackages.values()) { 7041 PackageSetting ps = (PackageSetting)pkg.mExtras; 7042 if (ps != null) { 7043 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 7044 userId); 7045 } 7046 } 7047 } 7048 7049 return new ParceledListSlice<PackageInfo>(list); 7050 } 7051 } 7052 7053 @Override 7054 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 7055 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7056 flags = updateFlagsForApplication(flags, userId, null); 7057 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7058 7059 // writer 7060 synchronized (mPackages) { 7061 ArrayList<ApplicationInfo> list; 7062 if (listUninstalled) { 7063 list = new ArrayList<>(mSettings.mPackages.size()); 7064 for (PackageSetting ps : mSettings.mPackages.values()) { 7065 ApplicationInfo ai; 7066 int effectiveFlags = flags; 7067 if (ps.isSystem()) { 7068 effectiveFlags |= PackageManager.MATCH_ANY_USER; 7069 } 7070 if (ps.pkg != null) { 7071 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 7072 continue; 7073 } 7074 ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags, 7075 ps.readUserState(userId), userId); 7076 if (ai != null) { 7077 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 7078 } 7079 } else { 7080 // Shared lib filtering done in generateApplicationInfoFromSettingsLPw 7081 // and already converts to externally visible package name 7082 ai = generateApplicationInfoFromSettingsLPw(ps.name, 7083 Binder.getCallingUid(), effectiveFlags, userId); 7084 } 7085 if (ai != null) { 7086 list.add(ai); 7087 } 7088 } 7089 } else { 7090 list = new ArrayList<>(mPackages.size()); 7091 for (PackageParser.Package p : mPackages.values()) { 7092 if (p.mExtras != null) { 7093 PackageSetting ps = (PackageSetting) p.mExtras; 7094 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 7095 continue; 7096 } 7097 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 7098 ps.readUserState(userId), userId); 7099 if (ai != null) { 7100 ai.packageName = resolveExternalPackageNameLPr(p); 7101 list.add(ai); 7102 } 7103 } 7104 } 7105 } 7106 7107 return new ParceledListSlice<>(list); 7108 } 7109 } 7110 7111 @Override 7112 public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) { 7113 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7114 return null; 7115 } 7116 7117 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS, 7118 "getEphemeralApplications"); 7119 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7120 true /* requireFullPermission */, false /* checkShell */, 7121 "getEphemeralApplications"); 7122 synchronized (mPackages) { 7123 List<InstantAppInfo> instantApps = mInstantAppRegistry 7124 .getInstantAppsLPr(userId); 7125 if (instantApps != null) { 7126 return new ParceledListSlice<>(instantApps); 7127 } 7128 } 7129 return null; 7130 } 7131 7132 @Override 7133 public boolean isInstantApp(String packageName, int userId) { 7134 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7135 true /* requireFullPermission */, false /* checkShell */, 7136 "isInstantApp"); 7137 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7138 return false; 7139 } 7140 7141 if (!isCallerSameApp(packageName)) { 7142 return false; 7143 } 7144 synchronized (mPackages) { 7145 PackageParser.Package pkg = mPackages.get(packageName); 7146 if (pkg != null) { 7147 return pkg.applicationInfo.isInstantApp(); 7148 } 7149 } 7150 return false; 7151 } 7152 7153 @Override 7154 public byte[] getInstantAppCookie(String packageName, int userId) { 7155 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7156 return null; 7157 } 7158 7159 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7160 true /* requireFullPermission */, false /* checkShell */, 7161 "getInstantAppCookie"); 7162 if (!isCallerSameApp(packageName)) { 7163 return null; 7164 } 7165 synchronized (mPackages) { 7166 return mInstantAppRegistry.getInstantAppCookieLPw( 7167 packageName, userId); 7168 } 7169 } 7170 7171 @Override 7172 public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) { 7173 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7174 return true; 7175 } 7176 7177 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7178 true /* requireFullPermission */, true /* checkShell */, 7179 "setInstantAppCookie"); 7180 if (!isCallerSameApp(packageName)) { 7181 return false; 7182 } 7183 synchronized (mPackages) { 7184 return mInstantAppRegistry.setInstantAppCookieLPw( 7185 packageName, cookie, userId); 7186 } 7187 } 7188 7189 @Override 7190 public Bitmap getInstantAppIcon(String packageName, int userId) { 7191 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7192 return null; 7193 } 7194 7195 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS, 7196 "getInstantAppIcon"); 7197 7198 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7199 true /* requireFullPermission */, false /* checkShell */, 7200 "getInstantAppIcon"); 7201 7202 synchronized (mPackages) { 7203 return mInstantAppRegistry.getInstantAppIconLPw( 7204 packageName, userId); 7205 } 7206 } 7207 7208 private boolean isCallerSameApp(String packageName) { 7209 PackageParser.Package pkg = mPackages.get(packageName); 7210 return pkg != null 7211 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 7212 } 7213 7214 @Override 7215 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 7216 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 7217 } 7218 7219 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 7220 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 7221 7222 // reader 7223 synchronized (mPackages) { 7224 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 7225 final int userId = UserHandle.getCallingUserId(); 7226 while (i.hasNext()) { 7227 final PackageParser.Package p = i.next(); 7228 if (p.applicationInfo == null) continue; 7229 7230 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 7231 && !p.applicationInfo.isDirectBootAware(); 7232 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 7233 && p.applicationInfo.isDirectBootAware(); 7234 7235 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 7236 && (!mSafeMode || isSystemApp(p)) 7237 && (matchesUnaware || matchesAware)) { 7238 PackageSetting ps = mSettings.mPackages.get(p.packageName); 7239 if (ps != null) { 7240 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 7241 ps.readUserState(userId), userId); 7242 if (ai != null) { 7243 finalList.add(ai); 7244 } 7245 } 7246 } 7247 } 7248 } 7249 7250 return finalList; 7251 } 7252 7253 @Override 7254 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 7255 if (!sUserManager.exists(userId)) return null; 7256 flags = updateFlagsForComponent(flags, userId, name); 7257 // reader 7258 synchronized (mPackages) { 7259 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 7260 PackageSetting ps = provider != null 7261 ? mSettings.mPackages.get(provider.owner.packageName) 7262 : null; 7263 return ps != null 7264 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 7265 ? PackageParser.generateProviderInfo(provider, flags, 7266 ps.readUserState(userId), userId) 7267 : null; 7268 } 7269 } 7270 7271 /** 7272 * @deprecated 7273 */ 7274 @Deprecated 7275 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 7276 // reader 7277 synchronized (mPackages) { 7278 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 7279 .entrySet().iterator(); 7280 final int userId = UserHandle.getCallingUserId(); 7281 while (i.hasNext()) { 7282 Map.Entry<String, PackageParser.Provider> entry = i.next(); 7283 PackageParser.Provider p = entry.getValue(); 7284 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 7285 7286 if (ps != null && p.syncable 7287 && (!mSafeMode || (p.info.applicationInfo.flags 7288 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 7289 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 7290 ps.readUserState(userId), userId); 7291 if (info != null) { 7292 outNames.add(entry.getKey()); 7293 outInfo.add(info); 7294 } 7295 } 7296 } 7297 } 7298 } 7299 7300 @Override 7301 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 7302 int uid, int flags) { 7303 final int userId = processName != null ? UserHandle.getUserId(uid) 7304 : UserHandle.getCallingUserId(); 7305 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7306 flags = updateFlagsForComponent(flags, userId, processName); 7307 7308 ArrayList<ProviderInfo> finalList = null; 7309 // reader 7310 synchronized (mPackages) { 7311 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 7312 while (i.hasNext()) { 7313 final PackageParser.Provider p = i.next(); 7314 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 7315 if (ps != null && p.info.authority != null 7316 && (processName == null 7317 || (p.info.processName.equals(processName) 7318 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 7319 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 7320 if (finalList == null) { 7321 finalList = new ArrayList<ProviderInfo>(3); 7322 } 7323 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 7324 ps.readUserState(userId), userId); 7325 if (info != null) { 7326 finalList.add(info); 7327 } 7328 } 7329 } 7330 } 7331 7332 if (finalList != null) { 7333 Collections.sort(finalList, mProviderInitOrderSorter); 7334 return new ParceledListSlice<ProviderInfo>(finalList); 7335 } 7336 7337 return ParceledListSlice.emptyList(); 7338 } 7339 7340 @Override 7341 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 7342 // reader 7343 synchronized (mPackages) { 7344 final PackageParser.Instrumentation i = mInstrumentation.get(name); 7345 return PackageParser.generateInstrumentationInfo(i, flags); 7346 } 7347 } 7348 7349 @Override 7350 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 7351 String targetPackage, int flags) { 7352 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 7353 } 7354 7355 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 7356 int flags) { 7357 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 7358 7359 // reader 7360 synchronized (mPackages) { 7361 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 7362 while (i.hasNext()) { 7363 final PackageParser.Instrumentation p = i.next(); 7364 if (targetPackage == null 7365 || targetPackage.equals(p.info.targetPackage)) { 7366 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 7367 flags); 7368 if (ii != null) { 7369 finalList.add(ii); 7370 } 7371 } 7372 } 7373 } 7374 7375 return finalList; 7376 } 7377 7378 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 7379 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 7380 if (overlays == null) { 7381 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 7382 return; 7383 } 7384 for (PackageParser.Package opkg : overlays.values()) { 7385 // Not much to do if idmap fails: we already logged the error 7386 // and we certainly don't want to abort installation of pkg simply 7387 // because an overlay didn't fit properly. For these reasons, 7388 // ignore the return value of createIdmapForPackagePairLI. 7389 createIdmapForPackagePairLI(pkg, opkg); 7390 } 7391 } 7392 7393 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 7394 PackageParser.Package opkg) { 7395 if (!opkg.mTrustedOverlay) { 7396 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 7397 opkg.baseCodePath + ": overlay not trusted"); 7398 return false; 7399 } 7400 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 7401 if (overlaySet == null) { 7402 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 7403 opkg.baseCodePath + " but target package has no known overlays"); 7404 return false; 7405 } 7406 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 7407 // TODO: generate idmap for split APKs 7408 try { 7409 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 7410 } catch (InstallerException e) { 7411 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 7412 + opkg.baseCodePath); 7413 return false; 7414 } 7415 PackageParser.Package[] overlayArray = 7416 overlaySet.values().toArray(new PackageParser.Package[0]); 7417 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 7418 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 7419 return p1.mOverlayPriority - p2.mOverlayPriority; 7420 } 7421 }; 7422 Arrays.sort(overlayArray, cmp); 7423 7424 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 7425 int i = 0; 7426 for (PackageParser.Package p : overlayArray) { 7427 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 7428 } 7429 return true; 7430 } 7431 7432 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 7433 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]"); 7434 try { 7435 scanDirLI(dir, parseFlags, scanFlags, currentTime); 7436 } finally { 7437 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7438 } 7439 } 7440 7441 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 7442 final File[] files = dir.listFiles(); 7443 if (ArrayUtils.isEmpty(files)) { 7444 Log.d(TAG, "No files in app dir " + dir); 7445 return; 7446 } 7447 7448 if (DEBUG_PACKAGE_SCANNING) { 7449 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 7450 + " flags=0x" + Integer.toHexString(parseFlags)); 7451 } 7452 ParallelPackageParser parallelPackageParser = new ParallelPackageParser( 7453 mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir); 7454 7455 // Submit files for parsing in parallel 7456 int fileCount = 0; 7457 for (File file : files) { 7458 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 7459 && !PackageInstallerService.isStageName(file.getName()); 7460 if (!isPackage) { 7461 // Ignore entries which are not packages 7462 continue; 7463 } 7464 parallelPackageParser.submit(file, parseFlags); 7465 fileCount++; 7466 } 7467 7468 // Process results one by one 7469 for (; fileCount > 0; fileCount--) { 7470 ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take(); 7471 Throwable throwable = parseResult.throwable; 7472 int errorCode = PackageManager.INSTALL_SUCCEEDED; 7473 7474 if (throwable == null) { 7475 // Static shared libraries have synthetic package names 7476 if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) { 7477 renameStaticSharedLibraryPackage(parseResult.pkg); 7478 } 7479 try { 7480 if (errorCode == PackageManager.INSTALL_SUCCEEDED) { 7481 scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags, 7482 currentTime, null); 7483 } 7484 } catch (PackageManagerException e) { 7485 errorCode = e.error; 7486 Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage()); 7487 } 7488 } else if (throwable instanceof PackageParser.PackageParserException) { 7489 PackageParser.PackageParserException e = (PackageParser.PackageParserException) 7490 throwable; 7491 errorCode = e.error; 7492 Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage()); 7493 } else { 7494 throw new IllegalStateException("Unexpected exception occurred while parsing " 7495 + parseResult.scanFile, throwable); 7496 } 7497 7498 // Delete invalid userdata apps 7499 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 7500 errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) { 7501 logCriticalInfo(Log.WARN, 7502 "Deleting invalid package at " + parseResult.scanFile); 7503 removeCodePathLI(parseResult.scanFile); 7504 } 7505 } 7506 parallelPackageParser.close(); 7507 } 7508 7509 private static File getSettingsProblemFile() { 7510 File dataDir = Environment.getDataDirectory(); 7511 File systemDir = new File(dataDir, "system"); 7512 File fname = new File(systemDir, "uiderrors.txt"); 7513 return fname; 7514 } 7515 7516 static void reportSettingsProblem(int priority, String msg) { 7517 logCriticalInfo(priority, msg); 7518 } 7519 7520 static void logCriticalInfo(int priority, String msg) { 7521 Slog.println(priority, TAG, msg); 7522 EventLogTags.writePmCriticalInfo(msg); 7523 try { 7524 File fname = getSettingsProblemFile(); 7525 FileOutputStream out = new FileOutputStream(fname, true); 7526 PrintWriter pw = new FastPrintWriter(out); 7527 SimpleDateFormat formatter = new SimpleDateFormat(); 7528 String dateString = formatter.format(new Date(System.currentTimeMillis())); 7529 pw.println(dateString + ": " + msg); 7530 pw.close(); 7531 FileUtils.setPermissions( 7532 fname.toString(), 7533 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 7534 -1, -1); 7535 } catch (java.io.IOException e) { 7536 } 7537 } 7538 7539 private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) { 7540 if (srcFile.isDirectory()) { 7541 final File baseFile = new File(pkg.baseCodePath); 7542 long maxModifiedTime = baseFile.lastModified(); 7543 if (pkg.splitCodePaths != null) { 7544 for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) { 7545 final File splitFile = new File(pkg.splitCodePaths[i]); 7546 maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified()); 7547 } 7548 } 7549 return maxModifiedTime; 7550 } 7551 return srcFile.lastModified(); 7552 } 7553 7554 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 7555 final int policyFlags) throws PackageManagerException { 7556 // When upgrading from pre-N MR1, verify the package time stamp using the package 7557 // directory and not the APK file. 7558 final long lastModifiedTime = mIsPreNMR1Upgrade 7559 ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile); 7560 if (ps != null 7561 && ps.codePath.equals(srcFile) 7562 && ps.timeStamp == lastModifiedTime 7563 && !isCompatSignatureUpdateNeeded(pkg) 7564 && !isRecoverSignatureUpdateNeeded(pkg)) { 7565 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 7566 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7567 ArraySet<PublicKey> signingKs; 7568 synchronized (mPackages) { 7569 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 7570 } 7571 if (ps.signatures.mSignatures != null 7572 && ps.signatures.mSignatures.length != 0 7573 && signingKs != null) { 7574 // Optimization: reuse the existing cached certificates 7575 // if the package appears to be unchanged. 7576 pkg.mSignatures = ps.signatures.mSignatures; 7577 pkg.mSigningKeys = signingKs; 7578 return; 7579 } 7580 7581 Slog.w(TAG, "PackageSetting for " + ps.name 7582 + " is missing signatures. Collecting certs again to recover them."); 7583 } else { 7584 Slog.i(TAG, srcFile.toString() + " changed; collecting certs"); 7585 } 7586 7587 try { 7588 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 7589 PackageParser.collectCertificates(pkg, policyFlags); 7590 } catch (PackageParserException e) { 7591 throw PackageManagerException.from(e); 7592 } finally { 7593 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7594 } 7595 } 7596 7597 /** 7598 * Traces a package scan. 7599 * @see #scanPackageLI(File, int, int, long, UserHandle) 7600 */ 7601 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 7602 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7603 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]"); 7604 try { 7605 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 7606 } finally { 7607 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7608 } 7609 } 7610 7611 /** 7612 * Scans a package and returns the newly parsed package. 7613 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 7614 */ 7615 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 7616 long currentTime, UserHandle user) throws PackageManagerException { 7617 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 7618 PackageParser pp = new PackageParser(); 7619 pp.setSeparateProcesses(mSeparateProcesses); 7620 pp.setOnlyCoreApps(mOnlyCore); 7621 pp.setDisplayMetrics(mMetrics); 7622 7623 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 7624 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 7625 } 7626 7627 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 7628 final PackageParser.Package pkg; 7629 try { 7630 pkg = pp.parsePackage(scanFile, parseFlags); 7631 } catch (PackageParserException e) { 7632 throw PackageManagerException.from(e); 7633 } finally { 7634 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7635 } 7636 7637 // Static shared libraries have synthetic package names 7638 if (pkg.applicationInfo.isStaticSharedLibrary()) { 7639 renameStaticSharedLibraryPackage(pkg); 7640 } 7641 7642 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 7643 } 7644 7645 /** 7646 * Scans a package and returns the newly parsed package. 7647 * @throws PackageManagerException on a parse error. 7648 */ 7649 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 7650 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 7651 throws PackageManagerException { 7652 // If the package has children and this is the first dive in the function 7653 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 7654 // packages (parent and children) would be successfully scanned before the 7655 // actual scan since scanning mutates internal state and we want to atomically 7656 // install the package and its children. 7657 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7658 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7659 scanFlags |= SCAN_CHECK_ONLY; 7660 } 7661 } else { 7662 scanFlags &= ~SCAN_CHECK_ONLY; 7663 } 7664 7665 // Scan the parent 7666 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 7667 scanFlags, currentTime, user); 7668 7669 // Scan the children 7670 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7671 for (int i = 0; i < childCount; i++) { 7672 PackageParser.Package childPackage = pkg.childPackages.get(i); 7673 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 7674 currentTime, user); 7675 } 7676 7677 7678 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7679 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 7680 } 7681 7682 return scannedPkg; 7683 } 7684 7685 /** 7686 * Scans a package and returns the newly parsed package. 7687 * @throws PackageManagerException on a parse error. 7688 */ 7689 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 7690 int policyFlags, int scanFlags, long currentTime, UserHandle user) 7691 throws PackageManagerException { 7692 PackageSetting ps = null; 7693 PackageSetting updatedPkg; 7694 // reader 7695 synchronized (mPackages) { 7696 // Look to see if we already know about this package. 7697 String oldName = mSettings.getRenamedPackageLPr(pkg.packageName); 7698 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 7699 // This package has been renamed to its original name. Let's 7700 // use that. 7701 ps = mSettings.getPackageLPr(oldName); 7702 } 7703 // If there was no original package, see one for the real package name. 7704 if (ps == null) { 7705 ps = mSettings.getPackageLPr(pkg.packageName); 7706 } 7707 // Check to see if this package could be hiding/updating a system 7708 // package. Must look for it either under the original or real 7709 // package name depending on our state. 7710 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 7711 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 7712 7713 // If this is a package we don't know about on the system partition, we 7714 // may need to remove disabled child packages on the system partition 7715 // or may need to not add child packages if the parent apk is updated 7716 // on the data partition and no longer defines this child package. 7717 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 7718 // If this is a parent package for an updated system app and this system 7719 // app got an OTA update which no longer defines some of the child packages 7720 // we have to prune them from the disabled system packages. 7721 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 7722 if (disabledPs != null) { 7723 final int scannedChildCount = (pkg.childPackages != null) 7724 ? pkg.childPackages.size() : 0; 7725 final int disabledChildCount = disabledPs.childPackageNames != null 7726 ? disabledPs.childPackageNames.size() : 0; 7727 for (int i = 0; i < disabledChildCount; i++) { 7728 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 7729 boolean disabledPackageAvailable = false; 7730 for (int j = 0; j < scannedChildCount; j++) { 7731 PackageParser.Package childPkg = pkg.childPackages.get(j); 7732 if (childPkg.packageName.equals(disabledChildPackageName)) { 7733 disabledPackageAvailable = true; 7734 break; 7735 } 7736 } 7737 if (!disabledPackageAvailable) { 7738 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 7739 } 7740 } 7741 } 7742 } 7743 } 7744 7745 boolean updatedPkgBetter = false; 7746 // First check if this is a system package that may involve an update 7747 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 7748 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 7749 // it needs to drop FLAG_PRIVILEGED. 7750 if (locationIsPrivileged(scanFile)) { 7751 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7752 } else { 7753 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7754 } 7755 7756 if (ps != null && !ps.codePath.equals(scanFile)) { 7757 // The path has changed from what was last scanned... check the 7758 // version of the new path against what we have stored to determine 7759 // what to do. 7760 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 7761 if (pkg.mVersionCode <= ps.versionCode) { 7762 // The system package has been updated and the code path does not match 7763 // Ignore entry. Skip it. 7764 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 7765 + " ignored: updated version " + ps.versionCode 7766 + " better than this " + pkg.mVersionCode); 7767 if (!updatedPkg.codePath.equals(scanFile)) { 7768 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 7769 + ps.name + " changing from " + updatedPkg.codePathString 7770 + " to " + scanFile); 7771 updatedPkg.codePath = scanFile; 7772 updatedPkg.codePathString = scanFile.toString(); 7773 updatedPkg.resourcePath = scanFile; 7774 updatedPkg.resourcePathString = scanFile.toString(); 7775 } 7776 updatedPkg.pkg = pkg; 7777 updatedPkg.versionCode = pkg.mVersionCode; 7778 7779 // Update the disabled system child packages to point to the package too. 7780 final int childCount = updatedPkg.childPackageNames != null 7781 ? updatedPkg.childPackageNames.size() : 0; 7782 for (int i = 0; i < childCount; i++) { 7783 String childPackageName = updatedPkg.childPackageNames.get(i); 7784 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 7785 childPackageName); 7786 if (updatedChildPkg != null) { 7787 updatedChildPkg.pkg = pkg; 7788 updatedChildPkg.versionCode = pkg.mVersionCode; 7789 } 7790 } 7791 7792 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 7793 + scanFile + " ignored: updated version " + ps.versionCode 7794 + " better than this " + pkg.mVersionCode); 7795 } else { 7796 // The current app on the system partition is better than 7797 // what we have updated to on the data partition; switch 7798 // back to the system partition version. 7799 // At this point, its safely assumed that package installation for 7800 // apps in system partition will go through. If not there won't be a working 7801 // version of the app 7802 // writer 7803 synchronized (mPackages) { 7804 // Just remove the loaded entries from package lists. 7805 mPackages.remove(ps.name); 7806 } 7807 7808 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7809 + " reverting from " + ps.codePathString 7810 + ": new version " + pkg.mVersionCode 7811 + " better than installed " + ps.versionCode); 7812 7813 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7814 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7815 synchronized (mInstallLock) { 7816 args.cleanUpResourcesLI(); 7817 } 7818 synchronized (mPackages) { 7819 mSettings.enableSystemPackageLPw(ps.name); 7820 } 7821 updatedPkgBetter = true; 7822 } 7823 } 7824 } 7825 7826 if (updatedPkg != null) { 7827 // An updated system app will not have the PARSE_IS_SYSTEM flag set 7828 // initially 7829 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 7830 7831 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 7832 // flag set initially 7833 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 7834 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 7835 } 7836 } 7837 7838 // Verify certificates against what was last scanned 7839 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 7840 7841 /* 7842 * A new system app appeared, but we already had a non-system one of the 7843 * same name installed earlier. 7844 */ 7845 boolean shouldHideSystemApp = false; 7846 if (updatedPkg == null && ps != null 7847 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 7848 /* 7849 * Check to make sure the signatures match first. If they don't, 7850 * wipe the installed application and its data. 7851 */ 7852 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 7853 != PackageManager.SIGNATURE_MATCH) { 7854 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 7855 + " signatures don't match existing userdata copy; removing"); 7856 try (PackageFreezer freezer = freezePackage(pkg.packageName, 7857 "scanPackageInternalLI")) { 7858 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 7859 } 7860 ps = null; 7861 } else { 7862 /* 7863 * If the newly-added system app is an older version than the 7864 * already installed version, hide it. It will be scanned later 7865 * and re-added like an update. 7866 */ 7867 if (pkg.mVersionCode <= ps.versionCode) { 7868 shouldHideSystemApp = true; 7869 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 7870 + " but new version " + pkg.mVersionCode + " better than installed " 7871 + ps.versionCode + "; hiding system"); 7872 } else { 7873 /* 7874 * The newly found system app is a newer version that the 7875 * one previously installed. Simply remove the 7876 * already-installed application and replace it with our own 7877 * while keeping the application data. 7878 */ 7879 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7880 + " reverting from " + ps.codePathString + ": new version " 7881 + pkg.mVersionCode + " better than installed " + ps.versionCode); 7882 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7883 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7884 synchronized (mInstallLock) { 7885 args.cleanUpResourcesLI(); 7886 } 7887 } 7888 } 7889 } 7890 7891 // The apk is forward locked (not public) if its code and resources 7892 // are kept in different files. (except for app in either system or 7893 // vendor path). 7894 // TODO grab this value from PackageSettings 7895 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7896 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 7897 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 7898 } 7899 } 7900 7901 // TODO: extend to support forward-locked splits 7902 String resourcePath = null; 7903 String baseResourcePath = null; 7904 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 7905 if (ps != null && ps.resourcePathString != null) { 7906 resourcePath = ps.resourcePathString; 7907 baseResourcePath = ps.resourcePathString; 7908 } else { 7909 // Should not happen at all. Just log an error. 7910 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 7911 } 7912 } else { 7913 resourcePath = pkg.codePath; 7914 baseResourcePath = pkg.baseCodePath; 7915 } 7916 7917 // Set application objects path explicitly. 7918 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 7919 pkg.setApplicationInfoCodePath(pkg.codePath); 7920 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 7921 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 7922 pkg.setApplicationInfoResourcePath(resourcePath); 7923 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 7924 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 7925 7926 // Note that we invoke the following method only if we are about to unpack an application 7927 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 7928 | SCAN_UPDATE_SIGNATURE, currentTime, user); 7929 7930 /* 7931 * If the system app should be overridden by a previously installed 7932 * data, hide the system app now and let the /data/app scan pick it up 7933 * again. 7934 */ 7935 if (shouldHideSystemApp) { 7936 synchronized (mPackages) { 7937 mSettings.disableSystemPackageLPw(pkg.packageName, true); 7938 } 7939 } 7940 7941 return scannedPkg; 7942 } 7943 7944 private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) { 7945 // Derive the new package synthetic package name 7946 pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER 7947 + pkg.staticSharedLibVersion); 7948 } 7949 7950 private static String fixProcessName(String defProcessName, 7951 String processName) { 7952 if (processName == null) { 7953 return defProcessName; 7954 } 7955 return processName; 7956 } 7957 7958 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 7959 throws PackageManagerException { 7960 if (pkgSetting.signatures.mSignatures != null) { 7961 // Already existing package. Make sure signatures match 7962 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 7963 == PackageManager.SIGNATURE_MATCH; 7964 if (!match) { 7965 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 7966 == PackageManager.SIGNATURE_MATCH; 7967 } 7968 if (!match) { 7969 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 7970 == PackageManager.SIGNATURE_MATCH; 7971 } 7972 if (!match) { 7973 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 7974 + pkg.packageName + " signatures do not match the " 7975 + "previously installed version; ignoring!"); 7976 } 7977 } 7978 7979 // Check for shared user signatures 7980 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 7981 // Already existing package. Make sure signatures match 7982 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7983 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 7984 if (!match) { 7985 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 7986 == PackageManager.SIGNATURE_MATCH; 7987 } 7988 if (!match) { 7989 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 7990 == PackageManager.SIGNATURE_MATCH; 7991 } 7992 if (!match) { 7993 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 7994 "Package " + pkg.packageName 7995 + " has no signatures that match those in shared user " 7996 + pkgSetting.sharedUser.name + "; ignoring!"); 7997 } 7998 } 7999 } 8000 8001 /** 8002 * Enforces that only the system UID or root's UID can call a method exposed 8003 * via Binder. 8004 * 8005 * @param message used as message if SecurityException is thrown 8006 * @throws SecurityException if the caller is not system or root 8007 */ 8008 private static final void enforceSystemOrRoot(String message) { 8009 final int uid = Binder.getCallingUid(); 8010 if (uid != Process.SYSTEM_UID && uid != 0) { 8011 throw new SecurityException(message); 8012 } 8013 } 8014 8015 @Override 8016 public void performFstrimIfNeeded() { 8017 enforceSystemOrRoot("Only the system can request fstrim"); 8018 8019 // Before everything else, see whether we need to fstrim. 8020 try { 8021 IStorageManager sm = PackageHelper.getStorageManager(); 8022 if (sm != null) { 8023 boolean doTrim = false; 8024 final long interval = android.provider.Settings.Global.getLong( 8025 mContext.getContentResolver(), 8026 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 8027 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 8028 if (interval > 0) { 8029 final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance(); 8030 if (timeSinceLast > interval) { 8031 doTrim = true; 8032 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 8033 + "; running immediately"); 8034 } 8035 } 8036 if (doTrim) { 8037 final boolean dexOptDialogShown; 8038 synchronized (mPackages) { 8039 dexOptDialogShown = mDexOptDialogShown; 8040 } 8041 if (!isFirstBoot() && dexOptDialogShown) { 8042 try { 8043 ActivityManager.getService().showBootMessage( 8044 mContext.getResources().getString( 8045 R.string.android_upgrading_fstrim), true); 8046 } catch (RemoteException e) { 8047 } 8048 } 8049 sm.runMaintenance(); 8050 } 8051 } else { 8052 Slog.e(TAG, "storageManager service unavailable!"); 8053 } 8054 } catch (RemoteException e) { 8055 // Can't happen; StorageManagerService is local 8056 } 8057 } 8058 8059 @Override 8060 public void updatePackagesIfNeeded() { 8061 enforceSystemOrRoot("Only the system can request package update"); 8062 8063 // We need to re-extract after an OTA. 8064 boolean causeUpgrade = isUpgrade(); 8065 8066 // First boot or factory reset. 8067 // Note: we also handle devices that are upgrading to N right now as if it is their 8068 // first boot, as they do not have profile data. 8069 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 8070 8071 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 8072 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 8073 8074 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 8075 return; 8076 } 8077 8078 List<PackageParser.Package> pkgs; 8079 synchronized (mPackages) { 8080 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 8081 } 8082 8083 final long startTime = System.nanoTime(); 8084 final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */, 8085 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT)); 8086 8087 final int elapsedTimeSeconds = 8088 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 8089 8090 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]); 8091 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]); 8092 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]); 8093 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 8094 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 8095 } 8096 8097 /** 8098 * Performs dexopt on the set of packages in {@code packages} and returns an int array 8099 * containing statistics about the invocation. The array consists of three elements, 8100 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped} 8101 * and {@code numberOfPackagesFailed}. 8102 */ 8103 private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog, 8104 String compilerFilter) { 8105 8106 int numberOfPackagesVisited = 0; 8107 int numberOfPackagesOptimized = 0; 8108 int numberOfPackagesSkipped = 0; 8109 int numberOfPackagesFailed = 0; 8110 final int numberOfPackagesToDexopt = pkgs.size(); 8111 8112 for (PackageParser.Package pkg : pkgs) { 8113 numberOfPackagesVisited++; 8114 8115 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 8116 if (DEBUG_DEXOPT) { 8117 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 8118 } 8119 numberOfPackagesSkipped++; 8120 continue; 8121 } 8122 8123 if (DEBUG_DEXOPT) { 8124 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 8125 numberOfPackagesToDexopt + ": " + pkg.packageName); 8126 } 8127 8128 if (showDialog) { 8129 try { 8130 ActivityManager.getService().showBootMessage( 8131 mContext.getResources().getString(R.string.android_upgrading_apk, 8132 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 8133 } catch (RemoteException e) { 8134 } 8135 synchronized (mPackages) { 8136 mDexOptDialogShown = true; 8137 } 8138 } 8139 8140 // If the OTA updates a system app which was previously preopted to a non-preopted state 8141 // the app might end up being verified at runtime. That's because by default the apps 8142 // are verify-profile but for preopted apps there's no profile. 8143 // Do a hacky check to ensure that if we have no profiles (a reasonable indication 8144 // that before the OTA the app was preopted) the app gets compiled with a non-profile 8145 // filter (by default interpret-only). 8146 // Note that at this stage unused apps are already filtered. 8147 if (isSystemApp(pkg) && 8148 DexFile.isProfileGuidedCompilerFilter(compilerFilter) && 8149 !Environment.getReferenceProfile(pkg.packageName).exists()) { 8150 compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter); 8151 } 8152 8153 // checkProfiles is false to avoid merging profiles during boot which 8154 // might interfere with background compilation (b/28612421). 8155 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 8156 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 8157 // trade-off worth doing to save boot time work. 8158 int dexOptStatus = performDexOptTraced(pkg.packageName, 8159 false /* checkProfiles */, 8160 compilerFilter, 8161 false /* force */); 8162 switch (dexOptStatus) { 8163 case PackageDexOptimizer.DEX_OPT_PERFORMED: 8164 numberOfPackagesOptimized++; 8165 break; 8166 case PackageDexOptimizer.DEX_OPT_SKIPPED: 8167 numberOfPackagesSkipped++; 8168 break; 8169 case PackageDexOptimizer.DEX_OPT_FAILED: 8170 numberOfPackagesFailed++; 8171 break; 8172 default: 8173 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus); 8174 break; 8175 } 8176 } 8177 8178 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped, 8179 numberOfPackagesFailed }; 8180 } 8181 8182 @Override 8183 public void notifyPackageUse(String packageName, int reason) { 8184 synchronized (mPackages) { 8185 PackageParser.Package p = mPackages.get(packageName); 8186 if (p == null) { 8187 return; 8188 } 8189 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 8190 } 8191 } 8192 8193 @Override 8194 public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) { 8195 int userId = UserHandle.getCallingUserId(); 8196 ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId); 8197 if (ai == null) { 8198 Slog.w(TAG, "Loading a package that does not exist for the calling user. package=" 8199 + loadingPackageName + ", user=" + userId); 8200 return; 8201 } 8202 mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId); 8203 } 8204 8205 // TODO: this is not used nor needed. Delete it. 8206 @Override 8207 public boolean performDexOptIfNeeded(String packageName) { 8208 int dexOptStatus = performDexOptTraced(packageName, 8209 false /* checkProfiles */, getFullCompilerFilter(), false /* force */); 8210 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 8211 } 8212 8213 @Override 8214 public boolean performDexOpt(String packageName, 8215 boolean checkProfiles, int compileReason, boolean force) { 8216 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 8217 getCompilerFilterForReason(compileReason), force); 8218 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 8219 } 8220 8221 @Override 8222 public boolean performDexOptMode(String packageName, 8223 boolean checkProfiles, String targetCompilerFilter, boolean force) { 8224 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 8225 targetCompilerFilter, force); 8226 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 8227 } 8228 8229 private int performDexOptTraced(String packageName, 8230 boolean checkProfiles, String targetCompilerFilter, boolean force) { 8231 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 8232 try { 8233 return performDexOptInternal(packageName, checkProfiles, 8234 targetCompilerFilter, force); 8235 } finally { 8236 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8237 } 8238 } 8239 8240 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 8241 // if the package can now be considered up to date for the given filter. 8242 private int performDexOptInternal(String packageName, 8243 boolean checkProfiles, String targetCompilerFilter, boolean force) { 8244 PackageParser.Package p; 8245 synchronized (mPackages) { 8246 p = mPackages.get(packageName); 8247 if (p == null) { 8248 // Package could not be found. Report failure. 8249 return PackageDexOptimizer.DEX_OPT_FAILED; 8250 } 8251 mPackageUsage.maybeWriteAsync(mPackages); 8252 mCompilerStats.maybeWriteAsync(); 8253 } 8254 long callingId = Binder.clearCallingIdentity(); 8255 try { 8256 synchronized (mInstallLock) { 8257 return performDexOptInternalWithDependenciesLI(p, checkProfiles, 8258 targetCompilerFilter, force); 8259 } 8260 } finally { 8261 Binder.restoreCallingIdentity(callingId); 8262 } 8263 } 8264 8265 public ArraySet<String> getOptimizablePackages() { 8266 ArraySet<String> pkgs = new ArraySet<String>(); 8267 synchronized (mPackages) { 8268 for (PackageParser.Package p : mPackages.values()) { 8269 if (PackageDexOptimizer.canOptimizePackage(p)) { 8270 pkgs.add(p.packageName); 8271 } 8272 } 8273 } 8274 return pkgs; 8275 } 8276 8277 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 8278 boolean checkProfiles, String targetCompilerFilter, 8279 boolean force) { 8280 // Select the dex optimizer based on the force parameter. 8281 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 8282 // allocate an object here. 8283 PackageDexOptimizer pdo = force 8284 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 8285 : mPackageDexOptimizer; 8286 8287 // Optimize all dependencies first. Note: we ignore the return value and march on 8288 // on errors. 8289 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 8290 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 8291 if (!deps.isEmpty()) { 8292 for (PackageParser.Package depPackage : deps) { 8293 // TODO: Analyze and investigate if we (should) profile libraries. 8294 // Currently this will do a full compilation of the library by default. 8295 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 8296 false /* checkProfiles */, 8297 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY), 8298 getOrCreateCompilerPackageStats(depPackage)); 8299 } 8300 } 8301 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 8302 targetCompilerFilter, getOrCreateCompilerPackageStats(p)); 8303 } 8304 8305 // Performs dexopt on the used secondary dex files belonging to the given package. 8306 // Returns true if all dex files were process successfully (which could mean either dexopt or 8307 // skip). Returns false if any of the files caused errors. 8308 @Override 8309 public boolean performDexOptSecondary(String packageName, String compilerFilter, 8310 boolean force) { 8311 return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force); 8312 } 8313 8314 /** 8315 * Reconcile the information we have about the secondary dex files belonging to 8316 * {@code packagName} and the actual dex files. For all dex files that were 8317 * deleted, update the internal records and delete the generated oat files. 8318 */ 8319 @Override 8320 public void reconcileSecondaryDexFiles(String packageName) { 8321 mDexManager.reconcileSecondaryDexFiles(packageName); 8322 } 8323 8324 // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject 8325 // a reference there. 8326 /*package*/ DexManager getDexManager() { 8327 return mDexManager; 8328 } 8329 8330 /** 8331 * Execute the background dexopt job immediately. 8332 */ 8333 @Override 8334 public boolean runBackgroundDexoptJob() { 8335 return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext); 8336 } 8337 8338 List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 8339 if (p.usesLibraries != null || p.usesOptionalLibraries != null 8340 || p.usesStaticLibraries != null) { 8341 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 8342 Set<String> collectedNames = new HashSet<>(); 8343 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 8344 8345 retValue.remove(p); 8346 8347 return retValue; 8348 } else { 8349 return Collections.emptyList(); 8350 } 8351 } 8352 8353 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 8354 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) { 8355 if (!collectedNames.contains(p.packageName)) { 8356 collectedNames.add(p.packageName); 8357 collected.add(p); 8358 8359 if (p.usesLibraries != null) { 8360 findSharedNonSystemLibrariesRecursive(p.usesLibraries, 8361 null, collected, collectedNames); 8362 } 8363 if (p.usesOptionalLibraries != null) { 8364 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, 8365 null, collected, collectedNames); 8366 } 8367 if (p.usesStaticLibraries != null) { 8368 findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries, 8369 p.usesStaticLibrariesVersions, collected, collectedNames); 8370 } 8371 } 8372 } 8373 8374 private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions, 8375 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) { 8376 final int libNameCount = libs.size(); 8377 for (int i = 0; i < libNameCount; i++) { 8378 String libName = libs.get(i); 8379 int version = (versions != null && versions.length == libNameCount) 8380 ? versions[i] : PackageManager.VERSION_CODE_HIGHEST; 8381 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version); 8382 if (libPkg != null) { 8383 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 8384 } 8385 } 8386 } 8387 8388 private PackageParser.Package findSharedNonSystemLibrary(String name, int version) { 8389 synchronized (mPackages) { 8390 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version); 8391 if (libEntry != null) { 8392 return mPackages.get(libEntry.apk); 8393 } 8394 return null; 8395 } 8396 } 8397 8398 private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) { 8399 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 8400 if (versionedLib == null) { 8401 return null; 8402 } 8403 return versionedLib.get(version); 8404 } 8405 8406 private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) { 8407 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get( 8408 pkg.staticSharedLibName); 8409 if (versionedLib == null) { 8410 return null; 8411 } 8412 int previousLibVersion = -1; 8413 final int versionCount = versionedLib.size(); 8414 for (int i = 0; i < versionCount; i++) { 8415 final int libVersion = versionedLib.keyAt(i); 8416 if (libVersion < pkg.staticSharedLibVersion) { 8417 previousLibVersion = Math.max(previousLibVersion, libVersion); 8418 } 8419 } 8420 if (previousLibVersion >= 0) { 8421 return versionedLib.get(previousLibVersion); 8422 } 8423 return null; 8424 } 8425 8426 public void shutdown() { 8427 mPackageUsage.writeNow(mPackages); 8428 mCompilerStats.writeNow(); 8429 } 8430 8431 @Override 8432 public void dumpProfiles(String packageName) { 8433 PackageParser.Package pkg; 8434 synchronized (mPackages) { 8435 pkg = mPackages.get(packageName); 8436 if (pkg == null) { 8437 throw new IllegalArgumentException("Unknown package: " + packageName); 8438 } 8439 } 8440 /* Only the shell, root, or the app user should be able to dump profiles. */ 8441 int callingUid = Binder.getCallingUid(); 8442 if (callingUid != Process.SHELL_UID && 8443 callingUid != Process.ROOT_UID && 8444 callingUid != pkg.applicationInfo.uid) { 8445 throw new SecurityException("dumpProfiles"); 8446 } 8447 8448 synchronized (mInstallLock) { 8449 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles"); 8450 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 8451 try { 8452 List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly(); 8453 String codePaths = TextUtils.join(";", allCodePaths); 8454 mInstaller.dumpProfiles(sharedGid, packageName, codePaths); 8455 } catch (InstallerException e) { 8456 Slog.w(TAG, "Failed to dump profiles", e); 8457 } 8458 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8459 } 8460 } 8461 8462 @Override 8463 public void forceDexOpt(String packageName) { 8464 enforceSystemOrRoot("forceDexOpt"); 8465 8466 PackageParser.Package pkg; 8467 synchronized (mPackages) { 8468 pkg = mPackages.get(packageName); 8469 if (pkg == null) { 8470 throw new IllegalArgumentException("Unknown package: " + packageName); 8471 } 8472 } 8473 8474 synchronized (mInstallLock) { 8475 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 8476 8477 // Whoever is calling forceDexOpt wants a fully compiled package. 8478 // Don't use profiles since that may cause compilation to be skipped. 8479 final int res = performDexOptInternalWithDependenciesLI(pkg, 8480 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 8481 true /* force */); 8482 8483 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8484 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 8485 throw new IllegalStateException("Failed to dexopt: " + res); 8486 } 8487 } 8488 } 8489 8490 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 8491 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 8492 Slog.w(TAG, "Unable to update from " + oldPkg.name 8493 + " to " + newPkg.packageName 8494 + ": old package not in system partition"); 8495 return false; 8496 } else if (mPackages.get(oldPkg.name) != null) { 8497 Slog.w(TAG, "Unable to update from " + oldPkg.name 8498 + " to " + newPkg.packageName 8499 + ": old package still exists"); 8500 return false; 8501 } 8502 return true; 8503 } 8504 8505 void removeCodePathLI(File codePath) { 8506 if (codePath.isDirectory()) { 8507 try { 8508 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 8509 } catch (InstallerException e) { 8510 Slog.w(TAG, "Failed to remove code path", e); 8511 } 8512 } else { 8513 codePath.delete(); 8514 } 8515 } 8516 8517 private int[] resolveUserIds(int userId) { 8518 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 8519 } 8520 8521 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 8522 if (pkg == null) { 8523 Slog.wtf(TAG, "Package was null!", new Throwable()); 8524 return; 8525 } 8526 clearAppDataLeafLIF(pkg, userId, flags); 8527 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8528 for (int i = 0; i < childCount; i++) { 8529 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 8530 } 8531 } 8532 8533 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 8534 final PackageSetting ps; 8535 synchronized (mPackages) { 8536 ps = mSettings.mPackages.get(pkg.packageName); 8537 } 8538 for (int realUserId : resolveUserIds(userId)) { 8539 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 8540 try { 8541 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 8542 ceDataInode); 8543 } catch (InstallerException e) { 8544 Slog.w(TAG, String.valueOf(e)); 8545 } 8546 } 8547 } 8548 8549 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 8550 if (pkg == null) { 8551 Slog.wtf(TAG, "Package was null!", new Throwable()); 8552 return; 8553 } 8554 destroyAppDataLeafLIF(pkg, userId, flags); 8555 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8556 for (int i = 0; i < childCount; i++) { 8557 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 8558 } 8559 } 8560 8561 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 8562 final PackageSetting ps; 8563 synchronized (mPackages) { 8564 ps = mSettings.mPackages.get(pkg.packageName); 8565 } 8566 for (int realUserId : resolveUserIds(userId)) { 8567 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 8568 try { 8569 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 8570 ceDataInode); 8571 } catch (InstallerException e) { 8572 Slog.w(TAG, String.valueOf(e)); 8573 } 8574 } 8575 } 8576 8577 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 8578 if (pkg == null) { 8579 Slog.wtf(TAG, "Package was null!", new Throwable()); 8580 return; 8581 } 8582 destroyAppProfilesLeafLIF(pkg); 8583 destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */); 8584 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8585 for (int i = 0; i < childCount; i++) { 8586 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 8587 destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId, 8588 true /* removeBaseMarker */); 8589 } 8590 } 8591 8592 private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId, 8593 boolean removeBaseMarker) { 8594 if (pkg.isForwardLocked()) { 8595 return; 8596 } 8597 8598 for (String path : pkg.getAllCodePathsExcludingResourceOnly()) { 8599 try { 8600 path = PackageManagerServiceUtils.realpath(new File(path)); 8601 } catch (IOException e) { 8602 // TODO: Should we return early here ? 8603 Slog.w(TAG, "Failed to get canonical path", e); 8604 continue; 8605 } 8606 8607 final String useMarker = path.replace('/', '@'); 8608 for (int realUserId : resolveUserIds(userId)) { 8609 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId); 8610 if (removeBaseMarker) { 8611 File foreignUseMark = new File(profileDir, useMarker); 8612 if (foreignUseMark.exists()) { 8613 if (!foreignUseMark.delete()) { 8614 Slog.w(TAG, "Unable to delete foreign user mark for package: " 8615 + pkg.packageName); 8616 } 8617 } 8618 } 8619 8620 File[] markers = profileDir.listFiles(); 8621 if (markers != null) { 8622 final String searchString = "@" + pkg.packageName + "@"; 8623 // We also delete all markers that contain the package name we're 8624 // uninstalling. These are associated with secondary dex-files belonging 8625 // to the package. Reconstructing the path of these dex files is messy 8626 // in general. 8627 for (File marker : markers) { 8628 if (marker.getName().indexOf(searchString) > 0) { 8629 if (!marker.delete()) { 8630 Slog.w(TAG, "Unable to delete foreign user mark for package: " 8631 + pkg.packageName); 8632 } 8633 } 8634 } 8635 } 8636 } 8637 } 8638 } 8639 8640 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 8641 try { 8642 mInstaller.destroyAppProfiles(pkg.packageName); 8643 } catch (InstallerException e) { 8644 Slog.w(TAG, String.valueOf(e)); 8645 } 8646 } 8647 8648 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 8649 if (pkg == null) { 8650 Slog.wtf(TAG, "Package was null!", new Throwable()); 8651 return; 8652 } 8653 clearAppProfilesLeafLIF(pkg); 8654 // We don't remove the base foreign use marker when clearing profiles because 8655 // we will rename it when the app is updated. Unlike the actual profile contents, 8656 // the foreign use marker is good across installs. 8657 destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */); 8658 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8659 for (int i = 0; i < childCount; i++) { 8660 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 8661 } 8662 } 8663 8664 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 8665 try { 8666 mInstaller.clearAppProfiles(pkg.packageName); 8667 } catch (InstallerException e) { 8668 Slog.w(TAG, String.valueOf(e)); 8669 } 8670 } 8671 8672 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 8673 long lastUpdateTime) { 8674 // Set parent install/update time 8675 PackageSetting ps = (PackageSetting) pkg.mExtras; 8676 if (ps != null) { 8677 ps.firstInstallTime = firstInstallTime; 8678 ps.lastUpdateTime = lastUpdateTime; 8679 } 8680 // Set children install/update time 8681 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8682 for (int i = 0; i < childCount; i++) { 8683 PackageParser.Package childPkg = pkg.childPackages.get(i); 8684 ps = (PackageSetting) childPkg.mExtras; 8685 if (ps != null) { 8686 ps.firstInstallTime = firstInstallTime; 8687 ps.lastUpdateTime = lastUpdateTime; 8688 } 8689 } 8690 } 8691 8692 private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 8693 PackageParser.Package changingLib) { 8694 if (file.path != null) { 8695 usesLibraryFiles.add(file.path); 8696 return; 8697 } 8698 PackageParser.Package p = mPackages.get(file.apk); 8699 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 8700 // If we are doing this while in the middle of updating a library apk, 8701 // then we need to make sure to use that new apk for determining the 8702 // dependencies here. (We haven't yet finished committing the new apk 8703 // to the package manager state.) 8704 if (p == null || p.packageName.equals(changingLib.packageName)) { 8705 p = changingLib; 8706 } 8707 } 8708 if (p != null) { 8709 usesLibraryFiles.addAll(p.getAllCodePaths()); 8710 } 8711 } 8712 8713 private void updateSharedLibrariesLPr(PackageParser.Package pkg, 8714 PackageParser.Package changingLib) throws PackageManagerException { 8715 if (pkg == null) { 8716 return; 8717 } 8718 ArraySet<String> usesLibraryFiles = null; 8719 if (pkg.usesLibraries != null) { 8720 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries, 8721 null, null, pkg.packageName, changingLib, true, null); 8722 } 8723 if (pkg.usesStaticLibraries != null) { 8724 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries, 8725 pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests, 8726 pkg.packageName, changingLib, true, usesLibraryFiles); 8727 } 8728 if (pkg.usesOptionalLibraries != null) { 8729 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries, 8730 null, null, pkg.packageName, changingLib, false, usesLibraryFiles); 8731 } 8732 if (!ArrayUtils.isEmpty(usesLibraryFiles)) { 8733 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]); 8734 } else { 8735 pkg.usesLibraryFiles = null; 8736 } 8737 } 8738 8739 private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries, 8740 @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests, 8741 @NonNull String packageName, @Nullable PackageParser.Package changingLib, 8742 boolean required, @Nullable ArraySet<String> outUsedLibraries) 8743 throws PackageManagerException { 8744 final int libCount = requestedLibraries.size(); 8745 for (int i = 0; i < libCount; i++) { 8746 final String libName = requestedLibraries.get(i); 8747 final int libVersion = requiredVersions != null ? requiredVersions[i] 8748 : SharedLibraryInfo.VERSION_UNDEFINED; 8749 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion); 8750 if (libEntry == null) { 8751 if (required) { 8752 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8753 "Package " + packageName + " requires unavailable shared library " 8754 + libName + "; failing!"); 8755 } else { 8756 Slog.w(TAG, "Package " + packageName 8757 + " desires unavailable shared library " 8758 + libName + "; ignoring!"); 8759 } 8760 } else { 8761 if (requiredVersions != null && requiredCertDigests != null) { 8762 if (libEntry.info.getVersion() != requiredVersions[i]) { 8763 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8764 "Package " + packageName + " requires unavailable static shared" 8765 + " library " + libName + " version " 8766 + libEntry.info.getVersion() + "; failing!"); 8767 } 8768 8769 PackageParser.Package libPkg = mPackages.get(libEntry.apk); 8770 if (libPkg == null) { 8771 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8772 "Package " + packageName + " requires unavailable static shared" 8773 + " library; failing!"); 8774 } 8775 8776 String expectedCertDigest = requiredCertDigests[i]; 8777 String libCertDigest = PackageUtils.computeCertSha256Digest( 8778 libPkg.mSignatures[0]); 8779 if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) { 8780 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8781 "Package " + packageName + " requires differently signed" + 8782 " static shared library; failing!"); 8783 } 8784 } 8785 8786 if (outUsedLibraries == null) { 8787 outUsedLibraries = new ArraySet<>(); 8788 } 8789 addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib); 8790 } 8791 } 8792 return outUsedLibraries; 8793 } 8794 8795 private static boolean hasString(List<String> list, List<String> which) { 8796 if (list == null) { 8797 return false; 8798 } 8799 for (int i=list.size()-1; i>=0; i--) { 8800 for (int j=which.size()-1; j>=0; j--) { 8801 if (which.get(j).equals(list.get(i))) { 8802 return true; 8803 } 8804 } 8805 } 8806 return false; 8807 } 8808 8809 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 8810 PackageParser.Package changingPkg) { 8811 ArrayList<PackageParser.Package> res = null; 8812 for (PackageParser.Package pkg : mPackages.values()) { 8813 if (changingPkg != null 8814 && !hasString(pkg.usesLibraries, changingPkg.libraryNames) 8815 && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames) 8816 && !ArrayUtils.contains(pkg.usesStaticLibraries, 8817 changingPkg.staticSharedLibName)) { 8818 return null; 8819 } 8820 if (res == null) { 8821 res = new ArrayList<>(); 8822 } 8823 res.add(pkg); 8824 try { 8825 updateSharedLibrariesLPr(pkg, changingPkg); 8826 } catch (PackageManagerException e) { 8827 // If a system app update or an app and a required lib missing we 8828 // delete the package and for updated system apps keep the data as 8829 // it is better for the user to reinstall than to be in an limbo 8830 // state. Also libs disappearing under an app should never happen 8831 // - just in case. 8832 if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) { 8833 final int flags = pkg.isUpdatedSystemApp() 8834 ? PackageManager.DELETE_KEEP_DATA : 0; 8835 deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(), 8836 flags , null, true, null); 8837 } 8838 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 8839 } 8840 } 8841 return res; 8842 } 8843 8844 /** 8845 * Derive the value of the {@code cpuAbiOverride} based on the provided 8846 * value and an optional stored value from the package settings. 8847 */ 8848 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 8849 String cpuAbiOverride = null; 8850 8851 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 8852 cpuAbiOverride = null; 8853 } else if (abiOverride != null) { 8854 cpuAbiOverride = abiOverride; 8855 } else if (settings != null) { 8856 cpuAbiOverride = settings.cpuAbiOverrideString; 8857 } 8858 8859 return cpuAbiOverride; 8860 } 8861 8862 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 8863 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 8864 throws PackageManagerException { 8865 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 8866 // If the package has children and this is the first dive in the function 8867 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 8868 // whether all packages (parent and children) would be successfully scanned 8869 // before the actual scan since scanning mutates internal state and we want 8870 // to atomically install the package and its children. 8871 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8872 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 8873 scanFlags |= SCAN_CHECK_ONLY; 8874 } 8875 } else { 8876 scanFlags &= ~SCAN_CHECK_ONLY; 8877 } 8878 8879 final PackageParser.Package scannedPkg; 8880 try { 8881 // Scan the parent 8882 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 8883 // Scan the children 8884 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8885 for (int i = 0; i < childCount; i++) { 8886 PackageParser.Package childPkg = pkg.childPackages.get(i); 8887 scanPackageLI(childPkg, policyFlags, 8888 scanFlags, currentTime, user); 8889 } 8890 } finally { 8891 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8892 } 8893 8894 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8895 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 8896 } 8897 8898 return scannedPkg; 8899 } 8900 8901 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 8902 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 8903 boolean success = false; 8904 try { 8905 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 8906 currentTime, user); 8907 success = true; 8908 return res; 8909 } finally { 8910 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 8911 // DELETE_DATA_ON_FAILURES is only used by frozen paths 8912 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 8913 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 8914 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 8915 } 8916 } 8917 } 8918 8919 /** 8920 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 8921 */ 8922 private static boolean apkHasCode(String fileName) { 8923 StrictJarFile jarFile = null; 8924 try { 8925 jarFile = new StrictJarFile(fileName, 8926 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 8927 return jarFile.findEntry("classes.dex") != null; 8928 } catch (IOException ignore) { 8929 } finally { 8930 try { 8931 if (jarFile != null) { 8932 jarFile.close(); 8933 } 8934 } catch (IOException ignore) {} 8935 } 8936 return false; 8937 } 8938 8939 /** 8940 * Enforces code policy for the package. This ensures that if an APK has 8941 * declared hasCode="true" in its manifest that the APK actually contains 8942 * code. 8943 * 8944 * @throws PackageManagerException If bytecode could not be found when it should exist 8945 */ 8946 private static void assertCodePolicy(PackageParser.Package pkg) 8947 throws PackageManagerException { 8948 final boolean shouldHaveCode = 8949 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 8950 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 8951 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8952 "Package " + pkg.baseCodePath + " code is missing"); 8953 } 8954 8955 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 8956 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 8957 final boolean splitShouldHaveCode = 8958 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 8959 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 8960 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8961 "Package " + pkg.splitCodePaths[i] + " code is missing"); 8962 } 8963 } 8964 } 8965 } 8966 8967 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 8968 final int policyFlags, final int scanFlags, long currentTime, UserHandle user) 8969 throws PackageManagerException { 8970 if (DEBUG_PACKAGE_SCANNING) { 8971 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8972 Log.d(TAG, "Scanning package " + pkg.packageName); 8973 } 8974 8975 applyPolicy(pkg, policyFlags); 8976 8977 assertPackageIsValid(pkg, policyFlags, scanFlags); 8978 8979 // Initialize package source and resource directories 8980 final File scanFile = new File(pkg.codePath); 8981 final File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 8982 final File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 8983 8984 SharedUserSetting suid = null; 8985 PackageSetting pkgSetting = null; 8986 8987 // Getting the package setting may have a side-effect, so if we 8988 // are only checking if scan would succeed, stash a copy of the 8989 // old setting to restore at the end. 8990 PackageSetting nonMutatedPs = null; 8991 8992 // We keep references to the derived CPU Abis from settings in oder to reuse 8993 // them in the case where we're not upgrading or booting for the first time. 8994 String primaryCpuAbiFromSettings = null; 8995 String secondaryCpuAbiFromSettings = null; 8996 8997 // writer 8998 synchronized (mPackages) { 8999 if (pkg.mSharedUserId != null) { 9000 // SIDE EFFECTS; may potentially allocate a new shared user 9001 suid = mSettings.getSharedUserLPw( 9002 pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/); 9003 if (DEBUG_PACKAGE_SCANNING) { 9004 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 9005 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 9006 + "): packages=" + suid.packages); 9007 } 9008 } 9009 9010 // Check if we are renaming from an original package name. 9011 PackageSetting origPackage = null; 9012 String realName = null; 9013 if (pkg.mOriginalPackages != null) { 9014 // This package may need to be renamed to a previously 9015 // installed name. Let's check on that... 9016 final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage); 9017 if (pkg.mOriginalPackages.contains(renamed)) { 9018 // This package had originally been installed as the 9019 // original name, and we have already taken care of 9020 // transitioning to the new one. Just update the new 9021 // one to continue using the old name. 9022 realName = pkg.mRealPackage; 9023 if (!pkg.packageName.equals(renamed)) { 9024 // Callers into this function may have already taken 9025 // care of renaming the package; only do it here if 9026 // it is not already done. 9027 pkg.setPackageName(renamed); 9028 } 9029 } else { 9030 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 9031 if ((origPackage = mSettings.getPackageLPr( 9032 pkg.mOriginalPackages.get(i))) != null) { 9033 // We do have the package already installed under its 9034 // original name... should we use it? 9035 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 9036 // New package is not compatible with original. 9037 origPackage = null; 9038 continue; 9039 } else if (origPackage.sharedUser != null) { 9040 // Make sure uid is compatible between packages. 9041 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 9042 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 9043 + " to " + pkg.packageName + ": old uid " 9044 + origPackage.sharedUser.name 9045 + " differs from " + pkg.mSharedUserId); 9046 origPackage = null; 9047 continue; 9048 } 9049 // TODO: Add case when shared user id is added [b/28144775] 9050 } else { 9051 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 9052 + pkg.packageName + " to old name " + origPackage.name); 9053 } 9054 break; 9055 } 9056 } 9057 } 9058 } 9059 9060 if (mTransferedPackages.contains(pkg.packageName)) { 9061 Slog.w(TAG, "Package " + pkg.packageName 9062 + " was transferred to another, but its .apk remains"); 9063 } 9064 9065 // See comments in nonMutatedPs declaration 9066 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 9067 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName); 9068 if (foundPs != null) { 9069 nonMutatedPs = new PackageSetting(foundPs); 9070 } 9071 } 9072 9073 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) { 9074 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName); 9075 if (foundPs != null) { 9076 primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString; 9077 secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString; 9078 } 9079 } 9080 9081 pkgSetting = mSettings.getPackageLPr(pkg.packageName); 9082 if (pkgSetting != null && pkgSetting.sharedUser != suid) { 9083 PackageManagerService.reportSettingsProblem(Log.WARN, 9084 "Package " + pkg.packageName + " shared user changed from " 9085 + (pkgSetting.sharedUser != null 9086 ? pkgSetting.sharedUser.name : "<nothing>") 9087 + " to " 9088 + (suid != null ? suid.name : "<nothing>") 9089 + "; replacing with new"); 9090 pkgSetting = null; 9091 } 9092 final PackageSetting oldPkgSetting = 9093 pkgSetting == null ? null : new PackageSetting(pkgSetting); 9094 final PackageSetting disabledPkgSetting = 9095 mSettings.getDisabledSystemPkgLPr(pkg.packageName); 9096 9097 String[] usesStaticLibraries = null; 9098 if (pkg.usesStaticLibraries != null) { 9099 usesStaticLibraries = new String[pkg.usesStaticLibraries.size()]; 9100 pkg.usesStaticLibraries.toArray(usesStaticLibraries); 9101 } 9102 9103 if (pkgSetting == null) { 9104 final String parentPackageName = (pkg.parentPackage != null) 9105 ? pkg.parentPackage.packageName : null; 9106 9107 // REMOVE SharedUserSetting from method; update in a separate call 9108 pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage, 9109 disabledPkgSetting, realName, suid, destCodeFile, destResourceFile, 9110 pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi, 9111 pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode, 9112 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user, 9113 true /*allowInstall*/, parentPackageName, pkg.getChildPackageNames(), 9114 UserManagerService.getInstance(), usesStaticLibraries, 9115 pkg.usesStaticLibrariesVersions); 9116 // SIDE EFFECTS; updates system state; move elsewhere 9117 if (origPackage != null) { 9118 mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name); 9119 } 9120 mSettings.addUserToSettingLPw(pkgSetting); 9121 } else { 9122 // REMOVE SharedUserSetting from method; update in a separate call. 9123 // 9124 // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi, 9125 // secondaryCpuAbi are not known at this point so we always update them 9126 // to null here, only to reset them at a later point. 9127 Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile, 9128 pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi, 9129 pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags, 9130 pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(), 9131 UserManagerService.getInstance(), usesStaticLibraries, 9132 pkg.usesStaticLibrariesVersions); 9133 } 9134 // SIDE EFFECTS; persists system state to files on disk; move elsewhere 9135 mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting); 9136 9137 // SIDE EFFECTS; modifies system state; move elsewhere 9138 if (pkgSetting.origPackage != null) { 9139 // If we are first transitioning from an original package, 9140 // fix up the new package's name now. We need to do this after 9141 // looking up the package under its new name, so getPackageLP 9142 // can take care of fiddling things correctly. 9143 pkg.setPackageName(origPackage.name); 9144 9145 // File a report about this. 9146 String msg = "New package " + pkgSetting.realName 9147 + " renamed to replace old package " + pkgSetting.name; 9148 reportSettingsProblem(Log.WARN, msg); 9149 9150 // Make a note of it. 9151 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 9152 mTransferedPackages.add(origPackage.name); 9153 } 9154 9155 // No longer need to retain this. 9156 pkgSetting.origPackage = null; 9157 } 9158 9159 // SIDE EFFECTS; modifies system state; move elsewhere 9160 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 9161 // Make a note of it. 9162 mTransferedPackages.add(pkg.packageName); 9163 } 9164 9165 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 9166 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 9167 } 9168 9169 if ((scanFlags & SCAN_BOOTING) == 0 9170 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 9171 // Check all shared libraries and map to their actual file path. 9172 // We only do this here for apps not on a system dir, because those 9173 // are the only ones that can fail an install due to this. We 9174 // will take care of the system apps by updating all of their 9175 // library paths after the scan is done. Also during the initial 9176 // scan don't update any libs as we do this wholesale after all 9177 // apps are scanned to avoid dependency based scanning. 9178 updateSharedLibrariesLPr(pkg, null); 9179 } 9180 9181 if (mFoundPolicyFile) { 9182 SELinuxMMAC.assignSeinfoValue(pkg); 9183 } 9184 9185 pkg.applicationInfo.uid = pkgSetting.appId; 9186 pkg.mExtras = pkgSetting; 9187 9188 9189 // Static shared libs have same package with different versions where 9190 // we internally use a synthetic package name to allow multiple versions 9191 // of the same package, therefore we need to compare signatures against 9192 // the package setting for the latest library version. 9193 PackageSetting signatureCheckPs = pkgSetting; 9194 if (pkg.applicationInfo.isStaticSharedLibrary()) { 9195 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg); 9196 if (libraryEntry != null) { 9197 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk); 9198 } 9199 } 9200 9201 if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) { 9202 if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) { 9203 // We just determined the app is signed correctly, so bring 9204 // over the latest parsed certs. 9205 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9206 } else { 9207 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 9208 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 9209 "Package " + pkg.packageName + " upgrade keys do not match the " 9210 + "previously installed version"); 9211 } else { 9212 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9213 String msg = "System package " + pkg.packageName 9214 + " signature changed; retaining data."; 9215 reportSettingsProblem(Log.WARN, msg); 9216 } 9217 } 9218 } else { 9219 try { 9220 // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService 9221 verifySignaturesLP(signatureCheckPs, pkg); 9222 // We just determined the app is signed correctly, so bring 9223 // over the latest parsed certs. 9224 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9225 } catch (PackageManagerException e) { 9226 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 9227 throw e; 9228 } 9229 // The signature has changed, but this package is in the system 9230 // image... let's recover! 9231 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9232 // However... if this package is part of a shared user, but it 9233 // doesn't match the signature of the shared user, let's fail. 9234 // What this means is that you can't change the signatures 9235 // associated with an overall shared user, which doesn't seem all 9236 // that unreasonable. 9237 if (signatureCheckPs.sharedUser != null) { 9238 if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures, 9239 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 9240 throw new PackageManagerException( 9241 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 9242 "Signature mismatch for shared user: " 9243 + pkgSetting.sharedUser); 9244 } 9245 } 9246 // File a report about this. 9247 String msg = "System package " + pkg.packageName 9248 + " signature changed; retaining data."; 9249 reportSettingsProblem(Log.WARN, msg); 9250 } 9251 } 9252 9253 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 9254 // This package wants to adopt ownership of permissions from 9255 // another package. 9256 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 9257 final String origName = pkg.mAdoptPermissions.get(i); 9258 final PackageSetting orig = mSettings.getPackageLPr(origName); 9259 if (orig != null) { 9260 if (verifyPackageUpdateLPr(orig, pkg)) { 9261 Slog.i(TAG, "Adopting permissions from " + origName + " to " 9262 + pkg.packageName); 9263 // SIDE EFFECTS; updates permissions system state; move elsewhere 9264 mSettings.transferPermissionsLPw(origName, pkg.packageName); 9265 } 9266 } 9267 } 9268 } 9269 } 9270 9271 pkg.applicationInfo.processName = fixProcessName( 9272 pkg.applicationInfo.packageName, 9273 pkg.applicationInfo.processName); 9274 9275 if (pkg != mPlatformPackage) { 9276 // Get all of our default paths setup 9277 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 9278 } 9279 9280 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 9281 9282 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 9283 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) { 9284 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi"); 9285 derivePackageAbi( 9286 pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir); 9287 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9288 9289 // Some system apps still use directory structure for native libraries 9290 // in which case we might end up not detecting abi solely based on apk 9291 // structure. Try to detect abi based on directory structure. 9292 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 9293 pkg.applicationInfo.primaryCpuAbi == null) { 9294 setBundledAppAbisAndRoots(pkg, pkgSetting); 9295 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 9296 } 9297 } else { 9298 // This is not a first boot or an upgrade, don't bother deriving the 9299 // ABI during the scan. Instead, trust the value that was stored in the 9300 // package setting. 9301 pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings; 9302 pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings; 9303 9304 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 9305 9306 if (DEBUG_ABI_SELECTION) { 9307 Slog.i(TAG, "Using ABIS and native lib paths from settings : " + 9308 pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " + 9309 pkg.applicationInfo.secondaryCpuAbi); 9310 } 9311 } 9312 } else { 9313 if ((scanFlags & SCAN_MOVE) != 0) { 9314 // We haven't run dex-opt for this move (since we've moved the compiled output too) 9315 // but we already have this packages package info in the PackageSetting. We just 9316 // use that and derive the native library path based on the new codepath. 9317 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 9318 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 9319 } 9320 9321 // Set native library paths again. For moves, the path will be updated based on the 9322 // ABIs we've determined above. For non-moves, the path will be updated based on the 9323 // ABIs we determined during compilation, but the path will depend on the final 9324 // package path (after the rename away from the stage path). 9325 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 9326 } 9327 9328 // This is a special case for the "system" package, where the ABI is 9329 // dictated by the zygote configuration (and init.rc). We should keep track 9330 // of this ABI so that we can deal with "normal" applications that run under 9331 // the same UID correctly. 9332 if (mPlatformPackage == pkg) { 9333 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 9334 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 9335 } 9336 9337 // If there's a mismatch between the abi-override in the package setting 9338 // and the abiOverride specified for the install. Warn about this because we 9339 // would've already compiled the app without taking the package setting into 9340 // account. 9341 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 9342 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 9343 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 9344 " for package " + pkg.packageName); 9345 } 9346 } 9347 9348 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9349 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9350 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 9351 9352 // Copy the derived override back to the parsed package, so that we can 9353 // update the package settings accordingly. 9354 pkg.cpuAbiOverride = cpuAbiOverride; 9355 9356 if (DEBUG_ABI_SELECTION) { 9357 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 9358 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 9359 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 9360 } 9361 9362 // Push the derived path down into PackageSettings so we know what to 9363 // clean up at uninstall time. 9364 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 9365 9366 if (DEBUG_ABI_SELECTION) { 9367 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 9368 " primary=" + pkg.applicationInfo.primaryCpuAbi + 9369 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 9370 } 9371 9372 // SIDE EFFECTS; removes DEX files from disk; move elsewhere 9373 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 9374 // We don't do this here during boot because we can do it all 9375 // at once after scanning all existing packages. 9376 // 9377 // We also do this *before* we perform dexopt on this package, so that 9378 // we can avoid redundant dexopts, and also to make sure we've got the 9379 // code and package path correct. 9380 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg); 9381 } 9382 9383 if (mFactoryTest && pkg.requestedPermissions.contains( 9384 android.Manifest.permission.FACTORY_TEST)) { 9385 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 9386 } 9387 9388 if (isSystemApp(pkg)) { 9389 pkgSetting.isOrphaned = true; 9390 } 9391 9392 // Take care of first install / last update times. 9393 final long scanFileTime = getLastModifiedTime(pkg, scanFile); 9394 if (currentTime != 0) { 9395 if (pkgSetting.firstInstallTime == 0) { 9396 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 9397 } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) { 9398 pkgSetting.lastUpdateTime = currentTime; 9399 } 9400 } else if (pkgSetting.firstInstallTime == 0) { 9401 // We need *something*. Take time time stamp of the file. 9402 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 9403 } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 9404 if (scanFileTime != pkgSetting.timeStamp) { 9405 // A package on the system image has changed; consider this 9406 // to be an update. 9407 pkgSetting.lastUpdateTime = scanFileTime; 9408 } 9409 } 9410 pkgSetting.setTimeStamp(scanFileTime); 9411 9412 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 9413 if (nonMutatedPs != null) { 9414 synchronized (mPackages) { 9415 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 9416 } 9417 } 9418 } else { 9419 // Modify state for the given package setting 9420 commitPackageSettings(pkg, pkgSetting, user, scanFlags, 9421 (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/); 9422 if (isEphemeral(pkg)) { 9423 final int userId = user == null ? 0 : user.getIdentifier(); 9424 mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId); 9425 } 9426 } 9427 return pkg; 9428 } 9429 9430 /** 9431 * Applies policy to the parsed package based upon the given policy flags. 9432 * Ensures the package is in a good state. 9433 * <p> 9434 * Implementation detail: This method must NOT have any side effect. It would 9435 * ideally be static, but, it requires locks to read system state. 9436 */ 9437 private void applyPolicy(PackageParser.Package pkg, int policyFlags) { 9438 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 9439 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 9440 if (pkg.applicationInfo.isDirectBootAware()) { 9441 // we're direct boot aware; set for all components 9442 for (PackageParser.Service s : pkg.services) { 9443 s.info.encryptionAware = s.info.directBootAware = true; 9444 } 9445 for (PackageParser.Provider p : pkg.providers) { 9446 p.info.encryptionAware = p.info.directBootAware = true; 9447 } 9448 for (PackageParser.Activity a : pkg.activities) { 9449 a.info.encryptionAware = a.info.directBootAware = true; 9450 } 9451 for (PackageParser.Activity r : pkg.receivers) { 9452 r.info.encryptionAware = r.info.directBootAware = true; 9453 } 9454 } 9455 } else { 9456 // Only allow system apps to be flagged as core apps. 9457 pkg.coreApp = false; 9458 // clear flags not applicable to regular apps 9459 pkg.applicationInfo.privateFlags &= 9460 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 9461 pkg.applicationInfo.privateFlags &= 9462 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 9463 } 9464 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 9465 9466 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 9467 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 9468 } 9469 9470 if (!isSystemApp(pkg)) { 9471 // Only system apps can use these features. 9472 pkg.mOriginalPackages = null; 9473 pkg.mRealPackage = null; 9474 pkg.mAdoptPermissions = null; 9475 } 9476 } 9477 9478 /** 9479 * Asserts the parsed package is valid according to the given policy. If the 9480 * package is invalid, for whatever reason, throws {@link PackgeManagerException}. 9481 * <p> 9482 * Implementation detail: This method must NOT have any side effects. It would 9483 * ideally be static, but, it requires locks to read system state. 9484 * 9485 * @throws PackageManagerException If the package fails any of the validation checks 9486 */ 9487 private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags) 9488 throws PackageManagerException { 9489 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 9490 assertCodePolicy(pkg); 9491 } 9492 9493 if (pkg.applicationInfo.getCodePath() == null || 9494 pkg.applicationInfo.getResourcePath() == null) { 9495 // Bail out. The resource and code paths haven't been set. 9496 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 9497 "Code and resource paths haven't been set correctly"); 9498 } 9499 9500 // Make sure we're not adding any bogus keyset info 9501 KeySetManagerService ksms = mSettings.mKeySetManagerService; 9502 ksms.assertScannedPackageValid(pkg); 9503 9504 synchronized (mPackages) { 9505 // The special "android" package can only be defined once 9506 if (pkg.packageName.equals("android")) { 9507 if (mAndroidApplication != null) { 9508 Slog.w(TAG, "*************************************************"); 9509 Slog.w(TAG, "Core android package being redefined. Skipping."); 9510 Slog.w(TAG, " codePath=" + pkg.codePath); 9511 Slog.w(TAG, "*************************************************"); 9512 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 9513 "Core android package being redefined. Skipping."); 9514 } 9515 } 9516 9517 // A package name must be unique; don't allow duplicates 9518 if (mPackages.containsKey(pkg.packageName)) { 9519 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 9520 "Application package " + pkg.packageName 9521 + " already installed. Skipping duplicate."); 9522 } 9523 9524 if (pkg.applicationInfo.isStaticSharedLibrary()) { 9525 // Static libs have a synthetic package name containing the version 9526 // but we still want the base name to be unique. 9527 if (mPackages.containsKey(pkg.manifestPackageName)) { 9528 throw new PackageManagerException( 9529 "Duplicate static shared lib provider package"); 9530 } 9531 9532 // Static shared libraries should have at least O target SDK 9533 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) { 9534 throw new PackageManagerException( 9535 "Packages declaring static-shared libs must target O SDK or higher"); 9536 } 9537 9538 // Package declaring static a shared lib cannot be ephemeral 9539 if (pkg.applicationInfo.isInstantApp()) { 9540 throw new PackageManagerException( 9541 "Packages declaring static-shared libs cannot be ephemeral"); 9542 } 9543 9544 // Package declaring static a shared lib cannot be renamed since the package 9545 // name is synthetic and apps can't code around package manager internals. 9546 if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) { 9547 throw new PackageManagerException( 9548 "Packages declaring static-shared libs cannot be renamed"); 9549 } 9550 9551 // Package declaring static a shared lib cannot declare child packages 9552 if (!ArrayUtils.isEmpty(pkg.childPackages)) { 9553 throw new PackageManagerException( 9554 "Packages declaring static-shared libs cannot have child packages"); 9555 } 9556 9557 // Package declaring static a shared lib cannot declare dynamic libs 9558 if (!ArrayUtils.isEmpty(pkg.libraryNames)) { 9559 throw new PackageManagerException( 9560 "Packages declaring static-shared libs cannot declare dynamic libs"); 9561 } 9562 9563 // Package declaring static a shared lib cannot declare shared users 9564 if (pkg.mSharedUserId != null) { 9565 throw new PackageManagerException( 9566 "Packages declaring static-shared libs cannot declare shared users"); 9567 } 9568 9569 // Static shared libs cannot declare activities 9570 if (!pkg.activities.isEmpty()) { 9571 throw new PackageManagerException( 9572 "Static shared libs cannot declare activities"); 9573 } 9574 9575 // Static shared libs cannot declare services 9576 if (!pkg.services.isEmpty()) { 9577 throw new PackageManagerException( 9578 "Static shared libs cannot declare services"); 9579 } 9580 9581 // Static shared libs cannot declare providers 9582 if (!pkg.providers.isEmpty()) { 9583 throw new PackageManagerException( 9584 "Static shared libs cannot declare content providers"); 9585 } 9586 9587 // Static shared libs cannot declare receivers 9588 if (!pkg.receivers.isEmpty()) { 9589 throw new PackageManagerException( 9590 "Static shared libs cannot declare broadcast receivers"); 9591 } 9592 9593 // Static shared libs cannot declare permission groups 9594 if (!pkg.permissionGroups.isEmpty()) { 9595 throw new PackageManagerException( 9596 "Static shared libs cannot declare permission groups"); 9597 } 9598 9599 // Static shared libs cannot declare permissions 9600 if (!pkg.permissions.isEmpty()) { 9601 throw new PackageManagerException( 9602 "Static shared libs cannot declare permissions"); 9603 } 9604 9605 // Static shared libs cannot declare protected broadcasts 9606 if (pkg.protectedBroadcasts != null) { 9607 throw new PackageManagerException( 9608 "Static shared libs cannot declare protected broadcasts"); 9609 } 9610 9611 // Static shared libs cannot be overlay targets 9612 if (pkg.mOverlayTarget != null) { 9613 throw new PackageManagerException( 9614 "Static shared libs cannot be overlay targets"); 9615 } 9616 9617 // The version codes must be ordered as lib versions 9618 int minVersionCode = Integer.MIN_VALUE; 9619 int maxVersionCode = Integer.MAX_VALUE; 9620 9621 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get( 9622 pkg.staticSharedLibName); 9623 if (versionedLib != null) { 9624 final int versionCount = versionedLib.size(); 9625 for (int i = 0; i < versionCount; i++) { 9626 SharedLibraryInfo libInfo = versionedLib.valueAt(i).info; 9627 // TODO: We will change version code to long, so in the new API it is long 9628 final int libVersionCode = (int) libInfo.getDeclaringPackage() 9629 .getVersionCode(); 9630 if (libInfo.getVersion() < pkg.staticSharedLibVersion) { 9631 minVersionCode = Math.max(minVersionCode, libVersionCode + 1); 9632 } else if (libInfo.getVersion() > pkg.staticSharedLibVersion) { 9633 maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1); 9634 } else { 9635 minVersionCode = maxVersionCode = libVersionCode; 9636 break; 9637 } 9638 } 9639 } 9640 if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) { 9641 throw new PackageManagerException("Static shared" 9642 + " lib version codes must be ordered as lib versions"); 9643 } 9644 } 9645 9646 // Only privileged apps and updated privileged apps can add child packages. 9647 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 9648 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 9649 throw new PackageManagerException("Only privileged apps can add child " 9650 + "packages. Ignoring package " + pkg.packageName); 9651 } 9652 final int childCount = pkg.childPackages.size(); 9653 for (int i = 0; i < childCount; i++) { 9654 PackageParser.Package childPkg = pkg.childPackages.get(i); 9655 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 9656 childPkg.packageName)) { 9657 throw new PackageManagerException("Can't override child of " 9658 + "another disabled app. Ignoring package " + pkg.packageName); 9659 } 9660 } 9661 } 9662 9663 // If we're only installing presumed-existing packages, require that the 9664 // scanned APK is both already known and at the path previously established 9665 // for it. Previously unknown packages we pick up normally, but if we have an 9666 // a priori expectation about this package's install presence, enforce it. 9667 // With a singular exception for new system packages. When an OTA contains 9668 // a new system package, we allow the codepath to change from a system location 9669 // to the user-installed location. If we don't allow this change, any newer, 9670 // user-installed version of the application will be ignored. 9671 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 9672 if (mExpectingBetter.containsKey(pkg.packageName)) { 9673 logCriticalInfo(Log.WARN, 9674 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 9675 } else { 9676 PackageSetting known = mSettings.getPackageLPr(pkg.packageName); 9677 if (known != null) { 9678 if (DEBUG_PACKAGE_SCANNING) { 9679 Log.d(TAG, "Examining " + pkg.codePath 9680 + " and requiring known paths " + known.codePathString 9681 + " & " + known.resourcePathString); 9682 } 9683 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 9684 || !pkg.applicationInfo.getResourcePath().equals( 9685 known.resourcePathString)) { 9686 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 9687 "Application package " + pkg.packageName 9688 + " found at " + pkg.applicationInfo.getCodePath() 9689 + " but expected at " + known.codePathString 9690 + "; ignoring."); 9691 } 9692 } 9693 } 9694 } 9695 9696 // Verify that this new package doesn't have any content providers 9697 // that conflict with existing packages. Only do this if the 9698 // package isn't already installed, since we don't want to break 9699 // things that are installed. 9700 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 9701 final int N = pkg.providers.size(); 9702 int i; 9703 for (i=0; i<N; i++) { 9704 PackageParser.Provider p = pkg.providers.get(i); 9705 if (p.info.authority != null) { 9706 String names[] = p.info.authority.split(";"); 9707 for (int j = 0; j < names.length; j++) { 9708 if (mProvidersByAuthority.containsKey(names[j])) { 9709 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 9710 final String otherPackageName = 9711 ((other != null && other.getComponentName() != null) ? 9712 other.getComponentName().getPackageName() : "?"); 9713 throw new PackageManagerException( 9714 INSTALL_FAILED_CONFLICTING_PROVIDER, 9715 "Can't install because provider name " + names[j] 9716 + " (in package " + pkg.applicationInfo.packageName 9717 + ") is already used by " + otherPackageName); 9718 } 9719 } 9720 } 9721 } 9722 } 9723 } 9724 } 9725 9726 private boolean addSharedLibraryLPw(String path, String apk, String name, int version, 9727 int type, String declaringPackageName, int declaringVersionCode) { 9728 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 9729 if (versionedLib == null) { 9730 versionedLib = new SparseArray<>(); 9731 mSharedLibraries.put(name, versionedLib); 9732 if (type == SharedLibraryInfo.TYPE_STATIC) { 9733 mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib); 9734 } 9735 } else if (versionedLib.indexOfKey(version) >= 0) { 9736 return false; 9737 } 9738 SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name, 9739 version, type, declaringPackageName, declaringVersionCode); 9740 versionedLib.put(version, libEntry); 9741 return true; 9742 } 9743 9744 private boolean removeSharedLibraryLPw(String name, int version) { 9745 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 9746 if (versionedLib == null) { 9747 return false; 9748 } 9749 final int libIdx = versionedLib.indexOfKey(version); 9750 if (libIdx < 0) { 9751 return false; 9752 } 9753 SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx); 9754 versionedLib.remove(version); 9755 if (versionedLib.size() <= 0) { 9756 mSharedLibraries.remove(name); 9757 if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) { 9758 mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage() 9759 .getPackageName()); 9760 } 9761 } 9762 return true; 9763 } 9764 9765 /** 9766 * Adds a scanned package to the system. When this method is finished, the package will 9767 * be available for query, resolution, etc... 9768 */ 9769 private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting, 9770 UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException { 9771 final String pkgName = pkg.packageName; 9772 if (mCustomResolverComponentName != null && 9773 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 9774 setUpCustomResolverActivity(pkg); 9775 } 9776 9777 if (pkg.packageName.equals("android")) { 9778 synchronized (mPackages) { 9779 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 9780 // Set up information for our fall-back user intent resolution activity. 9781 mPlatformPackage = pkg; 9782 pkg.mVersionCode = mSdkVersion; 9783 mAndroidApplication = pkg.applicationInfo; 9784 9785 if (!mResolverReplaced) { 9786 mResolveActivity.applicationInfo = mAndroidApplication; 9787 mResolveActivity.name = ResolverActivity.class.getName(); 9788 mResolveActivity.packageName = mAndroidApplication.packageName; 9789 mResolveActivity.processName = "system:ui"; 9790 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9791 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 9792 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 9793 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 9794 mResolveActivity.exported = true; 9795 mResolveActivity.enabled = true; 9796 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 9797 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 9798 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 9799 | ActivityInfo.CONFIG_SCREEN_LAYOUT 9800 | ActivityInfo.CONFIG_ORIENTATION 9801 | ActivityInfo.CONFIG_KEYBOARD 9802 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 9803 mResolveInfo.activityInfo = mResolveActivity; 9804 mResolveInfo.priority = 0; 9805 mResolveInfo.preferredOrder = 0; 9806 mResolveInfo.match = 0; 9807 mResolveComponentName = new ComponentName( 9808 mAndroidApplication.packageName, mResolveActivity.name); 9809 } 9810 } 9811 } 9812 } 9813 9814 ArrayList<PackageParser.Package> clientLibPkgs = null; 9815 // writer 9816 synchronized (mPackages) { 9817 boolean hasStaticSharedLibs = false; 9818 9819 // Any app can add new static shared libraries 9820 if (pkg.staticSharedLibName != null) { 9821 // Static shared libs don't allow renaming as they have synthetic package 9822 // names to allow install of multiple versions, so use name from manifest. 9823 if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName, 9824 pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC, 9825 pkg.manifestPackageName, pkg.mVersionCode)) { 9826 hasStaticSharedLibs = true; 9827 } else { 9828 Slog.w(TAG, "Package " + pkg.packageName + " library " 9829 + pkg.staticSharedLibName + " already exists; skipping"); 9830 } 9831 // Static shared libs cannot be updated once installed since they 9832 // use synthetic package name which includes the version code, so 9833 // not need to update other packages's shared lib dependencies. 9834 } 9835 9836 if (!hasStaticSharedLibs 9837 && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 9838 // Only system apps can add new dynamic shared libraries. 9839 if (pkg.libraryNames != null) { 9840 for (int i = 0; i < pkg.libraryNames.size(); i++) { 9841 String name = pkg.libraryNames.get(i); 9842 boolean allowed = false; 9843 if (pkg.isUpdatedSystemApp()) { 9844 // New library entries can only be added through the 9845 // system image. This is important to get rid of a lot 9846 // of nasty edge cases: for example if we allowed a non- 9847 // system update of the app to add a library, then uninstalling 9848 // the update would make the library go away, and assumptions 9849 // we made such as through app install filtering would now 9850 // have allowed apps on the device which aren't compatible 9851 // with it. Better to just have the restriction here, be 9852 // conservative, and create many fewer cases that can negatively 9853 // impact the user experience. 9854 final PackageSetting sysPs = mSettings 9855 .getDisabledSystemPkgLPr(pkg.packageName); 9856 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 9857 for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) { 9858 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 9859 allowed = true; 9860 break; 9861 } 9862 } 9863 } 9864 } else { 9865 allowed = true; 9866 } 9867 if (allowed) { 9868 if (!addSharedLibraryLPw(null, pkg.packageName, name, 9869 SharedLibraryInfo.VERSION_UNDEFINED, 9870 SharedLibraryInfo.TYPE_DYNAMIC, 9871 pkg.packageName, pkg.mVersionCode)) { 9872 Slog.w(TAG, "Package " + pkg.packageName + " library " 9873 + name + " already exists; skipping"); 9874 } 9875 } else { 9876 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 9877 + name + " that is not declared on system image; skipping"); 9878 } 9879 } 9880 9881 if ((scanFlags & SCAN_BOOTING) == 0) { 9882 // If we are not booting, we need to update any applications 9883 // that are clients of our shared library. If we are booting, 9884 // this will all be done once the scan is complete. 9885 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 9886 } 9887 } 9888 } 9889 } 9890 9891 if ((scanFlags & SCAN_BOOTING) != 0) { 9892 // No apps can run during boot scan, so they don't need to be frozen 9893 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 9894 // Caller asked to not kill app, so it's probably not frozen 9895 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 9896 // Caller asked us to ignore frozen check for some reason; they 9897 // probably didn't know the package name 9898 } else { 9899 // We're doing major surgery on this package, so it better be frozen 9900 // right now to keep it from launching 9901 checkPackageFrozen(pkgName); 9902 } 9903 9904 // Also need to kill any apps that are dependent on the library. 9905 if (clientLibPkgs != null) { 9906 for (int i=0; i<clientLibPkgs.size(); i++) { 9907 PackageParser.Package clientPkg = clientLibPkgs.get(i); 9908 killApplication(clientPkg.applicationInfo.packageName, 9909 clientPkg.applicationInfo.uid, "update lib"); 9910 } 9911 } 9912 9913 // writer 9914 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 9915 9916 boolean createIdmapFailed = false; 9917 synchronized (mPackages) { 9918 // We don't expect installation to fail beyond this point 9919 9920 if (pkgSetting.pkg != null) { 9921 // Note that |user| might be null during the initial boot scan. If a codePath 9922 // for an app has changed during a boot scan, it's due to an app update that's 9923 // part of the system partition and marker changes must be applied to all users. 9924 final int userId = ((user != null) ? user : UserHandle.ALL).getIdentifier(); 9925 final int[] userIds = resolveUserIds(userId); 9926 maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg, userIds); 9927 } 9928 9929 // Add the new setting to mSettings 9930 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 9931 // Add the new setting to mPackages 9932 mPackages.put(pkg.applicationInfo.packageName, pkg); 9933 // Make sure we don't accidentally delete its data. 9934 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 9935 while (iter.hasNext()) { 9936 PackageCleanItem item = iter.next(); 9937 if (pkgName.equals(item.packageName)) { 9938 iter.remove(); 9939 } 9940 } 9941 9942 // Add the package's KeySets to the global KeySetManagerService 9943 KeySetManagerService ksms = mSettings.mKeySetManagerService; 9944 ksms.addScannedPackageLPw(pkg); 9945 9946 int N = pkg.providers.size(); 9947 StringBuilder r = null; 9948 int i; 9949 for (i=0; i<N; i++) { 9950 PackageParser.Provider p = pkg.providers.get(i); 9951 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 9952 p.info.processName); 9953 mProviders.addProvider(p); 9954 p.syncable = p.info.isSyncable; 9955 if (p.info.authority != null) { 9956 String names[] = p.info.authority.split(";"); 9957 p.info.authority = null; 9958 for (int j = 0; j < names.length; j++) { 9959 if (j == 1 && p.syncable) { 9960 // We only want the first authority for a provider to possibly be 9961 // syncable, so if we already added this provider using a different 9962 // authority clear the syncable flag. We copy the provider before 9963 // changing it because the mProviders object contains a reference 9964 // to a provider that we don't want to change. 9965 // Only do this for the second authority since the resulting provider 9966 // object can be the same for all future authorities for this provider. 9967 p = new PackageParser.Provider(p); 9968 p.syncable = false; 9969 } 9970 if (!mProvidersByAuthority.containsKey(names[j])) { 9971 mProvidersByAuthority.put(names[j], p); 9972 if (p.info.authority == null) { 9973 p.info.authority = names[j]; 9974 } else { 9975 p.info.authority = p.info.authority + ";" + names[j]; 9976 } 9977 if (DEBUG_PACKAGE_SCANNING) { 9978 if (chatty) 9979 Log.d(TAG, "Registered content provider: " + names[j] 9980 + ", className = " + p.info.name + ", isSyncable = " 9981 + p.info.isSyncable); 9982 } 9983 } else { 9984 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 9985 Slog.w(TAG, "Skipping provider name " + names[j] + 9986 " (in package " + pkg.applicationInfo.packageName + 9987 "): name already used by " 9988 + ((other != null && other.getComponentName() != null) 9989 ? other.getComponentName().getPackageName() : "?")); 9990 } 9991 } 9992 } 9993 if (chatty) { 9994 if (r == null) { 9995 r = new StringBuilder(256); 9996 } else { 9997 r.append(' '); 9998 } 9999 r.append(p.info.name); 10000 } 10001 } 10002 if (r != null) { 10003 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 10004 } 10005 10006 N = pkg.services.size(); 10007 r = null; 10008 for (i=0; i<N; i++) { 10009 PackageParser.Service s = pkg.services.get(i); 10010 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 10011 s.info.processName); 10012 mServices.addService(s); 10013 if (chatty) { 10014 if (r == null) { 10015 r = new StringBuilder(256); 10016 } else { 10017 r.append(' '); 10018 } 10019 r.append(s.info.name); 10020 } 10021 } 10022 if (r != null) { 10023 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 10024 } 10025 10026 N = pkg.receivers.size(); 10027 r = null; 10028 for (i=0; i<N; i++) { 10029 PackageParser.Activity a = pkg.receivers.get(i); 10030 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 10031 a.info.processName); 10032 mReceivers.addActivity(a, "receiver"); 10033 if (chatty) { 10034 if (r == null) { 10035 r = new StringBuilder(256); 10036 } else { 10037 r.append(' '); 10038 } 10039 r.append(a.info.name); 10040 } 10041 } 10042 if (r != null) { 10043 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 10044 } 10045 10046 N = pkg.activities.size(); 10047 r = null; 10048 for (i=0; i<N; i++) { 10049 PackageParser.Activity a = pkg.activities.get(i); 10050 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 10051 a.info.processName); 10052 mActivities.addActivity(a, "activity"); 10053 if (chatty) { 10054 if (r == null) { 10055 r = new StringBuilder(256); 10056 } else { 10057 r.append(' '); 10058 } 10059 r.append(a.info.name); 10060 } 10061 } 10062 if (r != null) { 10063 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 10064 } 10065 10066 N = pkg.permissionGroups.size(); 10067 r = null; 10068 for (i=0; i<N; i++) { 10069 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 10070 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 10071 final String curPackageName = cur == null ? null : cur.info.packageName; 10072 // Dont allow ephemeral apps to define new permission groups. 10073 if (pkg.applicationInfo.isInstantApp()) { 10074 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 10075 + pg.info.packageName 10076 + " ignored: ephemeral apps cannot define new permission groups."); 10077 continue; 10078 } 10079 final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName); 10080 if (cur == null || isPackageUpdate) { 10081 mPermissionGroups.put(pg.info.name, pg); 10082 if (chatty) { 10083 if (r == null) { 10084 r = new StringBuilder(256); 10085 } else { 10086 r.append(' '); 10087 } 10088 if (isPackageUpdate) { 10089 r.append("UPD:"); 10090 } 10091 r.append(pg.info.name); 10092 } 10093 } else { 10094 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 10095 + pg.info.packageName + " ignored: original from " 10096 + cur.info.packageName); 10097 if (chatty) { 10098 if (r == null) { 10099 r = new StringBuilder(256); 10100 } else { 10101 r.append(' '); 10102 } 10103 r.append("DUP:"); 10104 r.append(pg.info.name); 10105 } 10106 } 10107 } 10108 if (r != null) { 10109 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 10110 } 10111 10112 N = pkg.permissions.size(); 10113 r = null; 10114 for (i=0; i<N; i++) { 10115 PackageParser.Permission p = pkg.permissions.get(i); 10116 10117 // Dont allow ephemeral apps to define new permissions. 10118 if (pkg.applicationInfo.isInstantApp()) { 10119 Slog.w(TAG, "Permission " + p.info.name + " from package " 10120 + p.info.packageName 10121 + " ignored: ephemeral apps cannot define new permissions."); 10122 continue; 10123 } 10124 10125 // Assume by default that we did not install this permission into the system. 10126 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 10127 10128 // Now that permission groups have a special meaning, we ignore permission 10129 // groups for legacy apps to prevent unexpected behavior. In particular, 10130 // permissions for one app being granted to someone just becase they happen 10131 // to be in a group defined by another app (before this had no implications). 10132 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 10133 p.group = mPermissionGroups.get(p.info.group); 10134 // Warn for a permission in an unknown group. 10135 if (p.info.group != null && p.group == null) { 10136 Slog.w(TAG, "Permission " + p.info.name + " from package " 10137 + p.info.packageName + " in an unknown group " + p.info.group); 10138 } 10139 } 10140 10141 ArrayMap<String, BasePermission> permissionMap = 10142 p.tree ? mSettings.mPermissionTrees 10143 : mSettings.mPermissions; 10144 BasePermission bp = permissionMap.get(p.info.name); 10145 10146 // Allow system apps to redefine non-system permissions 10147 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 10148 final boolean currentOwnerIsSystem = (bp.perm != null 10149 && isSystemApp(bp.perm.owner)); 10150 if (isSystemApp(p.owner)) { 10151 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 10152 // It's a built-in permission and no owner, take ownership now 10153 bp.packageSetting = pkgSetting; 10154 bp.perm = p; 10155 bp.uid = pkg.applicationInfo.uid; 10156 bp.sourcePackage = p.info.packageName; 10157 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 10158 } else if (!currentOwnerIsSystem) { 10159 String msg = "New decl " + p.owner + " of permission " 10160 + p.info.name + " is system; overriding " + bp.sourcePackage; 10161 reportSettingsProblem(Log.WARN, msg); 10162 bp = null; 10163 } 10164 } 10165 } 10166 10167 if (bp == null) { 10168 bp = new BasePermission(p.info.name, p.info.packageName, 10169 BasePermission.TYPE_NORMAL); 10170 permissionMap.put(p.info.name, bp); 10171 } 10172 10173 if (bp.perm == null) { 10174 if (bp.sourcePackage == null 10175 || bp.sourcePackage.equals(p.info.packageName)) { 10176 BasePermission tree = findPermissionTreeLP(p.info.name); 10177 if (tree == null 10178 || tree.sourcePackage.equals(p.info.packageName)) { 10179 bp.packageSetting = pkgSetting; 10180 bp.perm = p; 10181 bp.uid = pkg.applicationInfo.uid; 10182 bp.sourcePackage = p.info.packageName; 10183 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 10184 if (chatty) { 10185 if (r == null) { 10186 r = new StringBuilder(256); 10187 } else { 10188 r.append(' '); 10189 } 10190 r.append(p.info.name); 10191 } 10192 } else { 10193 Slog.w(TAG, "Permission " + p.info.name + " from package " 10194 + p.info.packageName + " ignored: base tree " 10195 + tree.name + " is from package " 10196 + tree.sourcePackage); 10197 } 10198 } else { 10199 Slog.w(TAG, "Permission " + p.info.name + " from package " 10200 + p.info.packageName + " ignored: original from " 10201 + bp.sourcePackage); 10202 } 10203 } else if (chatty) { 10204 if (r == null) { 10205 r = new StringBuilder(256); 10206 } else { 10207 r.append(' '); 10208 } 10209 r.append("DUP:"); 10210 r.append(p.info.name); 10211 } 10212 if (bp.perm == p) { 10213 bp.protectionLevel = p.info.protectionLevel; 10214 } 10215 } 10216 10217 if (r != null) { 10218 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 10219 } 10220 10221 N = pkg.instrumentation.size(); 10222 r = null; 10223 for (i=0; i<N; i++) { 10224 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 10225 a.info.packageName = pkg.applicationInfo.packageName; 10226 a.info.sourceDir = pkg.applicationInfo.sourceDir; 10227 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 10228 a.info.splitNames = pkg.splitNames; 10229 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 10230 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 10231 a.info.splitDependencies = pkg.applicationInfo.splitDependencies; 10232 a.info.dataDir = pkg.applicationInfo.dataDir; 10233 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 10234 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 10235 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 10236 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 10237 mInstrumentation.put(a.getComponentName(), a); 10238 if (chatty) { 10239 if (r == null) { 10240 r = new StringBuilder(256); 10241 } else { 10242 r.append(' '); 10243 } 10244 r.append(a.info.name); 10245 } 10246 } 10247 if (r != null) { 10248 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 10249 } 10250 10251 if (pkg.protectedBroadcasts != null) { 10252 N = pkg.protectedBroadcasts.size(); 10253 for (i=0; i<N; i++) { 10254 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 10255 } 10256 } 10257 10258 // Create idmap files for pairs of (packages, overlay packages). 10259 // Note: "android", ie framework-res.apk, is handled by native layers. 10260 if (pkg.mOverlayTarget != null) { 10261 // This is an overlay package. 10262 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 10263 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 10264 mOverlays.put(pkg.mOverlayTarget, 10265 new ArrayMap<String, PackageParser.Package>()); 10266 } 10267 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 10268 map.put(pkg.packageName, pkg); 10269 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 10270 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 10271 createIdmapFailed = true; 10272 } 10273 } 10274 } else if (mOverlays.containsKey(pkg.packageName) && 10275 !pkg.packageName.equals("android")) { 10276 // This is a regular package, with one or more known overlay packages. 10277 createIdmapsForPackageLI(pkg); 10278 } 10279 } 10280 10281 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10282 10283 if (createIdmapFailed) { 10284 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 10285 "scanPackageLI failed to createIdmap"); 10286 } 10287 } 10288 10289 private static void maybeRenameForeignDexMarkers(PackageParser.Package existing, 10290 PackageParser.Package update, int[] userIds) { 10291 if (existing.applicationInfo == null || update.applicationInfo == null) { 10292 // This isn't due to an app installation. 10293 return; 10294 } 10295 10296 final File oldCodePath = new File(existing.applicationInfo.getCodePath()); 10297 final File newCodePath = new File(update.applicationInfo.getCodePath()); 10298 10299 // The codePath hasn't changed, so there's nothing for us to do. 10300 if (Objects.equals(oldCodePath, newCodePath)) { 10301 return; 10302 } 10303 10304 File canonicalNewCodePath; 10305 try { 10306 canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath)); 10307 } catch (IOException e) { 10308 Slog.w(TAG, "Failed to get canonical path.", e); 10309 return; 10310 } 10311 10312 // This is a bit of a hack. The oldCodePath doesn't exist at this point (because 10313 // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume 10314 // that the last component of the path (i.e, the name) doesn't need canonicalization 10315 // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now 10316 // but may change in the future. Hopefully this function won't exist at that point. 10317 final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(), 10318 oldCodePath.getName()); 10319 10320 // Calculate the prefixes of the markers. These are just the paths with "/" replaced 10321 // with "@". 10322 String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@'); 10323 if (!oldMarkerPrefix.endsWith("@")) { 10324 oldMarkerPrefix += "@"; 10325 } 10326 String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@'); 10327 if (!newMarkerPrefix.endsWith("@")) { 10328 newMarkerPrefix += "@"; 10329 } 10330 10331 List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly(); 10332 List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size()); 10333 for (String updatedPath : updatedPaths) { 10334 String updatedPathName = new File(updatedPath).getName(); 10335 markerSuffixes.add(updatedPathName.replace('/', '@')); 10336 } 10337 10338 for (int userId : userIds) { 10339 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId); 10340 10341 for (String markerSuffix : markerSuffixes) { 10342 File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix); 10343 File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix); 10344 if (oldForeignUseMark.exists()) { 10345 try { 10346 Os.rename(oldForeignUseMark.getAbsolutePath(), 10347 newForeignUseMark.getAbsolutePath()); 10348 } catch (ErrnoException e) { 10349 Slog.w(TAG, "Failed to rename foreign use marker", e); 10350 oldForeignUseMark.delete(); 10351 } 10352 } 10353 } 10354 } 10355 } 10356 10357 /** 10358 * Derive the ABI of a non-system package located at {@code scanFile}. This information 10359 * is derived purely on the basis of the contents of {@code scanFile} and 10360 * {@code cpuAbiOverride}. 10361 * 10362 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 10363 */ 10364 private static void derivePackageAbi(PackageParser.Package pkg, File scanFile, 10365 String cpuAbiOverride, boolean extractLibs, 10366 File appLib32InstallDir) 10367 throws PackageManagerException { 10368 // Give ourselves some initial paths; we'll come back for another 10369 // pass once we've determined ABI below. 10370 setNativeLibraryPaths(pkg, appLib32InstallDir); 10371 10372 // We would never need to extract libs for forward-locked and external packages, 10373 // since the container service will do it for us. We shouldn't attempt to 10374 // extract libs from system app when it was not updated. 10375 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 10376 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 10377 extractLibs = false; 10378 } 10379 10380 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 10381 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 10382 10383 NativeLibraryHelper.Handle handle = null; 10384 try { 10385 handle = NativeLibraryHelper.Handle.create(pkg); 10386 // TODO(multiArch): This can be null for apps that didn't go through the 10387 // usual installation process. We can calculate it again, like we 10388 // do during install time. 10389 // 10390 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 10391 // unnecessary. 10392 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 10393 10394 // Null out the abis so that they can be recalculated. 10395 pkg.applicationInfo.primaryCpuAbi = null; 10396 pkg.applicationInfo.secondaryCpuAbi = null; 10397 if (isMultiArch(pkg.applicationInfo)) { 10398 // Warn if we've set an abiOverride for multi-lib packages.. 10399 // By definition, we need to copy both 32 and 64 bit libraries for 10400 // such packages. 10401 if (pkg.cpuAbiOverride != null 10402 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 10403 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 10404 } 10405 10406 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 10407 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 10408 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 10409 if (extractLibs) { 10410 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 10411 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 10412 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 10413 useIsaSpecificSubdirs); 10414 } else { 10415 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 10416 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 10417 } 10418 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10419 } 10420 10421 maybeThrowExceptionForMultiArchCopy( 10422 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 10423 10424 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 10425 if (extractLibs) { 10426 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 10427 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 10428 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 10429 useIsaSpecificSubdirs); 10430 } else { 10431 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 10432 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 10433 } 10434 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10435 } 10436 10437 maybeThrowExceptionForMultiArchCopy( 10438 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 10439 10440 if (abi64 >= 0) { 10441 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 10442 } 10443 10444 if (abi32 >= 0) { 10445 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 10446 if (abi64 >= 0) { 10447 if (pkg.use32bitAbi) { 10448 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 10449 pkg.applicationInfo.primaryCpuAbi = abi; 10450 } else { 10451 pkg.applicationInfo.secondaryCpuAbi = abi; 10452 } 10453 } else { 10454 pkg.applicationInfo.primaryCpuAbi = abi; 10455 } 10456 } 10457 10458 } else { 10459 String[] abiList = (cpuAbiOverride != null) ? 10460 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 10461 10462 // Enable gross and lame hacks for apps that are built with old 10463 // SDK tools. We must scan their APKs for renderscript bitcode and 10464 // not launch them if it's present. Don't bother checking on devices 10465 // that don't have 64 bit support. 10466 boolean needsRenderScriptOverride = false; 10467 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 10468 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 10469 abiList = Build.SUPPORTED_32_BIT_ABIS; 10470 needsRenderScriptOverride = true; 10471 } 10472 10473 final int copyRet; 10474 if (extractLibs) { 10475 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 10476 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 10477 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 10478 } else { 10479 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 10480 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 10481 } 10482 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10483 10484 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 10485 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 10486 "Error unpackaging native libs for app, errorCode=" + copyRet); 10487 } 10488 10489 if (copyRet >= 0) { 10490 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 10491 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 10492 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 10493 } else if (needsRenderScriptOverride) { 10494 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 10495 } 10496 } 10497 } catch (IOException ioe) { 10498 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 10499 } finally { 10500 IoUtils.closeQuietly(handle); 10501 } 10502 10503 // Now that we've calculated the ABIs and determined if it's an internal app, 10504 // we will go ahead and populate the nativeLibraryPath. 10505 setNativeLibraryPaths(pkg, appLib32InstallDir); 10506 } 10507 10508 /** 10509 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 10510 * i.e, so that all packages can be run inside a single process if required. 10511 * 10512 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 10513 * this function will either try and make the ABI for all packages in {@code packagesForUser} 10514 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 10515 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 10516 * updating a package that belongs to a shared user. 10517 * 10518 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 10519 * adds unnecessary complexity. 10520 */ 10521 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 10522 PackageParser.Package scannedPackage) { 10523 String requiredInstructionSet = null; 10524 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 10525 requiredInstructionSet = VMRuntime.getInstructionSet( 10526 scannedPackage.applicationInfo.primaryCpuAbi); 10527 } 10528 10529 PackageSetting requirer = null; 10530 for (PackageSetting ps : packagesForUser) { 10531 // If packagesForUser contains scannedPackage, we skip it. This will happen 10532 // when scannedPackage is an update of an existing package. Without this check, 10533 // we will never be able to change the ABI of any package belonging to a shared 10534 // user, even if it's compatible with other packages. 10535 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 10536 if (ps.primaryCpuAbiString == null) { 10537 continue; 10538 } 10539 10540 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 10541 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 10542 // We have a mismatch between instruction sets (say arm vs arm64) warn about 10543 // this but there's not much we can do. 10544 String errorMessage = "Instruction set mismatch, " 10545 + ((requirer == null) ? "[caller]" : requirer) 10546 + " requires " + requiredInstructionSet + " whereas " + ps 10547 + " requires " + instructionSet; 10548 Slog.w(TAG, errorMessage); 10549 } 10550 10551 if (requiredInstructionSet == null) { 10552 requiredInstructionSet = instructionSet; 10553 requirer = ps; 10554 } 10555 } 10556 } 10557 10558 if (requiredInstructionSet != null) { 10559 String adjustedAbi; 10560 if (requirer != null) { 10561 // requirer != null implies that either scannedPackage was null or that scannedPackage 10562 // did not require an ABI, in which case we have to adjust scannedPackage to match 10563 // the ABI of the set (which is the same as requirer's ABI) 10564 adjustedAbi = requirer.primaryCpuAbiString; 10565 if (scannedPackage != null) { 10566 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 10567 } 10568 } else { 10569 // requirer == null implies that we're updating all ABIs in the set to 10570 // match scannedPackage. 10571 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 10572 } 10573 10574 for (PackageSetting ps : packagesForUser) { 10575 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 10576 if (ps.primaryCpuAbiString != null) { 10577 continue; 10578 } 10579 10580 ps.primaryCpuAbiString = adjustedAbi; 10581 if (ps.pkg != null && ps.pkg.applicationInfo != null && 10582 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 10583 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 10584 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 10585 + " (requirer=" 10586 + (requirer == null ? "null" : requirer.pkg.packageName) 10587 + ", scannedPackage=" 10588 + (scannedPackage != null ? scannedPackage.packageName : "null") 10589 + ")"); 10590 try { 10591 mInstaller.rmdex(ps.codePathString, 10592 getDexCodeInstructionSet(getPreferredInstructionSet())); 10593 } catch (InstallerException ignored) { 10594 } 10595 } 10596 } 10597 } 10598 } 10599 } 10600 10601 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 10602 synchronized (mPackages) { 10603 mResolverReplaced = true; 10604 // Set up information for custom user intent resolution activity. 10605 mResolveActivity.applicationInfo = pkg.applicationInfo; 10606 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 10607 mResolveActivity.packageName = pkg.applicationInfo.packageName; 10608 mResolveActivity.processName = pkg.applicationInfo.packageName; 10609 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 10610 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 10611 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 10612 mResolveActivity.theme = 0; 10613 mResolveActivity.exported = true; 10614 mResolveActivity.enabled = true; 10615 mResolveInfo.activityInfo = mResolveActivity; 10616 mResolveInfo.priority = 0; 10617 mResolveInfo.preferredOrder = 0; 10618 mResolveInfo.match = 0; 10619 mResolveComponentName = mCustomResolverComponentName; 10620 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 10621 mResolveComponentName); 10622 } 10623 } 10624 10625 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 10626 if (installerComponent == null) { 10627 if (DEBUG_EPHEMERAL) { 10628 Slog.d(TAG, "Clear ephemeral installer activity"); 10629 } 10630 mEphemeralInstallerActivity.applicationInfo = null; 10631 return; 10632 } 10633 10634 if (DEBUG_EPHEMERAL) { 10635 Slog.d(TAG, "Set ephemeral installer activity: " + installerComponent); 10636 } 10637 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 10638 // Set up information for ephemeral installer activity 10639 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 10640 mEphemeralInstallerActivity.name = installerComponent.getClassName(); 10641 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 10642 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 10643 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 10644 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS 10645 | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 10646 mEphemeralInstallerActivity.theme = 0; 10647 mEphemeralInstallerActivity.exported = true; 10648 mEphemeralInstallerActivity.enabled = true; 10649 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 10650 mEphemeralInstallerInfo.priority = 0; 10651 mEphemeralInstallerInfo.preferredOrder = 1; 10652 mEphemeralInstallerInfo.isDefault = true; 10653 mEphemeralInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 10654 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 10655 } 10656 10657 private static String calculateBundledApkRoot(final String codePathString) { 10658 final File codePath = new File(codePathString); 10659 final File codeRoot; 10660 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 10661 codeRoot = Environment.getRootDirectory(); 10662 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 10663 codeRoot = Environment.getOemDirectory(); 10664 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 10665 codeRoot = Environment.getVendorDirectory(); 10666 } else { 10667 // Unrecognized code path; take its top real segment as the apk root: 10668 // e.g. /something/app/blah.apk => /something 10669 try { 10670 File f = codePath.getCanonicalFile(); 10671 File parent = f.getParentFile(); // non-null because codePath is a file 10672 File tmp; 10673 while ((tmp = parent.getParentFile()) != null) { 10674 f = parent; 10675 parent = tmp; 10676 } 10677 codeRoot = f; 10678 Slog.w(TAG, "Unrecognized code path " 10679 + codePath + " - using " + codeRoot); 10680 } catch (IOException e) { 10681 // Can't canonicalize the code path -- shenanigans? 10682 Slog.w(TAG, "Can't canonicalize code path " + codePath); 10683 return Environment.getRootDirectory().getPath(); 10684 } 10685 } 10686 return codeRoot.getPath(); 10687 } 10688 10689 /** 10690 * Derive and set the location of native libraries for the given package, 10691 * which varies depending on where and how the package was installed. 10692 */ 10693 private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) { 10694 final ApplicationInfo info = pkg.applicationInfo; 10695 final String codePath = pkg.codePath; 10696 final File codeFile = new File(codePath); 10697 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 10698 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 10699 10700 info.nativeLibraryRootDir = null; 10701 info.nativeLibraryRootRequiresIsa = false; 10702 info.nativeLibraryDir = null; 10703 info.secondaryNativeLibraryDir = null; 10704 10705 if (isApkFile(codeFile)) { 10706 // Monolithic install 10707 if (bundledApp) { 10708 // If "/system/lib64/apkname" exists, assume that is the per-package 10709 // native library directory to use; otherwise use "/system/lib/apkname". 10710 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 10711 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 10712 getPrimaryInstructionSet(info)); 10713 10714 // This is a bundled system app so choose the path based on the ABI. 10715 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 10716 // is just the default path. 10717 final String apkName = deriveCodePathName(codePath); 10718 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 10719 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 10720 apkName).getAbsolutePath(); 10721 10722 if (info.secondaryCpuAbi != null) { 10723 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 10724 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 10725 secondaryLibDir, apkName).getAbsolutePath(); 10726 } 10727 } else if (asecApp) { 10728 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 10729 .getAbsolutePath(); 10730 } else { 10731 final String apkName = deriveCodePathName(codePath); 10732 info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName) 10733 .getAbsolutePath(); 10734 } 10735 10736 info.nativeLibraryRootRequiresIsa = false; 10737 info.nativeLibraryDir = info.nativeLibraryRootDir; 10738 } else { 10739 // Cluster install 10740 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 10741 info.nativeLibraryRootRequiresIsa = true; 10742 10743 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 10744 getPrimaryInstructionSet(info)).getAbsolutePath(); 10745 10746 if (info.secondaryCpuAbi != null) { 10747 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 10748 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 10749 } 10750 } 10751 } 10752 10753 /** 10754 * Calculate the abis and roots for a bundled app. These can uniquely 10755 * be determined from the contents of the system partition, i.e whether 10756 * it contains 64 or 32 bit shared libraries etc. We do not validate any 10757 * of this information, and instead assume that the system was built 10758 * sensibly. 10759 */ 10760 private static void setBundledAppAbisAndRoots(PackageParser.Package pkg, 10761 PackageSetting pkgSetting) { 10762 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 10763 10764 // If "/system/lib64/apkname" exists, assume that is the per-package 10765 // native library directory to use; otherwise use "/system/lib/apkname". 10766 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 10767 setBundledAppAbi(pkg, apkRoot, apkName); 10768 // pkgSetting might be null during rescan following uninstall of updates 10769 // to a bundled app, so accommodate that possibility. The settings in 10770 // that case will be established later from the parsed package. 10771 // 10772 // If the settings aren't null, sync them up with what we've just derived. 10773 // note that apkRoot isn't stored in the package settings. 10774 if (pkgSetting != null) { 10775 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 10776 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 10777 } 10778 } 10779 10780 /** 10781 * Deduces the ABI of a bundled app and sets the relevant fields on the 10782 * parsed pkg object. 10783 * 10784 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 10785 * under which system libraries are installed. 10786 * @param apkName the name of the installed package. 10787 */ 10788 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 10789 final File codeFile = new File(pkg.codePath); 10790 10791 final boolean has64BitLibs; 10792 final boolean has32BitLibs; 10793 if (isApkFile(codeFile)) { 10794 // Monolithic install 10795 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 10796 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 10797 } else { 10798 // Cluster install 10799 final File rootDir = new File(codeFile, LIB_DIR_NAME); 10800 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 10801 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 10802 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 10803 has64BitLibs = (new File(rootDir, isa)).exists(); 10804 } else { 10805 has64BitLibs = false; 10806 } 10807 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 10808 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 10809 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 10810 has32BitLibs = (new File(rootDir, isa)).exists(); 10811 } else { 10812 has32BitLibs = false; 10813 } 10814 } 10815 10816 if (has64BitLibs && !has32BitLibs) { 10817 // The package has 64 bit libs, but not 32 bit libs. Its primary 10818 // ABI should be 64 bit. We can safely assume here that the bundled 10819 // native libraries correspond to the most preferred ABI in the list. 10820 10821 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 10822 pkg.applicationInfo.secondaryCpuAbi = null; 10823 } else if (has32BitLibs && !has64BitLibs) { 10824 // The package has 32 bit libs but not 64 bit libs. Its primary 10825 // ABI should be 32 bit. 10826 10827 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 10828 pkg.applicationInfo.secondaryCpuAbi = null; 10829 } else if (has32BitLibs && has64BitLibs) { 10830 // The application has both 64 and 32 bit bundled libraries. We check 10831 // here that the app declares multiArch support, and warn if it doesn't. 10832 // 10833 // We will be lenient here and record both ABIs. The primary will be the 10834 // ABI that's higher on the list, i.e, a device that's configured to prefer 10835 // 64 bit apps will see a 64 bit primary ABI, 10836 10837 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 10838 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 10839 } 10840 10841 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 10842 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 10843 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 10844 } else { 10845 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 10846 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 10847 } 10848 } else { 10849 pkg.applicationInfo.primaryCpuAbi = null; 10850 pkg.applicationInfo.secondaryCpuAbi = null; 10851 } 10852 } 10853 10854 private void killApplication(String pkgName, int appId, String reason) { 10855 killApplication(pkgName, appId, UserHandle.USER_ALL, reason); 10856 } 10857 10858 private void killApplication(String pkgName, int appId, int userId, String reason) { 10859 // Request the ActivityManager to kill the process(only for existing packages) 10860 // so that we do not end up in a confused state while the user is still using the older 10861 // version of the application while the new one gets installed. 10862 final long token = Binder.clearCallingIdentity(); 10863 try { 10864 IActivityManager am = ActivityManager.getService(); 10865 if (am != null) { 10866 try { 10867 am.killApplication(pkgName, appId, userId, reason); 10868 } catch (RemoteException e) { 10869 } 10870 } 10871 } finally { 10872 Binder.restoreCallingIdentity(token); 10873 } 10874 } 10875 10876 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 10877 // Remove the parent package setting 10878 PackageSetting ps = (PackageSetting) pkg.mExtras; 10879 if (ps != null) { 10880 removePackageLI(ps, chatty); 10881 } 10882 // Remove the child package setting 10883 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 10884 for (int i = 0; i < childCount; i++) { 10885 PackageParser.Package childPkg = pkg.childPackages.get(i); 10886 ps = (PackageSetting) childPkg.mExtras; 10887 if (ps != null) { 10888 removePackageLI(ps, chatty); 10889 } 10890 } 10891 } 10892 10893 void removePackageLI(PackageSetting ps, boolean chatty) { 10894 if (DEBUG_INSTALL) { 10895 if (chatty) 10896 Log.d(TAG, "Removing package " + ps.name); 10897 } 10898 10899 // writer 10900 synchronized (mPackages) { 10901 mPackages.remove(ps.name); 10902 final PackageParser.Package pkg = ps.pkg; 10903 if (pkg != null) { 10904 cleanPackageDataStructuresLILPw(pkg, chatty); 10905 } 10906 } 10907 } 10908 10909 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 10910 if (DEBUG_INSTALL) { 10911 if (chatty) 10912 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 10913 } 10914 10915 // writer 10916 synchronized (mPackages) { 10917 // Remove the parent package 10918 mPackages.remove(pkg.applicationInfo.packageName); 10919 cleanPackageDataStructuresLILPw(pkg, chatty); 10920 10921 // Remove the child packages 10922 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 10923 for (int i = 0; i < childCount; i++) { 10924 PackageParser.Package childPkg = pkg.childPackages.get(i); 10925 mPackages.remove(childPkg.applicationInfo.packageName); 10926 cleanPackageDataStructuresLILPw(childPkg, chatty); 10927 } 10928 } 10929 } 10930 10931 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 10932 int N = pkg.providers.size(); 10933 StringBuilder r = null; 10934 int i; 10935 for (i=0; i<N; i++) { 10936 PackageParser.Provider p = pkg.providers.get(i); 10937 mProviders.removeProvider(p); 10938 if (p.info.authority == null) { 10939 10940 /* There was another ContentProvider with this authority when 10941 * this app was installed so this authority is null, 10942 * Ignore it as we don't have to unregister the provider. 10943 */ 10944 continue; 10945 } 10946 String names[] = p.info.authority.split(";"); 10947 for (int j = 0; j < names.length; j++) { 10948 if (mProvidersByAuthority.get(names[j]) == p) { 10949 mProvidersByAuthority.remove(names[j]); 10950 if (DEBUG_REMOVE) { 10951 if (chatty) 10952 Log.d(TAG, "Unregistered content provider: " + names[j] 10953 + ", className = " + p.info.name + ", isSyncable = " 10954 + p.info.isSyncable); 10955 } 10956 } 10957 } 10958 if (DEBUG_REMOVE && chatty) { 10959 if (r == null) { 10960 r = new StringBuilder(256); 10961 } else { 10962 r.append(' '); 10963 } 10964 r.append(p.info.name); 10965 } 10966 } 10967 if (r != null) { 10968 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 10969 } 10970 10971 N = pkg.services.size(); 10972 r = null; 10973 for (i=0; i<N; i++) { 10974 PackageParser.Service s = pkg.services.get(i); 10975 mServices.removeService(s); 10976 if (chatty) { 10977 if (r == null) { 10978 r = new StringBuilder(256); 10979 } else { 10980 r.append(' '); 10981 } 10982 r.append(s.info.name); 10983 } 10984 } 10985 if (r != null) { 10986 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 10987 } 10988 10989 N = pkg.receivers.size(); 10990 r = null; 10991 for (i=0; i<N; i++) { 10992 PackageParser.Activity a = pkg.receivers.get(i); 10993 mReceivers.removeActivity(a, "receiver"); 10994 if (DEBUG_REMOVE && chatty) { 10995 if (r == null) { 10996 r = new StringBuilder(256); 10997 } else { 10998 r.append(' '); 10999 } 11000 r.append(a.info.name); 11001 } 11002 } 11003 if (r != null) { 11004 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 11005 } 11006 11007 N = pkg.activities.size(); 11008 r = null; 11009 for (i=0; i<N; i++) { 11010 PackageParser.Activity a = pkg.activities.get(i); 11011 mActivities.removeActivity(a, "activity"); 11012 if (DEBUG_REMOVE && chatty) { 11013 if (r == null) { 11014 r = new StringBuilder(256); 11015 } else { 11016 r.append(' '); 11017 } 11018 r.append(a.info.name); 11019 } 11020 } 11021 if (r != null) { 11022 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 11023 } 11024 11025 N = pkg.permissions.size(); 11026 r = null; 11027 for (i=0; i<N; i++) { 11028 PackageParser.Permission p = pkg.permissions.get(i); 11029 BasePermission bp = mSettings.mPermissions.get(p.info.name); 11030 if (bp == null) { 11031 bp = mSettings.mPermissionTrees.get(p.info.name); 11032 } 11033 if (bp != null && bp.perm == p) { 11034 bp.perm = null; 11035 if (DEBUG_REMOVE && chatty) { 11036 if (r == null) { 11037 r = new StringBuilder(256); 11038 } else { 11039 r.append(' '); 11040 } 11041 r.append(p.info.name); 11042 } 11043 } 11044 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 11045 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 11046 if (appOpPkgs != null) { 11047 appOpPkgs.remove(pkg.packageName); 11048 } 11049 } 11050 } 11051 if (r != null) { 11052 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 11053 } 11054 11055 N = pkg.requestedPermissions.size(); 11056 r = null; 11057 for (i=0; i<N; i++) { 11058 String perm = pkg.requestedPermissions.get(i); 11059 BasePermission bp = mSettings.mPermissions.get(perm); 11060 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 11061 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 11062 if (appOpPkgs != null) { 11063 appOpPkgs.remove(pkg.packageName); 11064 if (appOpPkgs.isEmpty()) { 11065 mAppOpPermissionPackages.remove(perm); 11066 } 11067 } 11068 } 11069 } 11070 if (r != null) { 11071 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 11072 } 11073 11074 N = pkg.instrumentation.size(); 11075 r = null; 11076 for (i=0; i<N; i++) { 11077 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 11078 mInstrumentation.remove(a.getComponentName()); 11079 if (DEBUG_REMOVE && chatty) { 11080 if (r == null) { 11081 r = new StringBuilder(256); 11082 } else { 11083 r.append(' '); 11084 } 11085 r.append(a.info.name); 11086 } 11087 } 11088 if (r != null) { 11089 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 11090 } 11091 11092 r = null; 11093 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 11094 // Only system apps can hold shared libraries. 11095 if (pkg.libraryNames != null) { 11096 for (i = 0; i < pkg.libraryNames.size(); i++) { 11097 String name = pkg.libraryNames.get(i); 11098 if (removeSharedLibraryLPw(name, 0)) { 11099 if (DEBUG_REMOVE && chatty) { 11100 if (r == null) { 11101 r = new StringBuilder(256); 11102 } else { 11103 r.append(' '); 11104 } 11105 r.append(name); 11106 } 11107 } 11108 } 11109 } 11110 } 11111 11112 r = null; 11113 11114 // Any package can hold static shared libraries. 11115 if (pkg.staticSharedLibName != null) { 11116 if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) { 11117 if (DEBUG_REMOVE && chatty) { 11118 if (r == null) { 11119 r = new StringBuilder(256); 11120 } else { 11121 r.append(' '); 11122 } 11123 r.append(pkg.staticSharedLibName); 11124 } 11125 } 11126 } 11127 11128 if (r != null) { 11129 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 11130 } 11131 } 11132 11133 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 11134 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 11135 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 11136 return true; 11137 } 11138 } 11139 return false; 11140 } 11141 11142 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 11143 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 11144 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 11145 11146 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 11147 // Update the parent permissions 11148 updatePermissionsLPw(pkg.packageName, pkg, flags); 11149 // Update the child permissions 11150 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 11151 for (int i = 0; i < childCount; i++) { 11152 PackageParser.Package childPkg = pkg.childPackages.get(i); 11153 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 11154 } 11155 } 11156 11157 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 11158 int flags) { 11159 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 11160 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 11161 } 11162 11163 private void updatePermissionsLPw(String changingPkg, 11164 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 11165 // Make sure there are no dangling permission trees. 11166 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 11167 while (it.hasNext()) { 11168 final BasePermission bp = it.next(); 11169 if (bp.packageSetting == null) { 11170 // We may not yet have parsed the package, so just see if 11171 // we still know about its settings. 11172 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 11173 } 11174 if (bp.packageSetting == null) { 11175 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 11176 + " from package " + bp.sourcePackage); 11177 it.remove(); 11178 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 11179 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 11180 Slog.i(TAG, "Removing old permission tree: " + bp.name 11181 + " from package " + bp.sourcePackage); 11182 flags |= UPDATE_PERMISSIONS_ALL; 11183 it.remove(); 11184 } 11185 } 11186 } 11187 11188 // Make sure all dynamic permissions have been assigned to a package, 11189 // and make sure there are no dangling permissions. 11190 it = mSettings.mPermissions.values().iterator(); 11191 while (it.hasNext()) { 11192 final BasePermission bp = it.next(); 11193 if (bp.type == BasePermission.TYPE_DYNAMIC) { 11194 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 11195 + bp.name + " pkg=" + bp.sourcePackage 11196 + " info=" + bp.pendingInfo); 11197 if (bp.packageSetting == null && bp.pendingInfo != null) { 11198 final BasePermission tree = findPermissionTreeLP(bp.name); 11199 if (tree != null && tree.perm != null) { 11200 bp.packageSetting = tree.packageSetting; 11201 bp.perm = new PackageParser.Permission(tree.perm.owner, 11202 new PermissionInfo(bp.pendingInfo)); 11203 bp.perm.info.packageName = tree.perm.info.packageName; 11204 bp.perm.info.name = bp.name; 11205 bp.uid = tree.uid; 11206 } 11207 } 11208 } 11209 if (bp.packageSetting == null) { 11210 // We may not yet have parsed the package, so just see if 11211 // we still know about its settings. 11212 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 11213 } 11214 if (bp.packageSetting == null) { 11215 Slog.w(TAG, "Removing dangling permission: " + bp.name 11216 + " from package " + bp.sourcePackage); 11217 it.remove(); 11218 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 11219 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 11220 Slog.i(TAG, "Removing old permission: " + bp.name 11221 + " from package " + bp.sourcePackage); 11222 flags |= UPDATE_PERMISSIONS_ALL; 11223 it.remove(); 11224 } 11225 } 11226 } 11227 11228 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 11229 // Now update the permissions for all packages, in particular 11230 // replace the granted permissions of the system packages. 11231 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 11232 for (PackageParser.Package pkg : mPackages.values()) { 11233 if (pkg != pkgInfo) { 11234 // Only replace for packages on requested volume 11235 final String volumeUuid = getVolumeUuidForPackage(pkg); 11236 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 11237 && Objects.equals(replaceVolumeUuid, volumeUuid); 11238 grantPermissionsLPw(pkg, replace, changingPkg); 11239 } 11240 } 11241 } 11242 11243 if (pkgInfo != null) { 11244 // Only replace for packages on requested volume 11245 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 11246 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 11247 && Objects.equals(replaceVolumeUuid, volumeUuid); 11248 grantPermissionsLPw(pkgInfo, replace, changingPkg); 11249 } 11250 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11251 } 11252 11253 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 11254 String packageOfInterest) { 11255 // IMPORTANT: There are two types of permissions: install and runtime. 11256 // Install time permissions are granted when the app is installed to 11257 // all device users and users added in the future. Runtime permissions 11258 // are granted at runtime explicitly to specific users. Normal and signature 11259 // protected permissions are install time permissions. Dangerous permissions 11260 // are install permissions if the app's target SDK is Lollipop MR1 or older, 11261 // otherwise they are runtime permissions. This function does not manage 11262 // runtime permissions except for the case an app targeting Lollipop MR1 11263 // being upgraded to target a newer SDK, in which case dangerous permissions 11264 // are transformed from install time to runtime ones. 11265 11266 final PackageSetting ps = (PackageSetting) pkg.mExtras; 11267 if (ps == null) { 11268 return; 11269 } 11270 11271 PermissionsState permissionsState = ps.getPermissionsState(); 11272 PermissionsState origPermissions = permissionsState; 11273 11274 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 11275 11276 boolean runtimePermissionsRevoked = false; 11277 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 11278 11279 boolean changedInstallPermission = false; 11280 11281 if (replace) { 11282 ps.installPermissionsFixed = false; 11283 if (!ps.isSharedUser()) { 11284 origPermissions = new PermissionsState(permissionsState); 11285 permissionsState.reset(); 11286 } else { 11287 // We need to know only about runtime permission changes since the 11288 // calling code always writes the install permissions state but 11289 // the runtime ones are written only if changed. The only cases of 11290 // changed runtime permissions here are promotion of an install to 11291 // runtime and revocation of a runtime from a shared user. 11292 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 11293 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 11294 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 11295 runtimePermissionsRevoked = true; 11296 } 11297 } 11298 } 11299 11300 permissionsState.setGlobalGids(mGlobalGids); 11301 11302 final int N = pkg.requestedPermissions.size(); 11303 for (int i=0; i<N; i++) { 11304 final String name = pkg.requestedPermissions.get(i); 11305 final BasePermission bp = mSettings.mPermissions.get(name); 11306 11307 if (DEBUG_INSTALL) { 11308 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 11309 } 11310 11311 if (bp == null || bp.packageSetting == null) { 11312 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 11313 Slog.w(TAG, "Unknown permission " + name 11314 + " in package " + pkg.packageName); 11315 } 11316 continue; 11317 } 11318 11319 11320 // Limit ephemeral apps to ephemeral allowed permissions. 11321 if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) { 11322 Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package " 11323 + pkg.packageName); 11324 continue; 11325 } 11326 11327 final String perm = bp.name; 11328 boolean allowedSig = false; 11329 int grant = GRANT_DENIED; 11330 11331 // Keep track of app op permissions. 11332 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 11333 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 11334 if (pkgs == null) { 11335 pkgs = new ArraySet<>(); 11336 mAppOpPermissionPackages.put(bp.name, pkgs); 11337 } 11338 pkgs.add(pkg.packageName); 11339 } 11340 11341 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 11342 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 11343 >= Build.VERSION_CODES.M; 11344 switch (level) { 11345 case PermissionInfo.PROTECTION_NORMAL: { 11346 // For all apps normal permissions are install time ones. 11347 grant = GRANT_INSTALL; 11348 } break; 11349 11350 case PermissionInfo.PROTECTION_DANGEROUS: { 11351 // If a permission review is required for legacy apps we represent 11352 // their permissions as always granted runtime ones since we need 11353 // to keep the review required permission flag per user while an 11354 // install permission's state is shared across all users. 11355 if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) { 11356 // For legacy apps dangerous permissions are install time ones. 11357 grant = GRANT_INSTALL; 11358 } else if (origPermissions.hasInstallPermission(bp.name)) { 11359 // For legacy apps that became modern, install becomes runtime. 11360 grant = GRANT_UPGRADE; 11361 } else if (mPromoteSystemApps 11362 && isSystemApp(ps) 11363 && mExistingSystemPackages.contains(ps.name)) { 11364 // For legacy system apps, install becomes runtime. 11365 // We cannot check hasInstallPermission() for system apps since those 11366 // permissions were granted implicitly and not persisted pre-M. 11367 grant = GRANT_UPGRADE; 11368 } else { 11369 // For modern apps keep runtime permissions unchanged. 11370 grant = GRANT_RUNTIME; 11371 } 11372 } break; 11373 11374 case PermissionInfo.PROTECTION_SIGNATURE: { 11375 // For all apps signature permissions are install time ones. 11376 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 11377 if (allowedSig) { 11378 grant = GRANT_INSTALL; 11379 } 11380 } break; 11381 } 11382 11383 if (DEBUG_INSTALL) { 11384 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 11385 } 11386 11387 if (grant != GRANT_DENIED) { 11388 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 11389 // If this is an existing, non-system package, then 11390 // we can't add any new permissions to it. 11391 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 11392 // Except... if this is a permission that was added 11393 // to the platform (note: need to only do this when 11394 // updating the platform). 11395 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 11396 grant = GRANT_DENIED; 11397 } 11398 } 11399 } 11400 11401 switch (grant) { 11402 case GRANT_INSTALL: { 11403 // Revoke this as runtime permission to handle the case of 11404 // a runtime permission being downgraded to an install one. 11405 // Also in permission review mode we keep dangerous permissions 11406 // for legacy apps 11407 for (int userId : UserManagerService.getInstance().getUserIds()) { 11408 if (origPermissions.getRuntimePermissionState( 11409 bp.name, userId) != null) { 11410 // Revoke the runtime permission and clear the flags. 11411 origPermissions.revokeRuntimePermission(bp, userId); 11412 origPermissions.updatePermissionFlags(bp, userId, 11413 PackageManager.MASK_PERMISSION_FLAGS, 0); 11414 // If we revoked a permission permission, we have to write. 11415 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11416 changedRuntimePermissionUserIds, userId); 11417 } 11418 } 11419 // Grant an install permission. 11420 if (permissionsState.grantInstallPermission(bp) != 11421 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11422 changedInstallPermission = true; 11423 } 11424 } break; 11425 11426 case GRANT_RUNTIME: { 11427 // Grant previously granted runtime permissions. 11428 for (int userId : UserManagerService.getInstance().getUserIds()) { 11429 PermissionState permissionState = origPermissions 11430 .getRuntimePermissionState(bp.name, userId); 11431 int flags = permissionState != null 11432 ? permissionState.getFlags() : 0; 11433 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 11434 // Don't propagate the permission in a permission review mode if 11435 // the former was revoked, i.e. marked to not propagate on upgrade. 11436 // Note that in a permission review mode install permissions are 11437 // represented as constantly granted runtime ones since we need to 11438 // keep a per user state associated with the permission. Also the 11439 // revoke on upgrade flag is no longer applicable and is reset. 11440 final boolean revokeOnUpgrade = (flags & PackageManager 11441 .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 11442 if (revokeOnUpgrade) { 11443 flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 11444 // Since we changed the flags, we have to write. 11445 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11446 changedRuntimePermissionUserIds, userId); 11447 } 11448 if (!mPermissionReviewRequired || !revokeOnUpgrade) { 11449 if (permissionsState.grantRuntimePermission(bp, userId) == 11450 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11451 // If we cannot put the permission as it was, 11452 // we have to write. 11453 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11454 changedRuntimePermissionUserIds, userId); 11455 } 11456 } 11457 11458 // If the app supports runtime permissions no need for a review. 11459 if (mPermissionReviewRequired 11460 && appSupportsRuntimePermissions 11461 && (flags & PackageManager 11462 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 11463 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 11464 // Since we changed the flags, we have to write. 11465 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11466 changedRuntimePermissionUserIds, userId); 11467 } 11468 } else if (mPermissionReviewRequired 11469 && !appSupportsRuntimePermissions) { 11470 // For legacy apps that need a permission review, every new 11471 // runtime permission is granted but it is pending a review. 11472 // We also need to review only platform defined runtime 11473 // permissions as these are the only ones the platform knows 11474 // how to disable the API to simulate revocation as legacy 11475 // apps don't expect to run with revoked permissions. 11476 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 11477 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 11478 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 11479 // We changed the flags, hence have to write. 11480 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11481 changedRuntimePermissionUserIds, userId); 11482 } 11483 } 11484 if (permissionsState.grantRuntimePermission(bp, userId) 11485 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 11486 // We changed the permission, hence have to write. 11487 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11488 changedRuntimePermissionUserIds, userId); 11489 } 11490 } 11491 // Propagate the permission flags. 11492 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 11493 } 11494 } break; 11495 11496 case GRANT_UPGRADE: { 11497 // Grant runtime permissions for a previously held install permission. 11498 PermissionState permissionState = origPermissions 11499 .getInstallPermissionState(bp.name); 11500 final int flags = permissionState != null ? permissionState.getFlags() : 0; 11501 11502 if (origPermissions.revokeInstallPermission(bp) 11503 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 11504 // We will be transferring the permission flags, so clear them. 11505 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 11506 PackageManager.MASK_PERMISSION_FLAGS, 0); 11507 changedInstallPermission = true; 11508 } 11509 11510 // If the permission is not to be promoted to runtime we ignore it and 11511 // also its other flags as they are not applicable to install permissions. 11512 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 11513 for (int userId : currentUserIds) { 11514 if (permissionsState.grantRuntimePermission(bp, userId) != 11515 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11516 // Transfer the permission flags. 11517 permissionsState.updatePermissionFlags(bp, userId, 11518 flags, flags); 11519 // If we granted the permission, we have to write. 11520 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11521 changedRuntimePermissionUserIds, userId); 11522 } 11523 } 11524 } 11525 } break; 11526 11527 default: { 11528 if (packageOfInterest == null 11529 || packageOfInterest.equals(pkg.packageName)) { 11530 Slog.w(TAG, "Not granting permission " + perm 11531 + " to package " + pkg.packageName 11532 + " because it was previously installed without"); 11533 } 11534 } break; 11535 } 11536 } else { 11537 if (permissionsState.revokeInstallPermission(bp) != 11538 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11539 // Also drop the permission flags. 11540 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 11541 PackageManager.MASK_PERMISSION_FLAGS, 0); 11542 changedInstallPermission = true; 11543 Slog.i(TAG, "Un-granting permission " + perm 11544 + " from package " + pkg.packageName 11545 + " (protectionLevel=" + bp.protectionLevel 11546 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 11547 + ")"); 11548 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 11549 // Don't print warning for app op permissions, since it is fine for them 11550 // not to be granted, there is a UI for the user to decide. 11551 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 11552 Slog.w(TAG, "Not granting permission " + perm 11553 + " to package " + pkg.packageName 11554 + " (protectionLevel=" + bp.protectionLevel 11555 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 11556 + ")"); 11557 } 11558 } 11559 } 11560 } 11561 11562 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 11563 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 11564 // This is the first that we have heard about this package, so the 11565 // permissions we have now selected are fixed until explicitly 11566 // changed. 11567 ps.installPermissionsFixed = true; 11568 } 11569 11570 // Persist the runtime permissions state for users with changes. If permissions 11571 // were revoked because no app in the shared user declares them we have to 11572 // write synchronously to avoid losing runtime permissions state. 11573 for (int userId : changedRuntimePermissionUserIds) { 11574 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 11575 } 11576 } 11577 11578 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 11579 boolean allowed = false; 11580 final int NP = PackageParser.NEW_PERMISSIONS.length; 11581 for (int ip=0; ip<NP; ip++) { 11582 final PackageParser.NewPermissionInfo npi 11583 = PackageParser.NEW_PERMISSIONS[ip]; 11584 if (npi.name.equals(perm) 11585 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 11586 allowed = true; 11587 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 11588 + pkg.packageName); 11589 break; 11590 } 11591 } 11592 return allowed; 11593 } 11594 11595 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 11596 BasePermission bp, PermissionsState origPermissions) { 11597 boolean privilegedPermission = (bp.protectionLevel 11598 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0; 11599 boolean privappPermissionsDisable = 11600 RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE; 11601 boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage); 11602 boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName); 11603 if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp() 11604 && !platformPackage && platformPermission) { 11605 ArraySet<String> wlPermissions = SystemConfig.getInstance() 11606 .getPrivAppPermissions(pkg.packageName); 11607 boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm); 11608 if (!whitelisted) { 11609 Slog.w(TAG, "Privileged permission " + perm + " for package " 11610 + pkg.packageName + " - not in privapp-permissions whitelist"); 11611 if (!mSystemReady) { 11612 if (mPrivappPermissionsViolations == null) { 11613 mPrivappPermissionsViolations = new ArraySet<>(); 11614 } 11615 mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm); 11616 } 11617 if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) { 11618 return false; 11619 } 11620 } 11621 } 11622 boolean allowed = (compareSignatures( 11623 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 11624 == PackageManager.SIGNATURE_MATCH) 11625 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 11626 == PackageManager.SIGNATURE_MATCH); 11627 if (!allowed && privilegedPermission) { 11628 if (isSystemApp(pkg)) { 11629 // For updated system applications, a system permission 11630 // is granted only if it had been defined by the original application. 11631 if (pkg.isUpdatedSystemApp()) { 11632 final PackageSetting sysPs = mSettings 11633 .getDisabledSystemPkgLPr(pkg.packageName); 11634 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 11635 // If the original was granted this permission, we take 11636 // that grant decision as read and propagate it to the 11637 // update. 11638 if (sysPs.isPrivileged()) { 11639 allowed = true; 11640 } 11641 } else { 11642 // The system apk may have been updated with an older 11643 // version of the one on the data partition, but which 11644 // granted a new system permission that it didn't have 11645 // before. In this case we do want to allow the app to 11646 // now get the new permission if the ancestral apk is 11647 // privileged to get it. 11648 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 11649 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 11650 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 11651 allowed = true; 11652 break; 11653 } 11654 } 11655 } 11656 // Also if a privileged parent package on the system image or any of 11657 // its children requested a privileged permission, the updated child 11658 // packages can also get the permission. 11659 if (pkg.parentPackage != null) { 11660 final PackageSetting disabledSysParentPs = mSettings 11661 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 11662 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 11663 && disabledSysParentPs.isPrivileged()) { 11664 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 11665 allowed = true; 11666 } else if (disabledSysParentPs.pkg.childPackages != null) { 11667 final int count = disabledSysParentPs.pkg.childPackages.size(); 11668 for (int i = 0; i < count; i++) { 11669 PackageParser.Package disabledSysChildPkg = 11670 disabledSysParentPs.pkg.childPackages.get(i); 11671 if (isPackageRequestingPermission(disabledSysChildPkg, 11672 perm)) { 11673 allowed = true; 11674 break; 11675 } 11676 } 11677 } 11678 } 11679 } 11680 } 11681 } else { 11682 allowed = isPrivilegedApp(pkg); 11683 } 11684 } 11685 } 11686 if (!allowed) { 11687 if (!allowed && (bp.protectionLevel 11688 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 11689 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 11690 // If this was a previously normal/dangerous permission that got moved 11691 // to a system permission as part of the runtime permission redesign, then 11692 // we still want to blindly grant it to old apps. 11693 allowed = true; 11694 } 11695 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 11696 && pkg.packageName.equals(mRequiredInstallerPackage)) { 11697 // If this permission is to be granted to the system installer and 11698 // this app is an installer, then it gets the permission. 11699 allowed = true; 11700 } 11701 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 11702 && pkg.packageName.equals(mRequiredVerifierPackage)) { 11703 // If this permission is to be granted to the system verifier and 11704 // this app is a verifier, then it gets the permission. 11705 allowed = true; 11706 } 11707 if (!allowed && (bp.protectionLevel 11708 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 11709 && isSystemApp(pkg)) { 11710 // Any pre-installed system app is allowed to get this permission. 11711 allowed = true; 11712 } 11713 if (!allowed && (bp.protectionLevel 11714 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 11715 // For development permissions, a development permission 11716 // is granted only if it was already granted. 11717 allowed = origPermissions.hasInstallPermission(perm); 11718 } 11719 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 11720 && pkg.packageName.equals(mSetupWizardPackage)) { 11721 // If this permission is to be granted to the system setup wizard and 11722 // this app is a setup wizard, then it gets the permission. 11723 allowed = true; 11724 } 11725 } 11726 return allowed; 11727 } 11728 11729 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 11730 final int permCount = pkg.requestedPermissions.size(); 11731 for (int j = 0; j < permCount; j++) { 11732 String requestedPermission = pkg.requestedPermissions.get(j); 11733 if (permission.equals(requestedPermission)) { 11734 return true; 11735 } 11736 } 11737 return false; 11738 } 11739 11740 final class ActivityIntentResolver 11741 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 11742 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 11743 boolean defaultOnly, boolean visibleToEphemeral, boolean isEphemeral, int userId) { 11744 if (!sUserManager.exists(userId)) return null; 11745 mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0) 11746 | (visibleToEphemeral ? PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY : 0) 11747 | (isEphemeral ? PackageManager.MATCH_EPHEMERAL : 0); 11748 return super.queryIntent(intent, resolvedType, defaultOnly, visibleToEphemeral, 11749 isEphemeral, userId); 11750 } 11751 11752 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 11753 int userId) { 11754 if (!sUserManager.exists(userId)) return null; 11755 mFlags = flags; 11756 return super.queryIntent(intent, resolvedType, 11757 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 11758 (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0, 11759 (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId); 11760 } 11761 11762 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 11763 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 11764 if (!sUserManager.exists(userId)) return null; 11765 if (packageActivities == null) { 11766 return null; 11767 } 11768 mFlags = flags; 11769 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 11770 final boolean vislbleToEphemeral = 11771 (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0; 11772 final boolean isEphemeral = (flags & PackageManager.MATCH_EPHEMERAL) != 0; 11773 final int N = packageActivities.size(); 11774 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 11775 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 11776 11777 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 11778 for (int i = 0; i < N; ++i) { 11779 intentFilters = packageActivities.get(i).intents; 11780 if (intentFilters != null && intentFilters.size() > 0) { 11781 PackageParser.ActivityIntentInfo[] array = 11782 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 11783 intentFilters.toArray(array); 11784 listCut.add(array); 11785 } 11786 } 11787 return super.queryIntentFromList(intent, resolvedType, defaultOnly, 11788 vislbleToEphemeral, isEphemeral, listCut, userId); 11789 } 11790 11791 /** 11792 * Finds a privileged activity that matches the specified activity names. 11793 */ 11794 private PackageParser.Activity findMatchingActivity( 11795 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 11796 for (PackageParser.Activity sysActivity : activityList) { 11797 if (sysActivity.info.name.equals(activityInfo.name)) { 11798 return sysActivity; 11799 } 11800 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 11801 return sysActivity; 11802 } 11803 if (sysActivity.info.targetActivity != null) { 11804 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 11805 return sysActivity; 11806 } 11807 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 11808 return sysActivity; 11809 } 11810 } 11811 } 11812 return null; 11813 } 11814 11815 public class IterGenerator<E> { 11816 public Iterator<E> generate(ActivityIntentInfo info) { 11817 return null; 11818 } 11819 } 11820 11821 public class ActionIterGenerator extends IterGenerator<String> { 11822 @Override 11823 public Iterator<String> generate(ActivityIntentInfo info) { 11824 return info.actionsIterator(); 11825 } 11826 } 11827 11828 public class CategoriesIterGenerator extends IterGenerator<String> { 11829 @Override 11830 public Iterator<String> generate(ActivityIntentInfo info) { 11831 return info.categoriesIterator(); 11832 } 11833 } 11834 11835 public class SchemesIterGenerator extends IterGenerator<String> { 11836 @Override 11837 public Iterator<String> generate(ActivityIntentInfo info) { 11838 return info.schemesIterator(); 11839 } 11840 } 11841 11842 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 11843 @Override 11844 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 11845 return info.authoritiesIterator(); 11846 } 11847 } 11848 11849 /** 11850 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 11851 * MODIFIED. Do not pass in a list that should not be changed. 11852 */ 11853 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 11854 IterGenerator<T> generator, Iterator<T> searchIterator) { 11855 // loop through the set of actions; every one must be found in the intent filter 11856 while (searchIterator.hasNext()) { 11857 // we must have at least one filter in the list to consider a match 11858 if (intentList.size() == 0) { 11859 break; 11860 } 11861 11862 final T searchAction = searchIterator.next(); 11863 11864 // loop through the set of intent filters 11865 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 11866 while (intentIter.hasNext()) { 11867 final ActivityIntentInfo intentInfo = intentIter.next(); 11868 boolean selectionFound = false; 11869 11870 // loop through the intent filter's selection criteria; at least one 11871 // of them must match the searched criteria 11872 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 11873 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 11874 final T intentSelection = intentSelectionIter.next(); 11875 if (intentSelection != null && intentSelection.equals(searchAction)) { 11876 selectionFound = true; 11877 break; 11878 } 11879 } 11880 11881 // the selection criteria wasn't found in this filter's set; this filter 11882 // is not a potential match 11883 if (!selectionFound) { 11884 intentIter.remove(); 11885 } 11886 } 11887 } 11888 } 11889 11890 private boolean isProtectedAction(ActivityIntentInfo filter) { 11891 final Iterator<String> actionsIter = filter.actionsIterator(); 11892 while (actionsIter != null && actionsIter.hasNext()) { 11893 final String filterAction = actionsIter.next(); 11894 if (PROTECTED_ACTIONS.contains(filterAction)) { 11895 return true; 11896 } 11897 } 11898 return false; 11899 } 11900 11901 /** 11902 * Adjusts the priority of the given intent filter according to policy. 11903 * <p> 11904 * <ul> 11905 * <li>The priority for non privileged applications is capped to '0'</li> 11906 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 11907 * <li>The priority for unbundled updates to privileged applications is capped to the 11908 * priority defined on the system partition</li> 11909 * </ul> 11910 * <p> 11911 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 11912 * allowed to obtain any priority on any action. 11913 */ 11914 private void adjustPriority( 11915 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 11916 // nothing to do; priority is fine as-is 11917 if (intent.getPriority() <= 0) { 11918 return; 11919 } 11920 11921 final ActivityInfo activityInfo = intent.activity.info; 11922 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 11923 11924 final boolean privilegedApp = 11925 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 11926 if (!privilegedApp) { 11927 // non-privileged applications can never define a priority >0 11928 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 11929 + " package: " + applicationInfo.packageName 11930 + " activity: " + intent.activity.className 11931 + " origPrio: " + intent.getPriority()); 11932 intent.setPriority(0); 11933 return; 11934 } 11935 11936 if (systemActivities == null) { 11937 // the system package is not disabled; we're parsing the system partition 11938 if (isProtectedAction(intent)) { 11939 if (mDeferProtectedFilters) { 11940 // We can't deal with these just yet. No component should ever obtain a 11941 // >0 priority for a protected actions, with ONE exception -- the setup 11942 // wizard. The setup wizard, however, cannot be known until we're able to 11943 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 11944 // until all intent filters have been processed. Chicken, meet egg. 11945 // Let the filter temporarily have a high priority and rectify the 11946 // priorities after all system packages have been scanned. 11947 mProtectedFilters.add(intent); 11948 if (DEBUG_FILTERS) { 11949 Slog.i(TAG, "Protected action; save for later;" 11950 + " package: " + applicationInfo.packageName 11951 + " activity: " + intent.activity.className 11952 + " origPrio: " + intent.getPriority()); 11953 } 11954 return; 11955 } else { 11956 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 11957 Slog.i(TAG, "No setup wizard;" 11958 + " All protected intents capped to priority 0"); 11959 } 11960 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 11961 if (DEBUG_FILTERS) { 11962 Slog.i(TAG, "Found setup wizard;" 11963 + " allow priority " + intent.getPriority() + ";" 11964 + " package: " + intent.activity.info.packageName 11965 + " activity: " + intent.activity.className 11966 + " priority: " + intent.getPriority()); 11967 } 11968 // setup wizard gets whatever it wants 11969 return; 11970 } 11971 Slog.w(TAG, "Protected action; cap priority to 0;" 11972 + " package: " + intent.activity.info.packageName 11973 + " activity: " + intent.activity.className 11974 + " origPrio: " + intent.getPriority()); 11975 intent.setPriority(0); 11976 return; 11977 } 11978 } 11979 // privileged apps on the system image get whatever priority they request 11980 return; 11981 } 11982 11983 // privileged app unbundled update ... try to find the same activity 11984 final PackageParser.Activity foundActivity = 11985 findMatchingActivity(systemActivities, activityInfo); 11986 if (foundActivity == null) { 11987 // this is a new activity; it cannot obtain >0 priority 11988 if (DEBUG_FILTERS) { 11989 Slog.i(TAG, "New activity; cap priority to 0;" 11990 + " package: " + applicationInfo.packageName 11991 + " activity: " + intent.activity.className 11992 + " origPrio: " + intent.getPriority()); 11993 } 11994 intent.setPriority(0); 11995 return; 11996 } 11997 11998 // found activity, now check for filter equivalence 11999 12000 // a shallow copy is enough; we modify the list, not its contents 12001 final List<ActivityIntentInfo> intentListCopy = 12002 new ArrayList<>(foundActivity.intents); 12003 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 12004 12005 // find matching action subsets 12006 final Iterator<String> actionsIterator = intent.actionsIterator(); 12007 if (actionsIterator != null) { 12008 getIntentListSubset( 12009 intentListCopy, new ActionIterGenerator(), actionsIterator); 12010 if (intentListCopy.size() == 0) { 12011 // no more intents to match; we're not equivalent 12012 if (DEBUG_FILTERS) { 12013 Slog.i(TAG, "Mismatched action; cap priority to 0;" 12014 + " package: " + applicationInfo.packageName 12015 + " activity: " + intent.activity.className 12016 + " origPrio: " + intent.getPriority()); 12017 } 12018 intent.setPriority(0); 12019 return; 12020 } 12021 } 12022 12023 // find matching category subsets 12024 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 12025 if (categoriesIterator != null) { 12026 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 12027 categoriesIterator); 12028 if (intentListCopy.size() == 0) { 12029 // no more intents to match; we're not equivalent 12030 if (DEBUG_FILTERS) { 12031 Slog.i(TAG, "Mismatched category; cap priority to 0;" 12032 + " package: " + applicationInfo.packageName 12033 + " activity: " + intent.activity.className 12034 + " origPrio: " + intent.getPriority()); 12035 } 12036 intent.setPriority(0); 12037 return; 12038 } 12039 } 12040 12041 // find matching schemes subsets 12042 final Iterator<String> schemesIterator = intent.schemesIterator(); 12043 if (schemesIterator != null) { 12044 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 12045 schemesIterator); 12046 if (intentListCopy.size() == 0) { 12047 // no more intents to match; we're not equivalent 12048 if (DEBUG_FILTERS) { 12049 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 12050 + " package: " + applicationInfo.packageName 12051 + " activity: " + intent.activity.className 12052 + " origPrio: " + intent.getPriority()); 12053 } 12054 intent.setPriority(0); 12055 return; 12056 } 12057 } 12058 12059 // find matching authorities subsets 12060 final Iterator<IntentFilter.AuthorityEntry> 12061 authoritiesIterator = intent.authoritiesIterator(); 12062 if (authoritiesIterator != null) { 12063 getIntentListSubset(intentListCopy, 12064 new AuthoritiesIterGenerator(), 12065 authoritiesIterator); 12066 if (intentListCopy.size() == 0) { 12067 // no more intents to match; we're not equivalent 12068 if (DEBUG_FILTERS) { 12069 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 12070 + " package: " + applicationInfo.packageName 12071 + " activity: " + intent.activity.className 12072 + " origPrio: " + intent.getPriority()); 12073 } 12074 intent.setPriority(0); 12075 return; 12076 } 12077 } 12078 12079 // we found matching filter(s); app gets the max priority of all intents 12080 int cappedPriority = 0; 12081 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 12082 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 12083 } 12084 if (intent.getPriority() > cappedPriority) { 12085 if (DEBUG_FILTERS) { 12086 Slog.i(TAG, "Found matching filter(s);" 12087 + " cap priority to " + cappedPriority + ";" 12088 + " package: " + applicationInfo.packageName 12089 + " activity: " + intent.activity.className 12090 + " origPrio: " + intent.getPriority()); 12091 } 12092 intent.setPriority(cappedPriority); 12093 return; 12094 } 12095 // all this for nothing; the requested priority was <= what was on the system 12096 } 12097 12098 public final void addActivity(PackageParser.Activity a, String type) { 12099 mActivities.put(a.getComponentName(), a); 12100 if (DEBUG_SHOW_INFO) 12101 Log.v( 12102 TAG, " " + type + " " + 12103 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 12104 if (DEBUG_SHOW_INFO) 12105 Log.v(TAG, " Class=" + a.info.name); 12106 final int NI = a.intents.size(); 12107 for (int j=0; j<NI; j++) { 12108 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 12109 if ("activity".equals(type)) { 12110 final PackageSetting ps = 12111 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 12112 final List<PackageParser.Activity> systemActivities = 12113 ps != null && ps.pkg != null ? ps.pkg.activities : null; 12114 adjustPriority(systemActivities, intent); 12115 } 12116 if (DEBUG_SHOW_INFO) { 12117 Log.v(TAG, " IntentFilter:"); 12118 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12119 } 12120 if (!intent.debugCheck()) { 12121 Log.w(TAG, "==> For Activity " + a.info.name); 12122 } 12123 addFilter(intent); 12124 } 12125 } 12126 12127 public final void removeActivity(PackageParser.Activity a, String type) { 12128 mActivities.remove(a.getComponentName()); 12129 if (DEBUG_SHOW_INFO) { 12130 Log.v(TAG, " " + type + " " 12131 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 12132 : a.info.name) + ":"); 12133 Log.v(TAG, " Class=" + a.info.name); 12134 } 12135 final int NI = a.intents.size(); 12136 for (int j=0; j<NI; j++) { 12137 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 12138 if (DEBUG_SHOW_INFO) { 12139 Log.v(TAG, " IntentFilter:"); 12140 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12141 } 12142 removeFilter(intent); 12143 } 12144 } 12145 12146 @Override 12147 protected boolean allowFilterResult( 12148 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 12149 ActivityInfo filterAi = filter.activity.info; 12150 for (int i=dest.size()-1; i>=0; i--) { 12151 ActivityInfo destAi = dest.get(i).activityInfo; 12152 if (destAi.name == filterAi.name 12153 && destAi.packageName == filterAi.packageName) { 12154 return false; 12155 } 12156 } 12157 return true; 12158 } 12159 12160 @Override 12161 protected ActivityIntentInfo[] newArray(int size) { 12162 return new ActivityIntentInfo[size]; 12163 } 12164 12165 @Override 12166 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 12167 if (!sUserManager.exists(userId)) return true; 12168 PackageParser.Package p = filter.activity.owner; 12169 if (p != null) { 12170 PackageSetting ps = (PackageSetting)p.mExtras; 12171 if (ps != null) { 12172 // System apps are never considered stopped for purposes of 12173 // filtering, because there may be no way for the user to 12174 // actually re-launch them. 12175 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 12176 && ps.getStopped(userId); 12177 } 12178 } 12179 return false; 12180 } 12181 12182 @Override 12183 protected boolean isPackageForFilter(String packageName, 12184 PackageParser.ActivityIntentInfo info) { 12185 return packageName.equals(info.activity.owner.packageName); 12186 } 12187 12188 @Override 12189 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 12190 int match, int userId) { 12191 if (!sUserManager.exists(userId)) return null; 12192 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 12193 return null; 12194 } 12195 final PackageParser.Activity activity = info.activity; 12196 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 12197 if (ps == null) { 12198 return null; 12199 } 12200 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 12201 ps.readUserState(userId), userId); 12202 if (ai == null) { 12203 return null; 12204 } 12205 final ResolveInfo res = new ResolveInfo(); 12206 res.activityInfo = ai; 12207 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 12208 res.filter = info; 12209 } 12210 if (info != null) { 12211 res.handleAllWebDataURI = info.handleAllWebDataURI(); 12212 } 12213 res.priority = info.getPriority(); 12214 res.preferredOrder = activity.owner.mPreferredOrder; 12215 //System.out.println("Result: " + res.activityInfo.className + 12216 // " = " + res.priority); 12217 res.match = match; 12218 res.isDefault = info.hasDefault; 12219 res.labelRes = info.labelRes; 12220 res.nonLocalizedLabel = info.nonLocalizedLabel; 12221 if (userNeedsBadging(userId)) { 12222 res.noResourceId = true; 12223 } else { 12224 res.icon = info.icon; 12225 } 12226 res.iconResourceId = info.icon; 12227 res.system = res.activityInfo.applicationInfo.isSystemApp(); 12228 return res; 12229 } 12230 12231 @Override 12232 protected void sortResults(List<ResolveInfo> results) { 12233 Collections.sort(results, mResolvePrioritySorter); 12234 } 12235 12236 @Override 12237 protected void dumpFilter(PrintWriter out, String prefix, 12238 PackageParser.ActivityIntentInfo filter) { 12239 out.print(prefix); out.print( 12240 Integer.toHexString(System.identityHashCode(filter.activity))); 12241 out.print(' '); 12242 filter.activity.printComponentShortName(out); 12243 out.print(" filter "); 12244 out.println(Integer.toHexString(System.identityHashCode(filter))); 12245 } 12246 12247 @Override 12248 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 12249 return filter.activity; 12250 } 12251 12252 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12253 PackageParser.Activity activity = (PackageParser.Activity)label; 12254 out.print(prefix); out.print( 12255 Integer.toHexString(System.identityHashCode(activity))); 12256 out.print(' '); 12257 activity.printComponentShortName(out); 12258 if (count > 1) { 12259 out.print(" ("); out.print(count); out.print(" filters)"); 12260 } 12261 out.println(); 12262 } 12263 12264 // Keys are String (activity class name), values are Activity. 12265 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 12266 = new ArrayMap<ComponentName, PackageParser.Activity>(); 12267 private int mFlags; 12268 } 12269 12270 private final class ServiceIntentResolver 12271 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 12272 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12273 boolean defaultOnly, boolean visibleToEphemeral, boolean isEphemeral, int userId) { 12274 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 12275 return super.queryIntent(intent, resolvedType, defaultOnly, visibleToEphemeral, 12276 isEphemeral, userId); 12277 } 12278 12279 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12280 int userId) { 12281 if (!sUserManager.exists(userId)) return null; 12282 mFlags = flags; 12283 return super.queryIntent(intent, resolvedType, 12284 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12285 (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0, 12286 (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId); 12287 } 12288 12289 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12290 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 12291 if (!sUserManager.exists(userId)) return null; 12292 if (packageServices == null) { 12293 return null; 12294 } 12295 mFlags = flags; 12296 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 12297 final boolean vislbleToEphemeral = 12298 (flags&PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0; 12299 final boolean isEphemeral = (flags&PackageManager.MATCH_EPHEMERAL) != 0; 12300 final int N = packageServices.size(); 12301 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 12302 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 12303 12304 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 12305 for (int i = 0; i < N; ++i) { 12306 intentFilters = packageServices.get(i).intents; 12307 if (intentFilters != null && intentFilters.size() > 0) { 12308 PackageParser.ServiceIntentInfo[] array = 12309 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 12310 intentFilters.toArray(array); 12311 listCut.add(array); 12312 } 12313 } 12314 return super.queryIntentFromList(intent, resolvedType, defaultOnly, 12315 vislbleToEphemeral, isEphemeral, listCut, userId); 12316 } 12317 12318 public final void addService(PackageParser.Service s) { 12319 mServices.put(s.getComponentName(), s); 12320 if (DEBUG_SHOW_INFO) { 12321 Log.v(TAG, " " 12322 + (s.info.nonLocalizedLabel != null 12323 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 12324 Log.v(TAG, " Class=" + s.info.name); 12325 } 12326 final int NI = s.intents.size(); 12327 int j; 12328 for (j=0; j<NI; j++) { 12329 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 12330 if (DEBUG_SHOW_INFO) { 12331 Log.v(TAG, " IntentFilter:"); 12332 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12333 } 12334 if (!intent.debugCheck()) { 12335 Log.w(TAG, "==> For Service " + s.info.name); 12336 } 12337 addFilter(intent); 12338 } 12339 } 12340 12341 public final void removeService(PackageParser.Service s) { 12342 mServices.remove(s.getComponentName()); 12343 if (DEBUG_SHOW_INFO) { 12344 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 12345 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 12346 Log.v(TAG, " Class=" + s.info.name); 12347 } 12348 final int NI = s.intents.size(); 12349 int j; 12350 for (j=0; j<NI; j++) { 12351 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 12352 if (DEBUG_SHOW_INFO) { 12353 Log.v(TAG, " IntentFilter:"); 12354 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12355 } 12356 removeFilter(intent); 12357 } 12358 } 12359 12360 @Override 12361 protected boolean allowFilterResult( 12362 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 12363 ServiceInfo filterSi = filter.service.info; 12364 for (int i=dest.size()-1; i>=0; i--) { 12365 ServiceInfo destAi = dest.get(i).serviceInfo; 12366 if (destAi.name == filterSi.name 12367 && destAi.packageName == filterSi.packageName) { 12368 return false; 12369 } 12370 } 12371 return true; 12372 } 12373 12374 @Override 12375 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 12376 return new PackageParser.ServiceIntentInfo[size]; 12377 } 12378 12379 @Override 12380 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 12381 if (!sUserManager.exists(userId)) return true; 12382 PackageParser.Package p = filter.service.owner; 12383 if (p != null) { 12384 PackageSetting ps = (PackageSetting)p.mExtras; 12385 if (ps != null) { 12386 // System apps are never considered stopped for purposes of 12387 // filtering, because there may be no way for the user to 12388 // actually re-launch them. 12389 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 12390 && ps.getStopped(userId); 12391 } 12392 } 12393 return false; 12394 } 12395 12396 @Override 12397 protected boolean isPackageForFilter(String packageName, 12398 PackageParser.ServiceIntentInfo info) { 12399 return packageName.equals(info.service.owner.packageName); 12400 } 12401 12402 @Override 12403 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 12404 int match, int userId) { 12405 if (!sUserManager.exists(userId)) return null; 12406 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 12407 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 12408 return null; 12409 } 12410 final PackageParser.Service service = info.service; 12411 PackageSetting ps = (PackageSetting) service.owner.mExtras; 12412 if (ps == null) { 12413 return null; 12414 } 12415 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 12416 ps.readUserState(userId), userId); 12417 if (si == null) { 12418 return null; 12419 } 12420 final ResolveInfo res = new ResolveInfo(); 12421 res.serviceInfo = si; 12422 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 12423 res.filter = filter; 12424 } 12425 res.priority = info.getPriority(); 12426 res.preferredOrder = service.owner.mPreferredOrder; 12427 res.match = match; 12428 res.isDefault = info.hasDefault; 12429 res.labelRes = info.labelRes; 12430 res.nonLocalizedLabel = info.nonLocalizedLabel; 12431 res.icon = info.icon; 12432 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 12433 return res; 12434 } 12435 12436 @Override 12437 protected void sortResults(List<ResolveInfo> results) { 12438 Collections.sort(results, mResolvePrioritySorter); 12439 } 12440 12441 @Override 12442 protected void dumpFilter(PrintWriter out, String prefix, 12443 PackageParser.ServiceIntentInfo filter) { 12444 out.print(prefix); out.print( 12445 Integer.toHexString(System.identityHashCode(filter.service))); 12446 out.print(' '); 12447 filter.service.printComponentShortName(out); 12448 out.print(" filter "); 12449 out.println(Integer.toHexString(System.identityHashCode(filter))); 12450 } 12451 12452 @Override 12453 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 12454 return filter.service; 12455 } 12456 12457 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12458 PackageParser.Service service = (PackageParser.Service)label; 12459 out.print(prefix); out.print( 12460 Integer.toHexString(System.identityHashCode(service))); 12461 out.print(' '); 12462 service.printComponentShortName(out); 12463 if (count > 1) { 12464 out.print(" ("); out.print(count); out.print(" filters)"); 12465 } 12466 out.println(); 12467 } 12468 12469// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 12470// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 12471// final List<ResolveInfo> retList = Lists.newArrayList(); 12472// while (i.hasNext()) { 12473// final ResolveInfo resolveInfo = (ResolveInfo) i; 12474// if (isEnabledLP(resolveInfo.serviceInfo)) { 12475// retList.add(resolveInfo); 12476// } 12477// } 12478// return retList; 12479// } 12480 12481 // Keys are String (activity class name), values are Activity. 12482 private final ArrayMap<ComponentName, PackageParser.Service> mServices 12483 = new ArrayMap<ComponentName, PackageParser.Service>(); 12484 private int mFlags; 12485 } 12486 12487 private final class ProviderIntentResolver 12488 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 12489 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12490 boolean defaultOnly, boolean visibleToEphemeral, boolean isEphemeral, int userId) { 12491 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 12492 return super.queryIntent(intent, resolvedType, defaultOnly, visibleToEphemeral, 12493 isEphemeral, userId); 12494 } 12495 12496 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12497 int userId) { 12498 if (!sUserManager.exists(userId)) 12499 return null; 12500 mFlags = flags; 12501 return super.queryIntent(intent, resolvedType, 12502 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12503 (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0, 12504 (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId); 12505 } 12506 12507 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12508 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 12509 if (!sUserManager.exists(userId)) 12510 return null; 12511 if (packageProviders == null) { 12512 return null; 12513 } 12514 mFlags = flags; 12515 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 12516 final boolean isEphemeral = (flags&PackageManager.MATCH_EPHEMERAL) != 0; 12517 final boolean vislbleToEphemeral = 12518 (flags&PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0; 12519 final int N = packageProviders.size(); 12520 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 12521 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 12522 12523 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 12524 for (int i = 0; i < N; ++i) { 12525 intentFilters = packageProviders.get(i).intents; 12526 if (intentFilters != null && intentFilters.size() > 0) { 12527 PackageParser.ProviderIntentInfo[] array = 12528 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 12529 intentFilters.toArray(array); 12530 listCut.add(array); 12531 } 12532 } 12533 return super.queryIntentFromList(intent, resolvedType, defaultOnly, 12534 vislbleToEphemeral, isEphemeral, listCut, userId); 12535 } 12536 12537 public final void addProvider(PackageParser.Provider p) { 12538 if (mProviders.containsKey(p.getComponentName())) { 12539 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 12540 return; 12541 } 12542 12543 mProviders.put(p.getComponentName(), p); 12544 if (DEBUG_SHOW_INFO) { 12545 Log.v(TAG, " " 12546 + (p.info.nonLocalizedLabel != null 12547 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 12548 Log.v(TAG, " Class=" + p.info.name); 12549 } 12550 final int NI = p.intents.size(); 12551 int j; 12552 for (j = 0; j < NI; j++) { 12553 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 12554 if (DEBUG_SHOW_INFO) { 12555 Log.v(TAG, " IntentFilter:"); 12556 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12557 } 12558 if (!intent.debugCheck()) { 12559 Log.w(TAG, "==> For Provider " + p.info.name); 12560 } 12561 addFilter(intent); 12562 } 12563 } 12564 12565 public final void removeProvider(PackageParser.Provider p) { 12566 mProviders.remove(p.getComponentName()); 12567 if (DEBUG_SHOW_INFO) { 12568 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 12569 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 12570 Log.v(TAG, " Class=" + p.info.name); 12571 } 12572 final int NI = p.intents.size(); 12573 int j; 12574 for (j = 0; j < NI; j++) { 12575 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 12576 if (DEBUG_SHOW_INFO) { 12577 Log.v(TAG, " IntentFilter:"); 12578 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12579 } 12580 removeFilter(intent); 12581 } 12582 } 12583 12584 @Override 12585 protected boolean allowFilterResult( 12586 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 12587 ProviderInfo filterPi = filter.provider.info; 12588 for (int i = dest.size() - 1; i >= 0; i--) { 12589 ProviderInfo destPi = dest.get(i).providerInfo; 12590 if (destPi.name == filterPi.name 12591 && destPi.packageName == filterPi.packageName) { 12592 return false; 12593 } 12594 } 12595 return true; 12596 } 12597 12598 @Override 12599 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 12600 return new PackageParser.ProviderIntentInfo[size]; 12601 } 12602 12603 @Override 12604 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 12605 if (!sUserManager.exists(userId)) 12606 return true; 12607 PackageParser.Package p = filter.provider.owner; 12608 if (p != null) { 12609 PackageSetting ps = (PackageSetting) p.mExtras; 12610 if (ps != null) { 12611 // System apps are never considered stopped for purposes of 12612 // filtering, because there may be no way for the user to 12613 // actually re-launch them. 12614 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 12615 && ps.getStopped(userId); 12616 } 12617 } 12618 return false; 12619 } 12620 12621 @Override 12622 protected boolean isPackageForFilter(String packageName, 12623 PackageParser.ProviderIntentInfo info) { 12624 return packageName.equals(info.provider.owner.packageName); 12625 } 12626 12627 @Override 12628 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 12629 int match, int userId) { 12630 if (!sUserManager.exists(userId)) 12631 return null; 12632 final PackageParser.ProviderIntentInfo info = filter; 12633 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 12634 return null; 12635 } 12636 final PackageParser.Provider provider = info.provider; 12637 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 12638 if (ps == null) { 12639 return null; 12640 } 12641 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 12642 ps.readUserState(userId), userId); 12643 if (pi == null) { 12644 return null; 12645 } 12646 final ResolveInfo res = new ResolveInfo(); 12647 res.providerInfo = pi; 12648 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 12649 res.filter = filter; 12650 } 12651 res.priority = info.getPriority(); 12652 res.preferredOrder = provider.owner.mPreferredOrder; 12653 res.match = match; 12654 res.isDefault = info.hasDefault; 12655 res.labelRes = info.labelRes; 12656 res.nonLocalizedLabel = info.nonLocalizedLabel; 12657 res.icon = info.icon; 12658 res.system = res.providerInfo.applicationInfo.isSystemApp(); 12659 return res; 12660 } 12661 12662 @Override 12663 protected void sortResults(List<ResolveInfo> results) { 12664 Collections.sort(results, mResolvePrioritySorter); 12665 } 12666 12667 @Override 12668 protected void dumpFilter(PrintWriter out, String prefix, 12669 PackageParser.ProviderIntentInfo filter) { 12670 out.print(prefix); 12671 out.print( 12672 Integer.toHexString(System.identityHashCode(filter.provider))); 12673 out.print(' '); 12674 filter.provider.printComponentShortName(out); 12675 out.print(" filter "); 12676 out.println(Integer.toHexString(System.identityHashCode(filter))); 12677 } 12678 12679 @Override 12680 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 12681 return filter.provider; 12682 } 12683 12684 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12685 PackageParser.Provider provider = (PackageParser.Provider)label; 12686 out.print(prefix); out.print( 12687 Integer.toHexString(System.identityHashCode(provider))); 12688 out.print(' '); 12689 provider.printComponentShortName(out); 12690 if (count > 1) { 12691 out.print(" ("); out.print(count); out.print(" filters)"); 12692 } 12693 out.println(); 12694 } 12695 12696 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 12697 = new ArrayMap<ComponentName, PackageParser.Provider>(); 12698 private int mFlags; 12699 } 12700 12701 static final class EphemeralIntentResolver 12702 extends IntentResolver<EphemeralResponse, EphemeralResponse> { 12703 /** 12704 * The result that has the highest defined order. Ordering applies on a 12705 * per-package basis. Mapping is from package name to Pair of order and 12706 * EphemeralResolveInfo. 12707 * <p> 12708 * NOTE: This is implemented as a field variable for convenience and efficiency. 12709 * By having a field variable, we're able to track filter ordering as soon as 12710 * a non-zero order is defined. Otherwise, multiple loops across the result set 12711 * would be needed to apply ordering. If the intent resolver becomes re-entrant, 12712 * this needs to be contained entirely within {@link #filterResults()}. 12713 */ 12714 final ArrayMap<String, Pair<Integer, EphemeralResolveInfo>> mOrderResult = new ArrayMap<>(); 12715 12716 @Override 12717 protected EphemeralResponse[] newArray(int size) { 12718 return new EphemeralResponse[size]; 12719 } 12720 12721 @Override 12722 protected boolean isPackageForFilter(String packageName, EphemeralResponse responseObj) { 12723 return true; 12724 } 12725 12726 @Override 12727 protected EphemeralResponse newResult(EphemeralResponse responseObj, int match, 12728 int userId) { 12729 if (!sUserManager.exists(userId)) { 12730 return null; 12731 } 12732 final String packageName = responseObj.resolveInfo.getPackageName(); 12733 final Integer order = responseObj.getOrder(); 12734 final Pair<Integer, EphemeralResolveInfo> lastOrderResult = 12735 mOrderResult.get(packageName); 12736 // ordering is enabled and this item's order isn't high enough 12737 if (lastOrderResult != null && lastOrderResult.first >= order) { 12738 return null; 12739 } 12740 final EphemeralResolveInfo res = responseObj.resolveInfo; 12741 if (order > 0) { 12742 // non-zero order, enable ordering 12743 mOrderResult.put(packageName, new Pair<>(order, res)); 12744 } 12745 return responseObj; 12746 } 12747 12748 @Override 12749 protected void filterResults(List<EphemeralResponse> results) { 12750 // only do work if ordering is enabled [most of the time it won't be] 12751 if (mOrderResult.size() == 0) { 12752 return; 12753 } 12754 int resultSize = results.size(); 12755 for (int i = 0; i < resultSize; i++) { 12756 final EphemeralResolveInfo info = results.get(i).resolveInfo; 12757 final String packageName = info.getPackageName(); 12758 final Pair<Integer, EphemeralResolveInfo> savedInfo = mOrderResult.get(packageName); 12759 if (savedInfo == null) { 12760 // package doesn't having ordering 12761 continue; 12762 } 12763 if (savedInfo.second == info) { 12764 // circled back to the highest ordered item; remove from order list 12765 mOrderResult.remove(savedInfo); 12766 if (mOrderResult.size() == 0) { 12767 // no more ordered items 12768 break; 12769 } 12770 continue; 12771 } 12772 // item has a worse order, remove it from the result list 12773 results.remove(i); 12774 resultSize--; 12775 i--; 12776 } 12777 } 12778 } 12779 12780 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 12781 new Comparator<ResolveInfo>() { 12782 public int compare(ResolveInfo r1, ResolveInfo r2) { 12783 int v1 = r1.priority; 12784 int v2 = r2.priority; 12785 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 12786 if (v1 != v2) { 12787 return (v1 > v2) ? -1 : 1; 12788 } 12789 v1 = r1.preferredOrder; 12790 v2 = r2.preferredOrder; 12791 if (v1 != v2) { 12792 return (v1 > v2) ? -1 : 1; 12793 } 12794 if (r1.isDefault != r2.isDefault) { 12795 return r1.isDefault ? -1 : 1; 12796 } 12797 v1 = r1.match; 12798 v2 = r2.match; 12799 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 12800 if (v1 != v2) { 12801 return (v1 > v2) ? -1 : 1; 12802 } 12803 if (r1.system != r2.system) { 12804 return r1.system ? -1 : 1; 12805 } 12806 if (r1.activityInfo != null) { 12807 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 12808 } 12809 if (r1.serviceInfo != null) { 12810 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 12811 } 12812 if (r1.providerInfo != null) { 12813 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 12814 } 12815 return 0; 12816 } 12817 }; 12818 12819 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 12820 new Comparator<ProviderInfo>() { 12821 public int compare(ProviderInfo p1, ProviderInfo p2) { 12822 final int v1 = p1.initOrder; 12823 final int v2 = p2.initOrder; 12824 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 12825 } 12826 }; 12827 12828 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 12829 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 12830 final int[] userIds) { 12831 mHandler.post(new Runnable() { 12832 @Override 12833 public void run() { 12834 try { 12835 final IActivityManager am = ActivityManager.getService(); 12836 if (am == null) return; 12837 final int[] resolvedUserIds; 12838 if (userIds == null) { 12839 resolvedUserIds = am.getRunningUserIds(); 12840 } else { 12841 resolvedUserIds = userIds; 12842 } 12843 for (int id : resolvedUserIds) { 12844 final Intent intent = new Intent(action, 12845 pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null); 12846 if (extras != null) { 12847 intent.putExtras(extras); 12848 } 12849 if (targetPkg != null) { 12850 intent.setPackage(targetPkg); 12851 } 12852 // Modify the UID when posting to other users 12853 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 12854 if (uid > 0 && UserHandle.getUserId(uid) != id) { 12855 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 12856 intent.putExtra(Intent.EXTRA_UID, uid); 12857 } 12858 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 12859 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 12860 if (DEBUG_BROADCASTS) { 12861 RuntimeException here = new RuntimeException("here"); 12862 here.fillInStackTrace(); 12863 Slog.d(TAG, "Sending to user " + id + ": " 12864 + intent.toShortString(false, true, false, false) 12865 + " " + intent.getExtras(), here); 12866 } 12867 am.broadcastIntent(null, intent, null, finishedReceiver, 12868 0, null, null, null, android.app.AppOpsManager.OP_NONE, 12869 null, finishedReceiver != null, false, id); 12870 } 12871 } catch (RemoteException ex) { 12872 } 12873 } 12874 }); 12875 } 12876 12877 /** 12878 * Check if the external storage media is available. This is true if there 12879 * is a mounted external storage medium or if the external storage is 12880 * emulated. 12881 */ 12882 private boolean isExternalMediaAvailable() { 12883 return mMediaMounted || Environment.isExternalStorageEmulated(); 12884 } 12885 12886 @Override 12887 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 12888 // writer 12889 synchronized (mPackages) { 12890 if (!isExternalMediaAvailable()) { 12891 // If the external storage is no longer mounted at this point, 12892 // the caller may not have been able to delete all of this 12893 // packages files and can not delete any more. Bail. 12894 return null; 12895 } 12896 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 12897 if (lastPackage != null) { 12898 pkgs.remove(lastPackage); 12899 } 12900 if (pkgs.size() > 0) { 12901 return pkgs.get(0); 12902 } 12903 } 12904 return null; 12905 } 12906 12907 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 12908 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 12909 userId, andCode ? 1 : 0, packageName); 12910 if (mSystemReady) { 12911 msg.sendToTarget(); 12912 } else { 12913 if (mPostSystemReadyMessages == null) { 12914 mPostSystemReadyMessages = new ArrayList<>(); 12915 } 12916 mPostSystemReadyMessages.add(msg); 12917 } 12918 } 12919 12920 void startCleaningPackages() { 12921 // reader 12922 if (!isExternalMediaAvailable()) { 12923 return; 12924 } 12925 synchronized (mPackages) { 12926 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 12927 return; 12928 } 12929 } 12930 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 12931 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 12932 IActivityManager am = ActivityManager.getService(); 12933 if (am != null) { 12934 try { 12935 am.startService(null, intent, null, -1, null, mContext.getOpPackageName(), 12936 UserHandle.USER_SYSTEM); 12937 } catch (RemoteException e) { 12938 } 12939 } 12940 } 12941 12942 @Override 12943 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 12944 int installFlags, String installerPackageName, int userId) { 12945 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 12946 12947 final int callingUid = Binder.getCallingUid(); 12948 enforceCrossUserPermission(callingUid, userId, 12949 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 12950 12951 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 12952 try { 12953 if (observer != null) { 12954 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 12955 } 12956 } catch (RemoteException re) { 12957 } 12958 return; 12959 } 12960 12961 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 12962 installFlags |= PackageManager.INSTALL_FROM_ADB; 12963 12964 } else { 12965 // Caller holds INSTALL_PACKAGES permission, so we're less strict 12966 // about installerPackageName. 12967 12968 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 12969 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 12970 } 12971 12972 UserHandle user; 12973 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 12974 user = UserHandle.ALL; 12975 } else { 12976 user = new UserHandle(userId); 12977 } 12978 12979 // Only system components can circumvent runtime permissions when installing. 12980 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 12981 && mContext.checkCallingOrSelfPermission(Manifest.permission 12982 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 12983 throw new SecurityException("You need the " 12984 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 12985 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 12986 } 12987 12988 final File originFile = new File(originPath); 12989 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 12990 12991 final Message msg = mHandler.obtainMessage(INIT_COPY); 12992 final VerificationInfo verificationInfo = new VerificationInfo( 12993 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 12994 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 12995 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 12996 null /*packageAbiOverride*/, null /*grantedPermissions*/, 12997 null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN); 12998 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 12999 msg.obj = params; 13000 13001 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 13002 System.identityHashCode(msg.obj)); 13003 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 13004 System.identityHashCode(msg.obj)); 13005 13006 mHandler.sendMessage(msg); 13007 } 13008 13009 13010 /** 13011 * Ensure that the install reason matches what we know about the package installer (e.g. whether 13012 * it is acting on behalf on an enterprise or the user). 13013 * 13014 * Note that the ordering of the conditionals in this method is important. The checks we perform 13015 * are as follows, in this order: 13016 * 13017 * 1) If the install is being performed by a system app, we can trust the app to have set the 13018 * install reason correctly. Thus, we pass through the install reason unchanged, no matter 13019 * what it is. 13020 * 2) If the install is being performed by a device or profile owner app, the install reason 13021 * should be enterprise policy. However, we cannot be sure that the device or profile owner 13022 * set the install reason correctly. If the app targets an older SDK version where install 13023 * reasons did not exist yet, or if the app author simply forgot, the install reason may be 13024 * unset or wrong. Thus, we force the install reason to be enterprise policy. 13025 * 3) In all other cases, the install is being performed by a regular app that is neither part 13026 * of the system nor a device or profile owner. We have no reason to believe that this app is 13027 * acting on behalf of the enterprise admin. Thus, we check whether the install reason was 13028 * set to enterprise policy and if so, change it to unknown instead. 13029 */ 13030 private int fixUpInstallReason(String installerPackageName, int installerUid, 13031 int installReason) { 13032 if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid) 13033 == PERMISSION_GRANTED) { 13034 // If the install is being performed by a system app, we trust that app to have set the 13035 // install reason correctly. 13036 return installReason; 13037 } 13038 13039 final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 13040 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 13041 if (dpm != null) { 13042 ComponentName owner = null; 13043 try { 13044 owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */); 13045 if (owner == null) { 13046 owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid)); 13047 } 13048 } catch (RemoteException e) { 13049 } 13050 if (owner != null && owner.getPackageName().equals(installerPackageName)) { 13051 // If the install is being performed by a device or profile owner, the install 13052 // reason should be enterprise policy. 13053 return PackageManager.INSTALL_REASON_POLICY; 13054 } 13055 } 13056 13057 if (installReason == PackageManager.INSTALL_REASON_POLICY) { 13058 // If the install is being performed by a regular app (i.e. neither system app nor 13059 // device or profile owner), we have no reason to believe that the app is acting on 13060 // behalf of an enterprise. If the app set the install reason to enterprise policy, 13061 // change it to unknown instead. 13062 return PackageManager.INSTALL_REASON_UNKNOWN; 13063 } 13064 13065 // If the install is being performed by a regular app and the install reason was set to any 13066 // value but enterprise policy, leave the install reason unchanged. 13067 return installReason; 13068 } 13069 13070 void installStage(String packageName, File stagedDir, String stagedCid, 13071 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 13072 String installerPackageName, int installerUid, UserHandle user, 13073 Certificate[][] certificates) { 13074 if (DEBUG_EPHEMERAL) { 13075 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 13076 Slog.d(TAG, "Ephemeral install of " + packageName); 13077 } 13078 } 13079 final VerificationInfo verificationInfo = new VerificationInfo( 13080 sessionParams.originatingUri, sessionParams.referrerUri, 13081 sessionParams.originatingUid, installerUid); 13082 13083 final OriginInfo origin; 13084 if (stagedDir != null) { 13085 origin = OriginInfo.fromStagedFile(stagedDir); 13086 } else { 13087 origin = OriginInfo.fromStagedContainer(stagedCid); 13088 } 13089 13090 final Message msg = mHandler.obtainMessage(INIT_COPY); 13091 final int installReason = fixUpInstallReason(installerPackageName, installerUid, 13092 sessionParams.installReason); 13093 final InstallParams params = new InstallParams(origin, null, observer, 13094 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 13095 verificationInfo, user, sessionParams.abiOverride, 13096 sessionParams.grantedRuntimePermissions, certificates, installReason); 13097 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 13098 msg.obj = params; 13099 13100 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 13101 System.identityHashCode(msg.obj)); 13102 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 13103 System.identityHashCode(msg.obj)); 13104 13105 mHandler.sendMessage(msg); 13106 } 13107 13108 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 13109 int userId) { 13110 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 13111 sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId); 13112 } 13113 13114 private void sendPackageAddedForNewUsers(String packageName, boolean isSystem, 13115 int appId, int... userIds) { 13116 if (ArrayUtils.isEmpty(userIds)) { 13117 return; 13118 } 13119 Bundle extras = new Bundle(1); 13120 // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast 13121 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId)); 13122 13123 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 13124 packageName, extras, 0, null, null, userIds); 13125 if (isSystem) { 13126 mHandler.post(() -> { 13127 for (int userId : userIds) { 13128 sendBootCompletedBroadcastToSystemApp(packageName, userId); 13129 } 13130 } 13131 ); 13132 } 13133 } 13134 13135 /** 13136 * The just-installed/enabled app is bundled on the system, so presumed to be able to run 13137 * automatically without needing an explicit launch. 13138 * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones. 13139 */ 13140 private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) { 13141 // If user is not running, the app didn't miss any broadcast 13142 if (!mUserManagerInternal.isUserRunning(userId)) { 13143 return; 13144 } 13145 final IActivityManager am = ActivityManager.getService(); 13146 try { 13147 // Deliver LOCKED_BOOT_COMPLETED first 13148 Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED) 13149 .setPackage(packageName); 13150 final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED}; 13151 am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions, 13152 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 13153 13154 // Deliver BOOT_COMPLETED only if user is unlocked 13155 if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) { 13156 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName); 13157 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions, 13158 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 13159 } 13160 } catch (RemoteException e) { 13161 throw e.rethrowFromSystemServer(); 13162 } 13163 } 13164 13165 @Override 13166 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 13167 int userId) { 13168 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13169 PackageSetting pkgSetting; 13170 final int uid = Binder.getCallingUid(); 13171 enforceCrossUserPermission(uid, userId, 13172 true /* requireFullPermission */, true /* checkShell */, 13173 "setApplicationHiddenSetting for user " + userId); 13174 13175 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 13176 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 13177 return false; 13178 } 13179 13180 long callingId = Binder.clearCallingIdentity(); 13181 try { 13182 boolean sendAdded = false; 13183 boolean sendRemoved = false; 13184 // writer 13185 synchronized (mPackages) { 13186 pkgSetting = mSettings.mPackages.get(packageName); 13187 if (pkgSetting == null) { 13188 return false; 13189 } 13190 // Do not allow "android" is being disabled 13191 if ("android".equals(packageName)) { 13192 Slog.w(TAG, "Cannot hide package: android"); 13193 return false; 13194 } 13195 // Cannot hide static shared libs as they are considered 13196 // a part of the using app (emulating static linking). Also 13197 // static libs are installed always on internal storage. 13198 PackageParser.Package pkg = mPackages.get(packageName); 13199 if (pkg != null && pkg.staticSharedLibName != null) { 13200 Slog.w(TAG, "Cannot hide package: " + packageName 13201 + " providing static shared library: " 13202 + pkg.staticSharedLibName); 13203 return false; 13204 } 13205 // Only allow protected packages to hide themselves. 13206 if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId) 13207 && mProtectedPackages.isPackageStateProtected(userId, packageName)) { 13208 Slog.w(TAG, "Not hiding protected package: " + packageName); 13209 return false; 13210 } 13211 13212 if (pkgSetting.getHidden(userId) != hidden) { 13213 pkgSetting.setHidden(hidden, userId); 13214 mSettings.writePackageRestrictionsLPr(userId); 13215 if (hidden) { 13216 sendRemoved = true; 13217 } else { 13218 sendAdded = true; 13219 } 13220 } 13221 } 13222 if (sendAdded) { 13223 sendPackageAddedForUser(packageName, pkgSetting, userId); 13224 return true; 13225 } 13226 if (sendRemoved) { 13227 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 13228 "hiding pkg"); 13229 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 13230 return true; 13231 } 13232 } finally { 13233 Binder.restoreCallingIdentity(callingId); 13234 } 13235 return false; 13236 } 13237 13238 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 13239 int userId) { 13240 final PackageRemovedInfo info = new PackageRemovedInfo(); 13241 info.removedPackage = packageName; 13242 info.removedUsers = new int[] {userId}; 13243 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 13244 info.sendPackageRemovedBroadcasts(true /*killApp*/); 13245 } 13246 13247 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 13248 if (pkgList.length > 0) { 13249 Bundle extras = new Bundle(1); 13250 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 13251 13252 sendPackageBroadcast( 13253 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 13254 : Intent.ACTION_PACKAGES_UNSUSPENDED, 13255 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 13256 new int[] {userId}); 13257 } 13258 } 13259 13260 /** 13261 * Returns true if application is not found or there was an error. Otherwise it returns 13262 * the hidden state of the package for the given user. 13263 */ 13264 @Override 13265 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 13266 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13267 enforceCrossUserPermission(Binder.getCallingUid(), userId, 13268 true /* requireFullPermission */, false /* checkShell */, 13269 "getApplicationHidden for user " + userId); 13270 PackageSetting pkgSetting; 13271 long callingId = Binder.clearCallingIdentity(); 13272 try { 13273 // writer 13274 synchronized (mPackages) { 13275 pkgSetting = mSettings.mPackages.get(packageName); 13276 if (pkgSetting == null) { 13277 return true; 13278 } 13279 return pkgSetting.getHidden(userId); 13280 } 13281 } finally { 13282 Binder.restoreCallingIdentity(callingId); 13283 } 13284 } 13285 13286 /** 13287 * @hide 13288 */ 13289 @Override 13290 public int installExistingPackageAsUser(String packageName, int userId, int installReason) { 13291 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 13292 null); 13293 PackageSetting pkgSetting; 13294 final int uid = Binder.getCallingUid(); 13295 enforceCrossUserPermission(uid, userId, 13296 true /* requireFullPermission */, true /* checkShell */, 13297 "installExistingPackage for user " + userId); 13298 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 13299 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 13300 } 13301 13302 long callingId = Binder.clearCallingIdentity(); 13303 try { 13304 boolean installed = false; 13305 13306 // writer 13307 synchronized (mPackages) { 13308 pkgSetting = mSettings.mPackages.get(packageName); 13309 if (pkgSetting == null) { 13310 return PackageManager.INSTALL_FAILED_INVALID_URI; 13311 } 13312 if (!pkgSetting.getInstalled(userId)) { 13313 pkgSetting.setInstalled(true, userId); 13314 pkgSetting.setHidden(false, userId); 13315 pkgSetting.setInstallReason(installReason, userId); 13316 mSettings.writePackageRestrictionsLPr(userId); 13317 mSettings.writeKernelMappingLPr(pkgSetting); 13318 installed = true; 13319 } 13320 } 13321 13322 if (installed) { 13323 if (pkgSetting.pkg != null) { 13324 synchronized (mInstallLock) { 13325 // We don't need to freeze for a brand new install 13326 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 13327 } 13328 } 13329 sendPackageAddedForUser(packageName, pkgSetting, userId); 13330 synchronized (mPackages) { 13331 updateSequenceNumberLP(packageName, new int[]{ userId }); 13332 } 13333 } 13334 } finally { 13335 Binder.restoreCallingIdentity(callingId); 13336 } 13337 13338 return PackageManager.INSTALL_SUCCEEDED; 13339 } 13340 13341 boolean isUserRestricted(int userId, String restrictionKey) { 13342 Bundle restrictions = sUserManager.getUserRestrictions(userId); 13343 if (restrictions.getBoolean(restrictionKey, false)) { 13344 Log.w(TAG, "User is restricted: " + restrictionKey); 13345 return true; 13346 } 13347 return false; 13348 } 13349 13350 @Override 13351 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 13352 int userId) { 13353 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13354 enforceCrossUserPermission(Binder.getCallingUid(), userId, 13355 true /* requireFullPermission */, true /* checkShell */, 13356 "setPackagesSuspended for user " + userId); 13357 13358 if (ArrayUtils.isEmpty(packageNames)) { 13359 return packageNames; 13360 } 13361 13362 // List of package names for whom the suspended state has changed. 13363 List<String> changedPackages = new ArrayList<>(packageNames.length); 13364 // List of package names for whom the suspended state is not set as requested in this 13365 // method. 13366 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 13367 long callingId = Binder.clearCallingIdentity(); 13368 try { 13369 for (int i = 0; i < packageNames.length; i++) { 13370 String packageName = packageNames[i]; 13371 boolean changed = false; 13372 final int appId; 13373 synchronized (mPackages) { 13374 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 13375 if (pkgSetting == null) { 13376 Slog.w(TAG, "Could not find package setting for package \"" + packageName 13377 + "\". Skipping suspending/un-suspending."); 13378 unactionedPackages.add(packageName); 13379 continue; 13380 } 13381 appId = pkgSetting.appId; 13382 if (pkgSetting.getSuspended(userId) != suspended) { 13383 if (!canSuspendPackageForUserLocked(packageName, userId)) { 13384 unactionedPackages.add(packageName); 13385 continue; 13386 } 13387 pkgSetting.setSuspended(suspended, userId); 13388 mSettings.writePackageRestrictionsLPr(userId); 13389 changed = true; 13390 changedPackages.add(packageName); 13391 } 13392 } 13393 13394 if (changed && suspended) { 13395 killApplication(packageName, UserHandle.getUid(userId, appId), 13396 "suspending package"); 13397 } 13398 } 13399 } finally { 13400 Binder.restoreCallingIdentity(callingId); 13401 } 13402 13403 if (!changedPackages.isEmpty()) { 13404 sendPackagesSuspendedForUser(changedPackages.toArray( 13405 new String[changedPackages.size()]), userId, suspended); 13406 } 13407 13408 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 13409 } 13410 13411 @Override 13412 public boolean isPackageSuspendedForUser(String packageName, int userId) { 13413 enforceCrossUserPermission(Binder.getCallingUid(), userId, 13414 true /* requireFullPermission */, false /* checkShell */, 13415 "isPackageSuspendedForUser for user " + userId); 13416 synchronized (mPackages) { 13417 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 13418 if (pkgSetting == null) { 13419 throw new IllegalArgumentException("Unknown target package: " + packageName); 13420 } 13421 return pkgSetting.getSuspended(userId); 13422 } 13423 } 13424 13425 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 13426 if (isPackageDeviceAdmin(packageName, userId)) { 13427 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13428 + "\": has an active device admin"); 13429 return false; 13430 } 13431 13432 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 13433 if (packageName.equals(activeLauncherPackageName)) { 13434 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13435 + "\": contains the active launcher"); 13436 return false; 13437 } 13438 13439 if (packageName.equals(mRequiredInstallerPackage)) { 13440 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13441 + "\": required for package installation"); 13442 return false; 13443 } 13444 13445 if (packageName.equals(mRequiredUninstallerPackage)) { 13446 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13447 + "\": required for package uninstallation"); 13448 return false; 13449 } 13450 13451 if (packageName.equals(mRequiredVerifierPackage)) { 13452 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13453 + "\": required for package verification"); 13454 return false; 13455 } 13456 13457 if (packageName.equals(getDefaultDialerPackageName(userId))) { 13458 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13459 + "\": is the default dialer"); 13460 return false; 13461 } 13462 13463 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 13464 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13465 + "\": protected package"); 13466 return false; 13467 } 13468 13469 // Cannot suspend static shared libs as they are considered 13470 // a part of the using app (emulating static linking). Also 13471 // static libs are installed always on internal storage. 13472 PackageParser.Package pkg = mPackages.get(packageName); 13473 if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) { 13474 Slog.w(TAG, "Cannot suspend package: " + packageName 13475 + " providing static shared library: " 13476 + pkg.staticSharedLibName); 13477 return false; 13478 } 13479 13480 return true; 13481 } 13482 13483 private String getActiveLauncherPackageName(int userId) { 13484 Intent intent = new Intent(Intent.ACTION_MAIN); 13485 intent.addCategory(Intent.CATEGORY_HOME); 13486 ResolveInfo resolveInfo = resolveIntent( 13487 intent, 13488 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 13489 PackageManager.MATCH_DEFAULT_ONLY, 13490 userId); 13491 13492 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 13493 } 13494 13495 private String getDefaultDialerPackageName(int userId) { 13496 synchronized (mPackages) { 13497 return mSettings.getDefaultDialerPackageNameLPw(userId); 13498 } 13499 } 13500 13501 @Override 13502 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 13503 mContext.enforceCallingOrSelfPermission( 13504 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13505 "Only package verification agents can verify applications"); 13506 13507 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 13508 final PackageVerificationResponse response = new PackageVerificationResponse( 13509 verificationCode, Binder.getCallingUid()); 13510 msg.arg1 = id; 13511 msg.obj = response; 13512 mHandler.sendMessage(msg); 13513 } 13514 13515 @Override 13516 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 13517 long millisecondsToDelay) { 13518 mContext.enforceCallingOrSelfPermission( 13519 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13520 "Only package verification agents can extend verification timeouts"); 13521 13522 final PackageVerificationState state = mPendingVerification.get(id); 13523 final PackageVerificationResponse response = new PackageVerificationResponse( 13524 verificationCodeAtTimeout, Binder.getCallingUid()); 13525 13526 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 13527 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 13528 } 13529 if (millisecondsToDelay < 0) { 13530 millisecondsToDelay = 0; 13531 } 13532 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 13533 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 13534 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 13535 } 13536 13537 if ((state != null) && !state.timeoutExtended()) { 13538 state.extendTimeout(); 13539 13540 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 13541 msg.arg1 = id; 13542 msg.obj = response; 13543 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 13544 } 13545 } 13546 13547 private void broadcastPackageVerified(int verificationId, Uri packageUri, 13548 int verificationCode, UserHandle user) { 13549 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 13550 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 13551 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 13552 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 13553 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 13554 13555 mContext.sendBroadcastAsUser(intent, user, 13556 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 13557 } 13558 13559 private ComponentName matchComponentForVerifier(String packageName, 13560 List<ResolveInfo> receivers) { 13561 ActivityInfo targetReceiver = null; 13562 13563 final int NR = receivers.size(); 13564 for (int i = 0; i < NR; i++) { 13565 final ResolveInfo info = receivers.get(i); 13566 if (info.activityInfo == null) { 13567 continue; 13568 } 13569 13570 if (packageName.equals(info.activityInfo.packageName)) { 13571 targetReceiver = info.activityInfo; 13572 break; 13573 } 13574 } 13575 13576 if (targetReceiver == null) { 13577 return null; 13578 } 13579 13580 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 13581 } 13582 13583 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 13584 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 13585 if (pkgInfo.verifiers.length == 0) { 13586 return null; 13587 } 13588 13589 final int N = pkgInfo.verifiers.length; 13590 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 13591 for (int i = 0; i < N; i++) { 13592 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 13593 13594 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 13595 receivers); 13596 if (comp == null) { 13597 continue; 13598 } 13599 13600 final int verifierUid = getUidForVerifier(verifierInfo); 13601 if (verifierUid == -1) { 13602 continue; 13603 } 13604 13605 if (DEBUG_VERIFY) { 13606 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 13607 + " with the correct signature"); 13608 } 13609 sufficientVerifiers.add(comp); 13610 verificationState.addSufficientVerifier(verifierUid); 13611 } 13612 13613 return sufficientVerifiers; 13614 } 13615 13616 private int getUidForVerifier(VerifierInfo verifierInfo) { 13617 synchronized (mPackages) { 13618 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 13619 if (pkg == null) { 13620 return -1; 13621 } else if (pkg.mSignatures.length != 1) { 13622 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 13623 + " has more than one signature; ignoring"); 13624 return -1; 13625 } 13626 13627 /* 13628 * If the public key of the package's signature does not match 13629 * our expected public key, then this is a different package and 13630 * we should skip. 13631 */ 13632 13633 final byte[] expectedPublicKey; 13634 try { 13635 final Signature verifierSig = pkg.mSignatures[0]; 13636 final PublicKey publicKey = verifierSig.getPublicKey(); 13637 expectedPublicKey = publicKey.getEncoded(); 13638 } catch (CertificateException e) { 13639 return -1; 13640 } 13641 13642 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 13643 13644 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 13645 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 13646 + " does not have the expected public key; ignoring"); 13647 return -1; 13648 } 13649 13650 return pkg.applicationInfo.uid; 13651 } 13652 } 13653 13654 @Override 13655 public void finishPackageInstall(int token, boolean didLaunch) { 13656 enforceSystemOrRoot("Only the system is allowed to finish installs"); 13657 13658 if (DEBUG_INSTALL) { 13659 Slog.v(TAG, "BM finishing package install for " + token); 13660 } 13661 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 13662 13663 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 13664 mHandler.sendMessage(msg); 13665 } 13666 13667 /** 13668 * Get the verification agent timeout. 13669 * 13670 * @return verification timeout in milliseconds 13671 */ 13672 private long getVerificationTimeout() { 13673 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 13674 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 13675 DEFAULT_VERIFICATION_TIMEOUT); 13676 } 13677 13678 /** 13679 * Get the default verification agent response code. 13680 * 13681 * @return default verification response code 13682 */ 13683 private int getDefaultVerificationResponse() { 13684 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13685 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 13686 DEFAULT_VERIFICATION_RESPONSE); 13687 } 13688 13689 /** 13690 * Check whether or not package verification has been enabled. 13691 * 13692 * @return true if verification should be performed 13693 */ 13694 private boolean isVerificationEnabled(int userId, int installFlags) { 13695 if (!DEFAULT_VERIFY_ENABLE) { 13696 return false; 13697 } 13698 // Ephemeral apps don't get the full verification treatment 13699 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 13700 if (DEBUG_EPHEMERAL) { 13701 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 13702 } 13703 return false; 13704 } 13705 13706 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 13707 13708 // Check if installing from ADB 13709 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 13710 // Do not run verification in a test harness environment 13711 if (ActivityManager.isRunningInTestHarness()) { 13712 return false; 13713 } 13714 if (ensureVerifyAppsEnabled) { 13715 return true; 13716 } 13717 // Check if the developer does not want package verification for ADB installs 13718 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13719 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 13720 return false; 13721 } 13722 } 13723 13724 if (ensureVerifyAppsEnabled) { 13725 return true; 13726 } 13727 13728 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13729 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 13730 } 13731 13732 @Override 13733 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 13734 throws RemoteException { 13735 mContext.enforceCallingOrSelfPermission( 13736 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 13737 "Only intentfilter verification agents can verify applications"); 13738 13739 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 13740 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 13741 Binder.getCallingUid(), verificationCode, failedDomains); 13742 msg.arg1 = id; 13743 msg.obj = response; 13744 mHandler.sendMessage(msg); 13745 } 13746 13747 @Override 13748 public int getIntentVerificationStatus(String packageName, int userId) { 13749 synchronized (mPackages) { 13750 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 13751 } 13752 } 13753 13754 @Override 13755 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 13756 mContext.enforceCallingOrSelfPermission( 13757 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13758 13759 boolean result = false; 13760 synchronized (mPackages) { 13761 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 13762 } 13763 if (result) { 13764 scheduleWritePackageRestrictionsLocked(userId); 13765 } 13766 return result; 13767 } 13768 13769 @Override 13770 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 13771 String packageName) { 13772 synchronized (mPackages) { 13773 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 13774 } 13775 } 13776 13777 @Override 13778 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 13779 if (TextUtils.isEmpty(packageName)) { 13780 return ParceledListSlice.emptyList(); 13781 } 13782 synchronized (mPackages) { 13783 PackageParser.Package pkg = mPackages.get(packageName); 13784 if (pkg == null || pkg.activities == null) { 13785 return ParceledListSlice.emptyList(); 13786 } 13787 final int count = pkg.activities.size(); 13788 ArrayList<IntentFilter> result = new ArrayList<>(); 13789 for (int n=0; n<count; n++) { 13790 PackageParser.Activity activity = pkg.activities.get(n); 13791 if (activity.intents != null && activity.intents.size() > 0) { 13792 result.addAll(activity.intents); 13793 } 13794 } 13795 return new ParceledListSlice<>(result); 13796 } 13797 } 13798 13799 @Override 13800 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 13801 mContext.enforceCallingOrSelfPermission( 13802 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13803 13804 synchronized (mPackages) { 13805 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 13806 if (packageName != null) { 13807 result |= updateIntentVerificationStatus(packageName, 13808 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 13809 userId); 13810 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 13811 packageName, userId); 13812 } 13813 return result; 13814 } 13815 } 13816 13817 @Override 13818 public String getDefaultBrowserPackageName(int userId) { 13819 synchronized (mPackages) { 13820 return mSettings.getDefaultBrowserPackageNameLPw(userId); 13821 } 13822 } 13823 13824 /** 13825 * Get the "allow unknown sources" setting. 13826 * 13827 * @return the current "allow unknown sources" setting 13828 */ 13829 private int getUnknownSourcesSettings() { 13830 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 13831 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 13832 -1); 13833 } 13834 13835 @Override 13836 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 13837 final int uid = Binder.getCallingUid(); 13838 // writer 13839 synchronized (mPackages) { 13840 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 13841 if (targetPackageSetting == null) { 13842 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 13843 } 13844 13845 PackageSetting installerPackageSetting; 13846 if (installerPackageName != null) { 13847 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 13848 if (installerPackageSetting == null) { 13849 throw new IllegalArgumentException("Unknown installer package: " 13850 + installerPackageName); 13851 } 13852 } else { 13853 installerPackageSetting = null; 13854 } 13855 13856 Signature[] callerSignature; 13857 Object obj = mSettings.getUserIdLPr(uid); 13858 if (obj != null) { 13859 if (obj instanceof SharedUserSetting) { 13860 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 13861 } else if (obj instanceof PackageSetting) { 13862 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 13863 } else { 13864 throw new SecurityException("Bad object " + obj + " for uid " + uid); 13865 } 13866 } else { 13867 throw new SecurityException("Unknown calling UID: " + uid); 13868 } 13869 13870 // Verify: can't set installerPackageName to a package that is 13871 // not signed with the same cert as the caller. 13872 if (installerPackageSetting != null) { 13873 if (compareSignatures(callerSignature, 13874 installerPackageSetting.signatures.mSignatures) 13875 != PackageManager.SIGNATURE_MATCH) { 13876 throw new SecurityException( 13877 "Caller does not have same cert as new installer package " 13878 + installerPackageName); 13879 } 13880 } 13881 13882 // Verify: if target already has an installer package, it must 13883 // be signed with the same cert as the caller. 13884 if (targetPackageSetting.installerPackageName != null) { 13885 PackageSetting setting = mSettings.mPackages.get( 13886 targetPackageSetting.installerPackageName); 13887 // If the currently set package isn't valid, then it's always 13888 // okay to change it. 13889 if (setting != null) { 13890 if (compareSignatures(callerSignature, 13891 setting.signatures.mSignatures) 13892 != PackageManager.SIGNATURE_MATCH) { 13893 throw new SecurityException( 13894 "Caller does not have same cert as old installer package " 13895 + targetPackageSetting.installerPackageName); 13896 } 13897 } 13898 } 13899 13900 // Okay! 13901 targetPackageSetting.installerPackageName = installerPackageName; 13902 if (installerPackageName != null) { 13903 mSettings.mInstallerPackages.add(installerPackageName); 13904 } 13905 scheduleWriteSettingsLocked(); 13906 } 13907 } 13908 13909 @Override 13910 public void setApplicationCategoryHint(String packageName, int categoryHint, 13911 String callerPackageName) { 13912 mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(), 13913 callerPackageName); 13914 synchronized (mPackages) { 13915 PackageSetting ps = mSettings.mPackages.get(packageName); 13916 if (ps == null) { 13917 throw new IllegalArgumentException("Unknown target package " + packageName); 13918 } 13919 13920 if (!Objects.equals(callerPackageName, ps.installerPackageName)) { 13921 throw new IllegalArgumentException("Calling package " + callerPackageName 13922 + " is not installer for " + packageName); 13923 } 13924 13925 if (ps.categoryHint != categoryHint) { 13926 ps.categoryHint = categoryHint; 13927 scheduleWriteSettingsLocked(); 13928 } 13929 } 13930 } 13931 13932 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 13933 // Queue up an async operation since the package installation may take a little while. 13934 mHandler.post(new Runnable() { 13935 public void run() { 13936 mHandler.removeCallbacks(this); 13937 // Result object to be returned 13938 PackageInstalledInfo res = new PackageInstalledInfo(); 13939 res.setReturnCode(currentStatus); 13940 res.uid = -1; 13941 res.pkg = null; 13942 res.removedInfo = null; 13943 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13944 args.doPreInstall(res.returnCode); 13945 synchronized (mInstallLock) { 13946 installPackageTracedLI(args, res); 13947 } 13948 args.doPostInstall(res.returnCode, res.uid); 13949 } 13950 13951 // A restore should be performed at this point if (a) the install 13952 // succeeded, (b) the operation is not an update, and (c) the new 13953 // package has not opted out of backup participation. 13954 final boolean update = res.removedInfo != null 13955 && res.removedInfo.removedPackage != null; 13956 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 13957 boolean doRestore = !update 13958 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 13959 13960 // Set up the post-install work request bookkeeping. This will be used 13961 // and cleaned up by the post-install event handling regardless of whether 13962 // there's a restore pass performed. Token values are >= 1. 13963 int token; 13964 if (mNextInstallToken < 0) mNextInstallToken = 1; 13965 token = mNextInstallToken++; 13966 13967 PostInstallData data = new PostInstallData(args, res); 13968 mRunningInstalls.put(token, data); 13969 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 13970 13971 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 13972 // Pass responsibility to the Backup Manager. It will perform a 13973 // restore if appropriate, then pass responsibility back to the 13974 // Package Manager to run the post-install observer callbacks 13975 // and broadcasts. 13976 IBackupManager bm = IBackupManager.Stub.asInterface( 13977 ServiceManager.getService(Context.BACKUP_SERVICE)); 13978 if (bm != null) { 13979 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 13980 + " to BM for possible restore"); 13981 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 13982 try { 13983 // TODO: http://b/22388012 13984 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 13985 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 13986 } else { 13987 doRestore = false; 13988 } 13989 } catch (RemoteException e) { 13990 // can't happen; the backup manager is local 13991 } catch (Exception e) { 13992 Slog.e(TAG, "Exception trying to enqueue restore", e); 13993 doRestore = false; 13994 } 13995 } else { 13996 Slog.e(TAG, "Backup Manager not found!"); 13997 doRestore = false; 13998 } 13999 } 14000 14001 if (!doRestore) { 14002 // No restore possible, or the Backup Manager was mysteriously not 14003 // available -- just fire the post-install work request directly. 14004 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 14005 14006 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 14007 14008 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 14009 mHandler.sendMessage(msg); 14010 } 14011 } 14012 }); 14013 } 14014 14015 /** 14016 * Callback from PackageSettings whenever an app is first transitioned out of the 14017 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 14018 * the app was "launched" for a restoreAtInstall operation. Therefore we check 14019 * here whether the app is the target of an ongoing install, and only send the 14020 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 14021 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 14022 * handling. 14023 */ 14024 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 14025 // Serialize this with the rest of the install-process message chain. In the 14026 // restore-at-install case, this Runnable will necessarily run before the 14027 // POST_INSTALL message is processed, so the contents of mRunningInstalls 14028 // are coherent. In the non-restore case, the app has already completed install 14029 // and been launched through some other means, so it is not in a problematic 14030 // state for observers to see the FIRST_LAUNCH signal. 14031 mHandler.post(new Runnable() { 14032 @Override 14033 public void run() { 14034 for (int i = 0; i < mRunningInstalls.size(); i++) { 14035 final PostInstallData data = mRunningInstalls.valueAt(i); 14036 if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14037 continue; 14038 } 14039 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 14040 // right package; but is it for the right user? 14041 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 14042 if (userId == data.res.newUsers[uIndex]) { 14043 if (DEBUG_BACKUP) { 14044 Slog.i(TAG, "Package " + pkgName 14045 + " being restored so deferring FIRST_LAUNCH"); 14046 } 14047 return; 14048 } 14049 } 14050 } 14051 } 14052 // didn't find it, so not being restored 14053 if (DEBUG_BACKUP) { 14054 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 14055 } 14056 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 14057 } 14058 }); 14059 } 14060 14061 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 14062 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 14063 installerPkg, null, userIds); 14064 } 14065 14066 private abstract class HandlerParams { 14067 private static final int MAX_RETRIES = 4; 14068 14069 /** 14070 * Number of times startCopy() has been attempted and had a non-fatal 14071 * error. 14072 */ 14073 private int mRetries = 0; 14074 14075 /** User handle for the user requesting the information or installation. */ 14076 private final UserHandle mUser; 14077 String traceMethod; 14078 int traceCookie; 14079 14080 HandlerParams(UserHandle user) { 14081 mUser = user; 14082 } 14083 14084 UserHandle getUser() { 14085 return mUser; 14086 } 14087 14088 HandlerParams setTraceMethod(String traceMethod) { 14089 this.traceMethod = traceMethod; 14090 return this; 14091 } 14092 14093 HandlerParams setTraceCookie(int traceCookie) { 14094 this.traceCookie = traceCookie; 14095 return this; 14096 } 14097 14098 final boolean startCopy() { 14099 boolean res; 14100 try { 14101 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 14102 14103 if (++mRetries > MAX_RETRIES) { 14104 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 14105 mHandler.sendEmptyMessage(MCS_GIVE_UP); 14106 handleServiceError(); 14107 return false; 14108 } else { 14109 handleStartCopy(); 14110 res = true; 14111 } 14112 } catch (RemoteException e) { 14113 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 14114 mHandler.sendEmptyMessage(MCS_RECONNECT); 14115 res = false; 14116 } 14117 handleReturnCode(); 14118 return res; 14119 } 14120 14121 final void serviceError() { 14122 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 14123 handleServiceError(); 14124 handleReturnCode(); 14125 } 14126 14127 abstract void handleStartCopy() throws RemoteException; 14128 abstract void handleServiceError(); 14129 abstract void handleReturnCode(); 14130 } 14131 14132 class MeasureParams extends HandlerParams { 14133 private final PackageStats mStats; 14134 private boolean mSuccess; 14135 14136 private final IPackageStatsObserver mObserver; 14137 14138 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 14139 super(new UserHandle(stats.userHandle)); 14140 mObserver = observer; 14141 mStats = stats; 14142 } 14143 14144 @Override 14145 public String toString() { 14146 return "MeasureParams{" 14147 + Integer.toHexString(System.identityHashCode(this)) 14148 + " " + mStats.packageName + "}"; 14149 } 14150 14151 @Override 14152 void handleStartCopy() throws RemoteException { 14153 synchronized (mInstallLock) { 14154 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 14155 } 14156 14157 if (mSuccess) { 14158 boolean mounted = false; 14159 try { 14160 final String status = Environment.getExternalStorageState(); 14161 mounted = (Environment.MEDIA_MOUNTED.equals(status) 14162 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 14163 } catch (Exception e) { 14164 } 14165 14166 if (mounted) { 14167 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 14168 14169 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 14170 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 14171 14172 mStats.externalDataSize = calculateDirectorySize(mContainerService, 14173 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 14174 14175 // Always subtract cache size, since it's a subdirectory 14176 mStats.externalDataSize -= mStats.externalCacheSize; 14177 14178 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 14179 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 14180 14181 mStats.externalObbSize = calculateDirectorySize(mContainerService, 14182 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 14183 } 14184 } 14185 } 14186 14187 @Override 14188 void handleReturnCode() { 14189 if (mObserver != null) { 14190 try { 14191 mObserver.onGetStatsCompleted(mStats, mSuccess); 14192 } catch (RemoteException e) { 14193 Slog.i(TAG, "Observer no longer exists."); 14194 } 14195 } 14196 } 14197 14198 @Override 14199 void handleServiceError() { 14200 Slog.e(TAG, "Could not measure application " + mStats.packageName 14201 + " external storage"); 14202 } 14203 } 14204 14205 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 14206 throws RemoteException { 14207 long result = 0; 14208 for (File path : paths) { 14209 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 14210 } 14211 return result; 14212 } 14213 14214 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 14215 for (File path : paths) { 14216 try { 14217 mcs.clearDirectory(path.getAbsolutePath()); 14218 } catch (RemoteException e) { 14219 } 14220 } 14221 } 14222 14223 static class OriginInfo { 14224 /** 14225 * Location where install is coming from, before it has been 14226 * copied/renamed into place. This could be a single monolithic APK 14227 * file, or a cluster directory. This location may be untrusted. 14228 */ 14229 final File file; 14230 final String cid; 14231 14232 /** 14233 * Flag indicating that {@link #file} or {@link #cid} has already been 14234 * staged, meaning downstream users don't need to defensively copy the 14235 * contents. 14236 */ 14237 final boolean staged; 14238 14239 /** 14240 * Flag indicating that {@link #file} or {@link #cid} is an already 14241 * installed app that is being moved. 14242 */ 14243 final boolean existing; 14244 14245 final String resolvedPath; 14246 final File resolvedFile; 14247 14248 static OriginInfo fromNothing() { 14249 return new OriginInfo(null, null, false, false); 14250 } 14251 14252 static OriginInfo fromUntrustedFile(File file) { 14253 return new OriginInfo(file, null, false, false); 14254 } 14255 14256 static OriginInfo fromExistingFile(File file) { 14257 return new OriginInfo(file, null, false, true); 14258 } 14259 14260 static OriginInfo fromStagedFile(File file) { 14261 return new OriginInfo(file, null, true, false); 14262 } 14263 14264 static OriginInfo fromStagedContainer(String cid) { 14265 return new OriginInfo(null, cid, true, false); 14266 } 14267 14268 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 14269 this.file = file; 14270 this.cid = cid; 14271 this.staged = staged; 14272 this.existing = existing; 14273 14274 if (cid != null) { 14275 resolvedPath = PackageHelper.getSdDir(cid); 14276 resolvedFile = new File(resolvedPath); 14277 } else if (file != null) { 14278 resolvedPath = file.getAbsolutePath(); 14279 resolvedFile = file; 14280 } else { 14281 resolvedPath = null; 14282 resolvedFile = null; 14283 } 14284 } 14285 } 14286 14287 static class MoveInfo { 14288 final int moveId; 14289 final String fromUuid; 14290 final String toUuid; 14291 final String packageName; 14292 final String dataAppName; 14293 final int appId; 14294 final String seinfo; 14295 final int targetSdkVersion; 14296 14297 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 14298 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 14299 this.moveId = moveId; 14300 this.fromUuid = fromUuid; 14301 this.toUuid = toUuid; 14302 this.packageName = packageName; 14303 this.dataAppName = dataAppName; 14304 this.appId = appId; 14305 this.seinfo = seinfo; 14306 this.targetSdkVersion = targetSdkVersion; 14307 } 14308 } 14309 14310 static class VerificationInfo { 14311 /** A constant used to indicate that a uid value is not present. */ 14312 public static final int NO_UID = -1; 14313 14314 /** URI referencing where the package was downloaded from. */ 14315 final Uri originatingUri; 14316 14317 /** HTTP referrer URI associated with the originatingURI. */ 14318 final Uri referrer; 14319 14320 /** UID of the application that the install request originated from. */ 14321 final int originatingUid; 14322 14323 /** UID of application requesting the install */ 14324 final int installerUid; 14325 14326 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 14327 this.originatingUri = originatingUri; 14328 this.referrer = referrer; 14329 this.originatingUid = originatingUid; 14330 this.installerUid = installerUid; 14331 } 14332 } 14333 14334 class InstallParams extends HandlerParams { 14335 final OriginInfo origin; 14336 final MoveInfo move; 14337 final IPackageInstallObserver2 observer; 14338 int installFlags; 14339 final String installerPackageName; 14340 final String volumeUuid; 14341 private InstallArgs mArgs; 14342 private int mRet; 14343 final String packageAbiOverride; 14344 final String[] grantedRuntimePermissions; 14345 final VerificationInfo verificationInfo; 14346 final Certificate[][] certificates; 14347 final int installReason; 14348 14349 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 14350 int installFlags, String installerPackageName, String volumeUuid, 14351 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 14352 String[] grantedPermissions, Certificate[][] certificates, int installReason) { 14353 super(user); 14354 this.origin = origin; 14355 this.move = move; 14356 this.observer = observer; 14357 this.installFlags = installFlags; 14358 this.installerPackageName = installerPackageName; 14359 this.volumeUuid = volumeUuid; 14360 this.verificationInfo = verificationInfo; 14361 this.packageAbiOverride = packageAbiOverride; 14362 this.grantedRuntimePermissions = grantedPermissions; 14363 this.certificates = certificates; 14364 this.installReason = installReason; 14365 } 14366 14367 @Override 14368 public String toString() { 14369 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 14370 + " file=" + origin.file + " cid=" + origin.cid + "}"; 14371 } 14372 14373 private int installLocationPolicy(PackageInfoLite pkgLite) { 14374 String packageName = pkgLite.packageName; 14375 int installLocation = pkgLite.installLocation; 14376 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14377 // reader 14378 synchronized (mPackages) { 14379 // Currently installed package which the new package is attempting to replace or 14380 // null if no such package is installed. 14381 PackageParser.Package installedPkg = mPackages.get(packageName); 14382 // Package which currently owns the data which the new package will own if installed. 14383 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 14384 // will be null whereas dataOwnerPkg will contain information about the package 14385 // which was uninstalled while keeping its data. 14386 PackageParser.Package dataOwnerPkg = installedPkg; 14387 if (dataOwnerPkg == null) { 14388 PackageSetting ps = mSettings.mPackages.get(packageName); 14389 if (ps != null) { 14390 dataOwnerPkg = ps.pkg; 14391 } 14392 } 14393 14394 if (dataOwnerPkg != null) { 14395 // If installed, the package will get access to data left on the device by its 14396 // predecessor. As a security measure, this is permited only if this is not a 14397 // version downgrade or if the predecessor package is marked as debuggable and 14398 // a downgrade is explicitly requested. 14399 // 14400 // On debuggable platform builds, downgrades are permitted even for 14401 // non-debuggable packages to make testing easier. Debuggable platform builds do 14402 // not offer security guarantees and thus it's OK to disable some security 14403 // mechanisms to make debugging/testing easier on those builds. However, even on 14404 // debuggable builds downgrades of packages are permitted only if requested via 14405 // installFlags. This is because we aim to keep the behavior of debuggable 14406 // platform builds as close as possible to the behavior of non-debuggable 14407 // platform builds. 14408 final boolean downgradeRequested = 14409 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 14410 final boolean packageDebuggable = 14411 (dataOwnerPkg.applicationInfo.flags 14412 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 14413 final boolean downgradePermitted = 14414 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 14415 if (!downgradePermitted) { 14416 try { 14417 checkDowngrade(dataOwnerPkg, pkgLite); 14418 } catch (PackageManagerException e) { 14419 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 14420 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 14421 } 14422 } 14423 } 14424 14425 if (installedPkg != null) { 14426 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14427 // Check for updated system application. 14428 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 14429 if (onSd) { 14430 Slog.w(TAG, "Cannot install update to system app on sdcard"); 14431 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 14432 } 14433 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14434 } else { 14435 if (onSd) { 14436 // Install flag overrides everything. 14437 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14438 } 14439 // If current upgrade specifies particular preference 14440 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 14441 // Application explicitly specified internal. 14442 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14443 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 14444 // App explictly prefers external. Let policy decide 14445 } else { 14446 // Prefer previous location 14447 if (isExternal(installedPkg)) { 14448 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14449 } 14450 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14451 } 14452 } 14453 } else { 14454 // Invalid install. Return error code 14455 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 14456 } 14457 } 14458 } 14459 // All the special cases have been taken care of. 14460 // Return result based on recommended install location. 14461 if (onSd) { 14462 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14463 } 14464 return pkgLite.recommendedInstallLocation; 14465 } 14466 14467 /* 14468 * Invoke remote method to get package information and install 14469 * location values. Override install location based on default 14470 * policy if needed and then create install arguments based 14471 * on the install location. 14472 */ 14473 public void handleStartCopy() throws RemoteException { 14474 int ret = PackageManager.INSTALL_SUCCEEDED; 14475 14476 // If we're already staged, we've firmly committed to an install location 14477 if (origin.staged) { 14478 if (origin.file != null) { 14479 installFlags |= PackageManager.INSTALL_INTERNAL; 14480 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 14481 } else if (origin.cid != null) { 14482 installFlags |= PackageManager.INSTALL_EXTERNAL; 14483 installFlags &= ~PackageManager.INSTALL_INTERNAL; 14484 } else { 14485 throw new IllegalStateException("Invalid stage location"); 14486 } 14487 } 14488 14489 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14490 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 14491 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 14492 PackageInfoLite pkgLite = null; 14493 14494 if (onInt && onSd) { 14495 // Check if both bits are set. 14496 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 14497 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14498 } else if (onSd && ephemeral) { 14499 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 14500 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14501 } else { 14502 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 14503 packageAbiOverride); 14504 14505 if (DEBUG_EPHEMERAL && ephemeral) { 14506 Slog.v(TAG, "pkgLite for install: " + pkgLite); 14507 } 14508 14509 /* 14510 * If we have too little free space, try to free cache 14511 * before giving up. 14512 */ 14513 if (!origin.staged && pkgLite.recommendedInstallLocation 14514 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 14515 // TODO: focus freeing disk space on the target device 14516 final StorageManager storage = StorageManager.from(mContext); 14517 final long lowThreshold = storage.getStorageLowBytes( 14518 Environment.getDataDirectory()); 14519 14520 final long sizeBytes = mContainerService.calculateInstalledSize( 14521 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 14522 14523 try { 14524 mInstaller.freeCache(null, sizeBytes + lowThreshold, 0); 14525 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 14526 installFlags, packageAbiOverride); 14527 } catch (InstallerException e) { 14528 Slog.w(TAG, "Failed to free cache", e); 14529 } 14530 14531 /* 14532 * The cache free must have deleted the file we 14533 * downloaded to install. 14534 * 14535 * TODO: fix the "freeCache" call to not delete 14536 * the file we care about. 14537 */ 14538 if (pkgLite.recommendedInstallLocation 14539 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 14540 pkgLite.recommendedInstallLocation 14541 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 14542 } 14543 } 14544 } 14545 14546 if (ret == PackageManager.INSTALL_SUCCEEDED) { 14547 int loc = pkgLite.recommendedInstallLocation; 14548 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 14549 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14550 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 14551 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 14552 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 14553 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 14554 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 14555 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 14556 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 14557 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 14558 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 14559 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 14560 } else { 14561 // Override with defaults if needed. 14562 loc = installLocationPolicy(pkgLite); 14563 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 14564 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 14565 } else if (!onSd && !onInt) { 14566 // Override install location with flags 14567 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 14568 // Set the flag to install on external media. 14569 installFlags |= PackageManager.INSTALL_EXTERNAL; 14570 installFlags &= ~PackageManager.INSTALL_INTERNAL; 14571 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 14572 if (DEBUG_EPHEMERAL) { 14573 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 14574 } 14575 installFlags |= PackageManager.INSTALL_EPHEMERAL; 14576 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 14577 |PackageManager.INSTALL_INTERNAL); 14578 } else { 14579 // Make sure the flag for installing on external 14580 // media is unset 14581 installFlags |= PackageManager.INSTALL_INTERNAL; 14582 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 14583 } 14584 } 14585 } 14586 } 14587 14588 final InstallArgs args = createInstallArgs(this); 14589 mArgs = args; 14590 14591 if (ret == PackageManager.INSTALL_SUCCEEDED) { 14592 // TODO: http://b/22976637 14593 // Apps installed for "all" users use the device owner to verify the app 14594 UserHandle verifierUser = getUser(); 14595 if (verifierUser == UserHandle.ALL) { 14596 verifierUser = UserHandle.SYSTEM; 14597 } 14598 14599 /* 14600 * Determine if we have any installed package verifiers. If we 14601 * do, then we'll defer to them to verify the packages. 14602 */ 14603 final int requiredUid = mRequiredVerifierPackage == null ? -1 14604 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 14605 verifierUser.getIdentifier()); 14606 if (!origin.existing && requiredUid != -1 14607 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 14608 final Intent verification = new Intent( 14609 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 14610 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 14611 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 14612 PACKAGE_MIME_TYPE); 14613 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 14614 14615 // Query all live verifiers based on current user state 14616 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 14617 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 14618 14619 if (DEBUG_VERIFY) { 14620 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 14621 + verification.toString() + " with " + pkgLite.verifiers.length 14622 + " optional verifiers"); 14623 } 14624 14625 final int verificationId = mPendingVerificationToken++; 14626 14627 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 14628 14629 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 14630 installerPackageName); 14631 14632 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 14633 installFlags); 14634 14635 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 14636 pkgLite.packageName); 14637 14638 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 14639 pkgLite.versionCode); 14640 14641 if (verificationInfo != null) { 14642 if (verificationInfo.originatingUri != null) { 14643 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 14644 verificationInfo.originatingUri); 14645 } 14646 if (verificationInfo.referrer != null) { 14647 verification.putExtra(Intent.EXTRA_REFERRER, 14648 verificationInfo.referrer); 14649 } 14650 if (verificationInfo.originatingUid >= 0) { 14651 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 14652 verificationInfo.originatingUid); 14653 } 14654 if (verificationInfo.installerUid >= 0) { 14655 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 14656 verificationInfo.installerUid); 14657 } 14658 } 14659 14660 final PackageVerificationState verificationState = new PackageVerificationState( 14661 requiredUid, args); 14662 14663 mPendingVerification.append(verificationId, verificationState); 14664 14665 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 14666 receivers, verificationState); 14667 14668 /* 14669 * If any sufficient verifiers were listed in the package 14670 * manifest, attempt to ask them. 14671 */ 14672 if (sufficientVerifiers != null) { 14673 final int N = sufficientVerifiers.size(); 14674 if (N == 0) { 14675 Slog.i(TAG, "Additional verifiers required, but none installed."); 14676 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 14677 } else { 14678 for (int i = 0; i < N; i++) { 14679 final ComponentName verifierComponent = sufficientVerifiers.get(i); 14680 14681 final Intent sufficientIntent = new Intent(verification); 14682 sufficientIntent.setComponent(verifierComponent); 14683 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 14684 } 14685 } 14686 } 14687 14688 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 14689 mRequiredVerifierPackage, receivers); 14690 if (ret == PackageManager.INSTALL_SUCCEEDED 14691 && mRequiredVerifierPackage != null) { 14692 Trace.asyncTraceBegin( 14693 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 14694 /* 14695 * Send the intent to the required verification agent, 14696 * but only start the verification timeout after the 14697 * target BroadcastReceivers have run. 14698 */ 14699 verification.setComponent(requiredVerifierComponent); 14700 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 14701 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 14702 new BroadcastReceiver() { 14703 @Override 14704 public void onReceive(Context context, Intent intent) { 14705 final Message msg = mHandler 14706 .obtainMessage(CHECK_PENDING_VERIFICATION); 14707 msg.arg1 = verificationId; 14708 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 14709 } 14710 }, null, 0, null, null); 14711 14712 /* 14713 * We don't want the copy to proceed until verification 14714 * succeeds, so null out this field. 14715 */ 14716 mArgs = null; 14717 } 14718 } else { 14719 /* 14720 * No package verification is enabled, so immediately start 14721 * the remote call to initiate copy using temporary file. 14722 */ 14723 ret = args.copyApk(mContainerService, true); 14724 } 14725 } 14726 14727 mRet = ret; 14728 } 14729 14730 @Override 14731 void handleReturnCode() { 14732 // If mArgs is null, then MCS couldn't be reached. When it 14733 // reconnects, it will try again to install. At that point, this 14734 // will succeed. 14735 if (mArgs != null) { 14736 processPendingInstall(mArgs, mRet); 14737 } 14738 } 14739 14740 @Override 14741 void handleServiceError() { 14742 mArgs = createInstallArgs(this); 14743 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 14744 } 14745 14746 public boolean isForwardLocked() { 14747 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 14748 } 14749 } 14750 14751 /** 14752 * Used during creation of InstallArgs 14753 * 14754 * @param installFlags package installation flags 14755 * @return true if should be installed on external storage 14756 */ 14757 private static boolean installOnExternalAsec(int installFlags) { 14758 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 14759 return false; 14760 } 14761 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 14762 return true; 14763 } 14764 return false; 14765 } 14766 14767 /** 14768 * Used during creation of InstallArgs 14769 * 14770 * @param installFlags package installation flags 14771 * @return true if should be installed as forward locked 14772 */ 14773 private static boolean installForwardLocked(int installFlags) { 14774 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 14775 } 14776 14777 private InstallArgs createInstallArgs(InstallParams params) { 14778 if (params.move != null) { 14779 return new MoveInstallArgs(params); 14780 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 14781 return new AsecInstallArgs(params); 14782 } else { 14783 return new FileInstallArgs(params); 14784 } 14785 } 14786 14787 /** 14788 * Create args that describe an existing installed package. Typically used 14789 * when cleaning up old installs, or used as a move source. 14790 */ 14791 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 14792 String resourcePath, String[] instructionSets) { 14793 final boolean isInAsec; 14794 if (installOnExternalAsec(installFlags)) { 14795 /* Apps on SD card are always in ASEC containers. */ 14796 isInAsec = true; 14797 } else if (installForwardLocked(installFlags) 14798 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 14799 /* 14800 * Forward-locked apps are only in ASEC containers if they're the 14801 * new style 14802 */ 14803 isInAsec = true; 14804 } else { 14805 isInAsec = false; 14806 } 14807 14808 if (isInAsec) { 14809 return new AsecInstallArgs(codePath, instructionSets, 14810 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 14811 } else { 14812 return new FileInstallArgs(codePath, resourcePath, instructionSets); 14813 } 14814 } 14815 14816 static abstract class InstallArgs { 14817 /** @see InstallParams#origin */ 14818 final OriginInfo origin; 14819 /** @see InstallParams#move */ 14820 final MoveInfo move; 14821 14822 final IPackageInstallObserver2 observer; 14823 // Always refers to PackageManager flags only 14824 final int installFlags; 14825 final String installerPackageName; 14826 final String volumeUuid; 14827 final UserHandle user; 14828 final String abiOverride; 14829 final String[] installGrantPermissions; 14830 /** If non-null, drop an async trace when the install completes */ 14831 final String traceMethod; 14832 final int traceCookie; 14833 final Certificate[][] certificates; 14834 final int installReason; 14835 14836 // The list of instruction sets supported by this app. This is currently 14837 // only used during the rmdex() phase to clean up resources. We can get rid of this 14838 // if we move dex files under the common app path. 14839 /* nullable */ String[] instructionSets; 14840 14841 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 14842 int installFlags, String installerPackageName, String volumeUuid, 14843 UserHandle user, String[] instructionSets, 14844 String abiOverride, String[] installGrantPermissions, 14845 String traceMethod, int traceCookie, Certificate[][] certificates, 14846 int installReason) { 14847 this.origin = origin; 14848 this.move = move; 14849 this.installFlags = installFlags; 14850 this.observer = observer; 14851 this.installerPackageName = installerPackageName; 14852 this.volumeUuid = volumeUuid; 14853 this.user = user; 14854 this.instructionSets = instructionSets; 14855 this.abiOverride = abiOverride; 14856 this.installGrantPermissions = installGrantPermissions; 14857 this.traceMethod = traceMethod; 14858 this.traceCookie = traceCookie; 14859 this.certificates = certificates; 14860 this.installReason = installReason; 14861 } 14862 14863 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 14864 abstract int doPreInstall(int status); 14865 14866 /** 14867 * Rename package into final resting place. All paths on the given 14868 * scanned package should be updated to reflect the rename. 14869 */ 14870 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 14871 abstract int doPostInstall(int status, int uid); 14872 14873 /** @see PackageSettingBase#codePathString */ 14874 abstract String getCodePath(); 14875 /** @see PackageSettingBase#resourcePathString */ 14876 abstract String getResourcePath(); 14877 14878 // Need installer lock especially for dex file removal. 14879 abstract void cleanUpResourcesLI(); 14880 abstract boolean doPostDeleteLI(boolean delete); 14881 14882 /** 14883 * Called before the source arguments are copied. This is used mostly 14884 * for MoveParams when it needs to read the source file to put it in the 14885 * destination. 14886 */ 14887 int doPreCopy() { 14888 return PackageManager.INSTALL_SUCCEEDED; 14889 } 14890 14891 /** 14892 * Called after the source arguments are copied. This is used mostly for 14893 * MoveParams when it needs to read the source file to put it in the 14894 * destination. 14895 */ 14896 int doPostCopy(int uid) { 14897 return PackageManager.INSTALL_SUCCEEDED; 14898 } 14899 14900 protected boolean isFwdLocked() { 14901 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 14902 } 14903 14904 protected boolean isExternalAsec() { 14905 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14906 } 14907 14908 protected boolean isEphemeral() { 14909 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 14910 } 14911 14912 UserHandle getUser() { 14913 return user; 14914 } 14915 } 14916 14917 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 14918 if (!allCodePaths.isEmpty()) { 14919 if (instructionSets == null) { 14920 throw new IllegalStateException("instructionSet == null"); 14921 } 14922 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 14923 for (String codePath : allCodePaths) { 14924 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 14925 try { 14926 mInstaller.rmdex(codePath, dexCodeInstructionSet); 14927 } catch (InstallerException ignored) { 14928 } 14929 } 14930 } 14931 } 14932 } 14933 14934 /** 14935 * Logic to handle installation of non-ASEC applications, including copying 14936 * and renaming logic. 14937 */ 14938 class FileInstallArgs extends InstallArgs { 14939 private File codeFile; 14940 private File resourceFile; 14941 14942 // Example topology: 14943 // /data/app/com.example/base.apk 14944 // /data/app/com.example/split_foo.apk 14945 // /data/app/com.example/lib/arm/libfoo.so 14946 // /data/app/com.example/lib/arm64/libfoo.so 14947 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 14948 14949 /** New install */ 14950 FileInstallArgs(InstallParams params) { 14951 super(params.origin, params.move, params.observer, params.installFlags, 14952 params.installerPackageName, params.volumeUuid, 14953 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 14954 params.grantedRuntimePermissions, 14955 params.traceMethod, params.traceCookie, params.certificates, 14956 params.installReason); 14957 if (isFwdLocked()) { 14958 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 14959 } 14960 } 14961 14962 /** Existing install */ 14963 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 14964 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 14965 null, null, null, 0, null /*certificates*/, 14966 PackageManager.INSTALL_REASON_UNKNOWN); 14967 this.codeFile = (codePath != null) ? new File(codePath) : null; 14968 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 14969 } 14970 14971 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 14972 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 14973 try { 14974 return doCopyApk(imcs, temp); 14975 } finally { 14976 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14977 } 14978 } 14979 14980 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 14981 if (origin.staged) { 14982 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 14983 codeFile = origin.file; 14984 resourceFile = origin.file; 14985 return PackageManager.INSTALL_SUCCEEDED; 14986 } 14987 14988 try { 14989 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 14990 final File tempDir = 14991 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 14992 codeFile = tempDir; 14993 resourceFile = tempDir; 14994 } catch (IOException e) { 14995 Slog.w(TAG, "Failed to create copy file: " + e); 14996 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 14997 } 14998 14999 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 15000 @Override 15001 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 15002 if (!FileUtils.isValidExtFilename(name)) { 15003 throw new IllegalArgumentException("Invalid filename: " + name); 15004 } 15005 try { 15006 final File file = new File(codeFile, name); 15007 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 15008 O_RDWR | O_CREAT, 0644); 15009 Os.chmod(file.getAbsolutePath(), 0644); 15010 return new ParcelFileDescriptor(fd); 15011 } catch (ErrnoException e) { 15012 throw new RemoteException("Failed to open: " + e.getMessage()); 15013 } 15014 } 15015 }; 15016 15017 int ret = PackageManager.INSTALL_SUCCEEDED; 15018 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 15019 if (ret != PackageManager.INSTALL_SUCCEEDED) { 15020 Slog.e(TAG, "Failed to copy package"); 15021 return ret; 15022 } 15023 15024 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 15025 NativeLibraryHelper.Handle handle = null; 15026 try { 15027 handle = NativeLibraryHelper.Handle.create(codeFile); 15028 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 15029 abiOverride); 15030 } catch (IOException e) { 15031 Slog.e(TAG, "Copying native libraries failed", e); 15032 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15033 } finally { 15034 IoUtils.closeQuietly(handle); 15035 } 15036 15037 return ret; 15038 } 15039 15040 int doPreInstall(int status) { 15041 if (status != PackageManager.INSTALL_SUCCEEDED) { 15042 cleanUp(); 15043 } 15044 return status; 15045 } 15046 15047 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15048 if (status != PackageManager.INSTALL_SUCCEEDED) { 15049 cleanUp(); 15050 return false; 15051 } 15052 15053 final File targetDir = codeFile.getParentFile(); 15054 final File beforeCodeFile = codeFile; 15055 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 15056 15057 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 15058 try { 15059 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 15060 } catch (ErrnoException e) { 15061 Slog.w(TAG, "Failed to rename", e); 15062 return false; 15063 } 15064 15065 if (!SELinux.restoreconRecursive(afterCodeFile)) { 15066 Slog.w(TAG, "Failed to restorecon"); 15067 return false; 15068 } 15069 15070 // Reflect the rename internally 15071 codeFile = afterCodeFile; 15072 resourceFile = afterCodeFile; 15073 15074 // Reflect the rename in scanned details 15075 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 15076 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 15077 afterCodeFile, pkg.baseCodePath)); 15078 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 15079 afterCodeFile, pkg.splitCodePaths)); 15080 15081 // Reflect the rename in app info 15082 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15083 pkg.setApplicationInfoCodePath(pkg.codePath); 15084 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15085 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15086 pkg.setApplicationInfoResourcePath(pkg.codePath); 15087 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15088 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15089 15090 return true; 15091 } 15092 15093 int doPostInstall(int status, int uid) { 15094 if (status != PackageManager.INSTALL_SUCCEEDED) { 15095 cleanUp(); 15096 } 15097 return status; 15098 } 15099 15100 @Override 15101 String getCodePath() { 15102 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 15103 } 15104 15105 @Override 15106 String getResourcePath() { 15107 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 15108 } 15109 15110 private boolean cleanUp() { 15111 if (codeFile == null || !codeFile.exists()) { 15112 return false; 15113 } 15114 15115 removeCodePathLI(codeFile); 15116 15117 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 15118 resourceFile.delete(); 15119 } 15120 15121 return true; 15122 } 15123 15124 void cleanUpResourcesLI() { 15125 // Try enumerating all code paths before deleting 15126 List<String> allCodePaths = Collections.EMPTY_LIST; 15127 if (codeFile != null && codeFile.exists()) { 15128 try { 15129 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 15130 allCodePaths = pkg.getAllCodePaths(); 15131 } catch (PackageParserException e) { 15132 // Ignored; we tried our best 15133 } 15134 } 15135 15136 cleanUp(); 15137 removeDexFiles(allCodePaths, instructionSets); 15138 } 15139 15140 boolean doPostDeleteLI(boolean delete) { 15141 // XXX err, shouldn't we respect the delete flag? 15142 cleanUpResourcesLI(); 15143 return true; 15144 } 15145 } 15146 15147 private boolean isAsecExternal(String cid) { 15148 final String asecPath = PackageHelper.getSdFilesystem(cid); 15149 return !asecPath.startsWith(mAsecInternalPath); 15150 } 15151 15152 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 15153 PackageManagerException { 15154 if (copyRet < 0) { 15155 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 15156 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 15157 throw new PackageManagerException(copyRet, message); 15158 } 15159 } 15160 } 15161 15162 /** 15163 * Extract the StorageManagerService "container ID" from the full code path of an 15164 * .apk. 15165 */ 15166 static String cidFromCodePath(String fullCodePath) { 15167 int eidx = fullCodePath.lastIndexOf("/"); 15168 String subStr1 = fullCodePath.substring(0, eidx); 15169 int sidx = subStr1.lastIndexOf("/"); 15170 return subStr1.substring(sidx+1, eidx); 15171 } 15172 15173 /** 15174 * Logic to handle installation of ASEC applications, including copying and 15175 * renaming logic. 15176 */ 15177 class AsecInstallArgs extends InstallArgs { 15178 static final String RES_FILE_NAME = "pkg.apk"; 15179 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 15180 15181 String cid; 15182 String packagePath; 15183 String resourcePath; 15184 15185 /** New install */ 15186 AsecInstallArgs(InstallParams params) { 15187 super(params.origin, params.move, params.observer, params.installFlags, 15188 params.installerPackageName, params.volumeUuid, 15189 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 15190 params.grantedRuntimePermissions, 15191 params.traceMethod, params.traceCookie, params.certificates, 15192 params.installReason); 15193 } 15194 15195 /** Existing install */ 15196 AsecInstallArgs(String fullCodePath, String[] instructionSets, 15197 boolean isExternal, boolean isForwardLocked) { 15198 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 15199 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 15200 instructionSets, null, null, null, 0, null /*certificates*/, 15201 PackageManager.INSTALL_REASON_UNKNOWN); 15202 // Hackily pretend we're still looking at a full code path 15203 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 15204 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 15205 } 15206 15207 // Extract cid from fullCodePath 15208 int eidx = fullCodePath.lastIndexOf("/"); 15209 String subStr1 = fullCodePath.substring(0, eidx); 15210 int sidx = subStr1.lastIndexOf("/"); 15211 cid = subStr1.substring(sidx+1, eidx); 15212 setMountPath(subStr1); 15213 } 15214 15215 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 15216 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 15217 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 15218 instructionSets, null, null, null, 0, null /*certificates*/, 15219 PackageManager.INSTALL_REASON_UNKNOWN); 15220 this.cid = cid; 15221 setMountPath(PackageHelper.getSdDir(cid)); 15222 } 15223 15224 void createCopyFile() { 15225 cid = mInstallerService.allocateExternalStageCidLegacy(); 15226 } 15227 15228 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 15229 if (origin.staged && origin.cid != null) { 15230 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 15231 cid = origin.cid; 15232 setMountPath(PackageHelper.getSdDir(cid)); 15233 return PackageManager.INSTALL_SUCCEEDED; 15234 } 15235 15236 if (temp) { 15237 createCopyFile(); 15238 } else { 15239 /* 15240 * Pre-emptively destroy the container since it's destroyed if 15241 * copying fails due to it existing anyway. 15242 */ 15243 PackageHelper.destroySdDir(cid); 15244 } 15245 15246 final String newMountPath = imcs.copyPackageToContainer( 15247 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 15248 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 15249 15250 if (newMountPath != null) { 15251 setMountPath(newMountPath); 15252 return PackageManager.INSTALL_SUCCEEDED; 15253 } else { 15254 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15255 } 15256 } 15257 15258 @Override 15259 String getCodePath() { 15260 return packagePath; 15261 } 15262 15263 @Override 15264 String getResourcePath() { 15265 return resourcePath; 15266 } 15267 15268 int doPreInstall(int status) { 15269 if (status != PackageManager.INSTALL_SUCCEEDED) { 15270 // Destroy container 15271 PackageHelper.destroySdDir(cid); 15272 } else { 15273 boolean mounted = PackageHelper.isContainerMounted(cid); 15274 if (!mounted) { 15275 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 15276 Process.SYSTEM_UID); 15277 if (newMountPath != null) { 15278 setMountPath(newMountPath); 15279 } else { 15280 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15281 } 15282 } 15283 } 15284 return status; 15285 } 15286 15287 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15288 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 15289 String newMountPath = null; 15290 if (PackageHelper.isContainerMounted(cid)) { 15291 // Unmount the container 15292 if (!PackageHelper.unMountSdDir(cid)) { 15293 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 15294 return false; 15295 } 15296 } 15297 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 15298 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 15299 " which might be stale. Will try to clean up."); 15300 // Clean up the stale container and proceed to recreate. 15301 if (!PackageHelper.destroySdDir(newCacheId)) { 15302 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 15303 return false; 15304 } 15305 // Successfully cleaned up stale container. Try to rename again. 15306 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 15307 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 15308 + " inspite of cleaning it up."); 15309 return false; 15310 } 15311 } 15312 if (!PackageHelper.isContainerMounted(newCacheId)) { 15313 Slog.w(TAG, "Mounting container " + newCacheId); 15314 newMountPath = PackageHelper.mountSdDir(newCacheId, 15315 getEncryptKey(), Process.SYSTEM_UID); 15316 } else { 15317 newMountPath = PackageHelper.getSdDir(newCacheId); 15318 } 15319 if (newMountPath == null) { 15320 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 15321 return false; 15322 } 15323 Log.i(TAG, "Succesfully renamed " + cid + 15324 " to " + newCacheId + 15325 " at new path: " + newMountPath); 15326 cid = newCacheId; 15327 15328 final File beforeCodeFile = new File(packagePath); 15329 setMountPath(newMountPath); 15330 final File afterCodeFile = new File(packagePath); 15331 15332 // Reflect the rename in scanned details 15333 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 15334 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 15335 afterCodeFile, pkg.baseCodePath)); 15336 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 15337 afterCodeFile, pkg.splitCodePaths)); 15338 15339 // Reflect the rename in app info 15340 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15341 pkg.setApplicationInfoCodePath(pkg.codePath); 15342 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15343 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15344 pkg.setApplicationInfoResourcePath(pkg.codePath); 15345 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15346 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15347 15348 return true; 15349 } 15350 15351 private void setMountPath(String mountPath) { 15352 final File mountFile = new File(mountPath); 15353 15354 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 15355 if (monolithicFile.exists()) { 15356 packagePath = monolithicFile.getAbsolutePath(); 15357 if (isFwdLocked()) { 15358 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 15359 } else { 15360 resourcePath = packagePath; 15361 } 15362 } else { 15363 packagePath = mountFile.getAbsolutePath(); 15364 resourcePath = packagePath; 15365 } 15366 } 15367 15368 int doPostInstall(int status, int uid) { 15369 if (status != PackageManager.INSTALL_SUCCEEDED) { 15370 cleanUp(); 15371 } else { 15372 final int groupOwner; 15373 final String protectedFile; 15374 if (isFwdLocked()) { 15375 groupOwner = UserHandle.getSharedAppGid(uid); 15376 protectedFile = RES_FILE_NAME; 15377 } else { 15378 groupOwner = -1; 15379 protectedFile = null; 15380 } 15381 15382 if (uid < Process.FIRST_APPLICATION_UID 15383 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 15384 Slog.e(TAG, "Failed to finalize " + cid); 15385 PackageHelper.destroySdDir(cid); 15386 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15387 } 15388 15389 boolean mounted = PackageHelper.isContainerMounted(cid); 15390 if (!mounted) { 15391 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 15392 } 15393 } 15394 return status; 15395 } 15396 15397 private void cleanUp() { 15398 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 15399 15400 // Destroy secure container 15401 PackageHelper.destroySdDir(cid); 15402 } 15403 15404 private List<String> getAllCodePaths() { 15405 final File codeFile = new File(getCodePath()); 15406 if (codeFile != null && codeFile.exists()) { 15407 try { 15408 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 15409 return pkg.getAllCodePaths(); 15410 } catch (PackageParserException e) { 15411 // Ignored; we tried our best 15412 } 15413 } 15414 return Collections.EMPTY_LIST; 15415 } 15416 15417 void cleanUpResourcesLI() { 15418 // Enumerate all code paths before deleting 15419 cleanUpResourcesLI(getAllCodePaths()); 15420 } 15421 15422 private void cleanUpResourcesLI(List<String> allCodePaths) { 15423 cleanUp(); 15424 removeDexFiles(allCodePaths, instructionSets); 15425 } 15426 15427 String getPackageName() { 15428 return getAsecPackageName(cid); 15429 } 15430 15431 boolean doPostDeleteLI(boolean delete) { 15432 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 15433 final List<String> allCodePaths = getAllCodePaths(); 15434 boolean mounted = PackageHelper.isContainerMounted(cid); 15435 if (mounted) { 15436 // Unmount first 15437 if (PackageHelper.unMountSdDir(cid)) { 15438 mounted = false; 15439 } 15440 } 15441 if (!mounted && delete) { 15442 cleanUpResourcesLI(allCodePaths); 15443 } 15444 return !mounted; 15445 } 15446 15447 @Override 15448 int doPreCopy() { 15449 if (isFwdLocked()) { 15450 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 15451 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 15452 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15453 } 15454 } 15455 15456 return PackageManager.INSTALL_SUCCEEDED; 15457 } 15458 15459 @Override 15460 int doPostCopy(int uid) { 15461 if (isFwdLocked()) { 15462 if (uid < Process.FIRST_APPLICATION_UID 15463 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 15464 RES_FILE_NAME)) { 15465 Slog.e(TAG, "Failed to finalize " + cid); 15466 PackageHelper.destroySdDir(cid); 15467 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15468 } 15469 } 15470 15471 return PackageManager.INSTALL_SUCCEEDED; 15472 } 15473 } 15474 15475 /** 15476 * Logic to handle movement of existing installed applications. 15477 */ 15478 class MoveInstallArgs extends InstallArgs { 15479 private File codeFile; 15480 private File resourceFile; 15481 15482 /** New install */ 15483 MoveInstallArgs(InstallParams params) { 15484 super(params.origin, params.move, params.observer, params.installFlags, 15485 params.installerPackageName, params.volumeUuid, 15486 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 15487 params.grantedRuntimePermissions, 15488 params.traceMethod, params.traceCookie, params.certificates, 15489 params.installReason); 15490 } 15491 15492 int copyApk(IMediaContainerService imcs, boolean temp) { 15493 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 15494 + move.fromUuid + " to " + move.toUuid); 15495 synchronized (mInstaller) { 15496 try { 15497 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 15498 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 15499 } catch (InstallerException e) { 15500 Slog.w(TAG, "Failed to move app", e); 15501 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15502 } 15503 } 15504 15505 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 15506 resourceFile = codeFile; 15507 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 15508 15509 return PackageManager.INSTALL_SUCCEEDED; 15510 } 15511 15512 int doPreInstall(int status) { 15513 if (status != PackageManager.INSTALL_SUCCEEDED) { 15514 cleanUp(move.toUuid); 15515 } 15516 return status; 15517 } 15518 15519 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15520 if (status != PackageManager.INSTALL_SUCCEEDED) { 15521 cleanUp(move.toUuid); 15522 return false; 15523 } 15524 15525 // Reflect the move in app info 15526 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15527 pkg.setApplicationInfoCodePath(pkg.codePath); 15528 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15529 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15530 pkg.setApplicationInfoResourcePath(pkg.codePath); 15531 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15532 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15533 15534 return true; 15535 } 15536 15537 int doPostInstall(int status, int uid) { 15538 if (status == PackageManager.INSTALL_SUCCEEDED) { 15539 cleanUp(move.fromUuid); 15540 } else { 15541 cleanUp(move.toUuid); 15542 } 15543 return status; 15544 } 15545 15546 @Override 15547 String getCodePath() { 15548 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 15549 } 15550 15551 @Override 15552 String getResourcePath() { 15553 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 15554 } 15555 15556 private boolean cleanUp(String volumeUuid) { 15557 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 15558 move.dataAppName); 15559 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 15560 final int[] userIds = sUserManager.getUserIds(); 15561 synchronized (mInstallLock) { 15562 // Clean up both app data and code 15563 // All package moves are frozen until finished 15564 for (int userId : userIds) { 15565 try { 15566 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 15567 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 15568 } catch (InstallerException e) { 15569 Slog.w(TAG, String.valueOf(e)); 15570 } 15571 } 15572 removeCodePathLI(codeFile); 15573 } 15574 return true; 15575 } 15576 15577 void cleanUpResourcesLI() { 15578 throw new UnsupportedOperationException(); 15579 } 15580 15581 boolean doPostDeleteLI(boolean delete) { 15582 throw new UnsupportedOperationException(); 15583 } 15584 } 15585 15586 static String getAsecPackageName(String packageCid) { 15587 int idx = packageCid.lastIndexOf("-"); 15588 if (idx == -1) { 15589 return packageCid; 15590 } 15591 return packageCid.substring(0, idx); 15592 } 15593 15594 // Utility method used to create code paths based on package name and available index. 15595 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 15596 String idxStr = ""; 15597 int idx = 1; 15598 // Fall back to default value of idx=1 if prefix is not 15599 // part of oldCodePath 15600 if (oldCodePath != null) { 15601 String subStr = oldCodePath; 15602 // Drop the suffix right away 15603 if (suffix != null && subStr.endsWith(suffix)) { 15604 subStr = subStr.substring(0, subStr.length() - suffix.length()); 15605 } 15606 // If oldCodePath already contains prefix find out the 15607 // ending index to either increment or decrement. 15608 int sidx = subStr.lastIndexOf(prefix); 15609 if (sidx != -1) { 15610 subStr = subStr.substring(sidx + prefix.length()); 15611 if (subStr != null) { 15612 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 15613 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 15614 } 15615 try { 15616 idx = Integer.parseInt(subStr); 15617 if (idx <= 1) { 15618 idx++; 15619 } else { 15620 idx--; 15621 } 15622 } catch(NumberFormatException e) { 15623 } 15624 } 15625 } 15626 } 15627 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 15628 return prefix + idxStr; 15629 } 15630 15631 private File getNextCodePath(File targetDir, String packageName) { 15632 File result; 15633 SecureRandom random = new SecureRandom(); 15634 byte[] bytes = new byte[16]; 15635 do { 15636 random.nextBytes(bytes); 15637 String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP); 15638 result = new File(targetDir, packageName + "-" + suffix); 15639 } while (result.exists()); 15640 return result; 15641 } 15642 15643 // Utility method that returns the relative package path with respect 15644 // to the installation directory. Like say for /data/data/com.test-1.apk 15645 // string com.test-1 is returned. 15646 static String deriveCodePathName(String codePath) { 15647 if (codePath == null) { 15648 return null; 15649 } 15650 final File codeFile = new File(codePath); 15651 final String name = codeFile.getName(); 15652 if (codeFile.isDirectory()) { 15653 return name; 15654 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 15655 final int lastDot = name.lastIndexOf('.'); 15656 return name.substring(0, lastDot); 15657 } else { 15658 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 15659 return null; 15660 } 15661 } 15662 15663 static class PackageInstalledInfo { 15664 String name; 15665 int uid; 15666 // The set of users that originally had this package installed. 15667 int[] origUsers; 15668 // The set of users that now have this package installed. 15669 int[] newUsers; 15670 PackageParser.Package pkg; 15671 int returnCode; 15672 String returnMsg; 15673 PackageRemovedInfo removedInfo; 15674 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 15675 15676 public void setError(int code, String msg) { 15677 setReturnCode(code); 15678 setReturnMessage(msg); 15679 Slog.w(TAG, msg); 15680 } 15681 15682 public void setError(String msg, PackageParserException e) { 15683 setReturnCode(e.error); 15684 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 15685 Slog.w(TAG, msg, e); 15686 } 15687 15688 public void setError(String msg, PackageManagerException e) { 15689 returnCode = e.error; 15690 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 15691 Slog.w(TAG, msg, e); 15692 } 15693 15694 public void setReturnCode(int returnCode) { 15695 this.returnCode = returnCode; 15696 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15697 for (int i = 0; i < childCount; i++) { 15698 addedChildPackages.valueAt(i).returnCode = returnCode; 15699 } 15700 } 15701 15702 private void setReturnMessage(String returnMsg) { 15703 this.returnMsg = returnMsg; 15704 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15705 for (int i = 0; i < childCount; i++) { 15706 addedChildPackages.valueAt(i).returnMsg = returnMsg; 15707 } 15708 } 15709 15710 // In some error cases we want to convey more info back to the observer 15711 String origPackage; 15712 String origPermission; 15713 } 15714 15715 /* 15716 * Install a non-existing package. 15717 */ 15718 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 15719 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 15720 PackageInstalledInfo res, int installReason) { 15721 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 15722 15723 // Remember this for later, in case we need to rollback this install 15724 String pkgName = pkg.packageName; 15725 15726 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 15727 15728 synchronized(mPackages) { 15729 final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName); 15730 if (renamedPackage != null) { 15731 // A package with the same name is already installed, though 15732 // it has been renamed to an older name. The package we 15733 // are trying to install should be installed as an update to 15734 // the existing one, but that has not been requested, so bail. 15735 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 15736 + " without first uninstalling package running as " 15737 + renamedPackage); 15738 return; 15739 } 15740 if (mPackages.containsKey(pkgName)) { 15741 // Don't allow installation over an existing package with the same name. 15742 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 15743 + " without first uninstalling."); 15744 return; 15745 } 15746 } 15747 15748 try { 15749 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 15750 System.currentTimeMillis(), user); 15751 15752 updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason); 15753 15754 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 15755 prepareAppDataAfterInstallLIF(newPackage); 15756 15757 } else { 15758 // Remove package from internal structures, but keep around any 15759 // data that might have already existed 15760 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 15761 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 15762 } 15763 } catch (PackageManagerException e) { 15764 res.setError("Package couldn't be installed in " + pkg.codePath, e); 15765 } 15766 15767 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15768 } 15769 15770 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 15771 // Can't rotate keys during boot or if sharedUser. 15772 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 15773 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 15774 return false; 15775 } 15776 // app is using upgradeKeySets; make sure all are valid 15777 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15778 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 15779 for (int i = 0; i < upgradeKeySets.length; i++) { 15780 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 15781 Slog.wtf(TAG, "Package " 15782 + (oldPs.name != null ? oldPs.name : "<null>") 15783 + " contains upgrade-key-set reference to unknown key-set: " 15784 + upgradeKeySets[i] 15785 + " reverting to signatures check."); 15786 return false; 15787 } 15788 } 15789 return true; 15790 } 15791 15792 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 15793 // Upgrade keysets are being used. Determine if new package has a superset of the 15794 // required keys. 15795 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 15796 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15797 for (int i = 0; i < upgradeKeySets.length; i++) { 15798 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 15799 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 15800 return true; 15801 } 15802 } 15803 return false; 15804 } 15805 15806 private static void updateDigest(MessageDigest digest, File file) throws IOException { 15807 try (DigestInputStream digestStream = 15808 new DigestInputStream(new FileInputStream(file), digest)) { 15809 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 15810 } 15811 } 15812 15813 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 15814 UserHandle user, String installerPackageName, PackageInstalledInfo res, 15815 int installReason) { 15816 final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 15817 15818 final PackageParser.Package oldPackage; 15819 final String pkgName = pkg.packageName; 15820 final int[] allUsers; 15821 final int[] installedUsers; 15822 15823 synchronized(mPackages) { 15824 oldPackage = mPackages.get(pkgName); 15825 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 15826 15827 // don't allow upgrade to target a release SDK from a pre-release SDK 15828 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 15829 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 15830 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 15831 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 15832 if (oldTargetsPreRelease 15833 && !newTargetsPreRelease 15834 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 15835 Slog.w(TAG, "Can't install package targeting released sdk"); 15836 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 15837 return; 15838 } 15839 15840 // don't allow an upgrade from full to ephemeral 15841 final boolean oldIsEphemeral = oldPackage.applicationInfo.isInstantApp(); 15842 if (isEphemeral && !oldIsEphemeral) { 15843 // can't downgrade from full to ephemeral 15844 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 15845 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 15846 return; 15847 } 15848 15849 // verify signatures are valid 15850 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15851 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 15852 if (!checkUpgradeKeySetLP(ps, pkg)) { 15853 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 15854 "New package not signed by keys specified by upgrade-keysets: " 15855 + pkgName); 15856 return; 15857 } 15858 } else { 15859 // default to original signature matching 15860 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 15861 != PackageManager.SIGNATURE_MATCH) { 15862 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 15863 "New package has a different signature: " + pkgName); 15864 return; 15865 } 15866 } 15867 15868 // don't allow a system upgrade unless the upgrade hash matches 15869 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 15870 byte[] digestBytes = null; 15871 try { 15872 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 15873 updateDigest(digest, new File(pkg.baseCodePath)); 15874 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 15875 for (String path : pkg.splitCodePaths) { 15876 updateDigest(digest, new File(path)); 15877 } 15878 } 15879 digestBytes = digest.digest(); 15880 } catch (NoSuchAlgorithmException | IOException e) { 15881 res.setError(INSTALL_FAILED_INVALID_APK, 15882 "Could not compute hash: " + pkgName); 15883 return; 15884 } 15885 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 15886 res.setError(INSTALL_FAILED_INVALID_APK, 15887 "New package fails restrict-update check: " + pkgName); 15888 return; 15889 } 15890 // retain upgrade restriction 15891 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 15892 } 15893 15894 // Check for shared user id changes 15895 String invalidPackageName = 15896 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 15897 if (invalidPackageName != null) { 15898 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 15899 "Package " + invalidPackageName + " tried to change user " 15900 + oldPackage.mSharedUserId); 15901 return; 15902 } 15903 15904 // In case of rollback, remember per-user/profile install state 15905 allUsers = sUserManager.getUserIds(); 15906 installedUsers = ps.queryInstalledUsers(allUsers, true); 15907 } 15908 15909 // Update what is removed 15910 res.removedInfo = new PackageRemovedInfo(); 15911 res.removedInfo.uid = oldPackage.applicationInfo.uid; 15912 res.removedInfo.removedPackage = oldPackage.packageName; 15913 res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null; 15914 res.removedInfo.isUpdate = true; 15915 res.removedInfo.origUsers = installedUsers; 15916 final PackageSetting ps = mSettings.getPackageLPr(pkgName); 15917 res.removedInfo.installReasons = new SparseArray<>(installedUsers.length); 15918 for (int i = 0; i < installedUsers.length; i++) { 15919 final int userId = installedUsers[i]; 15920 res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId)); 15921 } 15922 15923 final int childCount = (oldPackage.childPackages != null) 15924 ? oldPackage.childPackages.size() : 0; 15925 for (int i = 0; i < childCount; i++) { 15926 boolean childPackageUpdated = false; 15927 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 15928 final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 15929 if (res.addedChildPackages != null) { 15930 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 15931 if (childRes != null) { 15932 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 15933 childRes.removedInfo.removedPackage = childPkg.packageName; 15934 childRes.removedInfo.isUpdate = true; 15935 childRes.removedInfo.installReasons = res.removedInfo.installReasons; 15936 childPackageUpdated = true; 15937 } 15938 } 15939 if (!childPackageUpdated) { 15940 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 15941 childRemovedRes.removedPackage = childPkg.packageName; 15942 childRemovedRes.isUpdate = false; 15943 childRemovedRes.dataRemoved = true; 15944 synchronized (mPackages) { 15945 if (childPs != null) { 15946 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 15947 } 15948 } 15949 if (res.removedInfo.removedChildPackages == null) { 15950 res.removedInfo.removedChildPackages = new ArrayMap<>(); 15951 } 15952 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 15953 } 15954 } 15955 15956 boolean sysPkg = (isSystemApp(oldPackage)); 15957 if (sysPkg) { 15958 // Set the system/privileged flags as needed 15959 final boolean privileged = 15960 (oldPackage.applicationInfo.privateFlags 15961 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 15962 final int systemPolicyFlags = policyFlags 15963 | PackageParser.PARSE_IS_SYSTEM 15964 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 15965 15966 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 15967 user, allUsers, installerPackageName, res, installReason); 15968 } else { 15969 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 15970 user, allUsers, installerPackageName, res, installReason); 15971 } 15972 } 15973 15974 public List<String> getPreviousCodePaths(String packageName) { 15975 final PackageSetting ps = mSettings.mPackages.get(packageName); 15976 final List<String> result = new ArrayList<String>(); 15977 if (ps != null && ps.oldCodePaths != null) { 15978 result.addAll(ps.oldCodePaths); 15979 } 15980 return result; 15981 } 15982 15983 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 15984 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 15985 int[] allUsers, String installerPackageName, PackageInstalledInfo res, 15986 int installReason) { 15987 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 15988 + deletedPackage); 15989 15990 String pkgName = deletedPackage.packageName; 15991 boolean deletedPkg = true; 15992 boolean addedPkg = false; 15993 boolean updatedSettings = false; 15994 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 15995 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 15996 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 15997 15998 final long origUpdateTime = (pkg.mExtras != null) 15999 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 16000 16001 // First delete the existing package while retaining the data directory 16002 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 16003 res.removedInfo, true, pkg)) { 16004 // If the existing package wasn't successfully deleted 16005 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 16006 deletedPkg = false; 16007 } else { 16008 // Successfully deleted the old package; proceed with replace. 16009 16010 // If deleted package lived in a container, give users a chance to 16011 // relinquish resources before killing. 16012 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 16013 if (DEBUG_INSTALL) { 16014 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 16015 } 16016 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 16017 final ArrayList<String> pkgList = new ArrayList<String>(1); 16018 pkgList.add(deletedPackage.applicationInfo.packageName); 16019 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 16020 } 16021 16022 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 16023 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16024 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 16025 16026 try { 16027 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 16028 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 16029 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 16030 installReason); 16031 16032 // Update the in-memory copy of the previous code paths. 16033 PackageSetting ps = mSettings.mPackages.get(pkgName); 16034 if (!killApp) { 16035 if (ps.oldCodePaths == null) { 16036 ps.oldCodePaths = new ArraySet<>(); 16037 } 16038 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 16039 if (deletedPackage.splitCodePaths != null) { 16040 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 16041 } 16042 } else { 16043 ps.oldCodePaths = null; 16044 } 16045 if (ps.childPackageNames != null) { 16046 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 16047 final String childPkgName = ps.childPackageNames.get(i); 16048 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 16049 childPs.oldCodePaths = ps.oldCodePaths; 16050 } 16051 } 16052 prepareAppDataAfterInstallLIF(newPackage); 16053 addedPkg = true; 16054 } catch (PackageManagerException e) { 16055 res.setError("Package couldn't be installed in " + pkg.codePath, e); 16056 } 16057 } 16058 16059 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 16060 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 16061 16062 // Revert all internal state mutations and added folders for the failed install 16063 if (addedPkg) { 16064 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 16065 res.removedInfo, true, null); 16066 } 16067 16068 // Restore the old package 16069 if (deletedPkg) { 16070 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 16071 File restoreFile = new File(deletedPackage.codePath); 16072 // Parse old package 16073 boolean oldExternal = isExternal(deletedPackage); 16074 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 16075 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 16076 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 16077 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 16078 try { 16079 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 16080 null); 16081 } catch (PackageManagerException e) { 16082 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 16083 + e.getMessage()); 16084 return; 16085 } 16086 16087 synchronized (mPackages) { 16088 // Ensure the installer package name up to date 16089 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 16090 16091 // Update permissions for restored package 16092 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 16093 16094 mSettings.writeLPr(); 16095 } 16096 16097 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 16098 } 16099 } else { 16100 synchronized (mPackages) { 16101 PackageSetting ps = mSettings.getPackageLPr(pkg.packageName); 16102 if (ps != null) { 16103 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 16104 if (res.removedInfo.removedChildPackages != null) { 16105 final int childCount = res.removedInfo.removedChildPackages.size(); 16106 // Iterate in reverse as we may modify the collection 16107 for (int i = childCount - 1; i >= 0; i--) { 16108 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 16109 if (res.addedChildPackages.containsKey(childPackageName)) { 16110 res.removedInfo.removedChildPackages.removeAt(i); 16111 } else { 16112 PackageRemovedInfo childInfo = res.removedInfo 16113 .removedChildPackages.valueAt(i); 16114 childInfo.removedForAllUsers = mPackages.get( 16115 childInfo.removedPackage) == null; 16116 } 16117 } 16118 } 16119 } 16120 } 16121 } 16122 } 16123 16124 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 16125 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 16126 int[] allUsers, String installerPackageName, PackageInstalledInfo res, 16127 int installReason) { 16128 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 16129 + ", old=" + deletedPackage); 16130 16131 final boolean disabledSystem; 16132 16133 // Remove existing system package 16134 removePackageLI(deletedPackage, true); 16135 16136 synchronized (mPackages) { 16137 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 16138 } 16139 if (!disabledSystem) { 16140 // We didn't need to disable the .apk as a current system package, 16141 // which means we are replacing another update that is already 16142 // installed. We need to make sure to delete the older one's .apk. 16143 res.removedInfo.args = createInstallArgsForExisting(0, 16144 deletedPackage.applicationInfo.getCodePath(), 16145 deletedPackage.applicationInfo.getResourcePath(), 16146 getAppDexInstructionSets(deletedPackage.applicationInfo)); 16147 } else { 16148 res.removedInfo.args = null; 16149 } 16150 16151 // Successfully disabled the old package. Now proceed with re-installation 16152 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 16153 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16154 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 16155 16156 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16157 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 16158 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 16159 16160 PackageParser.Package newPackage = null; 16161 try { 16162 // Add the package to the internal data structures 16163 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 16164 16165 // Set the update and install times 16166 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 16167 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 16168 System.currentTimeMillis()); 16169 16170 // Update the package dynamic state if succeeded 16171 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 16172 // Now that the install succeeded make sure we remove data 16173 // directories for any child package the update removed. 16174 final int deletedChildCount = (deletedPackage.childPackages != null) 16175 ? deletedPackage.childPackages.size() : 0; 16176 final int newChildCount = (newPackage.childPackages != null) 16177 ? newPackage.childPackages.size() : 0; 16178 for (int i = 0; i < deletedChildCount; i++) { 16179 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 16180 boolean childPackageDeleted = true; 16181 for (int j = 0; j < newChildCount; j++) { 16182 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 16183 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 16184 childPackageDeleted = false; 16185 break; 16186 } 16187 } 16188 if (childPackageDeleted) { 16189 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 16190 deletedChildPkg.packageName); 16191 if (ps != null && res.removedInfo.removedChildPackages != null) { 16192 PackageRemovedInfo removedChildRes = res.removedInfo 16193 .removedChildPackages.get(deletedChildPkg.packageName); 16194 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 16195 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 16196 } 16197 } 16198 } 16199 16200 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 16201 installReason); 16202 prepareAppDataAfterInstallLIF(newPackage); 16203 } 16204 } catch (PackageManagerException e) { 16205 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 16206 res.setError("Package couldn't be installed in " + pkg.codePath, e); 16207 } 16208 16209 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 16210 // Re installation failed. Restore old information 16211 // Remove new pkg information 16212 if (newPackage != null) { 16213 removeInstalledPackageLI(newPackage, true); 16214 } 16215 // Add back the old system package 16216 try { 16217 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 16218 } catch (PackageManagerException e) { 16219 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 16220 } 16221 16222 synchronized (mPackages) { 16223 if (disabledSystem) { 16224 enableSystemPackageLPw(deletedPackage); 16225 } 16226 16227 // Ensure the installer package name up to date 16228 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 16229 16230 // Update permissions for restored package 16231 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 16232 16233 mSettings.writeLPr(); 16234 } 16235 16236 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 16237 + " after failed upgrade"); 16238 } 16239 } 16240 16241 /** 16242 * Checks whether the parent or any of the child packages have a change shared 16243 * user. For a package to be a valid update the shred users of the parent and 16244 * the children should match. We may later support changing child shared users. 16245 * @param oldPkg The updated package. 16246 * @param newPkg The update package. 16247 * @return The shared user that change between the versions. 16248 */ 16249 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 16250 PackageParser.Package newPkg) { 16251 // Check parent shared user 16252 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 16253 return newPkg.packageName; 16254 } 16255 // Check child shared users 16256 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 16257 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 16258 for (int i = 0; i < newChildCount; i++) { 16259 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 16260 // If this child was present, did it have the same shared user? 16261 for (int j = 0; j < oldChildCount; j++) { 16262 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 16263 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 16264 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 16265 return newChildPkg.packageName; 16266 } 16267 } 16268 } 16269 return null; 16270 } 16271 16272 private void removeNativeBinariesLI(PackageSetting ps) { 16273 // Remove the lib path for the parent package 16274 if (ps != null) { 16275 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 16276 // Remove the lib path for the child packages 16277 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 16278 for (int i = 0; i < childCount; i++) { 16279 PackageSetting childPs = null; 16280 synchronized (mPackages) { 16281 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 16282 } 16283 if (childPs != null) { 16284 NativeLibraryHelper.removeNativeBinariesLI(childPs 16285 .legacyNativeLibraryPathString); 16286 } 16287 } 16288 } 16289 } 16290 16291 private void enableSystemPackageLPw(PackageParser.Package pkg) { 16292 // Enable the parent package 16293 mSettings.enableSystemPackageLPw(pkg.packageName); 16294 // Enable the child packages 16295 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16296 for (int i = 0; i < childCount; i++) { 16297 PackageParser.Package childPkg = pkg.childPackages.get(i); 16298 mSettings.enableSystemPackageLPw(childPkg.packageName); 16299 } 16300 } 16301 16302 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 16303 PackageParser.Package newPkg) { 16304 // Disable the parent package (parent always replaced) 16305 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 16306 // Disable the child packages 16307 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 16308 for (int i = 0; i < childCount; i++) { 16309 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 16310 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 16311 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 16312 } 16313 return disabled; 16314 } 16315 16316 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 16317 String installerPackageName) { 16318 // Enable the parent package 16319 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 16320 // Enable the child packages 16321 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16322 for (int i = 0; i < childCount; i++) { 16323 PackageParser.Package childPkg = pkg.childPackages.get(i); 16324 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 16325 } 16326 } 16327 16328 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 16329 // Collect all used permissions in the UID 16330 ArraySet<String> usedPermissions = new ArraySet<>(); 16331 final int packageCount = su.packages.size(); 16332 for (int i = 0; i < packageCount; i++) { 16333 PackageSetting ps = su.packages.valueAt(i); 16334 if (ps.pkg == null) { 16335 continue; 16336 } 16337 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 16338 for (int j = 0; j < requestedPermCount; j++) { 16339 String permission = ps.pkg.requestedPermissions.get(j); 16340 BasePermission bp = mSettings.mPermissions.get(permission); 16341 if (bp != null) { 16342 usedPermissions.add(permission); 16343 } 16344 } 16345 } 16346 16347 PermissionsState permissionsState = su.getPermissionsState(); 16348 // Prune install permissions 16349 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 16350 final int installPermCount = installPermStates.size(); 16351 for (int i = installPermCount - 1; i >= 0; i--) { 16352 PermissionState permissionState = installPermStates.get(i); 16353 if (!usedPermissions.contains(permissionState.getName())) { 16354 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 16355 if (bp != null) { 16356 permissionsState.revokeInstallPermission(bp); 16357 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 16358 PackageManager.MASK_PERMISSION_FLAGS, 0); 16359 } 16360 } 16361 } 16362 16363 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 16364 16365 // Prune runtime permissions 16366 for (int userId : allUserIds) { 16367 List<PermissionState> runtimePermStates = permissionsState 16368 .getRuntimePermissionStates(userId); 16369 final int runtimePermCount = runtimePermStates.size(); 16370 for (int i = runtimePermCount - 1; i >= 0; i--) { 16371 PermissionState permissionState = runtimePermStates.get(i); 16372 if (!usedPermissions.contains(permissionState.getName())) { 16373 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 16374 if (bp != null) { 16375 permissionsState.revokeRuntimePermission(bp, userId); 16376 permissionsState.updatePermissionFlags(bp, userId, 16377 PackageManager.MASK_PERMISSION_FLAGS, 0); 16378 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 16379 runtimePermissionChangedUserIds, userId); 16380 } 16381 } 16382 } 16383 } 16384 16385 return runtimePermissionChangedUserIds; 16386 } 16387 16388 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 16389 int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) { 16390 // Update the parent package setting 16391 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 16392 res, user, installReason); 16393 // Update the child packages setting 16394 final int childCount = (newPackage.childPackages != null) 16395 ? newPackage.childPackages.size() : 0; 16396 for (int i = 0; i < childCount; i++) { 16397 PackageParser.Package childPackage = newPackage.childPackages.get(i); 16398 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 16399 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 16400 childRes.origUsers, childRes, user, installReason); 16401 } 16402 } 16403 16404 private void updateSettingsInternalLI(PackageParser.Package newPackage, 16405 String installerPackageName, int[] allUsers, int[] installedForUsers, 16406 PackageInstalledInfo res, UserHandle user, int installReason) { 16407 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 16408 16409 String pkgName = newPackage.packageName; 16410 synchronized (mPackages) { 16411 //write settings. the installStatus will be incomplete at this stage. 16412 //note that the new package setting would have already been 16413 //added to mPackages. It hasn't been persisted yet. 16414 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 16415 // TODO: Remove this write? It's also written at the end of this method 16416 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 16417 mSettings.writeLPr(); 16418 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16419 } 16420 16421 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 16422 synchronized (mPackages) { 16423 updatePermissionsLPw(newPackage.packageName, newPackage, 16424 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 16425 ? UPDATE_PERMISSIONS_ALL : 0)); 16426 // For system-bundled packages, we assume that installing an upgraded version 16427 // of the package implies that the user actually wants to run that new code, 16428 // so we enable the package. 16429 PackageSetting ps = mSettings.mPackages.get(pkgName); 16430 final int userId = user.getIdentifier(); 16431 if (ps != null) { 16432 if (isSystemApp(newPackage)) { 16433 if (DEBUG_INSTALL) { 16434 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 16435 } 16436 // Enable system package for requested users 16437 if (res.origUsers != null) { 16438 for (int origUserId : res.origUsers) { 16439 if (userId == UserHandle.USER_ALL || userId == origUserId) { 16440 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 16441 origUserId, installerPackageName); 16442 } 16443 } 16444 } 16445 // Also convey the prior install/uninstall state 16446 if (allUsers != null && installedForUsers != null) { 16447 for (int currentUserId : allUsers) { 16448 final boolean installed = ArrayUtils.contains( 16449 installedForUsers, currentUserId); 16450 if (DEBUG_INSTALL) { 16451 Slog.d(TAG, " user " + currentUserId + " => " + installed); 16452 } 16453 ps.setInstalled(installed, currentUserId); 16454 } 16455 // these install state changes will be persisted in the 16456 // upcoming call to mSettings.writeLPr(). 16457 } 16458 } 16459 // It's implied that when a user requests installation, they want the app to be 16460 // installed and enabled. 16461 if (userId != UserHandle.USER_ALL) { 16462 ps.setInstalled(true, userId); 16463 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 16464 } 16465 16466 // When replacing an existing package, preserve the original install reason for all 16467 // users that had the package installed before. 16468 final Set<Integer> previousUserIds = new ArraySet<>(); 16469 if (res.removedInfo != null && res.removedInfo.installReasons != null) { 16470 final int installReasonCount = res.removedInfo.installReasons.size(); 16471 for (int i = 0; i < installReasonCount; i++) { 16472 final int previousUserId = res.removedInfo.installReasons.keyAt(i); 16473 final int previousInstallReason = res.removedInfo.installReasons.valueAt(i); 16474 ps.setInstallReason(previousInstallReason, previousUserId); 16475 previousUserIds.add(previousUserId); 16476 } 16477 } 16478 16479 // Set install reason for users that are having the package newly installed. 16480 if (userId == UserHandle.USER_ALL) { 16481 for (int currentUserId : sUserManager.getUserIds()) { 16482 if (!previousUserIds.contains(currentUserId)) { 16483 ps.setInstallReason(installReason, currentUserId); 16484 } 16485 } 16486 } else if (!previousUserIds.contains(userId)) { 16487 ps.setInstallReason(installReason, userId); 16488 } 16489 mSettings.writeKernelMappingLPr(ps); 16490 } 16491 res.name = pkgName; 16492 res.uid = newPackage.applicationInfo.uid; 16493 res.pkg = newPackage; 16494 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 16495 mSettings.setInstallerPackageName(pkgName, installerPackageName); 16496 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16497 //to update install status 16498 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 16499 mSettings.writeLPr(); 16500 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16501 } 16502 16503 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16504 } 16505 16506 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 16507 try { 16508 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 16509 installPackageLI(args, res); 16510 } finally { 16511 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16512 } 16513 } 16514 16515 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 16516 final int installFlags = args.installFlags; 16517 final String installerPackageName = args.installerPackageName; 16518 final String volumeUuid = args.volumeUuid; 16519 final File tmpPackageFile = new File(args.getCodePath()); 16520 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 16521 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 16522 || (args.volumeUuid != null)); 16523 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 16524 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 16525 boolean replace = false; 16526 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 16527 if (args.move != null) { 16528 // moving a complete application; perform an initial scan on the new install location 16529 scanFlags |= SCAN_INITIAL; 16530 } 16531 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 16532 scanFlags |= SCAN_DONT_KILL_APP; 16533 } 16534 16535 // Result object to be returned 16536 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16537 16538 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 16539 16540 // Sanity check 16541 if (ephemeral && (forwardLocked || onExternal)) { 16542 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 16543 + " external=" + onExternal); 16544 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 16545 return; 16546 } 16547 16548 // Retrieve PackageSettings and parse package 16549 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 16550 | PackageParser.PARSE_ENFORCE_CODE 16551 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 16552 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 16553 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0) 16554 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 16555 PackageParser pp = new PackageParser(); 16556 pp.setSeparateProcesses(mSeparateProcesses); 16557 pp.setDisplayMetrics(mMetrics); 16558 16559 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 16560 final PackageParser.Package pkg; 16561 try { 16562 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 16563 } catch (PackageParserException e) { 16564 res.setError("Failed parse during installPackageLI", e); 16565 return; 16566 } finally { 16567 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16568 } 16569 16570// // Ephemeral apps must have target SDK >= O. 16571// // TODO: Update conditional and error message when O gets locked down 16572// if (ephemeral && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) { 16573// res.setError(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID, 16574// "Ephemeral apps must have target SDK version of at least O"); 16575// return; 16576// } 16577 16578 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16579 // Static shared libraries have synthetic package names 16580 renameStaticSharedLibraryPackage(pkg); 16581 16582 // No static shared libs on external storage 16583 if (onExternal) { 16584 Slog.i(TAG, "Static shared libs can only be installed on internal storage."); 16585 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 16586 "Packages declaring static-shared libs cannot be updated"); 16587 return; 16588 } 16589 } 16590 16591 // If we are installing a clustered package add results for the children 16592 if (pkg.childPackages != null) { 16593 synchronized (mPackages) { 16594 final int childCount = pkg.childPackages.size(); 16595 for (int i = 0; i < childCount; i++) { 16596 PackageParser.Package childPkg = pkg.childPackages.get(i); 16597 PackageInstalledInfo childRes = new PackageInstalledInfo(); 16598 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16599 childRes.pkg = childPkg; 16600 childRes.name = childPkg.packageName; 16601 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 16602 if (childPs != null) { 16603 childRes.origUsers = childPs.queryInstalledUsers( 16604 sUserManager.getUserIds(), true); 16605 } 16606 if ((mPackages.containsKey(childPkg.packageName))) { 16607 childRes.removedInfo = new PackageRemovedInfo(); 16608 childRes.removedInfo.removedPackage = childPkg.packageName; 16609 } 16610 if (res.addedChildPackages == null) { 16611 res.addedChildPackages = new ArrayMap<>(); 16612 } 16613 res.addedChildPackages.put(childPkg.packageName, childRes); 16614 } 16615 } 16616 } 16617 16618 // If package doesn't declare API override, mark that we have an install 16619 // time CPU ABI override. 16620 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 16621 pkg.cpuAbiOverride = args.abiOverride; 16622 } 16623 16624 String pkgName = res.name = pkg.packageName; 16625 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 16626 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 16627 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 16628 return; 16629 } 16630 } 16631 16632 try { 16633 // either use what we've been given or parse directly from the APK 16634 if (args.certificates != null) { 16635 try { 16636 PackageParser.populateCertificates(pkg, args.certificates); 16637 } catch (PackageParserException e) { 16638 // there was something wrong with the certificates we were given; 16639 // try to pull them from the APK 16640 PackageParser.collectCertificates(pkg, parseFlags); 16641 } 16642 } else { 16643 PackageParser.collectCertificates(pkg, parseFlags); 16644 } 16645 } catch (PackageParserException e) { 16646 res.setError("Failed collect during installPackageLI", e); 16647 return; 16648 } 16649 16650 // Get rid of all references to package scan path via parser. 16651 pp = null; 16652 String oldCodePath = null; 16653 boolean systemApp = false; 16654 synchronized (mPackages) { 16655 // Check if installing already existing package 16656 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 16657 String oldName = mSettings.getRenamedPackageLPr(pkgName); 16658 if (pkg.mOriginalPackages != null 16659 && pkg.mOriginalPackages.contains(oldName) 16660 && mPackages.containsKey(oldName)) { 16661 // This package is derived from an original package, 16662 // and this device has been updating from that original 16663 // name. We must continue using the original name, so 16664 // rename the new package here. 16665 pkg.setPackageName(oldName); 16666 pkgName = pkg.packageName; 16667 replace = true; 16668 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 16669 + oldName + " pkgName=" + pkgName); 16670 } else if (mPackages.containsKey(pkgName)) { 16671 // This package, under its official name, already exists 16672 // on the device; we should replace it. 16673 replace = true; 16674 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 16675 } 16676 16677 // Child packages are installed through the parent package 16678 if (pkg.parentPackage != null) { 16679 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 16680 "Package " + pkg.packageName + " is child of package " 16681 + pkg.parentPackage.parentPackage + ". Child packages " 16682 + "can be updated only through the parent package."); 16683 return; 16684 } 16685 16686 if (replace) { 16687 // Prevent apps opting out from runtime permissions 16688 PackageParser.Package oldPackage = mPackages.get(pkgName); 16689 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 16690 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 16691 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 16692 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 16693 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 16694 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 16695 + " doesn't support runtime permissions but the old" 16696 + " target SDK " + oldTargetSdk + " does."); 16697 return; 16698 } 16699 16700 // Prevent installing of child packages 16701 if (oldPackage.parentPackage != null) { 16702 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 16703 "Package " + pkg.packageName + " is child of package " 16704 + oldPackage.parentPackage + ". Child packages " 16705 + "can be updated only through the parent package."); 16706 return; 16707 } 16708 } 16709 } 16710 16711 PackageSetting ps = mSettings.mPackages.get(pkgName); 16712 if (ps != null) { 16713 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 16714 16715 // Static shared libs have same package with different versions where 16716 // we internally use a synthetic package name to allow multiple versions 16717 // of the same package, therefore we need to compare signatures against 16718 // the package setting for the latest library version. 16719 PackageSetting signatureCheckPs = ps; 16720 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16721 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg); 16722 if (libraryEntry != null) { 16723 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk); 16724 } 16725 } 16726 16727 // Quick sanity check that we're signed correctly if updating; 16728 // we'll check this again later when scanning, but we want to 16729 // bail early here before tripping over redefined permissions. 16730 if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) { 16731 if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) { 16732 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 16733 + pkg.packageName + " upgrade keys do not match the " 16734 + "previously installed version"); 16735 return; 16736 } 16737 } else { 16738 try { 16739 verifySignaturesLP(signatureCheckPs, pkg); 16740 } catch (PackageManagerException e) { 16741 res.setError(e.error, e.getMessage()); 16742 return; 16743 } 16744 } 16745 16746 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 16747 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 16748 systemApp = (ps.pkg.applicationInfo.flags & 16749 ApplicationInfo.FLAG_SYSTEM) != 0; 16750 } 16751 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 16752 } 16753 16754 // Check whether the newly-scanned package wants to define an already-defined perm 16755 int N = pkg.permissions.size(); 16756 for (int i = N-1; i >= 0; i--) { 16757 PackageParser.Permission perm = pkg.permissions.get(i); 16758 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 16759 if (bp != null) { 16760 // If the defining package is signed with our cert, it's okay. This 16761 // also includes the "updating the same package" case, of course. 16762 // "updating same package" could also involve key-rotation. 16763 final boolean sigsOk; 16764 if (bp.sourcePackage.equals(pkg.packageName) 16765 && (bp.packageSetting instanceof PackageSetting) 16766 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 16767 scanFlags))) { 16768 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 16769 } else { 16770 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 16771 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 16772 } 16773 if (!sigsOk) { 16774 // If the owning package is the system itself, we log but allow 16775 // install to proceed; we fail the install on all other permission 16776 // redefinitions. 16777 if (!bp.sourcePackage.equals("android")) { 16778 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 16779 + pkg.packageName + " attempting to redeclare permission " 16780 + perm.info.name + " already owned by " + bp.sourcePackage); 16781 res.origPermission = perm.info.name; 16782 res.origPackage = bp.sourcePackage; 16783 return; 16784 } else { 16785 Slog.w(TAG, "Package " + pkg.packageName 16786 + " attempting to redeclare system permission " 16787 + perm.info.name + "; ignoring new declaration"); 16788 pkg.permissions.remove(i); 16789 } 16790 } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) { 16791 // Prevent apps to change protection level to dangerous from any other 16792 // type as this would allow a privilege escalation where an app adds a 16793 // normal/signature permission in other app's group and later redefines 16794 // it as dangerous leading to the group auto-grant. 16795 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE) 16796 == PermissionInfo.PROTECTION_DANGEROUS) { 16797 if (bp != null && !bp.isRuntime()) { 16798 Slog.w(TAG, "Package " + pkg.packageName + " trying to change a " 16799 + "non-runtime permission " + perm.info.name 16800 + " to runtime; keeping old protection level"); 16801 perm.info.protectionLevel = bp.protectionLevel; 16802 } 16803 } 16804 } 16805 } 16806 } 16807 } 16808 16809 if (systemApp) { 16810 if (onExternal) { 16811 // Abort update; system app can't be replaced with app on sdcard 16812 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 16813 "Cannot install updates to system apps on sdcard"); 16814 return; 16815 } else if (ephemeral) { 16816 // Abort update; system app can't be replaced with an ephemeral app 16817 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 16818 "Cannot update a system app with an ephemeral app"); 16819 return; 16820 } 16821 } 16822 16823 if (args.move != null) { 16824 // We did an in-place move, so dex is ready to roll 16825 scanFlags |= SCAN_NO_DEX; 16826 scanFlags |= SCAN_MOVE; 16827 16828 synchronized (mPackages) { 16829 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16830 if (ps == null) { 16831 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 16832 "Missing settings for moved package " + pkgName); 16833 } 16834 16835 // We moved the entire application as-is, so bring over the 16836 // previously derived ABI information. 16837 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 16838 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 16839 } 16840 16841 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 16842 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 16843 scanFlags |= SCAN_NO_DEX; 16844 16845 try { 16846 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 16847 args.abiOverride : pkg.cpuAbiOverride); 16848 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 16849 true /*extractLibs*/, mAppLib32InstallDir); 16850 } catch (PackageManagerException pme) { 16851 Slog.e(TAG, "Error deriving application ABI", pme); 16852 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 16853 return; 16854 } 16855 16856 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 16857 // Do not run PackageDexOptimizer through the local performDexOpt 16858 // method because `pkg` may not be in `mPackages` yet. 16859 // 16860 // Also, don't fail application installs if the dexopt step fails. 16861 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 16862 null /* instructionSets */, false /* checkProfiles */, 16863 getCompilerFilterForReason(REASON_INSTALL), 16864 getOrCreateCompilerPackageStats(pkg)); 16865 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16866 16867 // Notify BackgroundDexOptJobService that the package has been changed. 16868 // If this is an update of a package which used to fail to compile, 16869 // BDOS will remove it from its blacklist. 16870 // TODO: Layering violation 16871 BackgroundDexOptJobService.notifyPackageChanged(pkg.packageName); 16872 } 16873 16874 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 16875 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 16876 return; 16877 } 16878 16879 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 16880 16881 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 16882 "installPackageLI")) { 16883 if (replace) { 16884 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16885 // Static libs have a synthetic package name containing the version 16886 // and cannot be updated as an update would get a new package name, 16887 // unless this is the exact same version code which is useful for 16888 // development. 16889 PackageParser.Package existingPkg = mPackages.get(pkg.packageName); 16890 if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) { 16891 res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring " 16892 + "static-shared libs cannot be updated"); 16893 return; 16894 } 16895 } 16896 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 16897 installerPackageName, res, args.installReason); 16898 } else { 16899 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 16900 args.user, installerPackageName, volumeUuid, res, args.installReason); 16901 } 16902 } 16903 synchronized (mPackages) { 16904 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16905 if (ps != null) { 16906 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 16907 } 16908 16909 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16910 for (int i = 0; i < childCount; i++) { 16911 PackageParser.Package childPkg = pkg.childPackages.get(i); 16912 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 16913 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 16914 if (childPs != null) { 16915 childRes.newUsers = childPs.queryInstalledUsers( 16916 sUserManager.getUserIds(), true); 16917 } 16918 } 16919 16920 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 16921 updateSequenceNumberLP(pkgName, res.newUsers); 16922 } 16923 } 16924 } 16925 16926 private void startIntentFilterVerifications(int userId, boolean replacing, 16927 PackageParser.Package pkg) { 16928 if (mIntentFilterVerifierComponent == null) { 16929 Slog.w(TAG, "No IntentFilter verification will not be done as " 16930 + "there is no IntentFilterVerifier available!"); 16931 return; 16932 } 16933 16934 final int verifierUid = getPackageUid( 16935 mIntentFilterVerifierComponent.getPackageName(), 16936 MATCH_DEBUG_TRIAGED_MISSING, 16937 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 16938 16939 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 16940 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 16941 mHandler.sendMessage(msg); 16942 16943 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16944 for (int i = 0; i < childCount; i++) { 16945 PackageParser.Package childPkg = pkg.childPackages.get(i); 16946 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 16947 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 16948 mHandler.sendMessage(msg); 16949 } 16950 } 16951 16952 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 16953 PackageParser.Package pkg) { 16954 int size = pkg.activities.size(); 16955 if (size == 0) { 16956 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 16957 "No activity, so no need to verify any IntentFilter!"); 16958 return; 16959 } 16960 16961 final boolean hasDomainURLs = hasDomainURLs(pkg); 16962 if (!hasDomainURLs) { 16963 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 16964 "No domain URLs, so no need to verify any IntentFilter!"); 16965 return; 16966 } 16967 16968 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 16969 + " if any IntentFilter from the " + size 16970 + " Activities needs verification ..."); 16971 16972 int count = 0; 16973 final String packageName = pkg.packageName; 16974 16975 synchronized (mPackages) { 16976 // If this is a new install and we see that we've already run verification for this 16977 // package, we have nothing to do: it means the state was restored from backup. 16978 if (!replacing) { 16979 IntentFilterVerificationInfo ivi = 16980 mSettings.getIntentFilterVerificationLPr(packageName); 16981 if (ivi != null) { 16982 if (DEBUG_DOMAIN_VERIFICATION) { 16983 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 16984 + ivi.getStatusString()); 16985 } 16986 return; 16987 } 16988 } 16989 16990 // If any filters need to be verified, then all need to be. 16991 boolean needToVerify = false; 16992 for (PackageParser.Activity a : pkg.activities) { 16993 for (ActivityIntentInfo filter : a.intents) { 16994 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 16995 if (DEBUG_DOMAIN_VERIFICATION) { 16996 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 16997 } 16998 needToVerify = true; 16999 break; 17000 } 17001 } 17002 } 17003 17004 if (needToVerify) { 17005 final int verificationId = mIntentFilterVerificationToken++; 17006 for (PackageParser.Activity a : pkg.activities) { 17007 for (ActivityIntentInfo filter : a.intents) { 17008 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 17009 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17010 "Verification needed for IntentFilter:" + filter.toString()); 17011 mIntentFilterVerifier.addOneIntentFilterVerification( 17012 verifierUid, userId, verificationId, filter, packageName); 17013 count++; 17014 } 17015 } 17016 } 17017 } 17018 } 17019 17020 if (count > 0) { 17021 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 17022 + " IntentFilter verification" + (count > 1 ? "s" : "") 17023 + " for userId:" + userId); 17024 mIntentFilterVerifier.startVerifications(userId); 17025 } else { 17026 if (DEBUG_DOMAIN_VERIFICATION) { 17027 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 17028 } 17029 } 17030 } 17031 17032 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 17033 final ComponentName cn = filter.activity.getComponentName(); 17034 final String packageName = cn.getPackageName(); 17035 17036 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 17037 packageName); 17038 if (ivi == null) { 17039 return true; 17040 } 17041 int status = ivi.getStatus(); 17042 switch (status) { 17043 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 17044 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 17045 return true; 17046 17047 default: 17048 // Nothing to do 17049 return false; 17050 } 17051 } 17052 17053 private static boolean isMultiArch(ApplicationInfo info) { 17054 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 17055 } 17056 17057 private static boolean isExternal(PackageParser.Package pkg) { 17058 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 17059 } 17060 17061 private static boolean isExternal(PackageSetting ps) { 17062 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 17063 } 17064 17065 private static boolean isEphemeral(PackageParser.Package pkg) { 17066 return pkg.applicationInfo.isInstantApp(); 17067 } 17068 17069 private static boolean isEphemeral(PackageSetting ps) { 17070 return ps.pkg != null && isEphemeral(ps.pkg); 17071 } 17072 17073 private static boolean isSystemApp(PackageParser.Package pkg) { 17074 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 17075 } 17076 17077 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 17078 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 17079 } 17080 17081 private static boolean hasDomainURLs(PackageParser.Package pkg) { 17082 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 17083 } 17084 17085 private static boolean isSystemApp(PackageSetting ps) { 17086 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 17087 } 17088 17089 private static boolean isUpdatedSystemApp(PackageSetting ps) { 17090 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 17091 } 17092 17093 private int packageFlagsToInstallFlags(PackageSetting ps) { 17094 int installFlags = 0; 17095 if (isEphemeral(ps)) { 17096 installFlags |= PackageManager.INSTALL_EPHEMERAL; 17097 } 17098 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 17099 // This existing package was an external ASEC install when we have 17100 // the external flag without a UUID 17101 installFlags |= PackageManager.INSTALL_EXTERNAL; 17102 } 17103 if (ps.isForwardLocked()) { 17104 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 17105 } 17106 return installFlags; 17107 } 17108 17109 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 17110 if (isExternal(pkg)) { 17111 if (TextUtils.isEmpty(pkg.volumeUuid)) { 17112 return StorageManager.UUID_PRIMARY_PHYSICAL; 17113 } else { 17114 return pkg.volumeUuid; 17115 } 17116 } else { 17117 return StorageManager.UUID_PRIVATE_INTERNAL; 17118 } 17119 } 17120 17121 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 17122 if (isExternal(pkg)) { 17123 if (TextUtils.isEmpty(pkg.volumeUuid)) { 17124 return mSettings.getExternalVersion(); 17125 } else { 17126 return mSettings.findOrCreateVersion(pkg.volumeUuid); 17127 } 17128 } else { 17129 return mSettings.getInternalVersion(); 17130 } 17131 } 17132 17133 private void deleteTempPackageFiles() { 17134 final FilenameFilter filter = new FilenameFilter() { 17135 public boolean accept(File dir, String name) { 17136 return name.startsWith("vmdl") && name.endsWith(".tmp"); 17137 } 17138 }; 17139 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 17140 file.delete(); 17141 } 17142 } 17143 17144 @Override 17145 public void deletePackageAsUser(String packageName, int versionCode, 17146 IPackageDeleteObserver observer, int userId, int flags) { 17147 deletePackageVersioned(new VersionedPackage(packageName, versionCode), 17148 new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags); 17149 } 17150 17151 @Override 17152 public void deletePackageVersioned(VersionedPackage versionedPackage, 17153 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 17154 mContext.enforceCallingOrSelfPermission( 17155 android.Manifest.permission.DELETE_PACKAGES, null); 17156 Preconditions.checkNotNull(versionedPackage); 17157 Preconditions.checkNotNull(observer); 17158 Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(), 17159 PackageManager.VERSION_CODE_HIGHEST, 17160 Integer.MAX_VALUE, "versionCode must be >= -1"); 17161 17162 final String packageName = versionedPackage.getPackageName(); 17163 // TODO: We will change version code to long, so in the new API it is long 17164 final int versionCode = (int) versionedPackage.getVersionCode(); 17165 final String internalPackageName; 17166 synchronized (mPackages) { 17167 // Normalize package name to handle renamed packages and static libs 17168 internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(), 17169 // TODO: We will change version code to long, so in the new API it is long 17170 (int) versionedPackage.getVersionCode()); 17171 } 17172 17173 final int uid = Binder.getCallingUid(); 17174 if (!isOrphaned(internalPackageName) 17175 && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) { 17176 try { 17177 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 17178 intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null)); 17179 intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder()); 17180 observer.onUserActionRequired(intent); 17181 } catch (RemoteException re) { 17182 } 17183 return; 17184 } 17185 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 17186 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 17187 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 17188 mContext.enforceCallingOrSelfPermission( 17189 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 17190 "deletePackage for user " + userId); 17191 } 17192 17193 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 17194 try { 17195 observer.onPackageDeleted(packageName, 17196 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 17197 } catch (RemoteException re) { 17198 } 17199 return; 17200 } 17201 17202 if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) { 17203 try { 17204 observer.onPackageDeleted(packageName, 17205 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 17206 } catch (RemoteException re) { 17207 } 17208 return; 17209 } 17210 17211 if (DEBUG_REMOVE) { 17212 Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId 17213 + " deleteAllUsers: " + deleteAllUsers + " version=" 17214 + (versionCode == PackageManager.VERSION_CODE_HIGHEST 17215 ? "VERSION_CODE_HIGHEST" : versionCode)); 17216 } 17217 // Queue up an async operation since the package deletion may take a little while. 17218 mHandler.post(new Runnable() { 17219 public void run() { 17220 mHandler.removeCallbacks(this); 17221 int returnCode; 17222 if (!deleteAllUsers) { 17223 returnCode = deletePackageX(internalPackageName, versionCode, 17224 userId, deleteFlags); 17225 } else { 17226 int[] blockUninstallUserIds = getBlockUninstallForUsers( 17227 internalPackageName, users); 17228 // If nobody is blocking uninstall, proceed with delete for all users 17229 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 17230 returnCode = deletePackageX(internalPackageName, versionCode, 17231 userId, deleteFlags); 17232 } else { 17233 // Otherwise uninstall individually for users with blockUninstalls=false 17234 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 17235 for (int userId : users) { 17236 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 17237 returnCode = deletePackageX(internalPackageName, versionCode, 17238 userId, userFlags); 17239 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 17240 Slog.w(TAG, "Package delete failed for user " + userId 17241 + ", returnCode " + returnCode); 17242 } 17243 } 17244 } 17245 // The app has only been marked uninstalled for certain users. 17246 // We still need to report that delete was blocked 17247 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 17248 } 17249 } 17250 try { 17251 observer.onPackageDeleted(packageName, returnCode, null); 17252 } catch (RemoteException e) { 17253 Log.i(TAG, "Observer no longer exists."); 17254 } //end catch 17255 } //end run 17256 }); 17257 } 17258 17259 private String resolveExternalPackageNameLPr(PackageParser.Package pkg) { 17260 if (pkg.staticSharedLibName != null) { 17261 return pkg.manifestPackageName; 17262 } 17263 return pkg.packageName; 17264 } 17265 17266 private String resolveInternalPackageNameLPr(String packageName, int versionCode) { 17267 // Handle renamed packages 17268 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 17269 packageName = normalizedPackageName != null ? normalizedPackageName : packageName; 17270 17271 // Is this a static library? 17272 SparseArray<SharedLibraryEntry> versionedLib = 17273 mStaticLibsByDeclaringPackage.get(packageName); 17274 if (versionedLib == null || versionedLib.size() <= 0) { 17275 return packageName; 17276 } 17277 17278 // Figure out which lib versions the caller can see 17279 SparseIntArray versionsCallerCanSee = null; 17280 final int callingAppId = UserHandle.getAppId(Binder.getCallingUid()); 17281 if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID 17282 && callingAppId != Process.ROOT_UID) { 17283 versionsCallerCanSee = new SparseIntArray(); 17284 String libName = versionedLib.valueAt(0).info.getName(); 17285 String[] uidPackages = getPackagesForUid(Binder.getCallingUid()); 17286 if (uidPackages != null) { 17287 for (String uidPackage : uidPackages) { 17288 PackageSetting ps = mSettings.getPackageLPr(uidPackage); 17289 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 17290 if (libIdx >= 0) { 17291 final int libVersion = ps.usesStaticLibrariesVersions[libIdx]; 17292 versionsCallerCanSee.append(libVersion, libVersion); 17293 } 17294 } 17295 } 17296 } 17297 17298 // Caller can see nothing - done 17299 if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) { 17300 return packageName; 17301 } 17302 17303 // Find the version the caller can see and the app version code 17304 SharedLibraryEntry highestVersion = null; 17305 final int versionCount = versionedLib.size(); 17306 for (int i = 0; i < versionCount; i++) { 17307 SharedLibraryEntry libEntry = versionedLib.valueAt(i); 17308 if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey( 17309 libEntry.info.getVersion()) < 0) { 17310 continue; 17311 } 17312 // TODO: We will change version code to long, so in the new API it is long 17313 final int libVersionCode = (int) libEntry.info.getDeclaringPackage().getVersionCode(); 17314 if (versionCode != PackageManager.VERSION_CODE_HIGHEST) { 17315 if (libVersionCode == versionCode) { 17316 return libEntry.apk; 17317 } 17318 } else if (highestVersion == null) { 17319 highestVersion = libEntry; 17320 } else if (libVersionCode > highestVersion.info 17321 .getDeclaringPackage().getVersionCode()) { 17322 highestVersion = libEntry; 17323 } 17324 } 17325 17326 if (highestVersion != null) { 17327 return highestVersion.apk; 17328 } 17329 17330 return packageName; 17331 } 17332 17333 private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) { 17334 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID 17335 || callingUid == Process.SYSTEM_UID) { 17336 return true; 17337 } 17338 final int callingUserId = UserHandle.getUserId(callingUid); 17339 // If the caller installed the pkgName, then allow it to silently uninstall. 17340 if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) { 17341 return true; 17342 } 17343 17344 // Allow package verifier to silently uninstall. 17345 if (mRequiredVerifierPackage != null && 17346 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) { 17347 return true; 17348 } 17349 17350 // Allow package uninstaller to silently uninstall. 17351 if (mRequiredUninstallerPackage != null && 17352 callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) { 17353 return true; 17354 } 17355 17356 // Allow storage manager to silently uninstall. 17357 if (mStorageManagerPackage != null && 17358 callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) { 17359 return true; 17360 } 17361 return false; 17362 } 17363 17364 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 17365 int[] result = EMPTY_INT_ARRAY; 17366 for (int userId : userIds) { 17367 if (getBlockUninstallForUser(packageName, userId)) { 17368 result = ArrayUtils.appendInt(result, userId); 17369 } 17370 } 17371 return result; 17372 } 17373 17374 @Override 17375 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 17376 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 17377 } 17378 17379 private boolean isPackageDeviceAdmin(String packageName, int userId) { 17380 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 17381 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 17382 try { 17383 if (dpm != null) { 17384 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 17385 /* callingUserOnly =*/ false); 17386 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 17387 : deviceOwnerComponentName.getPackageName(); 17388 // Does the package contains the device owner? 17389 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 17390 // this check is probably not needed, since DO should be registered as a device 17391 // admin on some user too. (Original bug for this: b/17657954) 17392 if (packageName.equals(deviceOwnerPackageName)) { 17393 return true; 17394 } 17395 // Does it contain a device admin for any user? 17396 int[] users; 17397 if (userId == UserHandle.USER_ALL) { 17398 users = sUserManager.getUserIds(); 17399 } else { 17400 users = new int[]{userId}; 17401 } 17402 for (int i = 0; i < users.length; ++i) { 17403 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 17404 return true; 17405 } 17406 } 17407 } 17408 } catch (RemoteException e) { 17409 } 17410 return false; 17411 } 17412 17413 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 17414 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 17415 } 17416 17417 /** 17418 * This method is an internal method that could be get invoked either 17419 * to delete an installed package or to clean up a failed installation. 17420 * After deleting an installed package, a broadcast is sent to notify any 17421 * listeners that the package has been removed. For cleaning up a failed 17422 * installation, the broadcast is not necessary since the package's 17423 * installation wouldn't have sent the initial broadcast either 17424 * The key steps in deleting a package are 17425 * deleting the package information in internal structures like mPackages, 17426 * deleting the packages base directories through installd 17427 * updating mSettings to reflect current status 17428 * persisting settings for later use 17429 * sending a broadcast if necessary 17430 */ 17431 private int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) { 17432 final PackageRemovedInfo info = new PackageRemovedInfo(); 17433 final boolean res; 17434 17435 final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 17436 ? UserHandle.USER_ALL : userId; 17437 17438 if (isPackageDeviceAdmin(packageName, removeUser)) { 17439 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 17440 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 17441 } 17442 17443 PackageSetting uninstalledPs = null; 17444 17445 // for the uninstall-updates case and restricted profiles, remember the per- 17446 // user handle installed state 17447 int[] allUsers; 17448 synchronized (mPackages) { 17449 uninstalledPs = mSettings.mPackages.get(packageName); 17450 if (uninstalledPs == null) { 17451 Slog.w(TAG, "Not removing non-existent package " + packageName); 17452 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17453 } 17454 17455 if (versionCode != PackageManager.VERSION_CODE_HIGHEST 17456 && uninstalledPs.versionCode != versionCode) { 17457 Slog.w(TAG, "Not removing package " + packageName + " with versionCode " 17458 + uninstalledPs.versionCode + " != " + versionCode); 17459 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17460 } 17461 17462 // Static shared libs can be declared by any package, so let us not 17463 // allow removing a package if it provides a lib others depend on. 17464 PackageParser.Package pkg = mPackages.get(packageName); 17465 if (pkg != null && pkg.staticSharedLibName != null) { 17466 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName, 17467 pkg.staticSharedLibVersion); 17468 if (libEntry != null) { 17469 List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr( 17470 libEntry.info, 0, userId); 17471 if (!ArrayUtils.isEmpty(libClientPackages)) { 17472 Slog.w(TAG, "Not removing package " + pkg.manifestPackageName 17473 + " hosting lib " + libEntry.info.getName() + " version " 17474 + libEntry.info.getVersion() + " used by " + libClientPackages); 17475 return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY; 17476 } 17477 } 17478 } 17479 17480 allUsers = sUserManager.getUserIds(); 17481 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 17482 } 17483 17484 final int freezeUser; 17485 if (isUpdatedSystemApp(uninstalledPs) 17486 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) { 17487 // We're downgrading a system app, which will apply to all users, so 17488 // freeze them all during the downgrade 17489 freezeUser = UserHandle.USER_ALL; 17490 } else { 17491 freezeUser = removeUser; 17492 } 17493 17494 synchronized (mInstallLock) { 17495 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 17496 try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser, 17497 deleteFlags, "deletePackageX")) { 17498 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers, 17499 deleteFlags | REMOVE_CHATTY, info, true, null); 17500 } 17501 synchronized (mPackages) { 17502 if (res) { 17503 mInstantAppRegistry.onPackageUninstalledLPw(uninstalledPs.pkg, 17504 info.removedUsers); 17505 updateSequenceNumberLP(packageName, info.removedUsers); 17506 } 17507 } 17508 } 17509 17510 if (res) { 17511 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 17512 info.sendPackageRemovedBroadcasts(killApp); 17513 info.sendSystemPackageUpdatedBroadcasts(); 17514 info.sendSystemPackageAppearedBroadcasts(); 17515 } 17516 // Force a gc here. 17517 Runtime.getRuntime().gc(); 17518 // Delete the resources here after sending the broadcast to let 17519 // other processes clean up before deleting resources. 17520 if (info.args != null) { 17521 synchronized (mInstallLock) { 17522 info.args.doPostDeleteLI(true); 17523 } 17524 } 17525 17526 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17527 } 17528 17529 class PackageRemovedInfo { 17530 String removedPackage; 17531 int uid = -1; 17532 int removedAppId = -1; 17533 int[] origUsers; 17534 int[] removedUsers = null; 17535 SparseArray<Integer> installReasons; 17536 boolean isRemovedPackageSystemUpdate = false; 17537 boolean isUpdate; 17538 boolean dataRemoved; 17539 boolean removedForAllUsers; 17540 boolean isStaticSharedLib; 17541 // Clean up resources deleted packages. 17542 InstallArgs args = null; 17543 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 17544 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 17545 17546 void sendPackageRemovedBroadcasts(boolean killApp) { 17547 sendPackageRemovedBroadcastInternal(killApp); 17548 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 17549 for (int i = 0; i < childCount; i++) { 17550 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 17551 childInfo.sendPackageRemovedBroadcastInternal(killApp); 17552 } 17553 } 17554 17555 void sendSystemPackageUpdatedBroadcasts() { 17556 if (isRemovedPackageSystemUpdate) { 17557 sendSystemPackageUpdatedBroadcastsInternal(); 17558 final int childCount = (removedChildPackages != null) 17559 ? removedChildPackages.size() : 0; 17560 for (int i = 0; i < childCount; i++) { 17561 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 17562 if (childInfo.isRemovedPackageSystemUpdate) { 17563 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 17564 } 17565 } 17566 } 17567 } 17568 17569 void sendSystemPackageAppearedBroadcasts() { 17570 final int packageCount = (appearedChildPackages != null) 17571 ? appearedChildPackages.size() : 0; 17572 for (int i = 0; i < packageCount; i++) { 17573 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 17574 sendPackageAddedForNewUsers(installedInfo.name, true, 17575 UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers); 17576 } 17577 } 17578 17579 private void sendSystemPackageUpdatedBroadcastsInternal() { 17580 Bundle extras = new Bundle(2); 17581 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 17582 extras.putBoolean(Intent.EXTRA_REPLACING, true); 17583 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 17584 extras, 0, null, null, null); 17585 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 17586 extras, 0, null, null, null); 17587 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 17588 null, 0, removedPackage, null, null); 17589 } 17590 17591 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 17592 // Don't send static shared library removal broadcasts as these 17593 // libs are visible only the the apps that depend on them an one 17594 // cannot remove the library if it has a dependency. 17595 if (isStaticSharedLib) { 17596 return; 17597 } 17598 Bundle extras = new Bundle(2); 17599 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 17600 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 17601 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 17602 if (isUpdate || isRemovedPackageSystemUpdate) { 17603 extras.putBoolean(Intent.EXTRA_REPLACING, true); 17604 } 17605 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 17606 if (removedPackage != null) { 17607 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 17608 extras, 0, null, null, removedUsers); 17609 if (dataRemoved && !isRemovedPackageSystemUpdate) { 17610 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 17611 removedPackage, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, 17612 null, null, removedUsers); 17613 } 17614 } 17615 if (removedAppId >= 0) { 17616 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 17617 removedUsers); 17618 } 17619 } 17620 } 17621 17622 /* 17623 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 17624 * flag is not set, the data directory is removed as well. 17625 * make sure this flag is set for partially installed apps. If not its meaningless to 17626 * delete a partially installed application. 17627 */ 17628 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 17629 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 17630 String packageName = ps.name; 17631 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 17632 // Retrieve object to delete permissions for shared user later on 17633 final PackageParser.Package deletedPkg; 17634 final PackageSetting deletedPs; 17635 // reader 17636 synchronized (mPackages) { 17637 deletedPkg = mPackages.get(packageName); 17638 deletedPs = mSettings.mPackages.get(packageName); 17639 if (outInfo != null) { 17640 outInfo.removedPackage = packageName; 17641 outInfo.isStaticSharedLib = deletedPkg != null 17642 && deletedPkg.staticSharedLibName != null; 17643 outInfo.removedUsers = deletedPs != null 17644 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 17645 : null; 17646 } 17647 } 17648 17649 removePackageLI(ps, (flags & REMOVE_CHATTY) != 0); 17650 17651 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 17652 final PackageParser.Package resolvedPkg; 17653 if (deletedPkg != null) { 17654 resolvedPkg = deletedPkg; 17655 } else { 17656 // We don't have a parsed package when it lives on an ejected 17657 // adopted storage device, so fake something together 17658 resolvedPkg = new PackageParser.Package(ps.name); 17659 resolvedPkg.setVolumeUuid(ps.volumeUuid); 17660 } 17661 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 17662 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 17663 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 17664 if (outInfo != null) { 17665 outInfo.dataRemoved = true; 17666 } 17667 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 17668 } 17669 17670 int removedAppId = -1; 17671 17672 // writer 17673 synchronized (mPackages) { 17674 boolean installedStateChanged = false; 17675 if (deletedPs != null) { 17676 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 17677 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 17678 clearDefaultBrowserIfNeeded(packageName); 17679 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 17680 removedAppId = mSettings.removePackageLPw(packageName); 17681 if (outInfo != null) { 17682 outInfo.removedAppId = removedAppId; 17683 } 17684 updatePermissionsLPw(deletedPs.name, null, 0); 17685 if (deletedPs.sharedUser != null) { 17686 // Remove permissions associated with package. Since runtime 17687 // permissions are per user we have to kill the removed package 17688 // or packages running under the shared user of the removed 17689 // package if revoking the permissions requested only by the removed 17690 // package is successful and this causes a change in gids. 17691 for (int userId : UserManagerService.getInstance().getUserIds()) { 17692 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 17693 userId); 17694 if (userIdToKill == UserHandle.USER_ALL 17695 || userIdToKill >= UserHandle.USER_SYSTEM) { 17696 // If gids changed for this user, kill all affected packages. 17697 mHandler.post(new Runnable() { 17698 @Override 17699 public void run() { 17700 // This has to happen with no lock held. 17701 killApplication(deletedPs.name, deletedPs.appId, 17702 KILL_APP_REASON_GIDS_CHANGED); 17703 } 17704 }); 17705 break; 17706 } 17707 } 17708 } 17709 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 17710 } 17711 // make sure to preserve per-user disabled state if this removal was just 17712 // a downgrade of a system app to the factory package 17713 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 17714 if (DEBUG_REMOVE) { 17715 Slog.d(TAG, "Propagating install state across downgrade"); 17716 } 17717 for (int userId : allUserHandles) { 17718 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 17719 if (DEBUG_REMOVE) { 17720 Slog.d(TAG, " user " + userId + " => " + installed); 17721 } 17722 if (installed != ps.getInstalled(userId)) { 17723 installedStateChanged = true; 17724 } 17725 ps.setInstalled(installed, userId); 17726 } 17727 } 17728 } 17729 // can downgrade to reader 17730 if (writeSettings) { 17731 // Save settings now 17732 mSettings.writeLPr(); 17733 } 17734 if (installedStateChanged) { 17735 mSettings.writeKernelMappingLPr(ps); 17736 } 17737 } 17738 if (removedAppId != -1) { 17739 // A user ID was deleted here. Go through all users and remove it 17740 // from KeyStore. 17741 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId); 17742 } 17743 } 17744 17745 static boolean locationIsPrivileged(File path) { 17746 try { 17747 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 17748 .getCanonicalPath(); 17749 return path.getCanonicalPath().startsWith(privilegedAppDir); 17750 } catch (IOException e) { 17751 Slog.e(TAG, "Unable to access code path " + path); 17752 } 17753 return false; 17754 } 17755 17756 /* 17757 * Tries to delete system package. 17758 */ 17759 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 17760 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 17761 boolean writeSettings) { 17762 if (deletedPs.parentPackageName != null) { 17763 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 17764 return false; 17765 } 17766 17767 final boolean applyUserRestrictions 17768 = (allUserHandles != null) && (outInfo.origUsers != null); 17769 final PackageSetting disabledPs; 17770 // Confirm if the system package has been updated 17771 // An updated system app can be deleted. This will also have to restore 17772 // the system pkg from system partition 17773 // reader 17774 synchronized (mPackages) { 17775 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 17776 } 17777 17778 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 17779 + " disabledPs=" + disabledPs); 17780 17781 if (disabledPs == null) { 17782 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 17783 return false; 17784 } else if (DEBUG_REMOVE) { 17785 Slog.d(TAG, "Deleting system pkg from data partition"); 17786 } 17787 17788 if (DEBUG_REMOVE) { 17789 if (applyUserRestrictions) { 17790 Slog.d(TAG, "Remembering install states:"); 17791 for (int userId : allUserHandles) { 17792 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 17793 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 17794 } 17795 } 17796 } 17797 17798 // Delete the updated package 17799 outInfo.isRemovedPackageSystemUpdate = true; 17800 if (outInfo.removedChildPackages != null) { 17801 final int childCount = (deletedPs.childPackageNames != null) 17802 ? deletedPs.childPackageNames.size() : 0; 17803 for (int i = 0; i < childCount; i++) { 17804 String childPackageName = deletedPs.childPackageNames.get(i); 17805 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 17806 .contains(childPackageName)) { 17807 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 17808 childPackageName); 17809 if (childInfo != null) { 17810 childInfo.isRemovedPackageSystemUpdate = true; 17811 } 17812 } 17813 } 17814 } 17815 17816 if (disabledPs.versionCode < deletedPs.versionCode) { 17817 // Delete data for downgrades 17818 flags &= ~PackageManager.DELETE_KEEP_DATA; 17819 } else { 17820 // Preserve data by setting flag 17821 flags |= PackageManager.DELETE_KEEP_DATA; 17822 } 17823 17824 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 17825 outInfo, writeSettings, disabledPs.pkg); 17826 if (!ret) { 17827 return false; 17828 } 17829 17830 // writer 17831 synchronized (mPackages) { 17832 // Reinstate the old system package 17833 enableSystemPackageLPw(disabledPs.pkg); 17834 // Remove any native libraries from the upgraded package. 17835 removeNativeBinariesLI(deletedPs); 17836 } 17837 17838 // Install the system package 17839 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 17840 int parseFlags = mDefParseFlags 17841 | PackageParser.PARSE_MUST_BE_APK 17842 | PackageParser.PARSE_IS_SYSTEM 17843 | PackageParser.PARSE_IS_SYSTEM_DIR; 17844 if (locationIsPrivileged(disabledPs.codePath)) { 17845 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 17846 } 17847 17848 final PackageParser.Package newPkg; 17849 try { 17850 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */, 17851 0 /* currentTime */, null); 17852 } catch (PackageManagerException e) { 17853 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 17854 + e.getMessage()); 17855 return false; 17856 } 17857 17858 try { 17859 // update shared libraries for the newly re-installed system package 17860 updateSharedLibrariesLPr(newPkg, null); 17861 } catch (PackageManagerException e) { 17862 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 17863 } 17864 17865 prepareAppDataAfterInstallLIF(newPkg); 17866 17867 // writer 17868 synchronized (mPackages) { 17869 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 17870 17871 // Propagate the permissions state as we do not want to drop on the floor 17872 // runtime permissions. The update permissions method below will take 17873 // care of removing obsolete permissions and grant install permissions. 17874 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 17875 updatePermissionsLPw(newPkg.packageName, newPkg, 17876 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 17877 17878 if (applyUserRestrictions) { 17879 boolean installedStateChanged = false; 17880 if (DEBUG_REMOVE) { 17881 Slog.d(TAG, "Propagating install state across reinstall"); 17882 } 17883 for (int userId : allUserHandles) { 17884 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 17885 if (DEBUG_REMOVE) { 17886 Slog.d(TAG, " user " + userId + " => " + installed); 17887 } 17888 if (installed != ps.getInstalled(userId)) { 17889 installedStateChanged = true; 17890 } 17891 ps.setInstalled(installed, userId); 17892 17893 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 17894 } 17895 // Regardless of writeSettings we need to ensure that this restriction 17896 // state propagation is persisted 17897 mSettings.writeAllUsersPackageRestrictionsLPr(); 17898 if (installedStateChanged) { 17899 mSettings.writeKernelMappingLPr(ps); 17900 } 17901 } 17902 // can downgrade to reader here 17903 if (writeSettings) { 17904 mSettings.writeLPr(); 17905 } 17906 } 17907 return true; 17908 } 17909 17910 private boolean deleteInstalledPackageLIF(PackageSetting ps, 17911 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 17912 PackageRemovedInfo outInfo, boolean writeSettings, 17913 PackageParser.Package replacingPackage) { 17914 synchronized (mPackages) { 17915 if (outInfo != null) { 17916 outInfo.uid = ps.appId; 17917 } 17918 17919 if (outInfo != null && outInfo.removedChildPackages != null) { 17920 final int childCount = (ps.childPackageNames != null) 17921 ? ps.childPackageNames.size() : 0; 17922 for (int i = 0; i < childCount; i++) { 17923 String childPackageName = ps.childPackageNames.get(i); 17924 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 17925 if (childPs == null) { 17926 return false; 17927 } 17928 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 17929 childPackageName); 17930 if (childInfo != null) { 17931 childInfo.uid = childPs.appId; 17932 } 17933 } 17934 } 17935 } 17936 17937 // Delete package data from internal structures and also remove data if flag is set 17938 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 17939 17940 // Delete the child packages data 17941 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 17942 for (int i = 0; i < childCount; i++) { 17943 PackageSetting childPs; 17944 synchronized (mPackages) { 17945 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 17946 } 17947 if (childPs != null) { 17948 PackageRemovedInfo childOutInfo = (outInfo != null 17949 && outInfo.removedChildPackages != null) 17950 ? outInfo.removedChildPackages.get(childPs.name) : null; 17951 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 17952 && (replacingPackage != null 17953 && !replacingPackage.hasChildPackage(childPs.name)) 17954 ? flags & ~DELETE_KEEP_DATA : flags; 17955 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 17956 deleteFlags, writeSettings); 17957 } 17958 } 17959 17960 // Delete application code and resources only for parent packages 17961 if (ps.parentPackageName == null) { 17962 if (deleteCodeAndResources && (outInfo != null)) { 17963 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 17964 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 17965 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 17966 } 17967 } 17968 17969 return true; 17970 } 17971 17972 @Override 17973 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 17974 int userId) { 17975 mContext.enforceCallingOrSelfPermission( 17976 android.Manifest.permission.DELETE_PACKAGES, null); 17977 synchronized (mPackages) { 17978 PackageSetting ps = mSettings.mPackages.get(packageName); 17979 if (ps == null) { 17980 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 17981 return false; 17982 } 17983 // Cannot block uninstall of static shared libs as they are 17984 // considered a part of the using app (emulating static linking). 17985 // Also static libs are installed always on internal storage. 17986 PackageParser.Package pkg = mPackages.get(packageName); 17987 if (pkg != null && pkg.staticSharedLibName != null) { 17988 Slog.w(TAG, "Cannot block uninstall of package: " + packageName 17989 + " providing static shared library: " + pkg.staticSharedLibName); 17990 return false; 17991 } 17992 if (!ps.getInstalled(userId)) { 17993 // Can't block uninstall for an app that is not installed or enabled. 17994 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 17995 return false; 17996 } 17997 ps.setBlockUninstall(blockUninstall, userId); 17998 mSettings.writePackageRestrictionsLPr(userId); 17999 } 18000 return true; 18001 } 18002 18003 @Override 18004 public boolean getBlockUninstallForUser(String packageName, int userId) { 18005 synchronized (mPackages) { 18006 PackageSetting ps = mSettings.mPackages.get(packageName); 18007 if (ps == null) { 18008 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 18009 return false; 18010 } 18011 return ps.getBlockUninstall(userId); 18012 } 18013 } 18014 18015 @Override 18016 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 18017 int callingUid = Binder.getCallingUid(); 18018 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 18019 throw new SecurityException( 18020 "setRequiredForSystemUser can only be run by the system or root"); 18021 } 18022 synchronized (mPackages) { 18023 PackageSetting ps = mSettings.mPackages.get(packageName); 18024 if (ps == null) { 18025 Log.w(TAG, "Package doesn't exist: " + packageName); 18026 return false; 18027 } 18028 if (systemUserApp) { 18029 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 18030 } else { 18031 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 18032 } 18033 mSettings.writeLPr(); 18034 } 18035 return true; 18036 } 18037 18038 /* 18039 * This method handles package deletion in general 18040 */ 18041 private boolean deletePackageLIF(String packageName, UserHandle user, 18042 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 18043 PackageRemovedInfo outInfo, boolean writeSettings, 18044 PackageParser.Package replacingPackage) { 18045 if (packageName == null) { 18046 Slog.w(TAG, "Attempt to delete null packageName."); 18047 return false; 18048 } 18049 18050 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 18051 18052 PackageSetting ps; 18053 synchronized (mPackages) { 18054 ps = mSettings.mPackages.get(packageName); 18055 if (ps == null) { 18056 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 18057 return false; 18058 } 18059 18060 if (ps.parentPackageName != null && (!isSystemApp(ps) 18061 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 18062 if (DEBUG_REMOVE) { 18063 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 18064 + ((user == null) ? UserHandle.USER_ALL : user)); 18065 } 18066 final int removedUserId = (user != null) ? user.getIdentifier() 18067 : UserHandle.USER_ALL; 18068 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 18069 return false; 18070 } 18071 markPackageUninstalledForUserLPw(ps, user); 18072 scheduleWritePackageRestrictionsLocked(user); 18073 return true; 18074 } 18075 } 18076 18077 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 18078 && user.getIdentifier() != UserHandle.USER_ALL)) { 18079 // The caller is asking that the package only be deleted for a single 18080 // user. To do this, we just mark its uninstalled state and delete 18081 // its data. If this is a system app, we only allow this to happen if 18082 // they have set the special DELETE_SYSTEM_APP which requests different 18083 // semantics than normal for uninstalling system apps. 18084 markPackageUninstalledForUserLPw(ps, user); 18085 18086 if (!isSystemApp(ps)) { 18087 // Do not uninstall the APK if an app should be cached 18088 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 18089 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 18090 // Other user still have this package installed, so all 18091 // we need to do is clear this user's data and save that 18092 // it is uninstalled. 18093 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 18094 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 18095 return false; 18096 } 18097 scheduleWritePackageRestrictionsLocked(user); 18098 return true; 18099 } else { 18100 // We need to set it back to 'installed' so the uninstall 18101 // broadcasts will be sent correctly. 18102 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 18103 ps.setInstalled(true, user.getIdentifier()); 18104 mSettings.writeKernelMappingLPr(ps); 18105 } 18106 } else { 18107 // This is a system app, so we assume that the 18108 // other users still have this package installed, so all 18109 // we need to do is clear this user's data and save that 18110 // it is uninstalled. 18111 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 18112 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 18113 return false; 18114 } 18115 scheduleWritePackageRestrictionsLocked(user); 18116 return true; 18117 } 18118 } 18119 18120 // If we are deleting a composite package for all users, keep track 18121 // of result for each child. 18122 if (ps.childPackageNames != null && outInfo != null) { 18123 synchronized (mPackages) { 18124 final int childCount = ps.childPackageNames.size(); 18125 outInfo.removedChildPackages = new ArrayMap<>(childCount); 18126 for (int i = 0; i < childCount; i++) { 18127 String childPackageName = ps.childPackageNames.get(i); 18128 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 18129 childInfo.removedPackage = childPackageName; 18130 outInfo.removedChildPackages.put(childPackageName, childInfo); 18131 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 18132 if (childPs != null) { 18133 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 18134 } 18135 } 18136 } 18137 } 18138 18139 boolean ret = false; 18140 if (isSystemApp(ps)) { 18141 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 18142 // When an updated system application is deleted we delete the existing resources 18143 // as well and fall back to existing code in system partition 18144 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 18145 } else { 18146 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 18147 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 18148 outInfo, writeSettings, replacingPackage); 18149 } 18150 18151 // Take a note whether we deleted the package for all users 18152 if (outInfo != null) { 18153 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 18154 if (outInfo.removedChildPackages != null) { 18155 synchronized (mPackages) { 18156 final int childCount = outInfo.removedChildPackages.size(); 18157 for (int i = 0; i < childCount; i++) { 18158 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 18159 if (childInfo != null) { 18160 childInfo.removedForAllUsers = mPackages.get( 18161 childInfo.removedPackage) == null; 18162 } 18163 } 18164 } 18165 } 18166 // If we uninstalled an update to a system app there may be some 18167 // child packages that appeared as they are declared in the system 18168 // app but were not declared in the update. 18169 if (isSystemApp(ps)) { 18170 synchronized (mPackages) { 18171 PackageSetting updatedPs = mSettings.getPackageLPr(ps.name); 18172 final int childCount = (updatedPs.childPackageNames != null) 18173 ? updatedPs.childPackageNames.size() : 0; 18174 for (int i = 0; i < childCount; i++) { 18175 String childPackageName = updatedPs.childPackageNames.get(i); 18176 if (outInfo.removedChildPackages == null 18177 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 18178 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 18179 if (childPs == null) { 18180 continue; 18181 } 18182 PackageInstalledInfo installRes = new PackageInstalledInfo(); 18183 installRes.name = childPackageName; 18184 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 18185 installRes.pkg = mPackages.get(childPackageName); 18186 installRes.uid = childPs.pkg.applicationInfo.uid; 18187 if (outInfo.appearedChildPackages == null) { 18188 outInfo.appearedChildPackages = new ArrayMap<>(); 18189 } 18190 outInfo.appearedChildPackages.put(childPackageName, installRes); 18191 } 18192 } 18193 } 18194 } 18195 } 18196 18197 return ret; 18198 } 18199 18200 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 18201 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 18202 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 18203 for (int nextUserId : userIds) { 18204 if (DEBUG_REMOVE) { 18205 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 18206 } 18207 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 18208 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 18209 false /*hidden*/, false /*suspended*/, null, null, null, 18210 false /*blockUninstall*/, 18211 ps.readUserState(nextUserId).domainVerificationStatus, 0, 18212 PackageManager.INSTALL_REASON_UNKNOWN); 18213 } 18214 mSettings.writeKernelMappingLPr(ps); 18215 } 18216 18217 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 18218 PackageRemovedInfo outInfo) { 18219 final PackageParser.Package pkg; 18220 synchronized (mPackages) { 18221 pkg = mPackages.get(ps.name); 18222 } 18223 18224 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 18225 : new int[] {userId}; 18226 for (int nextUserId : userIds) { 18227 if (DEBUG_REMOVE) { 18228 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 18229 + nextUserId); 18230 } 18231 18232 destroyAppDataLIF(pkg, userId, 18233 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18234 destroyAppProfilesLIF(pkg, userId); 18235 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 18236 schedulePackageCleaning(ps.name, nextUserId, false); 18237 synchronized (mPackages) { 18238 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 18239 scheduleWritePackageRestrictionsLocked(nextUserId); 18240 } 18241 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 18242 } 18243 } 18244 18245 if (outInfo != null) { 18246 outInfo.removedPackage = ps.name; 18247 outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null; 18248 outInfo.removedAppId = ps.appId; 18249 outInfo.removedUsers = userIds; 18250 } 18251 18252 return true; 18253 } 18254 18255 private final class ClearStorageConnection implements ServiceConnection { 18256 IMediaContainerService mContainerService; 18257 18258 @Override 18259 public void onServiceConnected(ComponentName name, IBinder service) { 18260 synchronized (this) { 18261 mContainerService = IMediaContainerService.Stub 18262 .asInterface(Binder.allowBlocking(service)); 18263 notifyAll(); 18264 } 18265 } 18266 18267 @Override 18268 public void onServiceDisconnected(ComponentName name) { 18269 } 18270 } 18271 18272 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 18273 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 18274 18275 final boolean mounted; 18276 if (Environment.isExternalStorageEmulated()) { 18277 mounted = true; 18278 } else { 18279 final String status = Environment.getExternalStorageState(); 18280 18281 mounted = status.equals(Environment.MEDIA_MOUNTED) 18282 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 18283 } 18284 18285 if (!mounted) { 18286 return; 18287 } 18288 18289 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 18290 int[] users; 18291 if (userId == UserHandle.USER_ALL) { 18292 users = sUserManager.getUserIds(); 18293 } else { 18294 users = new int[] { userId }; 18295 } 18296 final ClearStorageConnection conn = new ClearStorageConnection(); 18297 if (mContext.bindServiceAsUser( 18298 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 18299 try { 18300 for (int curUser : users) { 18301 long timeout = SystemClock.uptimeMillis() + 5000; 18302 synchronized (conn) { 18303 long now; 18304 while (conn.mContainerService == null && 18305 (now = SystemClock.uptimeMillis()) < timeout) { 18306 try { 18307 conn.wait(timeout - now); 18308 } catch (InterruptedException e) { 18309 } 18310 } 18311 } 18312 if (conn.mContainerService == null) { 18313 return; 18314 } 18315 18316 final UserEnvironment userEnv = new UserEnvironment(curUser); 18317 clearDirectory(conn.mContainerService, 18318 userEnv.buildExternalStorageAppCacheDirs(packageName)); 18319 if (allData) { 18320 clearDirectory(conn.mContainerService, 18321 userEnv.buildExternalStorageAppDataDirs(packageName)); 18322 clearDirectory(conn.mContainerService, 18323 userEnv.buildExternalStorageAppMediaDirs(packageName)); 18324 } 18325 } 18326 } finally { 18327 mContext.unbindService(conn); 18328 } 18329 } 18330 } 18331 18332 @Override 18333 public void clearApplicationProfileData(String packageName) { 18334 enforceSystemOrRoot("Only the system can clear all profile data"); 18335 18336 final PackageParser.Package pkg; 18337 synchronized (mPackages) { 18338 pkg = mPackages.get(packageName); 18339 } 18340 18341 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 18342 synchronized (mInstallLock) { 18343 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 18344 destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL, 18345 true /* removeBaseMarker */); 18346 } 18347 } 18348 } 18349 18350 @Override 18351 public void clearApplicationUserData(final String packageName, 18352 final IPackageDataObserver observer, final int userId) { 18353 mContext.enforceCallingOrSelfPermission( 18354 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 18355 18356 enforceCrossUserPermission(Binder.getCallingUid(), userId, 18357 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 18358 18359 if (mProtectedPackages.isPackageDataProtected(userId, packageName)) { 18360 throw new SecurityException("Cannot clear data for a protected package: " 18361 + packageName); 18362 } 18363 // Queue up an async operation since the package deletion may take a little while. 18364 mHandler.post(new Runnable() { 18365 public void run() { 18366 mHandler.removeCallbacks(this); 18367 final boolean succeeded; 18368 try (PackageFreezer freezer = freezePackage(packageName, 18369 "clearApplicationUserData")) { 18370 synchronized (mInstallLock) { 18371 succeeded = clearApplicationUserDataLIF(packageName, userId); 18372 } 18373 clearExternalStorageDataSync(packageName, userId, true); 18374 synchronized (mPackages) { 18375 mInstantAppRegistry.deleteInstantApplicationMetadataLPw( 18376 packageName, userId); 18377 } 18378 } 18379 if (succeeded) { 18380 // invoke DeviceStorageMonitor's update method to clear any notifications 18381 DeviceStorageMonitorInternal dsm = LocalServices 18382 .getService(DeviceStorageMonitorInternal.class); 18383 if (dsm != null) { 18384 dsm.checkMemory(); 18385 } 18386 } 18387 if(observer != null) { 18388 try { 18389 observer.onRemoveCompleted(packageName, succeeded); 18390 } catch (RemoteException e) { 18391 Log.i(TAG, "Observer no longer exists."); 18392 } 18393 } //end if observer 18394 } //end run 18395 }); 18396 } 18397 18398 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 18399 if (packageName == null) { 18400 Slog.w(TAG, "Attempt to delete null packageName."); 18401 return false; 18402 } 18403 18404 // Try finding details about the requested package 18405 PackageParser.Package pkg; 18406 synchronized (mPackages) { 18407 pkg = mPackages.get(packageName); 18408 if (pkg == null) { 18409 final PackageSetting ps = mSettings.mPackages.get(packageName); 18410 if (ps != null) { 18411 pkg = ps.pkg; 18412 } 18413 } 18414 18415 if (pkg == null) { 18416 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 18417 return false; 18418 } 18419 18420 PackageSetting ps = (PackageSetting) pkg.mExtras; 18421 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 18422 } 18423 18424 clearAppDataLIF(pkg, userId, 18425 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18426 18427 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 18428 removeKeystoreDataIfNeeded(userId, appId); 18429 18430 UserManagerInternal umInternal = getUserManagerInternal(); 18431 final int flags; 18432 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 18433 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18434 } else if (umInternal.isUserRunning(userId)) { 18435 flags = StorageManager.FLAG_STORAGE_DE; 18436 } else { 18437 flags = 0; 18438 } 18439 prepareAppDataContentsLIF(pkg, userId, flags); 18440 18441 return true; 18442 } 18443 18444 /** 18445 * Reverts user permission state changes (permissions and flags) in 18446 * all packages for a given user. 18447 * 18448 * @param userId The device user for which to do a reset. 18449 */ 18450 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 18451 final int packageCount = mPackages.size(); 18452 for (int i = 0; i < packageCount; i++) { 18453 PackageParser.Package pkg = mPackages.valueAt(i); 18454 PackageSetting ps = (PackageSetting) pkg.mExtras; 18455 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 18456 } 18457 } 18458 18459 private void resetNetworkPolicies(int userId) { 18460 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 18461 } 18462 18463 /** 18464 * Reverts user permission state changes (permissions and flags). 18465 * 18466 * @param ps The package for which to reset. 18467 * @param userId The device user for which to do a reset. 18468 */ 18469 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 18470 final PackageSetting ps, final int userId) { 18471 if (ps.pkg == null) { 18472 return; 18473 } 18474 18475 // These are flags that can change base on user actions. 18476 final int userSettableMask = FLAG_PERMISSION_USER_SET 18477 | FLAG_PERMISSION_USER_FIXED 18478 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 18479 | FLAG_PERMISSION_REVIEW_REQUIRED; 18480 18481 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 18482 | FLAG_PERMISSION_POLICY_FIXED; 18483 18484 boolean writeInstallPermissions = false; 18485 boolean writeRuntimePermissions = false; 18486 18487 final int permissionCount = ps.pkg.requestedPermissions.size(); 18488 for (int i = 0; i < permissionCount; i++) { 18489 String permission = ps.pkg.requestedPermissions.get(i); 18490 18491 BasePermission bp = mSettings.mPermissions.get(permission); 18492 if (bp == null) { 18493 continue; 18494 } 18495 18496 // If shared user we just reset the state to which only this app contributed. 18497 if (ps.sharedUser != null) { 18498 boolean used = false; 18499 final int packageCount = ps.sharedUser.packages.size(); 18500 for (int j = 0; j < packageCount; j++) { 18501 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 18502 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 18503 && pkg.pkg.requestedPermissions.contains(permission)) { 18504 used = true; 18505 break; 18506 } 18507 } 18508 if (used) { 18509 continue; 18510 } 18511 } 18512 18513 PermissionsState permissionsState = ps.getPermissionsState(); 18514 18515 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 18516 18517 // Always clear the user settable flags. 18518 final boolean hasInstallState = permissionsState.getInstallPermissionState( 18519 bp.name) != null; 18520 // If permission review is enabled and this is a legacy app, mark the 18521 // permission as requiring a review as this is the initial state. 18522 int flags = 0; 18523 if (mPermissionReviewRequired 18524 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 18525 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 18526 } 18527 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 18528 if (hasInstallState) { 18529 writeInstallPermissions = true; 18530 } else { 18531 writeRuntimePermissions = true; 18532 } 18533 } 18534 18535 // Below is only runtime permission handling. 18536 if (!bp.isRuntime()) { 18537 continue; 18538 } 18539 18540 // Never clobber system or policy. 18541 if ((oldFlags & policyOrSystemFlags) != 0) { 18542 continue; 18543 } 18544 18545 // If this permission was granted by default, make sure it is. 18546 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 18547 if (permissionsState.grantRuntimePermission(bp, userId) 18548 != PERMISSION_OPERATION_FAILURE) { 18549 writeRuntimePermissions = true; 18550 } 18551 // If permission review is enabled the permissions for a legacy apps 18552 // are represented as constantly granted runtime ones, so don't revoke. 18553 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 18554 // Otherwise, reset the permission. 18555 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 18556 switch (revokeResult) { 18557 case PERMISSION_OPERATION_SUCCESS: 18558 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 18559 writeRuntimePermissions = true; 18560 final int appId = ps.appId; 18561 mHandler.post(new Runnable() { 18562 @Override 18563 public void run() { 18564 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 18565 } 18566 }); 18567 } break; 18568 } 18569 } 18570 } 18571 18572 // Synchronously write as we are taking permissions away. 18573 if (writeRuntimePermissions) { 18574 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 18575 } 18576 18577 // Synchronously write as we are taking permissions away. 18578 if (writeInstallPermissions) { 18579 mSettings.writeLPr(); 18580 } 18581 } 18582 18583 /** 18584 * Remove entries from the keystore daemon. Will only remove it if the 18585 * {@code appId} is valid. 18586 */ 18587 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 18588 if (appId < 0) { 18589 return; 18590 } 18591 18592 final KeyStore keyStore = KeyStore.getInstance(); 18593 if (keyStore != null) { 18594 if (userId == UserHandle.USER_ALL) { 18595 for (final int individual : sUserManager.getUserIds()) { 18596 keyStore.clearUid(UserHandle.getUid(individual, appId)); 18597 } 18598 } else { 18599 keyStore.clearUid(UserHandle.getUid(userId, appId)); 18600 } 18601 } else { 18602 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 18603 } 18604 } 18605 18606 @Override 18607 public void deleteApplicationCacheFiles(final String packageName, 18608 final IPackageDataObserver observer) { 18609 final int userId = UserHandle.getCallingUserId(); 18610 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 18611 } 18612 18613 @Override 18614 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 18615 final IPackageDataObserver observer) { 18616 mContext.enforceCallingOrSelfPermission( 18617 android.Manifest.permission.DELETE_CACHE_FILES, null); 18618 enforceCrossUserPermission(Binder.getCallingUid(), userId, 18619 /* requireFullPermission= */ true, /* checkShell= */ false, 18620 "delete application cache files"); 18621 18622 final PackageParser.Package pkg; 18623 synchronized (mPackages) { 18624 pkg = mPackages.get(packageName); 18625 } 18626 18627 // Queue up an async operation since the package deletion may take a little while. 18628 mHandler.post(new Runnable() { 18629 public void run() { 18630 synchronized (mInstallLock) { 18631 final int flags = StorageManager.FLAG_STORAGE_DE 18632 | StorageManager.FLAG_STORAGE_CE; 18633 // We're only clearing cache files, so we don't care if the 18634 // app is unfrozen and still able to run 18635 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 18636 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 18637 } 18638 clearExternalStorageDataSync(packageName, userId, false); 18639 if (observer != null) { 18640 try { 18641 observer.onRemoveCompleted(packageName, true); 18642 } catch (RemoteException e) { 18643 Log.i(TAG, "Observer no longer exists."); 18644 } 18645 } 18646 } 18647 }); 18648 } 18649 18650 @Override 18651 public void getPackageSizeInfo(final String packageName, int userHandle, 18652 final IPackageStatsObserver observer) { 18653 mContext.enforceCallingOrSelfPermission( 18654 android.Manifest.permission.GET_PACKAGE_SIZE, null); 18655 if (packageName == null) { 18656 throw new IllegalArgumentException("Attempt to get size of null packageName"); 18657 } 18658 18659 PackageStats stats = new PackageStats(packageName, userHandle); 18660 18661 /* 18662 * Queue up an async operation since the package measurement may take a 18663 * little while. 18664 */ 18665 Message msg = mHandler.obtainMessage(INIT_COPY); 18666 msg.obj = new MeasureParams(stats, observer); 18667 mHandler.sendMessage(msg); 18668 } 18669 18670 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 18671 final PackageSetting ps; 18672 synchronized (mPackages) { 18673 ps = mSettings.mPackages.get(packageName); 18674 if (ps == null) { 18675 Slog.w(TAG, "Failed to find settings for " + packageName); 18676 return false; 18677 } 18678 } 18679 18680 final String[] packageNames = { packageName }; 18681 final long[] ceDataInodes = { ps.getCeDataInode(userId) }; 18682 final String[] codePaths = { ps.codePathString }; 18683 18684 try { 18685 mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0, 18686 ps.appId, ceDataInodes, codePaths, stats); 18687 18688 // For now, ignore code size of packages on system partition 18689 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 18690 stats.codeSize = 0; 18691 } 18692 18693 // External clients expect these to be tracked separately 18694 stats.dataSize -= stats.cacheSize; 18695 18696 } catch (InstallerException e) { 18697 Slog.w(TAG, String.valueOf(e)); 18698 return false; 18699 } 18700 18701 return true; 18702 } 18703 18704 private int getUidTargetSdkVersionLockedLPr(int uid) { 18705 Object obj = mSettings.getUserIdLPr(uid); 18706 if (obj instanceof SharedUserSetting) { 18707 final SharedUserSetting sus = (SharedUserSetting) obj; 18708 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 18709 final Iterator<PackageSetting> it = sus.packages.iterator(); 18710 while (it.hasNext()) { 18711 final PackageSetting ps = it.next(); 18712 if (ps.pkg != null) { 18713 int v = ps.pkg.applicationInfo.targetSdkVersion; 18714 if (v < vers) vers = v; 18715 } 18716 } 18717 return vers; 18718 } else if (obj instanceof PackageSetting) { 18719 final PackageSetting ps = (PackageSetting) obj; 18720 if (ps.pkg != null) { 18721 return ps.pkg.applicationInfo.targetSdkVersion; 18722 } 18723 } 18724 return Build.VERSION_CODES.CUR_DEVELOPMENT; 18725 } 18726 18727 @Override 18728 public void addPreferredActivity(IntentFilter filter, int match, 18729 ComponentName[] set, ComponentName activity, int userId) { 18730 addPreferredActivityInternal(filter, match, set, activity, true, userId, 18731 "Adding preferred"); 18732 } 18733 18734 private void addPreferredActivityInternal(IntentFilter filter, int match, 18735 ComponentName[] set, ComponentName activity, boolean always, int userId, 18736 String opname) { 18737 // writer 18738 int callingUid = Binder.getCallingUid(); 18739 enforceCrossUserPermission(callingUid, userId, 18740 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 18741 if (filter.countActions() == 0) { 18742 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 18743 return; 18744 } 18745 synchronized (mPackages) { 18746 if (mContext.checkCallingOrSelfPermission( 18747 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 18748 != PackageManager.PERMISSION_GRANTED) { 18749 if (getUidTargetSdkVersionLockedLPr(callingUid) 18750 < Build.VERSION_CODES.FROYO) { 18751 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 18752 + callingUid); 18753 return; 18754 } 18755 mContext.enforceCallingOrSelfPermission( 18756 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 18757 } 18758 18759 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 18760 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 18761 + userId + ":"); 18762 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18763 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 18764 scheduleWritePackageRestrictionsLocked(userId); 18765 postPreferredActivityChangedBroadcast(userId); 18766 } 18767 } 18768 18769 private void postPreferredActivityChangedBroadcast(int userId) { 18770 mHandler.post(() -> { 18771 final IActivityManager am = ActivityManager.getService(); 18772 if (am == null) { 18773 return; 18774 } 18775 18776 final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED); 18777 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 18778 try { 18779 am.broadcastIntent(null, intent, null, null, 18780 0, null, null, null, android.app.AppOpsManager.OP_NONE, 18781 null, false, false, userId); 18782 } catch (RemoteException e) { 18783 } 18784 }); 18785 } 18786 18787 @Override 18788 public void replacePreferredActivity(IntentFilter filter, int match, 18789 ComponentName[] set, ComponentName activity, int userId) { 18790 if (filter.countActions() != 1) { 18791 throw new IllegalArgumentException( 18792 "replacePreferredActivity expects filter to have only 1 action."); 18793 } 18794 if (filter.countDataAuthorities() != 0 18795 || filter.countDataPaths() != 0 18796 || filter.countDataSchemes() > 1 18797 || filter.countDataTypes() != 0) { 18798 throw new IllegalArgumentException( 18799 "replacePreferredActivity expects filter to have no data authorities, " + 18800 "paths, or types; and at most one scheme."); 18801 } 18802 18803 final int callingUid = Binder.getCallingUid(); 18804 enforceCrossUserPermission(callingUid, userId, 18805 true /* requireFullPermission */, false /* checkShell */, 18806 "replace preferred activity"); 18807 synchronized (mPackages) { 18808 if (mContext.checkCallingOrSelfPermission( 18809 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 18810 != PackageManager.PERMISSION_GRANTED) { 18811 if (getUidTargetSdkVersionLockedLPr(callingUid) 18812 < Build.VERSION_CODES.FROYO) { 18813 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 18814 + Binder.getCallingUid()); 18815 return; 18816 } 18817 mContext.enforceCallingOrSelfPermission( 18818 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 18819 } 18820 18821 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 18822 if (pir != null) { 18823 // Get all of the existing entries that exactly match this filter. 18824 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 18825 if (existing != null && existing.size() == 1) { 18826 PreferredActivity cur = existing.get(0); 18827 if (DEBUG_PREFERRED) { 18828 Slog.i(TAG, "Checking replace of preferred:"); 18829 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18830 if (!cur.mPref.mAlways) { 18831 Slog.i(TAG, " -- CUR; not mAlways!"); 18832 } else { 18833 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 18834 Slog.i(TAG, " -- CUR: mSet=" 18835 + Arrays.toString(cur.mPref.mSetComponents)); 18836 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 18837 Slog.i(TAG, " -- NEW: mMatch=" 18838 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 18839 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 18840 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 18841 } 18842 } 18843 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 18844 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 18845 && cur.mPref.sameSet(set)) { 18846 // Setting the preferred activity to what it happens to be already 18847 if (DEBUG_PREFERRED) { 18848 Slog.i(TAG, "Replacing with same preferred activity " 18849 + cur.mPref.mShortComponent + " for user " 18850 + userId + ":"); 18851 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18852 } 18853 return; 18854 } 18855 } 18856 18857 if (existing != null) { 18858 if (DEBUG_PREFERRED) { 18859 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 18860 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18861 } 18862 for (int i = 0; i < existing.size(); i++) { 18863 PreferredActivity pa = existing.get(i); 18864 if (DEBUG_PREFERRED) { 18865 Slog.i(TAG, "Removing existing preferred activity " 18866 + pa.mPref.mComponent + ":"); 18867 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 18868 } 18869 pir.removeFilter(pa); 18870 } 18871 } 18872 } 18873 addPreferredActivityInternal(filter, match, set, activity, true, userId, 18874 "Replacing preferred"); 18875 } 18876 } 18877 18878 @Override 18879 public void clearPackagePreferredActivities(String packageName) { 18880 final int uid = Binder.getCallingUid(); 18881 // writer 18882 synchronized (mPackages) { 18883 PackageParser.Package pkg = mPackages.get(packageName); 18884 if (pkg == null || pkg.applicationInfo.uid != uid) { 18885 if (mContext.checkCallingOrSelfPermission( 18886 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 18887 != PackageManager.PERMISSION_GRANTED) { 18888 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 18889 < Build.VERSION_CODES.FROYO) { 18890 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 18891 + Binder.getCallingUid()); 18892 return; 18893 } 18894 mContext.enforceCallingOrSelfPermission( 18895 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 18896 } 18897 } 18898 18899 int user = UserHandle.getCallingUserId(); 18900 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 18901 scheduleWritePackageRestrictionsLocked(user); 18902 } 18903 } 18904 } 18905 18906 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 18907 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 18908 ArrayList<PreferredActivity> removed = null; 18909 boolean changed = false; 18910 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18911 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 18912 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18913 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 18914 continue; 18915 } 18916 Iterator<PreferredActivity> it = pir.filterIterator(); 18917 while (it.hasNext()) { 18918 PreferredActivity pa = it.next(); 18919 // Mark entry for removal only if it matches the package name 18920 // and the entry is of type "always". 18921 if (packageName == null || 18922 (pa.mPref.mComponent.getPackageName().equals(packageName) 18923 && pa.mPref.mAlways)) { 18924 if (removed == null) { 18925 removed = new ArrayList<PreferredActivity>(); 18926 } 18927 removed.add(pa); 18928 } 18929 } 18930 if (removed != null) { 18931 for (int j=0; j<removed.size(); j++) { 18932 PreferredActivity pa = removed.get(j); 18933 pir.removeFilter(pa); 18934 } 18935 changed = true; 18936 } 18937 } 18938 if (changed) { 18939 postPreferredActivityChangedBroadcast(userId); 18940 } 18941 return changed; 18942 } 18943 18944 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 18945 private void clearIntentFilterVerificationsLPw(int userId) { 18946 final int packageCount = mPackages.size(); 18947 for (int i = 0; i < packageCount; i++) { 18948 PackageParser.Package pkg = mPackages.valueAt(i); 18949 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 18950 } 18951 } 18952 18953 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 18954 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 18955 if (userId == UserHandle.USER_ALL) { 18956 if (mSettings.removeIntentFilterVerificationLPw(packageName, 18957 sUserManager.getUserIds())) { 18958 for (int oneUserId : sUserManager.getUserIds()) { 18959 scheduleWritePackageRestrictionsLocked(oneUserId); 18960 } 18961 } 18962 } else { 18963 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 18964 scheduleWritePackageRestrictionsLocked(userId); 18965 } 18966 } 18967 } 18968 18969 void clearDefaultBrowserIfNeeded(String packageName) { 18970 for (int oneUserId : sUserManager.getUserIds()) { 18971 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 18972 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 18973 if (packageName.equals(defaultBrowserPackageName)) { 18974 setDefaultBrowserPackageName(null, oneUserId); 18975 } 18976 } 18977 } 18978 18979 @Override 18980 public void resetApplicationPreferences(int userId) { 18981 mContext.enforceCallingOrSelfPermission( 18982 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 18983 final long identity = Binder.clearCallingIdentity(); 18984 // writer 18985 try { 18986 synchronized (mPackages) { 18987 clearPackagePreferredActivitiesLPw(null, userId); 18988 mSettings.applyDefaultPreferredAppsLPw(this, userId); 18989 // TODO: We have to reset the default SMS and Phone. This requires 18990 // significant refactoring to keep all default apps in the package 18991 // manager (cleaner but more work) or have the services provide 18992 // callbacks to the package manager to request a default app reset. 18993 applyFactoryDefaultBrowserLPw(userId); 18994 clearIntentFilterVerificationsLPw(userId); 18995 primeDomainVerificationsLPw(userId); 18996 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 18997 scheduleWritePackageRestrictionsLocked(userId); 18998 } 18999 resetNetworkPolicies(userId); 19000 } finally { 19001 Binder.restoreCallingIdentity(identity); 19002 } 19003 } 19004 19005 @Override 19006 public int getPreferredActivities(List<IntentFilter> outFilters, 19007 List<ComponentName> outActivities, String packageName) { 19008 19009 int num = 0; 19010 final int userId = UserHandle.getCallingUserId(); 19011 // reader 19012 synchronized (mPackages) { 19013 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 19014 if (pir != null) { 19015 final Iterator<PreferredActivity> it = pir.filterIterator(); 19016 while (it.hasNext()) { 19017 final PreferredActivity pa = it.next(); 19018 if (packageName == null 19019 || (pa.mPref.mComponent.getPackageName().equals(packageName) 19020 && pa.mPref.mAlways)) { 19021 if (outFilters != null) { 19022 outFilters.add(new IntentFilter(pa)); 19023 } 19024 if (outActivities != null) { 19025 outActivities.add(pa.mPref.mComponent); 19026 } 19027 } 19028 } 19029 } 19030 } 19031 19032 return num; 19033 } 19034 19035 @Override 19036 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 19037 int userId) { 19038 int callingUid = Binder.getCallingUid(); 19039 if (callingUid != Process.SYSTEM_UID) { 19040 throw new SecurityException( 19041 "addPersistentPreferredActivity can only be run by the system"); 19042 } 19043 if (filter.countActions() == 0) { 19044 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 19045 return; 19046 } 19047 synchronized (mPackages) { 19048 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 19049 ":"); 19050 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19051 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 19052 new PersistentPreferredActivity(filter, activity)); 19053 scheduleWritePackageRestrictionsLocked(userId); 19054 postPreferredActivityChangedBroadcast(userId); 19055 } 19056 } 19057 19058 @Override 19059 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 19060 int callingUid = Binder.getCallingUid(); 19061 if (callingUid != Process.SYSTEM_UID) { 19062 throw new SecurityException( 19063 "clearPackagePersistentPreferredActivities can only be run by the system"); 19064 } 19065 ArrayList<PersistentPreferredActivity> removed = null; 19066 boolean changed = false; 19067 synchronized (mPackages) { 19068 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 19069 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 19070 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 19071 .valueAt(i); 19072 if (userId != thisUserId) { 19073 continue; 19074 } 19075 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 19076 while (it.hasNext()) { 19077 PersistentPreferredActivity ppa = it.next(); 19078 // Mark entry for removal only if it matches the package name. 19079 if (ppa.mComponent.getPackageName().equals(packageName)) { 19080 if (removed == null) { 19081 removed = new ArrayList<PersistentPreferredActivity>(); 19082 } 19083 removed.add(ppa); 19084 } 19085 } 19086 if (removed != null) { 19087 for (int j=0; j<removed.size(); j++) { 19088 PersistentPreferredActivity ppa = removed.get(j); 19089 ppir.removeFilter(ppa); 19090 } 19091 changed = true; 19092 } 19093 } 19094 19095 if (changed) { 19096 scheduleWritePackageRestrictionsLocked(userId); 19097 postPreferredActivityChangedBroadcast(userId); 19098 } 19099 } 19100 } 19101 19102 /** 19103 * Common machinery for picking apart a restored XML blob and passing 19104 * it to a caller-supplied functor to be applied to the running system. 19105 */ 19106 private void restoreFromXml(XmlPullParser parser, int userId, 19107 String expectedStartTag, BlobXmlRestorer functor) 19108 throws IOException, XmlPullParserException { 19109 int type; 19110 while ((type = parser.next()) != XmlPullParser.START_TAG 19111 && type != XmlPullParser.END_DOCUMENT) { 19112 } 19113 if (type != XmlPullParser.START_TAG) { 19114 // oops didn't find a start tag?! 19115 if (DEBUG_BACKUP) { 19116 Slog.e(TAG, "Didn't find start tag during restore"); 19117 } 19118 return; 19119 } 19120Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 19121 // this is supposed to be TAG_PREFERRED_BACKUP 19122 if (!expectedStartTag.equals(parser.getName())) { 19123 if (DEBUG_BACKUP) { 19124 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 19125 } 19126 return; 19127 } 19128 19129 // skip interfering stuff, then we're aligned with the backing implementation 19130 while ((type = parser.next()) == XmlPullParser.TEXT) { } 19131Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 19132 functor.apply(parser, userId); 19133 } 19134 19135 private interface BlobXmlRestorer { 19136 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 19137 } 19138 19139 /** 19140 * Non-Binder method, support for the backup/restore mechanism: write the 19141 * full set of preferred activities in its canonical XML format. Returns the 19142 * XML output as a byte array, or null if there is none. 19143 */ 19144 @Override 19145 public byte[] getPreferredActivityBackup(int userId) { 19146 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19147 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 19148 } 19149 19150 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19151 try { 19152 final XmlSerializer serializer = new FastXmlSerializer(); 19153 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19154 serializer.startDocument(null, true); 19155 serializer.startTag(null, TAG_PREFERRED_BACKUP); 19156 19157 synchronized (mPackages) { 19158 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 19159 } 19160 19161 serializer.endTag(null, TAG_PREFERRED_BACKUP); 19162 serializer.endDocument(); 19163 serializer.flush(); 19164 } catch (Exception e) { 19165 if (DEBUG_BACKUP) { 19166 Slog.e(TAG, "Unable to write preferred activities for backup", e); 19167 } 19168 return null; 19169 } 19170 19171 return dataStream.toByteArray(); 19172 } 19173 19174 @Override 19175 public void restorePreferredActivities(byte[] backup, int userId) { 19176 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19177 throw new SecurityException("Only the system may call restorePreferredActivities()"); 19178 } 19179 19180 try { 19181 final XmlPullParser parser = Xml.newPullParser(); 19182 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19183 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 19184 new BlobXmlRestorer() { 19185 @Override 19186 public void apply(XmlPullParser parser, int userId) 19187 throws XmlPullParserException, IOException { 19188 synchronized (mPackages) { 19189 mSettings.readPreferredActivitiesLPw(parser, userId); 19190 } 19191 } 19192 } ); 19193 } catch (Exception e) { 19194 if (DEBUG_BACKUP) { 19195 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19196 } 19197 } 19198 } 19199 19200 /** 19201 * Non-Binder method, support for the backup/restore mechanism: write the 19202 * default browser (etc) settings in its canonical XML format. Returns the default 19203 * browser XML representation as a byte array, or null if there is none. 19204 */ 19205 @Override 19206 public byte[] getDefaultAppsBackup(int userId) { 19207 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19208 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 19209 } 19210 19211 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19212 try { 19213 final XmlSerializer serializer = new FastXmlSerializer(); 19214 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19215 serializer.startDocument(null, true); 19216 serializer.startTag(null, TAG_DEFAULT_APPS); 19217 19218 synchronized (mPackages) { 19219 mSettings.writeDefaultAppsLPr(serializer, userId); 19220 } 19221 19222 serializer.endTag(null, TAG_DEFAULT_APPS); 19223 serializer.endDocument(); 19224 serializer.flush(); 19225 } catch (Exception e) { 19226 if (DEBUG_BACKUP) { 19227 Slog.e(TAG, "Unable to write default apps for backup", e); 19228 } 19229 return null; 19230 } 19231 19232 return dataStream.toByteArray(); 19233 } 19234 19235 @Override 19236 public void restoreDefaultApps(byte[] backup, int userId) { 19237 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19238 throw new SecurityException("Only the system may call restoreDefaultApps()"); 19239 } 19240 19241 try { 19242 final XmlPullParser parser = Xml.newPullParser(); 19243 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19244 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 19245 new BlobXmlRestorer() { 19246 @Override 19247 public void apply(XmlPullParser parser, int userId) 19248 throws XmlPullParserException, IOException { 19249 synchronized (mPackages) { 19250 mSettings.readDefaultAppsLPw(parser, userId); 19251 } 19252 } 19253 } ); 19254 } catch (Exception e) { 19255 if (DEBUG_BACKUP) { 19256 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 19257 } 19258 } 19259 } 19260 19261 @Override 19262 public byte[] getIntentFilterVerificationBackup(int userId) { 19263 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19264 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 19265 } 19266 19267 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19268 try { 19269 final XmlSerializer serializer = new FastXmlSerializer(); 19270 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19271 serializer.startDocument(null, true); 19272 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 19273 19274 synchronized (mPackages) { 19275 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 19276 } 19277 19278 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 19279 serializer.endDocument(); 19280 serializer.flush(); 19281 } catch (Exception e) { 19282 if (DEBUG_BACKUP) { 19283 Slog.e(TAG, "Unable to write default apps for backup", e); 19284 } 19285 return null; 19286 } 19287 19288 return dataStream.toByteArray(); 19289 } 19290 19291 @Override 19292 public void restoreIntentFilterVerification(byte[] backup, int userId) { 19293 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19294 throw new SecurityException("Only the system may call restorePreferredActivities()"); 19295 } 19296 19297 try { 19298 final XmlPullParser parser = Xml.newPullParser(); 19299 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19300 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 19301 new BlobXmlRestorer() { 19302 @Override 19303 public void apply(XmlPullParser parser, int userId) 19304 throws XmlPullParserException, IOException { 19305 synchronized (mPackages) { 19306 mSettings.readAllDomainVerificationsLPr(parser, userId); 19307 mSettings.writeLPr(); 19308 } 19309 } 19310 } ); 19311 } catch (Exception e) { 19312 if (DEBUG_BACKUP) { 19313 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19314 } 19315 } 19316 } 19317 19318 @Override 19319 public byte[] getPermissionGrantBackup(int userId) { 19320 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19321 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 19322 } 19323 19324 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19325 try { 19326 final XmlSerializer serializer = new FastXmlSerializer(); 19327 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19328 serializer.startDocument(null, true); 19329 serializer.startTag(null, TAG_PERMISSION_BACKUP); 19330 19331 synchronized (mPackages) { 19332 serializeRuntimePermissionGrantsLPr(serializer, userId); 19333 } 19334 19335 serializer.endTag(null, TAG_PERMISSION_BACKUP); 19336 serializer.endDocument(); 19337 serializer.flush(); 19338 } catch (Exception e) { 19339 if (DEBUG_BACKUP) { 19340 Slog.e(TAG, "Unable to write default apps for backup", e); 19341 } 19342 return null; 19343 } 19344 19345 return dataStream.toByteArray(); 19346 } 19347 19348 @Override 19349 public void restorePermissionGrants(byte[] backup, int userId) { 19350 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19351 throw new SecurityException("Only the system may call restorePermissionGrants()"); 19352 } 19353 19354 try { 19355 final XmlPullParser parser = Xml.newPullParser(); 19356 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19357 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 19358 new BlobXmlRestorer() { 19359 @Override 19360 public void apply(XmlPullParser parser, int userId) 19361 throws XmlPullParserException, IOException { 19362 synchronized (mPackages) { 19363 processRestoredPermissionGrantsLPr(parser, userId); 19364 } 19365 } 19366 } ); 19367 } catch (Exception e) { 19368 if (DEBUG_BACKUP) { 19369 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19370 } 19371 } 19372 } 19373 19374 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 19375 throws IOException { 19376 serializer.startTag(null, TAG_ALL_GRANTS); 19377 19378 final int N = mSettings.mPackages.size(); 19379 for (int i = 0; i < N; i++) { 19380 final PackageSetting ps = mSettings.mPackages.valueAt(i); 19381 boolean pkgGrantsKnown = false; 19382 19383 PermissionsState packagePerms = ps.getPermissionsState(); 19384 19385 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 19386 final int grantFlags = state.getFlags(); 19387 // only look at grants that are not system/policy fixed 19388 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 19389 final boolean isGranted = state.isGranted(); 19390 // And only back up the user-twiddled state bits 19391 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 19392 final String packageName = mSettings.mPackages.keyAt(i); 19393 if (!pkgGrantsKnown) { 19394 serializer.startTag(null, TAG_GRANT); 19395 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 19396 pkgGrantsKnown = true; 19397 } 19398 19399 final boolean userSet = 19400 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 19401 final boolean userFixed = 19402 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 19403 final boolean revoke = 19404 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 19405 19406 serializer.startTag(null, TAG_PERMISSION); 19407 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 19408 if (isGranted) { 19409 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 19410 } 19411 if (userSet) { 19412 serializer.attribute(null, ATTR_USER_SET, "true"); 19413 } 19414 if (userFixed) { 19415 serializer.attribute(null, ATTR_USER_FIXED, "true"); 19416 } 19417 if (revoke) { 19418 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 19419 } 19420 serializer.endTag(null, TAG_PERMISSION); 19421 } 19422 } 19423 } 19424 19425 if (pkgGrantsKnown) { 19426 serializer.endTag(null, TAG_GRANT); 19427 } 19428 } 19429 19430 serializer.endTag(null, TAG_ALL_GRANTS); 19431 } 19432 19433 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 19434 throws XmlPullParserException, IOException { 19435 String pkgName = null; 19436 int outerDepth = parser.getDepth(); 19437 int type; 19438 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 19439 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 19440 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 19441 continue; 19442 } 19443 19444 final String tagName = parser.getName(); 19445 if (tagName.equals(TAG_GRANT)) { 19446 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 19447 if (DEBUG_BACKUP) { 19448 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 19449 } 19450 } else if (tagName.equals(TAG_PERMISSION)) { 19451 19452 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 19453 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 19454 19455 int newFlagSet = 0; 19456 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 19457 newFlagSet |= FLAG_PERMISSION_USER_SET; 19458 } 19459 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 19460 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 19461 } 19462 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 19463 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 19464 } 19465 if (DEBUG_BACKUP) { 19466 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 19467 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 19468 } 19469 final PackageSetting ps = mSettings.mPackages.get(pkgName); 19470 if (ps != null) { 19471 // Already installed so we apply the grant immediately 19472 if (DEBUG_BACKUP) { 19473 Slog.v(TAG, " + already installed; applying"); 19474 } 19475 PermissionsState perms = ps.getPermissionsState(); 19476 BasePermission bp = mSettings.mPermissions.get(permName); 19477 if (bp != null) { 19478 if (isGranted) { 19479 perms.grantRuntimePermission(bp, userId); 19480 } 19481 if (newFlagSet != 0) { 19482 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 19483 } 19484 } 19485 } else { 19486 // Need to wait for post-restore install to apply the grant 19487 if (DEBUG_BACKUP) { 19488 Slog.v(TAG, " - not yet installed; saving for later"); 19489 } 19490 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 19491 isGranted, newFlagSet, userId); 19492 } 19493 } else { 19494 PackageManagerService.reportSettingsProblem(Log.WARN, 19495 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 19496 XmlUtils.skipCurrentTag(parser); 19497 } 19498 } 19499 19500 scheduleWriteSettingsLocked(); 19501 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 19502 } 19503 19504 @Override 19505 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 19506 int sourceUserId, int targetUserId, int flags) { 19507 mContext.enforceCallingOrSelfPermission( 19508 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 19509 int callingUid = Binder.getCallingUid(); 19510 enforceOwnerRights(ownerPackage, callingUid); 19511 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 19512 if (intentFilter.countActions() == 0) { 19513 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 19514 return; 19515 } 19516 synchronized (mPackages) { 19517 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 19518 ownerPackage, targetUserId, flags); 19519 CrossProfileIntentResolver resolver = 19520 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 19521 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 19522 // We have all those whose filter is equal. Now checking if the rest is equal as well. 19523 if (existing != null) { 19524 int size = existing.size(); 19525 for (int i = 0; i < size; i++) { 19526 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 19527 return; 19528 } 19529 } 19530 } 19531 resolver.addFilter(newFilter); 19532 scheduleWritePackageRestrictionsLocked(sourceUserId); 19533 } 19534 } 19535 19536 @Override 19537 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 19538 mContext.enforceCallingOrSelfPermission( 19539 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 19540 int callingUid = Binder.getCallingUid(); 19541 enforceOwnerRights(ownerPackage, callingUid); 19542 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 19543 synchronized (mPackages) { 19544 CrossProfileIntentResolver resolver = 19545 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 19546 ArraySet<CrossProfileIntentFilter> set = 19547 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 19548 for (CrossProfileIntentFilter filter : set) { 19549 if (filter.getOwnerPackage().equals(ownerPackage)) { 19550 resolver.removeFilter(filter); 19551 } 19552 } 19553 scheduleWritePackageRestrictionsLocked(sourceUserId); 19554 } 19555 } 19556 19557 // Enforcing that callingUid is owning pkg on userId 19558 private void enforceOwnerRights(String pkg, int callingUid) { 19559 // The system owns everything. 19560 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 19561 return; 19562 } 19563 int callingUserId = UserHandle.getUserId(callingUid); 19564 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 19565 if (pi == null) { 19566 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 19567 + callingUserId); 19568 } 19569 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 19570 throw new SecurityException("Calling uid " + callingUid 19571 + " does not own package " + pkg); 19572 } 19573 } 19574 19575 @Override 19576 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 19577 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 19578 } 19579 19580 private Intent getHomeIntent() { 19581 Intent intent = new Intent(Intent.ACTION_MAIN); 19582 intent.addCategory(Intent.CATEGORY_HOME); 19583 intent.addCategory(Intent.CATEGORY_DEFAULT); 19584 return intent; 19585 } 19586 19587 private IntentFilter getHomeFilter() { 19588 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 19589 filter.addCategory(Intent.CATEGORY_HOME); 19590 filter.addCategory(Intent.CATEGORY_DEFAULT); 19591 return filter; 19592 } 19593 19594 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 19595 int userId) { 19596 Intent intent = getHomeIntent(); 19597 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 19598 PackageManager.GET_META_DATA, userId); 19599 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 19600 true, false, false, userId); 19601 19602 allHomeCandidates.clear(); 19603 if (list != null) { 19604 for (ResolveInfo ri : list) { 19605 allHomeCandidates.add(ri); 19606 } 19607 } 19608 return (preferred == null || preferred.activityInfo == null) 19609 ? null 19610 : new ComponentName(preferred.activityInfo.packageName, 19611 preferred.activityInfo.name); 19612 } 19613 19614 @Override 19615 public void setHomeActivity(ComponentName comp, int userId) { 19616 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 19617 getHomeActivitiesAsUser(homeActivities, userId); 19618 19619 boolean found = false; 19620 19621 final int size = homeActivities.size(); 19622 final ComponentName[] set = new ComponentName[size]; 19623 for (int i = 0; i < size; i++) { 19624 final ResolveInfo candidate = homeActivities.get(i); 19625 final ActivityInfo info = candidate.activityInfo; 19626 final ComponentName activityName = new ComponentName(info.packageName, info.name); 19627 set[i] = activityName; 19628 if (!found && activityName.equals(comp)) { 19629 found = true; 19630 } 19631 } 19632 if (!found) { 19633 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 19634 + userId); 19635 } 19636 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 19637 set, comp, userId); 19638 } 19639 19640 private @Nullable String getSetupWizardPackageName() { 19641 final Intent intent = new Intent(Intent.ACTION_MAIN); 19642 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 19643 19644 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 19645 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 19646 | MATCH_DISABLED_COMPONENTS, 19647 UserHandle.myUserId()); 19648 if (matches.size() == 1) { 19649 return matches.get(0).getComponentInfo().packageName; 19650 } else { 19651 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 19652 + ": matches=" + matches); 19653 return null; 19654 } 19655 } 19656 19657 private @Nullable String getStorageManagerPackageName() { 19658 final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE); 19659 19660 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 19661 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 19662 | MATCH_DISABLED_COMPONENTS, 19663 UserHandle.myUserId()); 19664 if (matches.size() == 1) { 19665 return matches.get(0).getComponentInfo().packageName; 19666 } else { 19667 Slog.e(TAG, "There should probably be exactly one storage manager; found " 19668 + matches.size() + ": matches=" + matches); 19669 return null; 19670 } 19671 } 19672 19673 @Override 19674 public void setApplicationEnabledSetting(String appPackageName, 19675 int newState, int flags, int userId, String callingPackage) { 19676 if (!sUserManager.exists(userId)) return; 19677 if (callingPackage == null) { 19678 callingPackage = Integer.toString(Binder.getCallingUid()); 19679 } 19680 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 19681 } 19682 19683 @Override 19684 public void setComponentEnabledSetting(ComponentName componentName, 19685 int newState, int flags, int userId) { 19686 if (!sUserManager.exists(userId)) return; 19687 setEnabledSetting(componentName.getPackageName(), 19688 componentName.getClassName(), newState, flags, userId, null); 19689 } 19690 19691 private void setEnabledSetting(final String packageName, String className, int newState, 19692 final int flags, int userId, String callingPackage) { 19693 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 19694 || newState == COMPONENT_ENABLED_STATE_ENABLED 19695 || newState == COMPONENT_ENABLED_STATE_DISABLED 19696 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 19697 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 19698 throw new IllegalArgumentException("Invalid new component state: " 19699 + newState); 19700 } 19701 PackageSetting pkgSetting; 19702 final int uid = Binder.getCallingUid(); 19703 final int permission; 19704 if (uid == Process.SYSTEM_UID) { 19705 permission = PackageManager.PERMISSION_GRANTED; 19706 } else { 19707 permission = mContext.checkCallingOrSelfPermission( 19708 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 19709 } 19710 enforceCrossUserPermission(uid, userId, 19711 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 19712 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 19713 boolean sendNow = false; 19714 boolean isApp = (className == null); 19715 String componentName = isApp ? packageName : className; 19716 int packageUid = -1; 19717 ArrayList<String> components; 19718 19719 // writer 19720 synchronized (mPackages) { 19721 pkgSetting = mSettings.mPackages.get(packageName); 19722 if (pkgSetting == null) { 19723 if (className == null) { 19724 throw new IllegalArgumentException("Unknown package: " + packageName); 19725 } 19726 throw new IllegalArgumentException( 19727 "Unknown component: " + packageName + "/" + className); 19728 } 19729 } 19730 19731 // Limit who can change which apps 19732 if (!UserHandle.isSameApp(uid, pkgSetting.appId)) { 19733 // Don't allow apps that don't have permission to modify other apps 19734 if (!allowedByPermission) { 19735 throw new SecurityException( 19736 "Permission Denial: attempt to change component state from pid=" 19737 + Binder.getCallingPid() 19738 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 19739 } 19740 // Don't allow changing protected packages. 19741 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 19742 throw new SecurityException("Cannot disable a protected package: " + packageName); 19743 } 19744 } 19745 19746 synchronized (mPackages) { 19747 if (uid == Process.SHELL_UID 19748 && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) { 19749 // Shell can only change whole packages between ENABLED and DISABLED_USER states 19750 // unless it is a test package. 19751 int oldState = pkgSetting.getEnabled(userId); 19752 if (className == null 19753 && 19754 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 19755 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 19756 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 19757 && 19758 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 19759 || newState == COMPONENT_ENABLED_STATE_DEFAULT 19760 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 19761 // ok 19762 } else { 19763 throw new SecurityException( 19764 "Shell cannot change component state for " + packageName + "/" 19765 + className + " to " + newState); 19766 } 19767 } 19768 if (className == null) { 19769 // We're dealing with an application/package level state change 19770 if (pkgSetting.getEnabled(userId) == newState) { 19771 // Nothing to do 19772 return; 19773 } 19774 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 19775 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 19776 // Don't care about who enables an app. 19777 callingPackage = null; 19778 } 19779 pkgSetting.setEnabled(newState, userId, callingPackage); 19780 // pkgSetting.pkg.mSetEnabled = newState; 19781 } else { 19782 // We're dealing with a component level state change 19783 // First, verify that this is a valid class name. 19784 PackageParser.Package pkg = pkgSetting.pkg; 19785 if (pkg == null || !pkg.hasComponentClassName(className)) { 19786 if (pkg != null && 19787 pkg.applicationInfo.targetSdkVersion >= 19788 Build.VERSION_CODES.JELLY_BEAN) { 19789 throw new IllegalArgumentException("Component class " + className 19790 + " does not exist in " + packageName); 19791 } else { 19792 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 19793 + className + " does not exist in " + packageName); 19794 } 19795 } 19796 switch (newState) { 19797 case COMPONENT_ENABLED_STATE_ENABLED: 19798 if (!pkgSetting.enableComponentLPw(className, userId)) { 19799 return; 19800 } 19801 break; 19802 case COMPONENT_ENABLED_STATE_DISABLED: 19803 if (!pkgSetting.disableComponentLPw(className, userId)) { 19804 return; 19805 } 19806 break; 19807 case COMPONENT_ENABLED_STATE_DEFAULT: 19808 if (!pkgSetting.restoreComponentLPw(className, userId)) { 19809 return; 19810 } 19811 break; 19812 default: 19813 Slog.e(TAG, "Invalid new component state: " + newState); 19814 return; 19815 } 19816 } 19817 scheduleWritePackageRestrictionsLocked(userId); 19818 updateSequenceNumberLP(packageName, new int[] { userId }); 19819 components = mPendingBroadcasts.get(userId, packageName); 19820 final boolean newPackage = components == null; 19821 if (newPackage) { 19822 components = new ArrayList<String>(); 19823 } 19824 if (!components.contains(componentName)) { 19825 components.add(componentName); 19826 } 19827 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 19828 sendNow = true; 19829 // Purge entry from pending broadcast list if another one exists already 19830 // since we are sending one right away. 19831 mPendingBroadcasts.remove(userId, packageName); 19832 } else { 19833 if (newPackage) { 19834 mPendingBroadcasts.put(userId, packageName, components); 19835 } 19836 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 19837 // Schedule a message 19838 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 19839 } 19840 } 19841 } 19842 19843 long callingId = Binder.clearCallingIdentity(); 19844 try { 19845 if (sendNow) { 19846 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 19847 sendPackageChangedBroadcast(packageName, 19848 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 19849 } 19850 } finally { 19851 Binder.restoreCallingIdentity(callingId); 19852 } 19853 } 19854 19855 @Override 19856 public void flushPackageRestrictionsAsUser(int userId) { 19857 if (!sUserManager.exists(userId)) { 19858 return; 19859 } 19860 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 19861 false /* checkShell */, "flushPackageRestrictions"); 19862 synchronized (mPackages) { 19863 mSettings.writePackageRestrictionsLPr(userId); 19864 mDirtyUsers.remove(userId); 19865 if (mDirtyUsers.isEmpty()) { 19866 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 19867 } 19868 } 19869 } 19870 19871 private void sendPackageChangedBroadcast(String packageName, 19872 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 19873 if (DEBUG_INSTALL) 19874 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 19875 + componentNames); 19876 Bundle extras = new Bundle(4); 19877 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 19878 String nameList[] = new String[componentNames.size()]; 19879 componentNames.toArray(nameList); 19880 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 19881 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 19882 extras.putInt(Intent.EXTRA_UID, packageUid); 19883 // If this is not reporting a change of the overall package, then only send it 19884 // to registered receivers. We don't want to launch a swath of apps for every 19885 // little component state change. 19886 final int flags = !componentNames.contains(packageName) 19887 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 19888 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 19889 new int[] {UserHandle.getUserId(packageUid)}); 19890 } 19891 19892 @Override 19893 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 19894 if (!sUserManager.exists(userId)) return; 19895 final int uid = Binder.getCallingUid(); 19896 final int permission = mContext.checkCallingOrSelfPermission( 19897 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 19898 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 19899 enforceCrossUserPermission(uid, userId, 19900 true /* requireFullPermission */, true /* checkShell */, "stop package"); 19901 // writer 19902 synchronized (mPackages) { 19903 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 19904 allowedByPermission, uid, userId)) { 19905 scheduleWritePackageRestrictionsLocked(userId); 19906 } 19907 } 19908 } 19909 19910 @Override 19911 public String getInstallerPackageName(String packageName) { 19912 // reader 19913 synchronized (mPackages) { 19914 return mSettings.getInstallerPackageNameLPr(packageName); 19915 } 19916 } 19917 19918 public boolean isOrphaned(String packageName) { 19919 // reader 19920 synchronized (mPackages) { 19921 return mSettings.isOrphaned(packageName); 19922 } 19923 } 19924 19925 @Override 19926 public int getApplicationEnabledSetting(String packageName, int userId) { 19927 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 19928 int uid = Binder.getCallingUid(); 19929 enforceCrossUserPermission(uid, userId, 19930 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 19931 // reader 19932 synchronized (mPackages) { 19933 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 19934 } 19935 } 19936 19937 @Override 19938 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 19939 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 19940 int uid = Binder.getCallingUid(); 19941 enforceCrossUserPermission(uid, userId, 19942 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 19943 // reader 19944 synchronized (mPackages) { 19945 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 19946 } 19947 } 19948 19949 @Override 19950 public void enterSafeMode() { 19951 enforceSystemOrRoot("Only the system can request entering safe mode"); 19952 19953 if (!mSystemReady) { 19954 mSafeMode = true; 19955 } 19956 } 19957 19958 @Override 19959 public void systemReady() { 19960 mSystemReady = true; 19961 19962 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 19963 // disabled after already being started. 19964 CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this, 19965 mContext.getContentResolver(), UserHandle.USER_SYSTEM); 19966 19967 // Read the compatibilty setting when the system is ready. 19968 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 19969 mContext.getContentResolver(), 19970 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 19971 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 19972 if (DEBUG_SETTINGS) { 19973 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 19974 } 19975 19976 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 19977 19978 synchronized (mPackages) { 19979 // Verify that all of the preferred activity components actually 19980 // exist. It is possible for applications to be updated and at 19981 // that point remove a previously declared activity component that 19982 // had been set as a preferred activity. We try to clean this up 19983 // the next time we encounter that preferred activity, but it is 19984 // possible for the user flow to never be able to return to that 19985 // situation so here we do a sanity check to make sure we haven't 19986 // left any junk around. 19987 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 19988 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 19989 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 19990 removed.clear(); 19991 for (PreferredActivity pa : pir.filterSet()) { 19992 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 19993 removed.add(pa); 19994 } 19995 } 19996 if (removed.size() > 0) { 19997 for (int r=0; r<removed.size(); r++) { 19998 PreferredActivity pa = removed.get(r); 19999 Slog.w(TAG, "Removing dangling preferred activity: " 20000 + pa.mPref.mComponent); 20001 pir.removeFilter(pa); 20002 } 20003 mSettings.writePackageRestrictionsLPr( 20004 mSettings.mPreferredActivities.keyAt(i)); 20005 } 20006 } 20007 20008 for (int userId : UserManagerService.getInstance().getUserIds()) { 20009 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 20010 grantPermissionsUserIds = ArrayUtils.appendInt( 20011 grantPermissionsUserIds, userId); 20012 } 20013 } 20014 } 20015 sUserManager.systemReady(); 20016 20017 // If we upgraded grant all default permissions before kicking off. 20018 for (int userId : grantPermissionsUserIds) { 20019 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 20020 } 20021 20022 // If we did not grant default permissions, we preload from this the 20023 // default permission exceptions lazily to ensure we don't hit the 20024 // disk on a new user creation. 20025 if (grantPermissionsUserIds == EMPTY_INT_ARRAY) { 20026 mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions(); 20027 } 20028 20029 // Kick off any messages waiting for system ready 20030 if (mPostSystemReadyMessages != null) { 20031 for (Message msg : mPostSystemReadyMessages) { 20032 msg.sendToTarget(); 20033 } 20034 mPostSystemReadyMessages = null; 20035 } 20036 20037 // Watch for external volumes that come and go over time 20038 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20039 storage.registerListener(mStorageListener); 20040 20041 mInstallerService.systemReady(); 20042 mPackageDexOptimizer.systemReady(); 20043 20044 StorageManagerInternal StorageManagerInternal = LocalServices.getService( 20045 StorageManagerInternal.class); 20046 StorageManagerInternal.addExternalStoragePolicy( 20047 new StorageManagerInternal.ExternalStorageMountPolicy() { 20048 @Override 20049 public int getMountMode(int uid, String packageName) { 20050 if (Process.isIsolated(uid)) { 20051 return Zygote.MOUNT_EXTERNAL_NONE; 20052 } 20053 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 20054 return Zygote.MOUNT_EXTERNAL_DEFAULT; 20055 } 20056 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 20057 return Zygote.MOUNT_EXTERNAL_DEFAULT; 20058 } 20059 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 20060 return Zygote.MOUNT_EXTERNAL_READ; 20061 } 20062 return Zygote.MOUNT_EXTERNAL_WRITE; 20063 } 20064 20065 @Override 20066 public boolean hasExternalStorage(int uid, String packageName) { 20067 return true; 20068 } 20069 }); 20070 20071 // Now that we're mostly running, clean up stale users and apps 20072 sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 20073 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 20074 20075 if (mPrivappPermissionsViolations != null) { 20076 Slog.wtf(TAG,"Signature|privileged permissions not in " 20077 + "privapp-permissions whitelist: " + mPrivappPermissionsViolations); 20078 mPrivappPermissionsViolations = null; 20079 } 20080 } 20081 20082 @Override 20083 public boolean isSafeMode() { 20084 return mSafeMode; 20085 } 20086 20087 @Override 20088 public boolean hasSystemUidErrors() { 20089 return mHasSystemUidErrors; 20090 } 20091 20092 static String arrayToString(int[] array) { 20093 StringBuffer buf = new StringBuffer(128); 20094 buf.append('['); 20095 if (array != null) { 20096 for (int i=0; i<array.length; i++) { 20097 if (i > 0) buf.append(", "); 20098 buf.append(array[i]); 20099 } 20100 } 20101 buf.append(']'); 20102 return buf.toString(); 20103 } 20104 20105 static class DumpState { 20106 public static final int DUMP_LIBS = 1 << 0; 20107 public static final int DUMP_FEATURES = 1 << 1; 20108 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 20109 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 20110 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 20111 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 20112 public static final int DUMP_PERMISSIONS = 1 << 6; 20113 public static final int DUMP_PACKAGES = 1 << 7; 20114 public static final int DUMP_SHARED_USERS = 1 << 8; 20115 public static final int DUMP_MESSAGES = 1 << 9; 20116 public static final int DUMP_PROVIDERS = 1 << 10; 20117 public static final int DUMP_VERIFIERS = 1 << 11; 20118 public static final int DUMP_PREFERRED = 1 << 12; 20119 public static final int DUMP_PREFERRED_XML = 1 << 13; 20120 public static final int DUMP_KEYSETS = 1 << 14; 20121 public static final int DUMP_VERSION = 1 << 15; 20122 public static final int DUMP_INSTALLS = 1 << 16; 20123 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 20124 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 20125 public static final int DUMP_FROZEN = 1 << 19; 20126 public static final int DUMP_DEXOPT = 1 << 20; 20127 public static final int DUMP_COMPILER_STATS = 1 << 21; 20128 20129 public static final int OPTION_SHOW_FILTERS = 1 << 0; 20130 20131 private int mTypes; 20132 20133 private int mOptions; 20134 20135 private boolean mTitlePrinted; 20136 20137 private SharedUserSetting mSharedUser; 20138 20139 public boolean isDumping(int type) { 20140 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 20141 return true; 20142 } 20143 20144 return (mTypes & type) != 0; 20145 } 20146 20147 public void setDump(int type) { 20148 mTypes |= type; 20149 } 20150 20151 public boolean isOptionEnabled(int option) { 20152 return (mOptions & option) != 0; 20153 } 20154 20155 public void setOptionEnabled(int option) { 20156 mOptions |= option; 20157 } 20158 20159 public boolean onTitlePrinted() { 20160 final boolean printed = mTitlePrinted; 20161 mTitlePrinted = true; 20162 return printed; 20163 } 20164 20165 public boolean getTitlePrinted() { 20166 return mTitlePrinted; 20167 } 20168 20169 public void setTitlePrinted(boolean enabled) { 20170 mTitlePrinted = enabled; 20171 } 20172 20173 public SharedUserSetting getSharedUser() { 20174 return mSharedUser; 20175 } 20176 20177 public void setSharedUser(SharedUserSetting user) { 20178 mSharedUser = user; 20179 } 20180 } 20181 20182 @Override 20183 public void onShellCommand(FileDescriptor in, FileDescriptor out, 20184 FileDescriptor err, String[] args, ShellCallback callback, 20185 ResultReceiver resultReceiver) { 20186 (new PackageManagerShellCommand(this)).exec( 20187 this, in, out, err, args, callback, resultReceiver); 20188 } 20189 20190 @Override 20191 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 20192 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 20193 != PackageManager.PERMISSION_GRANTED) { 20194 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 20195 + Binder.getCallingPid() 20196 + ", uid=" + Binder.getCallingUid() 20197 + " without permission " 20198 + android.Manifest.permission.DUMP); 20199 return; 20200 } 20201 20202 DumpState dumpState = new DumpState(); 20203 boolean fullPreferred = false; 20204 boolean checkin = false; 20205 20206 String packageName = null; 20207 ArraySet<String> permissionNames = null; 20208 20209 int opti = 0; 20210 while (opti < args.length) { 20211 String opt = args[opti]; 20212 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 20213 break; 20214 } 20215 opti++; 20216 20217 if ("-a".equals(opt)) { 20218 // Right now we only know how to print all. 20219 } else if ("-h".equals(opt)) { 20220 pw.println("Package manager dump options:"); 20221 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 20222 pw.println(" --checkin: dump for a checkin"); 20223 pw.println(" -f: print details of intent filters"); 20224 pw.println(" -h: print this help"); 20225 pw.println(" cmd may be one of:"); 20226 pw.println(" l[ibraries]: list known shared libraries"); 20227 pw.println(" f[eatures]: list device features"); 20228 pw.println(" k[eysets]: print known keysets"); 20229 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 20230 pw.println(" perm[issions]: dump permissions"); 20231 pw.println(" permission [name ...]: dump declaration and use of given permission"); 20232 pw.println(" pref[erred]: print preferred package settings"); 20233 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 20234 pw.println(" prov[iders]: dump content providers"); 20235 pw.println(" p[ackages]: dump installed packages"); 20236 pw.println(" s[hared-users]: dump shared user IDs"); 20237 pw.println(" m[essages]: print collected runtime messages"); 20238 pw.println(" v[erifiers]: print package verifier info"); 20239 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 20240 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 20241 pw.println(" version: print database version info"); 20242 pw.println(" write: write current settings now"); 20243 pw.println(" installs: details about install sessions"); 20244 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 20245 pw.println(" dexopt: dump dexopt state"); 20246 pw.println(" compiler-stats: dump compiler statistics"); 20247 pw.println(" <package.name>: info about given package"); 20248 return; 20249 } else if ("--checkin".equals(opt)) { 20250 checkin = true; 20251 } else if ("-f".equals(opt)) { 20252 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 20253 } else { 20254 pw.println("Unknown argument: " + opt + "; use -h for help"); 20255 } 20256 } 20257 20258 // Is the caller requesting to dump a particular piece of data? 20259 if (opti < args.length) { 20260 String cmd = args[opti]; 20261 opti++; 20262 // Is this a package name? 20263 if ("android".equals(cmd) || cmd.contains(".")) { 20264 packageName = cmd; 20265 // When dumping a single package, we always dump all of its 20266 // filter information since the amount of data will be reasonable. 20267 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 20268 } else if ("check-permission".equals(cmd)) { 20269 if (opti >= args.length) { 20270 pw.println("Error: check-permission missing permission argument"); 20271 return; 20272 } 20273 String perm = args[opti]; 20274 opti++; 20275 if (opti >= args.length) { 20276 pw.println("Error: check-permission missing package argument"); 20277 return; 20278 } 20279 20280 String pkg = args[opti]; 20281 opti++; 20282 int user = UserHandle.getUserId(Binder.getCallingUid()); 20283 if (opti < args.length) { 20284 try { 20285 user = Integer.parseInt(args[opti]); 20286 } catch (NumberFormatException e) { 20287 pw.println("Error: check-permission user argument is not a number: " 20288 + args[opti]); 20289 return; 20290 } 20291 } 20292 20293 // Normalize package name to handle renamed packages and static libs 20294 pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST); 20295 20296 pw.println(checkPermission(perm, pkg, user)); 20297 return; 20298 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 20299 dumpState.setDump(DumpState.DUMP_LIBS); 20300 } else if ("f".equals(cmd) || "features".equals(cmd)) { 20301 dumpState.setDump(DumpState.DUMP_FEATURES); 20302 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 20303 if (opti >= args.length) { 20304 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 20305 | DumpState.DUMP_SERVICE_RESOLVERS 20306 | DumpState.DUMP_RECEIVER_RESOLVERS 20307 | DumpState.DUMP_CONTENT_RESOLVERS); 20308 } else { 20309 while (opti < args.length) { 20310 String name = args[opti]; 20311 if ("a".equals(name) || "activity".equals(name)) { 20312 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 20313 } else if ("s".equals(name) || "service".equals(name)) { 20314 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 20315 } else if ("r".equals(name) || "receiver".equals(name)) { 20316 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 20317 } else if ("c".equals(name) || "content".equals(name)) { 20318 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 20319 } else { 20320 pw.println("Error: unknown resolver table type: " + name); 20321 return; 20322 } 20323 opti++; 20324 } 20325 } 20326 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 20327 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 20328 } else if ("permission".equals(cmd)) { 20329 if (opti >= args.length) { 20330 pw.println("Error: permission requires permission name"); 20331 return; 20332 } 20333 permissionNames = new ArraySet<>(); 20334 while (opti < args.length) { 20335 permissionNames.add(args[opti]); 20336 opti++; 20337 } 20338 dumpState.setDump(DumpState.DUMP_PERMISSIONS 20339 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 20340 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 20341 dumpState.setDump(DumpState.DUMP_PREFERRED); 20342 } else if ("preferred-xml".equals(cmd)) { 20343 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 20344 if (opti < args.length && "--full".equals(args[opti])) { 20345 fullPreferred = true; 20346 opti++; 20347 } 20348 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 20349 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 20350 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 20351 dumpState.setDump(DumpState.DUMP_PACKAGES); 20352 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 20353 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 20354 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 20355 dumpState.setDump(DumpState.DUMP_PROVIDERS); 20356 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 20357 dumpState.setDump(DumpState.DUMP_MESSAGES); 20358 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 20359 dumpState.setDump(DumpState.DUMP_VERIFIERS); 20360 } else if ("i".equals(cmd) || "ifv".equals(cmd) 20361 || "intent-filter-verifiers".equals(cmd)) { 20362 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 20363 } else if ("version".equals(cmd)) { 20364 dumpState.setDump(DumpState.DUMP_VERSION); 20365 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 20366 dumpState.setDump(DumpState.DUMP_KEYSETS); 20367 } else if ("installs".equals(cmd)) { 20368 dumpState.setDump(DumpState.DUMP_INSTALLS); 20369 } else if ("frozen".equals(cmd)) { 20370 dumpState.setDump(DumpState.DUMP_FROZEN); 20371 } else if ("dexopt".equals(cmd)) { 20372 dumpState.setDump(DumpState.DUMP_DEXOPT); 20373 } else if ("compiler-stats".equals(cmd)) { 20374 dumpState.setDump(DumpState.DUMP_COMPILER_STATS); 20375 } else if ("write".equals(cmd)) { 20376 synchronized (mPackages) { 20377 mSettings.writeLPr(); 20378 pw.println("Settings written."); 20379 return; 20380 } 20381 } 20382 } 20383 20384 if (checkin) { 20385 pw.println("vers,1"); 20386 } 20387 20388 // reader 20389 synchronized (mPackages) { 20390 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 20391 if (!checkin) { 20392 if (dumpState.onTitlePrinted()) 20393 pw.println(); 20394 pw.println("Database versions:"); 20395 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 20396 } 20397 } 20398 20399 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 20400 if (!checkin) { 20401 if (dumpState.onTitlePrinted()) 20402 pw.println(); 20403 pw.println("Verifiers:"); 20404 pw.print(" Required: "); 20405 pw.print(mRequiredVerifierPackage); 20406 pw.print(" (uid="); 20407 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 20408 UserHandle.USER_SYSTEM)); 20409 pw.println(")"); 20410 } else if (mRequiredVerifierPackage != null) { 20411 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 20412 pw.print(","); 20413 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 20414 UserHandle.USER_SYSTEM)); 20415 } 20416 } 20417 20418 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 20419 packageName == null) { 20420 if (mIntentFilterVerifierComponent != null) { 20421 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 20422 if (!checkin) { 20423 if (dumpState.onTitlePrinted()) 20424 pw.println(); 20425 pw.println("Intent Filter Verifier:"); 20426 pw.print(" Using: "); 20427 pw.print(verifierPackageName); 20428 pw.print(" (uid="); 20429 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 20430 UserHandle.USER_SYSTEM)); 20431 pw.println(")"); 20432 } else if (verifierPackageName != null) { 20433 pw.print("ifv,"); pw.print(verifierPackageName); 20434 pw.print(","); 20435 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 20436 UserHandle.USER_SYSTEM)); 20437 } 20438 } else { 20439 pw.println(); 20440 pw.println("No Intent Filter Verifier available!"); 20441 } 20442 } 20443 20444 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 20445 boolean printedHeader = false; 20446 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 20447 while (it.hasNext()) { 20448 String libName = it.next(); 20449 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName); 20450 if (versionedLib == null) { 20451 continue; 20452 } 20453 final int versionCount = versionedLib.size(); 20454 for (int i = 0; i < versionCount; i++) { 20455 SharedLibraryEntry libEntry = versionedLib.valueAt(i); 20456 if (!checkin) { 20457 if (!printedHeader) { 20458 if (dumpState.onTitlePrinted()) 20459 pw.println(); 20460 pw.println("Libraries:"); 20461 printedHeader = true; 20462 } 20463 pw.print(" "); 20464 } else { 20465 pw.print("lib,"); 20466 } 20467 pw.print(libEntry.info.getName()); 20468 if (libEntry.info.isStatic()) { 20469 pw.print(" version=" + libEntry.info.getVersion()); 20470 } 20471 if (!checkin) { 20472 pw.print(" -> "); 20473 } 20474 if (libEntry.path != null) { 20475 pw.print(" (jar) "); 20476 pw.print(libEntry.path); 20477 } else { 20478 pw.print(" (apk) "); 20479 pw.print(libEntry.apk); 20480 } 20481 pw.println(); 20482 } 20483 } 20484 } 20485 20486 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 20487 if (dumpState.onTitlePrinted()) 20488 pw.println(); 20489 if (!checkin) { 20490 pw.println("Features:"); 20491 } 20492 20493 synchronized (mAvailableFeatures) { 20494 for (FeatureInfo feat : mAvailableFeatures.values()) { 20495 if (checkin) { 20496 pw.print("feat,"); 20497 pw.print(feat.name); 20498 pw.print(","); 20499 pw.println(feat.version); 20500 } else { 20501 pw.print(" "); 20502 pw.print(feat.name); 20503 if (feat.version > 0) { 20504 pw.print(" version="); 20505 pw.print(feat.version); 20506 } 20507 pw.println(); 20508 } 20509 } 20510 } 20511 } 20512 20513 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 20514 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 20515 : "Activity Resolver Table:", " ", packageName, 20516 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20517 dumpState.setTitlePrinted(true); 20518 } 20519 } 20520 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 20521 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 20522 : "Receiver Resolver Table:", " ", packageName, 20523 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20524 dumpState.setTitlePrinted(true); 20525 } 20526 } 20527 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 20528 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 20529 : "Service Resolver Table:", " ", packageName, 20530 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20531 dumpState.setTitlePrinted(true); 20532 } 20533 } 20534 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 20535 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 20536 : "Provider Resolver Table:", " ", packageName, 20537 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20538 dumpState.setTitlePrinted(true); 20539 } 20540 } 20541 20542 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 20543 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 20544 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 20545 int user = mSettings.mPreferredActivities.keyAt(i); 20546 if (pir.dump(pw, 20547 dumpState.getTitlePrinted() 20548 ? "\nPreferred Activities User " + user + ":" 20549 : "Preferred Activities User " + user + ":", " ", 20550 packageName, true, false)) { 20551 dumpState.setTitlePrinted(true); 20552 } 20553 } 20554 } 20555 20556 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 20557 pw.flush(); 20558 FileOutputStream fout = new FileOutputStream(fd); 20559 BufferedOutputStream str = new BufferedOutputStream(fout); 20560 XmlSerializer serializer = new FastXmlSerializer(); 20561 try { 20562 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 20563 serializer.startDocument(null, true); 20564 serializer.setFeature( 20565 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 20566 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 20567 serializer.endDocument(); 20568 serializer.flush(); 20569 } catch (IllegalArgumentException e) { 20570 pw.println("Failed writing: " + e); 20571 } catch (IllegalStateException e) { 20572 pw.println("Failed writing: " + e); 20573 } catch (IOException e) { 20574 pw.println("Failed writing: " + e); 20575 } 20576 } 20577 20578 if (!checkin 20579 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 20580 && packageName == null) { 20581 pw.println(); 20582 int count = mSettings.mPackages.size(); 20583 if (count == 0) { 20584 pw.println("No applications!"); 20585 pw.println(); 20586 } else { 20587 final String prefix = " "; 20588 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 20589 if (allPackageSettings.size() == 0) { 20590 pw.println("No domain preferred apps!"); 20591 pw.println(); 20592 } else { 20593 pw.println("App verification status:"); 20594 pw.println(); 20595 count = 0; 20596 for (PackageSetting ps : allPackageSettings) { 20597 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 20598 if (ivi == null || ivi.getPackageName() == null) continue; 20599 pw.println(prefix + "Package: " + ivi.getPackageName()); 20600 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 20601 pw.println(prefix + "Status: " + ivi.getStatusString()); 20602 pw.println(); 20603 count++; 20604 } 20605 if (count == 0) { 20606 pw.println(prefix + "No app verification established."); 20607 pw.println(); 20608 } 20609 for (int userId : sUserManager.getUserIds()) { 20610 pw.println("App linkages for user " + userId + ":"); 20611 pw.println(); 20612 count = 0; 20613 for (PackageSetting ps : allPackageSettings) { 20614 final long status = ps.getDomainVerificationStatusForUser(userId); 20615 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 20616 && !DEBUG_DOMAIN_VERIFICATION) { 20617 continue; 20618 } 20619 pw.println(prefix + "Package: " + ps.name); 20620 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 20621 String statusStr = IntentFilterVerificationInfo. 20622 getStatusStringFromValue(status); 20623 pw.println(prefix + "Status: " + statusStr); 20624 pw.println(); 20625 count++; 20626 } 20627 if (count == 0) { 20628 pw.println(prefix + "No configured app linkages."); 20629 pw.println(); 20630 } 20631 } 20632 } 20633 } 20634 } 20635 20636 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 20637 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 20638 if (packageName == null && permissionNames == null) { 20639 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 20640 if (iperm == 0) { 20641 if (dumpState.onTitlePrinted()) 20642 pw.println(); 20643 pw.println("AppOp Permissions:"); 20644 } 20645 pw.print(" AppOp Permission "); 20646 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 20647 pw.println(":"); 20648 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 20649 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 20650 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 20651 } 20652 } 20653 } 20654 } 20655 20656 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 20657 boolean printedSomething = false; 20658 for (PackageParser.Provider p : mProviders.mProviders.values()) { 20659 if (packageName != null && !packageName.equals(p.info.packageName)) { 20660 continue; 20661 } 20662 if (!printedSomething) { 20663 if (dumpState.onTitlePrinted()) 20664 pw.println(); 20665 pw.println("Registered ContentProviders:"); 20666 printedSomething = true; 20667 } 20668 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 20669 pw.print(" "); pw.println(p.toString()); 20670 } 20671 printedSomething = false; 20672 for (Map.Entry<String, PackageParser.Provider> entry : 20673 mProvidersByAuthority.entrySet()) { 20674 PackageParser.Provider p = entry.getValue(); 20675 if (packageName != null && !packageName.equals(p.info.packageName)) { 20676 continue; 20677 } 20678 if (!printedSomething) { 20679 if (dumpState.onTitlePrinted()) 20680 pw.println(); 20681 pw.println("ContentProvider Authorities:"); 20682 printedSomething = true; 20683 } 20684 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 20685 pw.print(" "); pw.println(p.toString()); 20686 if (p.info != null && p.info.applicationInfo != null) { 20687 final String appInfo = p.info.applicationInfo.toString(); 20688 pw.print(" applicationInfo="); pw.println(appInfo); 20689 } 20690 } 20691 } 20692 20693 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 20694 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 20695 } 20696 20697 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 20698 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 20699 } 20700 20701 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 20702 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 20703 } 20704 20705 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 20706 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 20707 } 20708 20709 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 20710 // XXX should handle packageName != null by dumping only install data that 20711 // the given package is involved with. 20712 if (dumpState.onTitlePrinted()) pw.println(); 20713 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 20714 } 20715 20716 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 20717 // XXX should handle packageName != null by dumping only install data that 20718 // the given package is involved with. 20719 if (dumpState.onTitlePrinted()) pw.println(); 20720 20721 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 20722 ipw.println(); 20723 ipw.println("Frozen packages:"); 20724 ipw.increaseIndent(); 20725 if (mFrozenPackages.size() == 0) { 20726 ipw.println("(none)"); 20727 } else { 20728 for (int i = 0; i < mFrozenPackages.size(); i++) { 20729 ipw.println(mFrozenPackages.valueAt(i)); 20730 } 20731 } 20732 ipw.decreaseIndent(); 20733 } 20734 20735 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 20736 if (dumpState.onTitlePrinted()) pw.println(); 20737 dumpDexoptStateLPr(pw, packageName); 20738 } 20739 20740 if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) { 20741 if (dumpState.onTitlePrinted()) pw.println(); 20742 dumpCompilerStatsLPr(pw, packageName); 20743 } 20744 20745 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 20746 if (dumpState.onTitlePrinted()) pw.println(); 20747 mSettings.dumpReadMessagesLPr(pw, dumpState); 20748 20749 pw.println(); 20750 pw.println("Package warning messages:"); 20751 BufferedReader in = null; 20752 String line = null; 20753 try { 20754 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 20755 while ((line = in.readLine()) != null) { 20756 if (line.contains("ignored: updated version")) continue; 20757 pw.println(line); 20758 } 20759 } catch (IOException ignored) { 20760 } finally { 20761 IoUtils.closeQuietly(in); 20762 } 20763 } 20764 20765 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 20766 BufferedReader in = null; 20767 String line = null; 20768 try { 20769 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 20770 while ((line = in.readLine()) != null) { 20771 if (line.contains("ignored: updated version")) continue; 20772 pw.print("msg,"); 20773 pw.println(line); 20774 } 20775 } catch (IOException ignored) { 20776 } finally { 20777 IoUtils.closeQuietly(in); 20778 } 20779 } 20780 } 20781 } 20782 20783 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 20784 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 20785 ipw.println(); 20786 ipw.println("Dexopt state:"); 20787 ipw.increaseIndent(); 20788 Collection<PackageParser.Package> packages = null; 20789 if (packageName != null) { 20790 PackageParser.Package targetPackage = mPackages.get(packageName); 20791 if (targetPackage != null) { 20792 packages = Collections.singletonList(targetPackage); 20793 } else { 20794 ipw.println("Unable to find package: " + packageName); 20795 return; 20796 } 20797 } else { 20798 packages = mPackages.values(); 20799 } 20800 20801 for (PackageParser.Package pkg : packages) { 20802 ipw.println("[" + pkg.packageName + "]"); 20803 ipw.increaseIndent(); 20804 mPackageDexOptimizer.dumpDexoptState(ipw, pkg); 20805 ipw.decreaseIndent(); 20806 } 20807 } 20808 20809 private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) { 20810 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 20811 ipw.println(); 20812 ipw.println("Compiler stats:"); 20813 ipw.increaseIndent(); 20814 Collection<PackageParser.Package> packages = null; 20815 if (packageName != null) { 20816 PackageParser.Package targetPackage = mPackages.get(packageName); 20817 if (targetPackage != null) { 20818 packages = Collections.singletonList(targetPackage); 20819 } else { 20820 ipw.println("Unable to find package: " + packageName); 20821 return; 20822 } 20823 } else { 20824 packages = mPackages.values(); 20825 } 20826 20827 for (PackageParser.Package pkg : packages) { 20828 ipw.println("[" + pkg.packageName + "]"); 20829 ipw.increaseIndent(); 20830 20831 CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName); 20832 if (stats == null) { 20833 ipw.println("(No recorded stats)"); 20834 } else { 20835 stats.dump(ipw); 20836 } 20837 ipw.decreaseIndent(); 20838 } 20839 } 20840 20841 private String dumpDomainString(String packageName) { 20842 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 20843 .getList(); 20844 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 20845 20846 ArraySet<String> result = new ArraySet<>(); 20847 if (iviList.size() > 0) { 20848 for (IntentFilterVerificationInfo ivi : iviList) { 20849 for (String host : ivi.getDomains()) { 20850 result.add(host); 20851 } 20852 } 20853 } 20854 if (filters != null && filters.size() > 0) { 20855 for (IntentFilter filter : filters) { 20856 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 20857 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 20858 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 20859 result.addAll(filter.getHostsList()); 20860 } 20861 } 20862 } 20863 20864 StringBuilder sb = new StringBuilder(result.size() * 16); 20865 for (String domain : result) { 20866 if (sb.length() > 0) sb.append(" "); 20867 sb.append(domain); 20868 } 20869 return sb.toString(); 20870 } 20871 20872 // ------- apps on sdcard specific code ------- 20873 static final boolean DEBUG_SD_INSTALL = false; 20874 20875 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 20876 20877 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 20878 20879 private boolean mMediaMounted = false; 20880 20881 static String getEncryptKey() { 20882 try { 20883 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 20884 SD_ENCRYPTION_KEYSTORE_NAME); 20885 if (sdEncKey == null) { 20886 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 20887 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 20888 if (sdEncKey == null) { 20889 Slog.e(TAG, "Failed to create encryption keys"); 20890 return null; 20891 } 20892 } 20893 return sdEncKey; 20894 } catch (NoSuchAlgorithmException nsae) { 20895 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 20896 return null; 20897 } catch (IOException ioe) { 20898 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 20899 return null; 20900 } 20901 } 20902 20903 /* 20904 * Update media status on PackageManager. 20905 */ 20906 @Override 20907 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 20908 int callingUid = Binder.getCallingUid(); 20909 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 20910 throw new SecurityException("Media status can only be updated by the system"); 20911 } 20912 // reader; this apparently protects mMediaMounted, but should probably 20913 // be a different lock in that case. 20914 synchronized (mPackages) { 20915 Log.i(TAG, "Updating external media status from " 20916 + (mMediaMounted ? "mounted" : "unmounted") + " to " 20917 + (mediaStatus ? "mounted" : "unmounted")); 20918 if (DEBUG_SD_INSTALL) 20919 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 20920 + ", mMediaMounted=" + mMediaMounted); 20921 if (mediaStatus == mMediaMounted) { 20922 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 20923 : 0, -1); 20924 mHandler.sendMessage(msg); 20925 return; 20926 } 20927 mMediaMounted = mediaStatus; 20928 } 20929 // Queue up an async operation since the package installation may take a 20930 // little while. 20931 mHandler.post(new Runnable() { 20932 public void run() { 20933 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 20934 } 20935 }); 20936 } 20937 20938 /** 20939 * Called by StorageManagerService when the initial ASECs to scan are available. 20940 * Should block until all the ASEC containers are finished being scanned. 20941 */ 20942 public void scanAvailableAsecs() { 20943 updateExternalMediaStatusInner(true, false, false); 20944 } 20945 20946 /* 20947 * Collect information of applications on external media, map them against 20948 * existing containers and update information based on current mount status. 20949 * Please note that we always have to report status if reportStatus has been 20950 * set to true especially when unloading packages. 20951 */ 20952 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 20953 boolean externalStorage) { 20954 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 20955 int[] uidArr = EmptyArray.INT; 20956 20957 final String[] list = PackageHelper.getSecureContainerList(); 20958 if (ArrayUtils.isEmpty(list)) { 20959 Log.i(TAG, "No secure containers found"); 20960 } else { 20961 // Process list of secure containers and categorize them 20962 // as active or stale based on their package internal state. 20963 20964 // reader 20965 synchronized (mPackages) { 20966 for (String cid : list) { 20967 // Leave stages untouched for now; installer service owns them 20968 if (PackageInstallerService.isStageName(cid)) continue; 20969 20970 if (DEBUG_SD_INSTALL) 20971 Log.i(TAG, "Processing container " + cid); 20972 String pkgName = getAsecPackageName(cid); 20973 if (pkgName == null) { 20974 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 20975 continue; 20976 } 20977 if (DEBUG_SD_INSTALL) 20978 Log.i(TAG, "Looking for pkg : " + pkgName); 20979 20980 final PackageSetting ps = mSettings.mPackages.get(pkgName); 20981 if (ps == null) { 20982 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 20983 continue; 20984 } 20985 20986 /* 20987 * Skip packages that are not external if we're unmounting 20988 * external storage. 20989 */ 20990 if (externalStorage && !isMounted && !isExternal(ps)) { 20991 continue; 20992 } 20993 20994 final AsecInstallArgs args = new AsecInstallArgs(cid, 20995 getAppDexInstructionSets(ps), ps.isForwardLocked()); 20996 // The package status is changed only if the code path 20997 // matches between settings and the container id. 20998 if (ps.codePathString != null 20999 && ps.codePathString.startsWith(args.getCodePath())) { 21000 if (DEBUG_SD_INSTALL) { 21001 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 21002 + " at code path: " + ps.codePathString); 21003 } 21004 21005 // We do have a valid package installed on sdcard 21006 processCids.put(args, ps.codePathString); 21007 final int uid = ps.appId; 21008 if (uid != -1) { 21009 uidArr = ArrayUtils.appendInt(uidArr, uid); 21010 } 21011 } else { 21012 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 21013 + ps.codePathString); 21014 } 21015 } 21016 } 21017 21018 Arrays.sort(uidArr); 21019 } 21020 21021 // Process packages with valid entries. 21022 if (isMounted) { 21023 if (DEBUG_SD_INSTALL) 21024 Log.i(TAG, "Loading packages"); 21025 loadMediaPackages(processCids, uidArr, externalStorage); 21026 startCleaningPackages(); 21027 mInstallerService.onSecureContainersAvailable(); 21028 } else { 21029 if (DEBUG_SD_INSTALL) 21030 Log.i(TAG, "Unloading packages"); 21031 unloadMediaPackages(processCids, uidArr, reportStatus); 21032 } 21033 } 21034 21035 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21036 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 21037 final int size = infos.size(); 21038 final String[] packageNames = new String[size]; 21039 final int[] packageUids = new int[size]; 21040 for (int i = 0; i < size; i++) { 21041 final ApplicationInfo info = infos.get(i); 21042 packageNames[i] = info.packageName; 21043 packageUids[i] = info.uid; 21044 } 21045 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 21046 finishedReceiver); 21047 } 21048 21049 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21050 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 21051 sendResourcesChangedBroadcast(mediaStatus, replacing, 21052 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 21053 } 21054 21055 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21056 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 21057 int size = pkgList.length; 21058 if (size > 0) { 21059 // Send broadcasts here 21060 Bundle extras = new Bundle(); 21061 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 21062 if (uidArr != null) { 21063 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 21064 } 21065 if (replacing) { 21066 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 21067 } 21068 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 21069 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 21070 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 21071 } 21072 } 21073 21074 /* 21075 * Look at potentially valid container ids from processCids If package 21076 * information doesn't match the one on record or package scanning fails, 21077 * the cid is added to list of removeCids. We currently don't delete stale 21078 * containers. 21079 */ 21080 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 21081 boolean externalStorage) { 21082 ArrayList<String> pkgList = new ArrayList<String>(); 21083 Set<AsecInstallArgs> keys = processCids.keySet(); 21084 21085 for (AsecInstallArgs args : keys) { 21086 String codePath = processCids.get(args); 21087 if (DEBUG_SD_INSTALL) 21088 Log.i(TAG, "Loading container : " + args.cid); 21089 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 21090 try { 21091 // Make sure there are no container errors first. 21092 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 21093 Slog.e(TAG, "Failed to mount cid : " + args.cid 21094 + " when installing from sdcard"); 21095 continue; 21096 } 21097 // Check code path here. 21098 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 21099 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 21100 + " does not match one in settings " + codePath); 21101 continue; 21102 } 21103 // Parse package 21104 int parseFlags = mDefParseFlags; 21105 if (args.isExternalAsec()) { 21106 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 21107 } 21108 if (args.isFwdLocked()) { 21109 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 21110 } 21111 21112 synchronized (mInstallLock) { 21113 PackageParser.Package pkg = null; 21114 try { 21115 // Sadly we don't know the package name yet to freeze it 21116 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 21117 SCAN_IGNORE_FROZEN, 0, null); 21118 } catch (PackageManagerException e) { 21119 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 21120 } 21121 // Scan the package 21122 if (pkg != null) { 21123 /* 21124 * TODO why is the lock being held? doPostInstall is 21125 * called in other places without the lock. This needs 21126 * to be straightened out. 21127 */ 21128 // writer 21129 synchronized (mPackages) { 21130 retCode = PackageManager.INSTALL_SUCCEEDED; 21131 pkgList.add(pkg.packageName); 21132 // Post process args 21133 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 21134 pkg.applicationInfo.uid); 21135 } 21136 } else { 21137 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 21138 } 21139 } 21140 21141 } finally { 21142 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 21143 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 21144 } 21145 } 21146 } 21147 // writer 21148 synchronized (mPackages) { 21149 // If the platform SDK has changed since the last time we booted, 21150 // we need to re-grant app permission to catch any new ones that 21151 // appear. This is really a hack, and means that apps can in some 21152 // cases get permissions that the user didn't initially explicitly 21153 // allow... it would be nice to have some better way to handle 21154 // this situation. 21155 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 21156 : mSettings.getInternalVersion(); 21157 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 21158 : StorageManager.UUID_PRIVATE_INTERNAL; 21159 21160 int updateFlags = UPDATE_PERMISSIONS_ALL; 21161 if (ver.sdkVersion != mSdkVersion) { 21162 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 21163 + mSdkVersion + "; regranting permissions for external"); 21164 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 21165 } 21166 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 21167 21168 // Yay, everything is now upgraded 21169 ver.forceCurrent(); 21170 21171 // can downgrade to reader 21172 // Persist settings 21173 mSettings.writeLPr(); 21174 } 21175 // Send a broadcast to let everyone know we are done processing 21176 if (pkgList.size() > 0) { 21177 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 21178 } 21179 } 21180 21181 /* 21182 * Utility method to unload a list of specified containers 21183 */ 21184 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 21185 // Just unmount all valid containers. 21186 for (AsecInstallArgs arg : cidArgs) { 21187 synchronized (mInstallLock) { 21188 arg.doPostDeleteLI(false); 21189 } 21190 } 21191 } 21192 21193 /* 21194 * Unload packages mounted on external media. This involves deleting package 21195 * data from internal structures, sending broadcasts about disabled packages, 21196 * gc'ing to free up references, unmounting all secure containers 21197 * corresponding to packages on external media, and posting a 21198 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 21199 * that we always have to post this message if status has been requested no 21200 * matter what. 21201 */ 21202 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 21203 final boolean reportStatus) { 21204 if (DEBUG_SD_INSTALL) 21205 Log.i(TAG, "unloading media packages"); 21206 ArrayList<String> pkgList = new ArrayList<String>(); 21207 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 21208 final Set<AsecInstallArgs> keys = processCids.keySet(); 21209 for (AsecInstallArgs args : keys) { 21210 String pkgName = args.getPackageName(); 21211 if (DEBUG_SD_INSTALL) 21212 Log.i(TAG, "Trying to unload pkg : " + pkgName); 21213 // Delete package internally 21214 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 21215 synchronized (mInstallLock) { 21216 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 21217 final boolean res; 21218 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 21219 "unloadMediaPackages")) { 21220 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 21221 null); 21222 } 21223 if (res) { 21224 pkgList.add(pkgName); 21225 } else { 21226 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 21227 failedList.add(args); 21228 } 21229 } 21230 } 21231 21232 // reader 21233 synchronized (mPackages) { 21234 // We didn't update the settings after removing each package; 21235 // write them now for all packages. 21236 mSettings.writeLPr(); 21237 } 21238 21239 // We have to absolutely send UPDATED_MEDIA_STATUS only 21240 // after confirming that all the receivers processed the ordered 21241 // broadcast when packages get disabled, force a gc to clean things up. 21242 // and unload all the containers. 21243 if (pkgList.size() > 0) { 21244 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 21245 new IIntentReceiver.Stub() { 21246 public void performReceive(Intent intent, int resultCode, String data, 21247 Bundle extras, boolean ordered, boolean sticky, 21248 int sendingUser) throws RemoteException { 21249 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 21250 reportStatus ? 1 : 0, 1, keys); 21251 mHandler.sendMessage(msg); 21252 } 21253 }); 21254 } else { 21255 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 21256 keys); 21257 mHandler.sendMessage(msg); 21258 } 21259 } 21260 21261 private void loadPrivatePackages(final VolumeInfo vol) { 21262 mHandler.post(new Runnable() { 21263 @Override 21264 public void run() { 21265 loadPrivatePackagesInner(vol); 21266 } 21267 }); 21268 } 21269 21270 private void loadPrivatePackagesInner(VolumeInfo vol) { 21271 final String volumeUuid = vol.fsUuid; 21272 if (TextUtils.isEmpty(volumeUuid)) { 21273 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 21274 return; 21275 } 21276 21277 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 21278 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 21279 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 21280 21281 final VersionInfo ver; 21282 final List<PackageSetting> packages; 21283 synchronized (mPackages) { 21284 ver = mSettings.findOrCreateVersion(volumeUuid); 21285 packages = mSettings.getVolumePackagesLPr(volumeUuid); 21286 } 21287 21288 for (PackageSetting ps : packages) { 21289 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 21290 synchronized (mInstallLock) { 21291 final PackageParser.Package pkg; 21292 try { 21293 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 21294 loaded.add(pkg.applicationInfo); 21295 21296 } catch (PackageManagerException e) { 21297 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 21298 } 21299 21300 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 21301 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 21302 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 21303 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 21304 } 21305 } 21306 } 21307 21308 // Reconcile app data for all started/unlocked users 21309 final StorageManager sm = mContext.getSystemService(StorageManager.class); 21310 final UserManager um = mContext.getSystemService(UserManager.class); 21311 UserManagerInternal umInternal = getUserManagerInternal(); 21312 for (UserInfo user : um.getUsers()) { 21313 final int flags; 21314 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 21315 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 21316 } else if (umInternal.isUserRunning(user.id)) { 21317 flags = StorageManager.FLAG_STORAGE_DE; 21318 } else { 21319 continue; 21320 } 21321 21322 try { 21323 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 21324 synchronized (mInstallLock) { 21325 reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */); 21326 } 21327 } catch (IllegalStateException e) { 21328 // Device was probably ejected, and we'll process that event momentarily 21329 Slog.w(TAG, "Failed to prepare storage: " + e); 21330 } 21331 } 21332 21333 synchronized (mPackages) { 21334 int updateFlags = UPDATE_PERMISSIONS_ALL; 21335 if (ver.sdkVersion != mSdkVersion) { 21336 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 21337 + mSdkVersion + "; regranting permissions for " + volumeUuid); 21338 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 21339 } 21340 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 21341 21342 // Yay, everything is now upgraded 21343 ver.forceCurrent(); 21344 21345 mSettings.writeLPr(); 21346 } 21347 21348 for (PackageFreezer freezer : freezers) { 21349 freezer.close(); 21350 } 21351 21352 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 21353 sendResourcesChangedBroadcast(true, false, loaded, null); 21354 } 21355 21356 private void unloadPrivatePackages(final VolumeInfo vol) { 21357 mHandler.post(new Runnable() { 21358 @Override 21359 public void run() { 21360 unloadPrivatePackagesInner(vol); 21361 } 21362 }); 21363 } 21364 21365 private void unloadPrivatePackagesInner(VolumeInfo vol) { 21366 final String volumeUuid = vol.fsUuid; 21367 if (TextUtils.isEmpty(volumeUuid)) { 21368 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 21369 return; 21370 } 21371 21372 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 21373 synchronized (mInstallLock) { 21374 synchronized (mPackages) { 21375 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 21376 for (PackageSetting ps : packages) { 21377 if (ps.pkg == null) continue; 21378 21379 final ApplicationInfo info = ps.pkg.applicationInfo; 21380 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 21381 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 21382 21383 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 21384 "unloadPrivatePackagesInner")) { 21385 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 21386 false, null)) { 21387 unloaded.add(info); 21388 } else { 21389 Slog.w(TAG, "Failed to unload " + ps.codePath); 21390 } 21391 } 21392 21393 // Try very hard to release any references to this package 21394 // so we don't risk the system server being killed due to 21395 // open FDs 21396 AttributeCache.instance().removePackage(ps.name); 21397 } 21398 21399 mSettings.writeLPr(); 21400 } 21401 } 21402 21403 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 21404 sendResourcesChangedBroadcast(false, false, unloaded, null); 21405 21406 // Try very hard to release any references to this path so we don't risk 21407 // the system server being killed due to open FDs 21408 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 21409 21410 for (int i = 0; i < 3; i++) { 21411 System.gc(); 21412 System.runFinalization(); 21413 } 21414 } 21415 21416 private void assertPackageKnown(String volumeUuid, String packageName) 21417 throws PackageManagerException { 21418 synchronized (mPackages) { 21419 // Normalize package name to handle renamed packages 21420 packageName = normalizePackageNameLPr(packageName); 21421 21422 final PackageSetting ps = mSettings.mPackages.get(packageName); 21423 if (ps == null) { 21424 throw new PackageManagerException("Package " + packageName + " is unknown"); 21425 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 21426 throw new PackageManagerException( 21427 "Package " + packageName + " found on unknown volume " + volumeUuid 21428 + "; expected volume " + ps.volumeUuid); 21429 } 21430 } 21431 } 21432 21433 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 21434 throws PackageManagerException { 21435 synchronized (mPackages) { 21436 // Normalize package name to handle renamed packages 21437 packageName = normalizePackageNameLPr(packageName); 21438 21439 final PackageSetting ps = mSettings.mPackages.get(packageName); 21440 if (ps == null) { 21441 throw new PackageManagerException("Package " + packageName + " is unknown"); 21442 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 21443 throw new PackageManagerException( 21444 "Package " + packageName + " found on unknown volume " + volumeUuid 21445 + "; expected volume " + ps.volumeUuid); 21446 } else if (!ps.getInstalled(userId)) { 21447 throw new PackageManagerException( 21448 "Package " + packageName + " not installed for user " + userId); 21449 } 21450 } 21451 } 21452 21453 private List<String> collectAbsoluteCodePaths() { 21454 synchronized (mPackages) { 21455 List<String> codePaths = new ArrayList<>(); 21456 final int packageCount = mSettings.mPackages.size(); 21457 for (int i = 0; i < packageCount; i++) { 21458 final PackageSetting ps = mSettings.mPackages.valueAt(i); 21459 codePaths.add(ps.codePath.getAbsolutePath()); 21460 } 21461 return codePaths; 21462 } 21463 } 21464 21465 /** 21466 * Examine all apps present on given mounted volume, and destroy apps that 21467 * aren't expected, either due to uninstallation or reinstallation on 21468 * another volume. 21469 */ 21470 private void reconcileApps(String volumeUuid) { 21471 List<String> absoluteCodePaths = collectAbsoluteCodePaths(); 21472 List<File> filesToDelete = null; 21473 21474 final File[] files = FileUtils.listFilesOrEmpty( 21475 Environment.getDataAppDirectory(volumeUuid)); 21476 for (File file : files) { 21477 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 21478 && !PackageInstallerService.isStageName(file.getName()); 21479 if (!isPackage) { 21480 // Ignore entries which are not packages 21481 continue; 21482 } 21483 21484 String absolutePath = file.getAbsolutePath(); 21485 21486 boolean pathValid = false; 21487 final int absoluteCodePathCount = absoluteCodePaths.size(); 21488 for (int i = 0; i < absoluteCodePathCount; i++) { 21489 String absoluteCodePath = absoluteCodePaths.get(i); 21490 if (absolutePath.startsWith(absoluteCodePath)) { 21491 pathValid = true; 21492 break; 21493 } 21494 } 21495 21496 if (!pathValid) { 21497 if (filesToDelete == null) { 21498 filesToDelete = new ArrayList<>(); 21499 } 21500 filesToDelete.add(file); 21501 } 21502 } 21503 21504 if (filesToDelete != null) { 21505 final int fileToDeleteCount = filesToDelete.size(); 21506 for (int i = 0; i < fileToDeleteCount; i++) { 21507 File fileToDelete = filesToDelete.get(i); 21508 logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete); 21509 synchronized (mInstallLock) { 21510 removeCodePathLI(fileToDelete); 21511 } 21512 } 21513 } 21514 } 21515 21516 /** 21517 * Reconcile all app data for the given user. 21518 * <p> 21519 * Verifies that directories exist and that ownership and labeling is 21520 * correct for all installed apps on all mounted volumes. 21521 */ 21522 void reconcileAppsData(int userId, int flags, boolean migrateAppsData) { 21523 final StorageManager storage = mContext.getSystemService(StorageManager.class); 21524 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 21525 final String volumeUuid = vol.getFsUuid(); 21526 synchronized (mInstallLock) { 21527 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData); 21528 } 21529 } 21530 } 21531 21532 /** 21533 * Reconcile all app data on given mounted volume. 21534 * <p> 21535 * Destroys app data that isn't expected, either due to uninstallation or 21536 * reinstallation on another volume. 21537 * <p> 21538 * Verifies that directories exist and that ownership and labeling is 21539 * correct for all installed apps. 21540 */ 21541 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags, 21542 boolean migrateAppData) { 21543 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 21544 + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData); 21545 21546 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 21547 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 21548 21549 // First look for stale data that doesn't belong, and check if things 21550 // have changed since we did our last restorecon 21551 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 21552 if (StorageManager.isFileEncryptedNativeOrEmulated() 21553 && !StorageManager.isUserKeyUnlocked(userId)) { 21554 throw new RuntimeException( 21555 "Yikes, someone asked us to reconcile CE storage while " + userId 21556 + " was still locked; this would have caused massive data loss!"); 21557 } 21558 21559 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 21560 for (File file : files) { 21561 final String packageName = file.getName(); 21562 try { 21563 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 21564 } catch (PackageManagerException e) { 21565 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 21566 try { 21567 mInstaller.destroyAppData(volumeUuid, packageName, userId, 21568 StorageManager.FLAG_STORAGE_CE, 0); 21569 } catch (InstallerException e2) { 21570 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 21571 } 21572 } 21573 } 21574 } 21575 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 21576 final File[] files = FileUtils.listFilesOrEmpty(deDir); 21577 for (File file : files) { 21578 final String packageName = file.getName(); 21579 try { 21580 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 21581 } catch (PackageManagerException e) { 21582 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 21583 try { 21584 mInstaller.destroyAppData(volumeUuid, packageName, userId, 21585 StorageManager.FLAG_STORAGE_DE, 0); 21586 } catch (InstallerException e2) { 21587 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 21588 } 21589 } 21590 } 21591 } 21592 21593 // Ensure that data directories are ready to roll for all packages 21594 // installed for this volume and user 21595 final List<PackageSetting> packages; 21596 synchronized (mPackages) { 21597 packages = mSettings.getVolumePackagesLPr(volumeUuid); 21598 } 21599 int preparedCount = 0; 21600 for (PackageSetting ps : packages) { 21601 final String packageName = ps.name; 21602 if (ps.pkg == null) { 21603 Slog.w(TAG, "Odd, missing scanned package " + packageName); 21604 // TODO: might be due to legacy ASEC apps; we should circle back 21605 // and reconcile again once they're scanned 21606 continue; 21607 } 21608 21609 if (ps.getInstalled(userId)) { 21610 prepareAppDataLIF(ps.pkg, userId, flags); 21611 21612 if (migrateAppData && maybeMigrateAppDataLIF(ps.pkg, userId)) { 21613 // We may have just shuffled around app data directories, so 21614 // prepare them one more time 21615 prepareAppDataLIF(ps.pkg, userId, flags); 21616 } 21617 21618 preparedCount++; 21619 } 21620 } 21621 21622 Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages"); 21623 } 21624 21625 /** 21626 * Prepare app data for the given app just after it was installed or 21627 * upgraded. This method carefully only touches users that it's installed 21628 * for, and it forces a restorecon to handle any seinfo changes. 21629 * <p> 21630 * Verifies that directories exist and that ownership and labeling is 21631 * correct for all installed apps. If there is an ownership mismatch, it 21632 * will try recovering system apps by wiping data; third-party app data is 21633 * left intact. 21634 * <p> 21635 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 21636 */ 21637 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 21638 final PackageSetting ps; 21639 synchronized (mPackages) { 21640 ps = mSettings.mPackages.get(pkg.packageName); 21641 mSettings.writeKernelMappingLPr(ps); 21642 } 21643 21644 final UserManager um = mContext.getSystemService(UserManager.class); 21645 UserManagerInternal umInternal = getUserManagerInternal(); 21646 for (UserInfo user : um.getUsers()) { 21647 final int flags; 21648 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 21649 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 21650 } else if (umInternal.isUserRunning(user.id)) { 21651 flags = StorageManager.FLAG_STORAGE_DE; 21652 } else { 21653 continue; 21654 } 21655 21656 if (ps.getInstalled(user.id)) { 21657 // TODO: when user data is locked, mark that we're still dirty 21658 prepareAppDataLIF(pkg, user.id, flags); 21659 } 21660 } 21661 } 21662 21663 /** 21664 * Prepare app data for the given app. 21665 * <p> 21666 * Verifies that directories exist and that ownership and labeling is 21667 * correct for all installed apps. If there is an ownership mismatch, this 21668 * will try recovering system apps by wiping data; third-party app data is 21669 * left intact. 21670 */ 21671 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 21672 if (pkg == null) { 21673 Slog.wtf(TAG, "Package was null!", new Throwable()); 21674 return; 21675 } 21676 prepareAppDataLeafLIF(pkg, userId, flags); 21677 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 21678 for (int i = 0; i < childCount; i++) { 21679 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 21680 } 21681 } 21682 21683 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 21684 if (DEBUG_APP_DATA) { 21685 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 21686 + Integer.toHexString(flags)); 21687 } 21688 21689 final String volumeUuid = pkg.volumeUuid; 21690 final String packageName = pkg.packageName; 21691 final ApplicationInfo app = pkg.applicationInfo; 21692 final int appId = UserHandle.getAppId(app.uid); 21693 21694 Preconditions.checkNotNull(app.seinfo); 21695 21696 long ceDataInode = -1; 21697 try { 21698 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 21699 appId, app.seinfo, app.targetSdkVersion); 21700 } catch (InstallerException e) { 21701 if (app.isSystemApp()) { 21702 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 21703 + ", but trying to recover: " + e); 21704 destroyAppDataLeafLIF(pkg, userId, flags); 21705 try { 21706 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 21707 appId, app.seinfo, app.targetSdkVersion); 21708 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 21709 } catch (InstallerException e2) { 21710 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 21711 } 21712 } else { 21713 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 21714 } 21715 } 21716 21717 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) { 21718 // TODO: mark this structure as dirty so we persist it! 21719 synchronized (mPackages) { 21720 final PackageSetting ps = mSettings.mPackages.get(packageName); 21721 if (ps != null) { 21722 ps.setCeDataInode(ceDataInode, userId); 21723 } 21724 } 21725 } 21726 21727 prepareAppDataContentsLeafLIF(pkg, userId, flags); 21728 } 21729 21730 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 21731 if (pkg == null) { 21732 Slog.wtf(TAG, "Package was null!", new Throwable()); 21733 return; 21734 } 21735 prepareAppDataContentsLeafLIF(pkg, userId, flags); 21736 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 21737 for (int i = 0; i < childCount; i++) { 21738 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 21739 } 21740 } 21741 21742 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 21743 final String volumeUuid = pkg.volumeUuid; 21744 final String packageName = pkg.packageName; 21745 final ApplicationInfo app = pkg.applicationInfo; 21746 21747 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 21748 // Create a native library symlink only if we have native libraries 21749 // and if the native libraries are 32 bit libraries. We do not provide 21750 // this symlink for 64 bit libraries. 21751 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 21752 final String nativeLibPath = app.nativeLibraryDir; 21753 try { 21754 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 21755 nativeLibPath, userId); 21756 } catch (InstallerException e) { 21757 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 21758 } 21759 } 21760 } 21761 } 21762 21763 /** 21764 * For system apps on non-FBE devices, this method migrates any existing 21765 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 21766 * requested by the app. 21767 */ 21768 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 21769 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 21770 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 21771 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 21772 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 21773 try { 21774 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 21775 storageTarget); 21776 } catch (InstallerException e) { 21777 logCriticalInfo(Log.WARN, 21778 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 21779 } 21780 return true; 21781 } else { 21782 return false; 21783 } 21784 } 21785 21786 public PackageFreezer freezePackage(String packageName, String killReason) { 21787 return freezePackage(packageName, UserHandle.USER_ALL, killReason); 21788 } 21789 21790 public PackageFreezer freezePackage(String packageName, int userId, String killReason) { 21791 return new PackageFreezer(packageName, userId, killReason); 21792 } 21793 21794 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 21795 String killReason) { 21796 return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason); 21797 } 21798 21799 public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags, 21800 String killReason) { 21801 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 21802 return new PackageFreezer(); 21803 } else { 21804 return freezePackage(packageName, userId, killReason); 21805 } 21806 } 21807 21808 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 21809 String killReason) { 21810 return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason); 21811 } 21812 21813 public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags, 21814 String killReason) { 21815 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 21816 return new PackageFreezer(); 21817 } else { 21818 return freezePackage(packageName, userId, killReason); 21819 } 21820 } 21821 21822 /** 21823 * Class that freezes and kills the given package upon creation, and 21824 * unfreezes it upon closing. This is typically used when doing surgery on 21825 * app code/data to prevent the app from running while you're working. 21826 */ 21827 private class PackageFreezer implements AutoCloseable { 21828 private final String mPackageName; 21829 private final PackageFreezer[] mChildren; 21830 21831 private final boolean mWeFroze; 21832 21833 private final AtomicBoolean mClosed = new AtomicBoolean(); 21834 private final CloseGuard mCloseGuard = CloseGuard.get(); 21835 21836 /** 21837 * Create and return a stub freezer that doesn't actually do anything, 21838 * typically used when someone requested 21839 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 21840 * {@link PackageManager#DELETE_DONT_KILL_APP}. 21841 */ 21842 public PackageFreezer() { 21843 mPackageName = null; 21844 mChildren = null; 21845 mWeFroze = false; 21846 mCloseGuard.open("close"); 21847 } 21848 21849 public PackageFreezer(String packageName, int userId, String killReason) { 21850 synchronized (mPackages) { 21851 mPackageName = packageName; 21852 mWeFroze = mFrozenPackages.add(mPackageName); 21853 21854 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 21855 if (ps != null) { 21856 killApplication(ps.name, ps.appId, userId, killReason); 21857 } 21858 21859 final PackageParser.Package p = mPackages.get(packageName); 21860 if (p != null && p.childPackages != null) { 21861 final int N = p.childPackages.size(); 21862 mChildren = new PackageFreezer[N]; 21863 for (int i = 0; i < N; i++) { 21864 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 21865 userId, killReason); 21866 } 21867 } else { 21868 mChildren = null; 21869 } 21870 } 21871 mCloseGuard.open("close"); 21872 } 21873 21874 @Override 21875 protected void finalize() throws Throwable { 21876 try { 21877 mCloseGuard.warnIfOpen(); 21878 close(); 21879 } finally { 21880 super.finalize(); 21881 } 21882 } 21883 21884 @Override 21885 public void close() { 21886 mCloseGuard.close(); 21887 if (mClosed.compareAndSet(false, true)) { 21888 synchronized (mPackages) { 21889 if (mWeFroze) { 21890 mFrozenPackages.remove(mPackageName); 21891 } 21892 21893 if (mChildren != null) { 21894 for (PackageFreezer freezer : mChildren) { 21895 freezer.close(); 21896 } 21897 } 21898 } 21899 } 21900 } 21901 } 21902 21903 /** 21904 * Verify that given package is currently frozen. 21905 */ 21906 private void checkPackageFrozen(String packageName) { 21907 synchronized (mPackages) { 21908 if (!mFrozenPackages.contains(packageName)) { 21909 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 21910 } 21911 } 21912 } 21913 21914 @Override 21915 public int movePackage(final String packageName, final String volumeUuid) { 21916 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 21917 21918 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 21919 final int moveId = mNextMoveId.getAndIncrement(); 21920 mHandler.post(new Runnable() { 21921 @Override 21922 public void run() { 21923 try { 21924 movePackageInternal(packageName, volumeUuid, moveId, user); 21925 } catch (PackageManagerException e) { 21926 Slog.w(TAG, "Failed to move " + packageName, e); 21927 mMoveCallbacks.notifyStatusChanged(moveId, 21928 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 21929 } 21930 } 21931 }); 21932 return moveId; 21933 } 21934 21935 private void movePackageInternal(final String packageName, final String volumeUuid, 21936 final int moveId, UserHandle user) throws PackageManagerException { 21937 final StorageManager storage = mContext.getSystemService(StorageManager.class); 21938 final PackageManager pm = mContext.getPackageManager(); 21939 21940 final boolean currentAsec; 21941 final String currentVolumeUuid; 21942 final File codeFile; 21943 final String installerPackageName; 21944 final String packageAbiOverride; 21945 final int appId; 21946 final String seinfo; 21947 final String label; 21948 final int targetSdkVersion; 21949 final PackageFreezer freezer; 21950 final int[] installedUserIds; 21951 21952 // reader 21953 synchronized (mPackages) { 21954 final PackageParser.Package pkg = mPackages.get(packageName); 21955 final PackageSetting ps = mSettings.mPackages.get(packageName); 21956 if (pkg == null || ps == null) { 21957 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 21958 } 21959 21960 if (pkg.applicationInfo.isSystemApp()) { 21961 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 21962 "Cannot move system application"); 21963 } 21964 21965 final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid); 21966 final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean( 21967 com.android.internal.R.bool.config_allow3rdPartyAppOnInternal); 21968 if (isInternalStorage && !allow3rdPartyOnInternal) { 21969 throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL, 21970 "3rd party apps are not allowed on internal storage"); 21971 } 21972 21973 if (pkg.applicationInfo.isExternalAsec()) { 21974 currentAsec = true; 21975 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 21976 } else if (pkg.applicationInfo.isForwardLocked()) { 21977 currentAsec = true; 21978 currentVolumeUuid = "forward_locked"; 21979 } else { 21980 currentAsec = false; 21981 currentVolumeUuid = ps.volumeUuid; 21982 21983 final File probe = new File(pkg.codePath); 21984 final File probeOat = new File(probe, "oat"); 21985 if (!probe.isDirectory() || !probeOat.isDirectory()) { 21986 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 21987 "Move only supported for modern cluster style installs"); 21988 } 21989 } 21990 21991 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 21992 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 21993 "Package already moved to " + volumeUuid); 21994 } 21995 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 21996 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 21997 "Device admin cannot be moved"); 21998 } 21999 22000 if (mFrozenPackages.contains(packageName)) { 22001 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 22002 "Failed to move already frozen package"); 22003 } 22004 22005 codeFile = new File(pkg.codePath); 22006 installerPackageName = ps.installerPackageName; 22007 packageAbiOverride = ps.cpuAbiOverrideString; 22008 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 22009 seinfo = pkg.applicationInfo.seinfo; 22010 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 22011 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 22012 freezer = freezePackage(packageName, "movePackageInternal"); 22013 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 22014 } 22015 22016 final Bundle extras = new Bundle(); 22017 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 22018 extras.putString(Intent.EXTRA_TITLE, label); 22019 mMoveCallbacks.notifyCreated(moveId, extras); 22020 22021 int installFlags; 22022 final boolean moveCompleteApp; 22023 final File measurePath; 22024 22025 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 22026 installFlags = INSTALL_INTERNAL; 22027 moveCompleteApp = !currentAsec; 22028 measurePath = Environment.getDataAppDirectory(volumeUuid); 22029 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 22030 installFlags = INSTALL_EXTERNAL; 22031 moveCompleteApp = false; 22032 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 22033 } else { 22034 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 22035 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 22036 || !volume.isMountedWritable()) { 22037 freezer.close(); 22038 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22039 "Move location not mounted private volume"); 22040 } 22041 22042 Preconditions.checkState(!currentAsec); 22043 22044 installFlags = INSTALL_INTERNAL; 22045 moveCompleteApp = true; 22046 measurePath = Environment.getDataAppDirectory(volumeUuid); 22047 } 22048 22049 final PackageStats stats = new PackageStats(null, -1); 22050 synchronized (mInstaller) { 22051 for (int userId : installedUserIds) { 22052 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 22053 freezer.close(); 22054 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22055 "Failed to measure package size"); 22056 } 22057 } 22058 } 22059 22060 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 22061 + stats.dataSize); 22062 22063 final long startFreeBytes = measurePath.getFreeSpace(); 22064 final long sizeBytes; 22065 if (moveCompleteApp) { 22066 sizeBytes = stats.codeSize + stats.dataSize; 22067 } else { 22068 sizeBytes = stats.codeSize; 22069 } 22070 22071 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 22072 freezer.close(); 22073 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22074 "Not enough free space to move"); 22075 } 22076 22077 mMoveCallbacks.notifyStatusChanged(moveId, 10); 22078 22079 final CountDownLatch installedLatch = new CountDownLatch(1); 22080 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 22081 @Override 22082 public void onUserActionRequired(Intent intent) throws RemoteException { 22083 throw new IllegalStateException(); 22084 } 22085 22086 @Override 22087 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 22088 Bundle extras) throws RemoteException { 22089 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 22090 + PackageManager.installStatusToString(returnCode, msg)); 22091 22092 installedLatch.countDown(); 22093 freezer.close(); 22094 22095 final int status = PackageManager.installStatusToPublicStatus(returnCode); 22096 switch (status) { 22097 case PackageInstaller.STATUS_SUCCESS: 22098 mMoveCallbacks.notifyStatusChanged(moveId, 22099 PackageManager.MOVE_SUCCEEDED); 22100 break; 22101 case PackageInstaller.STATUS_FAILURE_STORAGE: 22102 mMoveCallbacks.notifyStatusChanged(moveId, 22103 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 22104 break; 22105 default: 22106 mMoveCallbacks.notifyStatusChanged(moveId, 22107 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 22108 break; 22109 } 22110 } 22111 }; 22112 22113 final MoveInfo move; 22114 if (moveCompleteApp) { 22115 // Kick off a thread to report progress estimates 22116 new Thread() { 22117 @Override 22118 public void run() { 22119 while (true) { 22120 try { 22121 if (installedLatch.await(1, TimeUnit.SECONDS)) { 22122 break; 22123 } 22124 } catch (InterruptedException ignored) { 22125 } 22126 22127 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 22128 final int progress = 10 + (int) MathUtils.constrain( 22129 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 22130 mMoveCallbacks.notifyStatusChanged(moveId, progress); 22131 } 22132 } 22133 }.start(); 22134 22135 final String dataAppName = codeFile.getName(); 22136 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 22137 dataAppName, appId, seinfo, targetSdkVersion); 22138 } else { 22139 move = null; 22140 } 22141 22142 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 22143 22144 final Message msg = mHandler.obtainMessage(INIT_COPY); 22145 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 22146 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 22147 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 22148 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/, 22149 PackageManager.INSTALL_REASON_UNKNOWN); 22150 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 22151 msg.obj = params; 22152 22153 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 22154 System.identityHashCode(msg.obj)); 22155 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 22156 System.identityHashCode(msg.obj)); 22157 22158 mHandler.sendMessage(msg); 22159 } 22160 22161 @Override 22162 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 22163 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 22164 22165 final int realMoveId = mNextMoveId.getAndIncrement(); 22166 final Bundle extras = new Bundle(); 22167 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 22168 mMoveCallbacks.notifyCreated(realMoveId, extras); 22169 22170 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 22171 @Override 22172 public void onCreated(int moveId, Bundle extras) { 22173 // Ignored 22174 } 22175 22176 @Override 22177 public void onStatusChanged(int moveId, int status, long estMillis) { 22178 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 22179 } 22180 }; 22181 22182 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22183 storage.setPrimaryStorageUuid(volumeUuid, callback); 22184 return realMoveId; 22185 } 22186 22187 @Override 22188 public int getMoveStatus(int moveId) { 22189 mContext.enforceCallingOrSelfPermission( 22190 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22191 return mMoveCallbacks.mLastStatus.get(moveId); 22192 } 22193 22194 @Override 22195 public void registerMoveCallback(IPackageMoveObserver callback) { 22196 mContext.enforceCallingOrSelfPermission( 22197 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22198 mMoveCallbacks.register(callback); 22199 } 22200 22201 @Override 22202 public void unregisterMoveCallback(IPackageMoveObserver callback) { 22203 mContext.enforceCallingOrSelfPermission( 22204 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22205 mMoveCallbacks.unregister(callback); 22206 } 22207 22208 @Override 22209 public boolean setInstallLocation(int loc) { 22210 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 22211 null); 22212 if (getInstallLocation() == loc) { 22213 return true; 22214 } 22215 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 22216 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 22217 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 22218 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 22219 return true; 22220 } 22221 return false; 22222 } 22223 22224 @Override 22225 public int getInstallLocation() { 22226 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 22227 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 22228 PackageHelper.APP_INSTALL_AUTO); 22229 } 22230 22231 /** Called by UserManagerService */ 22232 void cleanUpUser(UserManagerService userManager, int userHandle) { 22233 synchronized (mPackages) { 22234 mDirtyUsers.remove(userHandle); 22235 mUserNeedsBadging.delete(userHandle); 22236 mSettings.removeUserLPw(userHandle); 22237 mPendingBroadcasts.remove(userHandle); 22238 mInstantAppRegistry.onUserRemovedLPw(userHandle); 22239 removeUnusedPackagesLPw(userManager, userHandle); 22240 } 22241 } 22242 22243 /** 22244 * We're removing userHandle and would like to remove any downloaded packages 22245 * that are no longer in use by any other user. 22246 * @param userHandle the user being removed 22247 */ 22248 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 22249 final boolean DEBUG_CLEAN_APKS = false; 22250 int [] users = userManager.getUserIds(); 22251 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 22252 while (psit.hasNext()) { 22253 PackageSetting ps = psit.next(); 22254 if (ps.pkg == null) { 22255 continue; 22256 } 22257 final String packageName = ps.pkg.packageName; 22258 // Skip over if system app 22259 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 22260 continue; 22261 } 22262 if (DEBUG_CLEAN_APKS) { 22263 Slog.i(TAG, "Checking package " + packageName); 22264 } 22265 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 22266 if (keep) { 22267 if (DEBUG_CLEAN_APKS) { 22268 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 22269 } 22270 } else { 22271 for (int i = 0; i < users.length; i++) { 22272 if (users[i] != userHandle && ps.getInstalled(users[i])) { 22273 keep = true; 22274 if (DEBUG_CLEAN_APKS) { 22275 Slog.i(TAG, " Keeping package " + packageName + " for user " 22276 + users[i]); 22277 } 22278 break; 22279 } 22280 } 22281 } 22282 if (!keep) { 22283 if (DEBUG_CLEAN_APKS) { 22284 Slog.i(TAG, " Removing package " + packageName); 22285 } 22286 mHandler.post(new Runnable() { 22287 public void run() { 22288 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 22289 userHandle, 0); 22290 } //end run 22291 }); 22292 } 22293 } 22294 } 22295 22296 /** Called by UserManagerService */ 22297 void createNewUser(int userId, String[] disallowedPackages) { 22298 synchronized (mInstallLock) { 22299 mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages); 22300 } 22301 synchronized (mPackages) { 22302 scheduleWritePackageRestrictionsLocked(userId); 22303 scheduleWritePackageListLocked(userId); 22304 applyFactoryDefaultBrowserLPw(userId); 22305 primeDomainVerificationsLPw(userId); 22306 } 22307 } 22308 22309 void onNewUserCreated(final int userId) { 22310 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 22311 // If permission review for legacy apps is required, we represent 22312 // dagerous permissions for such apps as always granted runtime 22313 // permissions to keep per user flag state whether review is needed. 22314 // Hence, if a new user is added we have to propagate dangerous 22315 // permission grants for these legacy apps. 22316 if (mPermissionReviewRequired) { 22317 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 22318 | UPDATE_PERMISSIONS_REPLACE_ALL); 22319 } 22320 } 22321 22322 @Override 22323 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 22324 mContext.enforceCallingOrSelfPermission( 22325 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 22326 "Only package verification agents can read the verifier device identity"); 22327 22328 synchronized (mPackages) { 22329 return mSettings.getVerifierDeviceIdentityLPw(); 22330 } 22331 } 22332 22333 @Override 22334 public void setPermissionEnforced(String permission, boolean enforced) { 22335 // TODO: Now that we no longer change GID for storage, this should to away. 22336 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 22337 "setPermissionEnforced"); 22338 if (READ_EXTERNAL_STORAGE.equals(permission)) { 22339 synchronized (mPackages) { 22340 if (mSettings.mReadExternalStorageEnforced == null 22341 || mSettings.mReadExternalStorageEnforced != enforced) { 22342 mSettings.mReadExternalStorageEnforced = enforced; 22343 mSettings.writeLPr(); 22344 } 22345 } 22346 // kill any non-foreground processes so we restart them and 22347 // grant/revoke the GID. 22348 final IActivityManager am = ActivityManager.getService(); 22349 if (am != null) { 22350 final long token = Binder.clearCallingIdentity(); 22351 try { 22352 am.killProcessesBelowForeground("setPermissionEnforcement"); 22353 } catch (RemoteException e) { 22354 } finally { 22355 Binder.restoreCallingIdentity(token); 22356 } 22357 } 22358 } else { 22359 throw new IllegalArgumentException("No selective enforcement for " + permission); 22360 } 22361 } 22362 22363 @Override 22364 @Deprecated 22365 public boolean isPermissionEnforced(String permission) { 22366 return true; 22367 } 22368 22369 @Override 22370 public boolean isStorageLow() { 22371 final long token = Binder.clearCallingIdentity(); 22372 try { 22373 final DeviceStorageMonitorInternal 22374 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 22375 if (dsm != null) { 22376 return dsm.isMemoryLow(); 22377 } else { 22378 return false; 22379 } 22380 } finally { 22381 Binder.restoreCallingIdentity(token); 22382 } 22383 } 22384 22385 @Override 22386 public IPackageInstaller getPackageInstaller() { 22387 return mInstallerService; 22388 } 22389 22390 private boolean userNeedsBadging(int userId) { 22391 int index = mUserNeedsBadging.indexOfKey(userId); 22392 if (index < 0) { 22393 final UserInfo userInfo; 22394 final long token = Binder.clearCallingIdentity(); 22395 try { 22396 userInfo = sUserManager.getUserInfo(userId); 22397 } finally { 22398 Binder.restoreCallingIdentity(token); 22399 } 22400 final boolean b; 22401 if (userInfo != null && userInfo.isManagedProfile()) { 22402 b = true; 22403 } else { 22404 b = false; 22405 } 22406 mUserNeedsBadging.put(userId, b); 22407 return b; 22408 } 22409 return mUserNeedsBadging.valueAt(index); 22410 } 22411 22412 @Override 22413 public KeySet getKeySetByAlias(String packageName, String alias) { 22414 if (packageName == null || alias == null) { 22415 return null; 22416 } 22417 synchronized(mPackages) { 22418 final PackageParser.Package pkg = mPackages.get(packageName); 22419 if (pkg == null) { 22420 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22421 throw new IllegalArgumentException("Unknown package: " + packageName); 22422 } 22423 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22424 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 22425 } 22426 } 22427 22428 @Override 22429 public KeySet getSigningKeySet(String packageName) { 22430 if (packageName == null) { 22431 return null; 22432 } 22433 synchronized(mPackages) { 22434 final PackageParser.Package pkg = mPackages.get(packageName); 22435 if (pkg == null) { 22436 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22437 throw new IllegalArgumentException("Unknown package: " + packageName); 22438 } 22439 if (pkg.applicationInfo.uid != Binder.getCallingUid() 22440 && Process.SYSTEM_UID != Binder.getCallingUid()) { 22441 throw new SecurityException("May not access signing KeySet of other apps."); 22442 } 22443 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22444 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 22445 } 22446 } 22447 22448 @Override 22449 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 22450 if (packageName == null || ks == null) { 22451 return false; 22452 } 22453 synchronized(mPackages) { 22454 final PackageParser.Package pkg = mPackages.get(packageName); 22455 if (pkg == null) { 22456 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22457 throw new IllegalArgumentException("Unknown package: " + packageName); 22458 } 22459 IBinder ksh = ks.getToken(); 22460 if (ksh instanceof KeySetHandle) { 22461 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22462 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 22463 } 22464 return false; 22465 } 22466 } 22467 22468 @Override 22469 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 22470 if (packageName == null || ks == null) { 22471 return false; 22472 } 22473 synchronized(mPackages) { 22474 final PackageParser.Package pkg = mPackages.get(packageName); 22475 if (pkg == null) { 22476 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22477 throw new IllegalArgumentException("Unknown package: " + packageName); 22478 } 22479 IBinder ksh = ks.getToken(); 22480 if (ksh instanceof KeySetHandle) { 22481 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22482 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 22483 } 22484 return false; 22485 } 22486 } 22487 22488 private void deletePackageIfUnusedLPr(final String packageName) { 22489 PackageSetting ps = mSettings.mPackages.get(packageName); 22490 if (ps == null) { 22491 return; 22492 } 22493 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 22494 // TODO Implement atomic delete if package is unused 22495 // It is currently possible that the package will be deleted even if it is installed 22496 // after this method returns. 22497 mHandler.post(new Runnable() { 22498 public void run() { 22499 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 22500 0, PackageManager.DELETE_ALL_USERS); 22501 } 22502 }); 22503 } 22504 } 22505 22506 /** 22507 * Check and throw if the given before/after packages would be considered a 22508 * downgrade. 22509 */ 22510 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 22511 throws PackageManagerException { 22512 if (after.versionCode < before.mVersionCode) { 22513 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 22514 "Update version code " + after.versionCode + " is older than current " 22515 + before.mVersionCode); 22516 } else if (after.versionCode == before.mVersionCode) { 22517 if (after.baseRevisionCode < before.baseRevisionCode) { 22518 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 22519 "Update base revision code " + after.baseRevisionCode 22520 + " is older than current " + before.baseRevisionCode); 22521 } 22522 22523 if (!ArrayUtils.isEmpty(after.splitNames)) { 22524 for (int i = 0; i < after.splitNames.length; i++) { 22525 final String splitName = after.splitNames[i]; 22526 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 22527 if (j != -1) { 22528 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 22529 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 22530 "Update split " + splitName + " revision code " 22531 + after.splitRevisionCodes[i] + " is older than current " 22532 + before.splitRevisionCodes[j]); 22533 } 22534 } 22535 } 22536 } 22537 } 22538 } 22539 22540 private static class MoveCallbacks extends Handler { 22541 private static final int MSG_CREATED = 1; 22542 private static final int MSG_STATUS_CHANGED = 2; 22543 22544 private final RemoteCallbackList<IPackageMoveObserver> 22545 mCallbacks = new RemoteCallbackList<>(); 22546 22547 private final SparseIntArray mLastStatus = new SparseIntArray(); 22548 22549 public MoveCallbacks(Looper looper) { 22550 super(looper); 22551 } 22552 22553 public void register(IPackageMoveObserver callback) { 22554 mCallbacks.register(callback); 22555 } 22556 22557 public void unregister(IPackageMoveObserver callback) { 22558 mCallbacks.unregister(callback); 22559 } 22560 22561 @Override 22562 public void handleMessage(Message msg) { 22563 final SomeArgs args = (SomeArgs) msg.obj; 22564 final int n = mCallbacks.beginBroadcast(); 22565 for (int i = 0; i < n; i++) { 22566 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 22567 try { 22568 invokeCallback(callback, msg.what, args); 22569 } catch (RemoteException ignored) { 22570 } 22571 } 22572 mCallbacks.finishBroadcast(); 22573 args.recycle(); 22574 } 22575 22576 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 22577 throws RemoteException { 22578 switch (what) { 22579 case MSG_CREATED: { 22580 callback.onCreated(args.argi1, (Bundle) args.arg2); 22581 break; 22582 } 22583 case MSG_STATUS_CHANGED: { 22584 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 22585 break; 22586 } 22587 } 22588 } 22589 22590 private void notifyCreated(int moveId, Bundle extras) { 22591 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 22592 22593 final SomeArgs args = SomeArgs.obtain(); 22594 args.argi1 = moveId; 22595 args.arg2 = extras; 22596 obtainMessage(MSG_CREATED, args).sendToTarget(); 22597 } 22598 22599 private void notifyStatusChanged(int moveId, int status) { 22600 notifyStatusChanged(moveId, status, -1); 22601 } 22602 22603 private void notifyStatusChanged(int moveId, int status, long estMillis) { 22604 Slog.v(TAG, "Move " + moveId + " status " + status); 22605 22606 final SomeArgs args = SomeArgs.obtain(); 22607 args.argi1 = moveId; 22608 args.argi2 = status; 22609 args.arg3 = estMillis; 22610 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 22611 22612 synchronized (mLastStatus) { 22613 mLastStatus.put(moveId, status); 22614 } 22615 } 22616 } 22617 22618 private final static class OnPermissionChangeListeners extends Handler { 22619 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 22620 22621 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 22622 new RemoteCallbackList<>(); 22623 22624 public OnPermissionChangeListeners(Looper looper) { 22625 super(looper); 22626 } 22627 22628 @Override 22629 public void handleMessage(Message msg) { 22630 switch (msg.what) { 22631 case MSG_ON_PERMISSIONS_CHANGED: { 22632 final int uid = msg.arg1; 22633 handleOnPermissionsChanged(uid); 22634 } break; 22635 } 22636 } 22637 22638 public void addListenerLocked(IOnPermissionsChangeListener listener) { 22639 mPermissionListeners.register(listener); 22640 22641 } 22642 22643 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 22644 mPermissionListeners.unregister(listener); 22645 } 22646 22647 public void onPermissionsChanged(int uid) { 22648 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 22649 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 22650 } 22651 } 22652 22653 private void handleOnPermissionsChanged(int uid) { 22654 final int count = mPermissionListeners.beginBroadcast(); 22655 try { 22656 for (int i = 0; i < count; i++) { 22657 IOnPermissionsChangeListener callback = mPermissionListeners 22658 .getBroadcastItem(i); 22659 try { 22660 callback.onPermissionsChanged(uid); 22661 } catch (RemoteException e) { 22662 Log.e(TAG, "Permission listener is dead", e); 22663 } 22664 } 22665 } finally { 22666 mPermissionListeners.finishBroadcast(); 22667 } 22668 } 22669 } 22670 22671 private class PackageManagerInternalImpl extends PackageManagerInternal { 22672 @Override 22673 public void setLocationPackagesProvider(PackagesProvider provider) { 22674 synchronized (mPackages) { 22675 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 22676 } 22677 } 22678 22679 @Override 22680 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 22681 synchronized (mPackages) { 22682 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 22683 } 22684 } 22685 22686 @Override 22687 public void setSmsAppPackagesProvider(PackagesProvider provider) { 22688 synchronized (mPackages) { 22689 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 22690 } 22691 } 22692 22693 @Override 22694 public void setDialerAppPackagesProvider(PackagesProvider provider) { 22695 synchronized (mPackages) { 22696 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 22697 } 22698 } 22699 22700 @Override 22701 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 22702 synchronized (mPackages) { 22703 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 22704 } 22705 } 22706 22707 @Override 22708 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 22709 synchronized (mPackages) { 22710 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 22711 } 22712 } 22713 22714 @Override 22715 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 22716 synchronized (mPackages) { 22717 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 22718 packageName, userId); 22719 } 22720 } 22721 22722 @Override 22723 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 22724 synchronized (mPackages) { 22725 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 22726 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 22727 packageName, userId); 22728 } 22729 } 22730 22731 @Override 22732 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 22733 synchronized (mPackages) { 22734 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 22735 packageName, userId); 22736 } 22737 } 22738 22739 @Override 22740 public void setKeepUninstalledPackages(final List<String> packageList) { 22741 Preconditions.checkNotNull(packageList); 22742 List<String> removedFromList = null; 22743 synchronized (mPackages) { 22744 if (mKeepUninstalledPackages != null) { 22745 final int packagesCount = mKeepUninstalledPackages.size(); 22746 for (int i = 0; i < packagesCount; i++) { 22747 String oldPackage = mKeepUninstalledPackages.get(i); 22748 if (packageList != null && packageList.contains(oldPackage)) { 22749 continue; 22750 } 22751 if (removedFromList == null) { 22752 removedFromList = new ArrayList<>(); 22753 } 22754 removedFromList.add(oldPackage); 22755 } 22756 } 22757 mKeepUninstalledPackages = new ArrayList<>(packageList); 22758 if (removedFromList != null) { 22759 final int removedCount = removedFromList.size(); 22760 for (int i = 0; i < removedCount; i++) { 22761 deletePackageIfUnusedLPr(removedFromList.get(i)); 22762 } 22763 } 22764 } 22765 } 22766 22767 @Override 22768 public boolean isPermissionsReviewRequired(String packageName, int userId) { 22769 synchronized (mPackages) { 22770 // If we do not support permission review, done. 22771 if (!mPermissionReviewRequired) { 22772 return false; 22773 } 22774 22775 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 22776 if (packageSetting == null) { 22777 return false; 22778 } 22779 22780 // Permission review applies only to apps not supporting the new permission model. 22781 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 22782 return false; 22783 } 22784 22785 // Legacy apps have the permission and get user consent on launch. 22786 PermissionsState permissionsState = packageSetting.getPermissionsState(); 22787 return permissionsState.isPermissionReviewRequired(userId); 22788 } 22789 } 22790 22791 @Override 22792 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 22793 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 22794 } 22795 22796 @Override 22797 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 22798 int userId) { 22799 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 22800 } 22801 22802 @Override 22803 public void setDeviceAndProfileOwnerPackages( 22804 int deviceOwnerUserId, String deviceOwnerPackage, 22805 SparseArray<String> profileOwnerPackages) { 22806 mProtectedPackages.setDeviceAndProfileOwnerPackages( 22807 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages); 22808 } 22809 22810 @Override 22811 public boolean isPackageDataProtected(int userId, String packageName) { 22812 return mProtectedPackages.isPackageDataProtected(userId, packageName); 22813 } 22814 22815 @Override 22816 public boolean isPackageEphemeral(int userId, String packageName) { 22817 synchronized (mPackages) { 22818 PackageParser.Package p = mPackages.get(packageName); 22819 return p != null ? p.applicationInfo.isInstantApp() : false; 22820 } 22821 } 22822 22823 @Override 22824 public boolean wasPackageEverLaunched(String packageName, int userId) { 22825 synchronized (mPackages) { 22826 return mSettings.wasPackageEverLaunchedLPr(packageName, userId); 22827 } 22828 } 22829 22830 @Override 22831 public void grantRuntimePermission(String packageName, String name, int userId, 22832 boolean overridePolicy) { 22833 PackageManagerService.this.grantRuntimePermission(packageName, name, userId, 22834 overridePolicy); 22835 } 22836 22837 @Override 22838 public void revokeRuntimePermission(String packageName, String name, int userId, 22839 boolean overridePolicy) { 22840 PackageManagerService.this.revokeRuntimePermission(packageName, name, userId, 22841 overridePolicy); 22842 } 22843 22844 @Override 22845 public String getNameForUid(int uid) { 22846 return PackageManagerService.this.getNameForUid(uid); 22847 } 22848 22849 @Override 22850 public void requestEphemeralResolutionPhaseTwo(EphemeralResponse responseObj, 22851 Intent origIntent, String resolvedType, Intent launchIntent, 22852 String callingPackage, int userId) { 22853 PackageManagerService.this.requestEphemeralResolutionPhaseTwo( 22854 responseObj, origIntent, resolvedType, launchIntent, callingPackage, userId); 22855 } 22856 22857 @Override 22858 public void grantEphemeralAccess(int userId, Intent intent, 22859 int targetAppId, int ephemeralAppId) { 22860 synchronized (mPackages) { 22861 mInstantAppRegistry.grantInstantAccessLPw(userId, intent, 22862 targetAppId, ephemeralAppId); 22863 } 22864 } 22865 22866 @Override 22867 public void pruneInstantApps() { 22868 synchronized (mPackages) { 22869 mInstantAppRegistry.pruneInstantAppsLPw(); 22870 } 22871 } 22872 22873 @Override 22874 public String getSetupWizardPackageName() { 22875 return mSetupWizardPackage; 22876 } 22877 22878 public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) { 22879 if (policy != null) { 22880 mExternalSourcesPolicy = policy; 22881 } 22882 } 22883 22884 @Override 22885 public boolean isPackagePersistent(String packageName) { 22886 synchronized (mPackages) { 22887 PackageParser.Package pkg = mPackages.get(packageName); 22888 return pkg != null 22889 ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM 22890 | ApplicationInfo.FLAG_PERSISTENT)) == 22891 (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT)) 22892 : false; 22893 } 22894 } 22895 22896 @Override 22897 public List<PackageInfo> getOverlayPackages(int userId) { 22898 final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>(); 22899 synchronized (mPackages) { 22900 for (PackageParser.Package p : mPackages.values()) { 22901 if (p.mOverlayTarget != null) { 22902 PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId); 22903 if (pkg != null) { 22904 overlayPackages.add(pkg); 22905 } 22906 } 22907 } 22908 } 22909 return overlayPackages; 22910 } 22911 22912 @Override 22913 public List<String> getTargetPackageNames(int userId) { 22914 List<String> targetPackages = new ArrayList<>(); 22915 synchronized (mPackages) { 22916 for (PackageParser.Package p : mPackages.values()) { 22917 if (p.mOverlayTarget == null) { 22918 targetPackages.add(p.packageName); 22919 } 22920 } 22921 } 22922 return targetPackages; 22923 } 22924 22925 22926 @Override 22927 public boolean setEnabledOverlayPackages(int userId, String targetPackageName, 22928 List<String> overlayPackageNames) { 22929 // TODO: implement when we integrate OMS properly 22930 return false; 22931 } 22932 } 22933 22934 @Override 22935 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 22936 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 22937 synchronized (mPackages) { 22938 final long identity = Binder.clearCallingIdentity(); 22939 try { 22940 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 22941 packageNames, userId); 22942 } finally { 22943 Binder.restoreCallingIdentity(identity); 22944 } 22945 } 22946 } 22947 22948 @Override 22949 public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) { 22950 enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices"); 22951 synchronized (mPackages) { 22952 final long identity = Binder.clearCallingIdentity(); 22953 try { 22954 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr( 22955 packageNames, userId); 22956 } finally { 22957 Binder.restoreCallingIdentity(identity); 22958 } 22959 } 22960 } 22961 22962 private static void enforceSystemOrPhoneCaller(String tag) { 22963 int callingUid = Binder.getCallingUid(); 22964 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 22965 throw new SecurityException( 22966 "Cannot call " + tag + " from UID " + callingUid); 22967 } 22968 } 22969 22970 boolean isHistoricalPackageUsageAvailable() { 22971 return mPackageUsage.isHistoricalPackageUsageAvailable(); 22972 } 22973 22974 /** 22975 * Return a <b>copy</b> of the collection of packages known to the package manager. 22976 * @return A copy of the values of mPackages. 22977 */ 22978 Collection<PackageParser.Package> getPackages() { 22979 synchronized (mPackages) { 22980 return new ArrayList<>(mPackages.values()); 22981 } 22982 } 22983 22984 /** 22985 * Logs process start information (including base APK hash) to the security log. 22986 * @hide 22987 */ 22988 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 22989 String apkFile, int pid) { 22990 if (!SecurityLog.isLoggingEnabled()) { 22991 return; 22992 } 22993 Bundle data = new Bundle(); 22994 data.putLong("startTimestamp", System.currentTimeMillis()); 22995 data.putString("processName", processName); 22996 data.putInt("uid", uid); 22997 data.putString("seinfo", seinfo); 22998 data.putString("apkFile", apkFile); 22999 data.putInt("pid", pid); 23000 Message msg = mProcessLoggingHandler.obtainMessage( 23001 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 23002 msg.setData(data); 23003 mProcessLoggingHandler.sendMessage(msg); 23004 } 23005 23006 public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) { 23007 return mCompilerStats.getPackageStats(pkgName); 23008 } 23009 23010 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) { 23011 return getOrCreateCompilerPackageStats(pkg.packageName); 23012 } 23013 23014 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) { 23015 return mCompilerStats.getOrCreatePackageStats(pkgName); 23016 } 23017 23018 public void deleteCompilerPackageStats(String pkgName) { 23019 mCompilerStats.deletePackageStats(pkgName); 23020 } 23021 23022 @Override 23023 public int getInstallReason(String packageName, int userId) { 23024 enforceCrossUserPermission(Binder.getCallingUid(), userId, 23025 true /* requireFullPermission */, false /* checkShell */, 23026 "get install reason"); 23027 synchronized (mPackages) { 23028 final PackageSetting ps = mSettings.mPackages.get(packageName); 23029 if (ps != null) { 23030 return ps.getInstallReason(userId); 23031 } 23032 } 23033 return PackageManager.INSTALL_REASON_UNKNOWN; 23034 } 23035 23036 @Override 23037 public boolean canRequestPackageInstalls(String packageName, int userId) { 23038 int callingUid = Binder.getCallingUid(); 23039 int uid = getPackageUid(packageName, 0, userId); 23040 if (callingUid != uid && callingUid != Process.ROOT_UID 23041 && callingUid != Process.SYSTEM_UID) { 23042 throw new SecurityException( 23043 "Caller uid " + callingUid + " does not own package " + packageName); 23044 } 23045 ApplicationInfo info = getApplicationInfo(packageName, 0, userId); 23046 if (info == null) { 23047 return false; 23048 } 23049 if (info.targetSdkVersion < Build.VERSION_CODES.O) { 23050 throw new UnsupportedOperationException( 23051 "Operation only supported on apps targeting Android O or higher"); 23052 } 23053 String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES; 23054 String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission); 23055 if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) { 23056 throw new SecurityException("Need to declare " + appOpPermission + " to call this api"); 23057 } 23058 if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) { 23059 return false; 23060 } 23061 if (mExternalSourcesPolicy != null) { 23062 int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid); 23063 if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) { 23064 return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED; 23065 } 23066 } 23067 return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED; 23068 } 23069} 23070