PackageManagerService.java revision aef2513c7157a28236d097a81fe74d7ba6b710c9
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.ComponentInfo; 130import android.content.pm.EphemeralApplicationInfo; 131import android.content.pm.EphemeralRequest; 132import android.content.pm.EphemeralResolveInfo; 133import android.content.pm.EphemeralResponse; 134import android.content.pm.FallbackCategoryProvider; 135import android.content.pm.FeatureInfo; 136import android.content.pm.IOnPermissionsChangeListener; 137import android.content.pm.IPackageDataObserver; 138import android.content.pm.IPackageDeleteObserver; 139import android.content.pm.IPackageDeleteObserver2; 140import android.content.pm.IPackageInstallObserver2; 141import android.content.pm.IPackageInstaller; 142import android.content.pm.IPackageManager; 143import android.content.pm.IPackageMoveObserver; 144import android.content.pm.IPackageStatsObserver; 145import android.content.pm.InstrumentationInfo; 146import android.content.pm.IntentFilterVerificationInfo; 147import android.content.pm.KeySet; 148import android.content.pm.PackageCleanItem; 149import android.content.pm.PackageInfo; 150import android.content.pm.PackageInfoLite; 151import android.content.pm.PackageInstaller; 152import android.content.pm.PackageManager; 153import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 154import android.content.pm.PackageManagerInternal; 155import android.content.pm.PackageParser; 156import android.content.pm.PackageParser.ActivityIntentInfo; 157import android.content.pm.PackageParser.PackageLite; 158import android.content.pm.PackageParser.PackageParserException; 159import android.content.pm.PackageStats; 160import android.content.pm.PackageUserState; 161import android.content.pm.ParceledListSlice; 162import android.content.pm.PermissionGroupInfo; 163import android.content.pm.PermissionInfo; 164import android.content.pm.ProviderInfo; 165import android.content.pm.ResolveInfo; 166import android.content.pm.ServiceInfo; 167import android.content.pm.SharedLibraryInfo; 168import android.content.pm.Signature; 169import android.content.pm.UserInfo; 170import android.content.pm.VerifierDeviceIdentity; 171import android.content.pm.VerifierInfo; 172import android.content.pm.VersionedPackage; 173import android.content.res.Resources; 174import android.graphics.Bitmap; 175import android.hardware.display.DisplayManager; 176import android.net.Uri; 177import android.os.Binder; 178import android.os.Build; 179import android.os.Bundle; 180import android.os.Debug; 181import android.os.Environment; 182import android.os.Environment.UserEnvironment; 183import android.os.FileUtils; 184import android.os.Handler; 185import android.os.IBinder; 186import android.os.Looper; 187import android.os.Message; 188import android.os.Parcel; 189import android.os.ParcelFileDescriptor; 190import android.os.PatternMatcher; 191import android.os.Process; 192import android.os.RemoteCallbackList; 193import android.os.RemoteException; 194import android.os.ResultReceiver; 195import android.os.SELinux; 196import android.os.ServiceManager; 197import android.os.ShellCallback; 198import android.os.SystemClock; 199import android.os.SystemProperties; 200import android.os.Trace; 201import android.os.UserHandle; 202import android.os.UserManager; 203import android.os.UserManagerInternal; 204import android.os.storage.IStorageManager; 205import android.os.storage.StorageManagerInternal; 206import android.os.storage.StorageEventListener; 207import android.os.storage.StorageManager; 208import android.os.storage.VolumeInfo; 209import android.os.storage.VolumeRecord; 210import android.provider.Settings.Global; 211import android.provider.Settings.Secure; 212import android.security.KeyStore; 213import android.security.SystemKeyStore; 214import android.system.ErrnoException; 215import android.system.Os; 216import android.text.TextUtils; 217import android.text.format.DateUtils; 218import android.util.ArrayMap; 219import android.util.ArraySet; 220import android.util.Base64; 221import android.util.DisplayMetrics; 222import android.util.EventLog; 223import android.util.ExceptionUtils; 224import android.util.Log; 225import android.util.LogPrinter; 226import android.util.MathUtils; 227import android.util.PackageUtils; 228import android.util.Pair; 229import android.util.PrintStreamPrinter; 230import android.util.Slog; 231import android.util.SparseArray; 232import android.util.SparseBooleanArray; 233import android.util.SparseIntArray; 234import android.util.Xml; 235import android.util.jar.StrictJarFile; 236import android.view.Display; 237 238import com.android.internal.R; 239import com.android.internal.annotations.GuardedBy; 240import com.android.internal.app.IMediaContainerService; 241import com.android.internal.app.ResolverActivity; 242import com.android.internal.content.NativeLibraryHelper; 243import com.android.internal.content.PackageHelper; 244import com.android.internal.logging.MetricsLogger; 245import com.android.internal.logging.nano.MetricsProto.MetricsEvent; 246import com.android.internal.os.IParcelFileDescriptorFactory; 247import com.android.internal.os.RoSystemProperties; 248import com.android.internal.os.SomeArgs; 249import com.android.internal.os.Zygote; 250import com.android.internal.telephony.CarrierAppUtils; 251import com.android.internal.util.ArrayUtils; 252import com.android.internal.util.FastPrintWriter; 253import com.android.internal.util.FastXmlSerializer; 254import com.android.internal.util.IndentingPrintWriter; 255import com.android.internal.util.Preconditions; 256import com.android.internal.util.XmlUtils; 257import com.android.server.AttributeCache; 258import com.android.server.EventLogTags; 259import com.android.server.FgThread; 260import com.android.server.IntentResolver; 261import com.android.server.LocalServices; 262import com.android.server.ServiceThread; 263import com.android.server.SystemConfig; 264import com.android.server.Watchdog; 265import com.android.server.net.NetworkPolicyManagerInternal; 266import com.android.server.pm.Installer.InstallerException; 267import com.android.server.pm.PermissionsState.PermissionState; 268import com.android.server.pm.Settings.DatabaseVersion; 269import com.android.server.pm.Settings.VersionInfo; 270import com.android.server.pm.dex.DexManager; 271import com.android.server.storage.DeviceStorageMonitorInternal; 272 273import dalvik.system.CloseGuard; 274import dalvik.system.DexFile; 275import dalvik.system.VMRuntime; 276 277import libcore.io.IoUtils; 278import libcore.util.EmptyArray; 279 280import org.xmlpull.v1.XmlPullParser; 281import org.xmlpull.v1.XmlPullParserException; 282import org.xmlpull.v1.XmlSerializer; 283 284import java.io.BufferedOutputStream; 285import java.io.BufferedReader; 286import java.io.ByteArrayInputStream; 287import java.io.ByteArrayOutputStream; 288import java.io.File; 289import java.io.FileDescriptor; 290import java.io.FileInputStream; 291import java.io.FileNotFoundException; 292import java.io.FileOutputStream; 293import java.io.FileReader; 294import java.io.FilenameFilter; 295import java.io.IOException; 296import java.io.PrintWriter; 297import java.nio.charset.StandardCharsets; 298import java.security.DigestInputStream; 299import java.security.MessageDigest; 300import java.security.NoSuchAlgorithmException; 301import java.security.PublicKey; 302import java.security.SecureRandom; 303import java.security.cert.Certificate; 304import java.security.cert.CertificateEncodingException; 305import java.security.cert.CertificateException; 306import java.text.SimpleDateFormat; 307import java.util.ArrayList; 308import java.util.Arrays; 309import java.util.Collection; 310import java.util.Collections; 311import java.util.Comparator; 312import java.util.Date; 313import java.util.HashSet; 314import java.util.HashMap; 315import java.util.Iterator; 316import java.util.List; 317import java.util.Map; 318import java.util.Objects; 319import java.util.Set; 320import java.util.concurrent.CountDownLatch; 321import java.util.concurrent.TimeUnit; 322import java.util.concurrent.atomic.AtomicBoolean; 323import java.util.concurrent.atomic.AtomicInteger; 324 325/** 326 * Keep track of all those APKs everywhere. 327 * <p> 328 * Internally there are two important locks: 329 * <ul> 330 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 331 * and other related state. It is a fine-grained lock that should only be held 332 * momentarily, as it's one of the most contended locks in the system. 333 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 334 * operations typically involve heavy lifting of application data on disk. Since 335 * {@code installd} is single-threaded, and it's operations can often be slow, 336 * this lock should never be acquired while already holding {@link #mPackages}. 337 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 338 * holding {@link #mInstallLock}. 339 * </ul> 340 * Many internal methods rely on the caller to hold the appropriate locks, and 341 * this contract is expressed through method name suffixes: 342 * <ul> 343 * <li>fooLI(): the caller must hold {@link #mInstallLock} 344 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 345 * being modified must be frozen 346 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 347 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 348 * </ul> 349 * <p> 350 * Because this class is very central to the platform's security; please run all 351 * CTS and unit tests whenever making modifications: 352 * 353 * <pre> 354 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 355 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases 356 * </pre> 357 */ 358public class PackageManagerService extends IPackageManager.Stub { 359 static final String TAG = "PackageManager"; 360 static final boolean DEBUG_SETTINGS = false; 361 static final boolean DEBUG_PREFERRED = false; 362 static final boolean DEBUG_UPGRADE = false; 363 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 364 private static final boolean DEBUG_BACKUP = false; 365 private static final boolean DEBUG_INSTALL = false; 366 private static final boolean DEBUG_REMOVE = false; 367 private static final boolean DEBUG_BROADCASTS = false; 368 private static final boolean DEBUG_SHOW_INFO = false; 369 private static final boolean DEBUG_PACKAGE_INFO = false; 370 private static final boolean DEBUG_INTENT_MATCHING = false; 371 private static final boolean DEBUG_PACKAGE_SCANNING = false; 372 private static final boolean DEBUG_VERIFY = false; 373 private static final boolean DEBUG_FILTERS = false; 374 375 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 376 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 377 // user, but by default initialize to this. 378 static final boolean DEBUG_DEXOPT = false; 379 380 private static final boolean DEBUG_ABI_SELECTION = false; 381 private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE; 382 private static final boolean DEBUG_TRIAGED_MISSING = false; 383 private static final boolean DEBUG_APP_DATA = false; 384 385 /** REMOVE. According to Svet, this was only used to reset permissions during development. */ 386 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 387 388 private static final boolean DISABLE_EPHEMERAL_APPS = false; 389 private static final boolean HIDE_EPHEMERAL_APIS = true; 390 391 private static final boolean ENABLE_QUOTA = 392 SystemProperties.getBoolean("persist.fw.quota", false); 393 394 private static final int RADIO_UID = Process.PHONE_UID; 395 private static final int LOG_UID = Process.LOG_UID; 396 private static final int NFC_UID = Process.NFC_UID; 397 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 398 private static final int SHELL_UID = Process.SHELL_UID; 399 400 // Cap the size of permission trees that 3rd party apps can define 401 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 402 403 // Suffix used during package installation when copying/moving 404 // package apks to install directory. 405 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 406 407 static final int SCAN_NO_DEX = 1<<1; 408 static final int SCAN_FORCE_DEX = 1<<2; 409 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 410 static final int SCAN_NEW_INSTALL = 1<<4; 411 static final int SCAN_UPDATE_TIME = 1<<5; 412 static final int SCAN_BOOTING = 1<<6; 413 static final int SCAN_TRUSTED_OVERLAY = 1<<7; 414 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8; 415 static final int SCAN_REPLACING = 1<<9; 416 static final int SCAN_REQUIRE_KNOWN = 1<<10; 417 static final int SCAN_MOVE = 1<<11; 418 static final int SCAN_INITIAL = 1<<12; 419 static final int SCAN_CHECK_ONLY = 1<<13; 420 static final int SCAN_DONT_KILL_APP = 1<<14; 421 static final int SCAN_IGNORE_FROZEN = 1<<15; 422 static final int REMOVE_CHATTY = 1<<16; 423 static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<17; 424 425 private static final String STATIC_SHARED_LIB_DELIMITER = "_"; 426 427 private static final int[] EMPTY_INT_ARRAY = new int[0]; 428 429 /** 430 * Timeout (in milliseconds) after which the watchdog should declare that 431 * our handler thread is wedged. The usual default for such things is one 432 * minute but we sometimes do very lengthy I/O operations on this thread, 433 * such as installing multi-gigabyte applications, so ours needs to be longer. 434 */ 435 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 436 437 /** 438 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 439 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 440 * settings entry if available, otherwise we use the hardcoded default. If it's been 441 * more than this long since the last fstrim, we force one during the boot sequence. 442 * 443 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 444 * one gets run at the next available charging+idle time. This final mandatory 445 * no-fstrim check kicks in only of the other scheduling criteria is never met. 446 */ 447 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 448 449 /** 450 * Whether verification is enabled by default. 451 */ 452 private static final boolean DEFAULT_VERIFY_ENABLE = true; 453 454 /** 455 * The default maximum time to wait for the verification agent to return in 456 * milliseconds. 457 */ 458 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 459 460 /** 461 * The default response for package verification timeout. 462 * 463 * This can be either PackageManager.VERIFICATION_ALLOW or 464 * PackageManager.VERIFICATION_REJECT. 465 */ 466 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 467 468 static final String PLATFORM_PACKAGE_NAME = "android"; 469 470 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 471 472 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 473 DEFAULT_CONTAINER_PACKAGE, 474 "com.android.defcontainer.DefaultContainerService"); 475 476 private static final String KILL_APP_REASON_GIDS_CHANGED = 477 "permission grant or revoke changed gids"; 478 479 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 480 "permissions revoked"; 481 482 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 483 484 private static final String PACKAGE_SCHEME = "package"; 485 486 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 487 /** 488 * If VENDOR_OVERLAY_THEME_PROPERTY is set, search for runtime resource overlay APKs also in 489 * VENDOR_OVERLAY_DIR/<value of VENDOR_OVERLAY_THEME_PROPERTY> in addition to 490 * VENDOR_OVERLAY_DIR. 491 */ 492 private static final String VENDOR_OVERLAY_THEME_PROPERTY = "ro.boot.vendor.overlay.theme"; 493 /** 494 * Same as VENDOR_OVERLAY_THEME_PROPERTY, except persistent. If set will override whatever 495 * is in VENDOR_OVERLAY_THEME_PROPERTY. 496 */ 497 private static final String VENDOR_OVERLAY_THEME_PERSIST_PROPERTY 498 = "persist.vendor.overlay.theme"; 499 500 /** Permission grant: not grant the permission. */ 501 private static final int GRANT_DENIED = 1; 502 503 /** Permission grant: grant the permission as an install permission. */ 504 private static final int GRANT_INSTALL = 2; 505 506 /** Permission grant: grant the permission as a runtime one. */ 507 private static final int GRANT_RUNTIME = 3; 508 509 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 510 private static final int GRANT_UPGRADE = 4; 511 512 /** Canonical intent used to identify what counts as a "web browser" app */ 513 private static final Intent sBrowserIntent; 514 static { 515 sBrowserIntent = new Intent(); 516 sBrowserIntent.setAction(Intent.ACTION_VIEW); 517 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 518 sBrowserIntent.setData(Uri.parse("http:")); 519 } 520 521 /** 522 * The set of all protected actions [i.e. those actions for which a high priority 523 * intent filter is disallowed]. 524 */ 525 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 526 static { 527 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 528 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 529 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 530 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 531 } 532 533 // Compilation reasons. 534 public static final int REASON_FIRST_BOOT = 0; 535 public static final int REASON_BOOT = 1; 536 public static final int REASON_INSTALL = 2; 537 public static final int REASON_BACKGROUND_DEXOPT = 3; 538 public static final int REASON_AB_OTA = 4; 539 public static final int REASON_NON_SYSTEM_LIBRARY = 5; 540 public static final int REASON_SHARED_APK = 6; 541 public static final int REASON_FORCED_DEXOPT = 7; 542 public static final int REASON_CORE_APP = 8; 543 544 public static final int REASON_LAST = REASON_CORE_APP; 545 546 /** Special library name that skips shared libraries check during compilation. */ 547 private static final String SKIP_SHARED_LIBRARY_CHECK = "&"; 548 549 /** All dangerous permission names in the same order as the events in MetricsEvent */ 550 private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList( 551 Manifest.permission.READ_CALENDAR, 552 Manifest.permission.WRITE_CALENDAR, 553 Manifest.permission.CAMERA, 554 Manifest.permission.READ_CONTACTS, 555 Manifest.permission.WRITE_CONTACTS, 556 Manifest.permission.GET_ACCOUNTS, 557 Manifest.permission.ACCESS_FINE_LOCATION, 558 Manifest.permission.ACCESS_COARSE_LOCATION, 559 Manifest.permission.RECORD_AUDIO, 560 Manifest.permission.READ_PHONE_STATE, 561 Manifest.permission.CALL_PHONE, 562 Manifest.permission.READ_CALL_LOG, 563 Manifest.permission.WRITE_CALL_LOG, 564 Manifest.permission.ADD_VOICEMAIL, 565 Manifest.permission.USE_SIP, 566 Manifest.permission.PROCESS_OUTGOING_CALLS, 567 Manifest.permission.READ_CELL_BROADCASTS, 568 Manifest.permission.BODY_SENSORS, 569 Manifest.permission.SEND_SMS, 570 Manifest.permission.RECEIVE_SMS, 571 Manifest.permission.READ_SMS, 572 Manifest.permission.RECEIVE_WAP_PUSH, 573 Manifest.permission.RECEIVE_MMS, 574 Manifest.permission.READ_EXTERNAL_STORAGE, 575 Manifest.permission.WRITE_EXTERNAL_STORAGE, 576 Manifest.permission.READ_PHONE_NUMBER); 577 578 579 /** 580 * Version number for the package parser cache. Increment this whenever the format or 581 * extent of cached data changes. See {@code PackageParser#setCacheDir}. 582 */ 583 private static final String PACKAGE_PARSER_CACHE_VERSION = "1"; 584 585 /** 586 * Whether the package parser cache is enabled. 587 */ 588 private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true; 589 590 final ServiceThread mHandlerThread; 591 592 final PackageHandler mHandler; 593 594 private final ProcessLoggingHandler mProcessLoggingHandler; 595 596 /** 597 * Messages for {@link #mHandler} that need to wait for system ready before 598 * being dispatched. 599 */ 600 private ArrayList<Message> mPostSystemReadyMessages; 601 602 final int mSdkVersion = Build.VERSION.SDK_INT; 603 604 final Context mContext; 605 final boolean mFactoryTest; 606 final boolean mOnlyCore; 607 final DisplayMetrics mMetrics; 608 final int mDefParseFlags; 609 final String[] mSeparateProcesses; 610 final boolean mIsUpgrade; 611 final boolean mIsPreNUpgrade; 612 final boolean mIsPreNMR1Upgrade; 613 614 @GuardedBy("mPackages") 615 private boolean mDexOptDialogShown; 616 617 /** The location for ASEC container files on internal storage. */ 618 final String mAsecInternalPath; 619 620 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 621 // LOCK HELD. Can be called with mInstallLock held. 622 @GuardedBy("mInstallLock") 623 final Installer mInstaller; 624 625 /** Directory where installed third-party apps stored */ 626 final File mAppInstallDir; 627 final File mEphemeralInstallDir; 628 629 /** 630 * Directory to which applications installed internally have their 631 * 32 bit native libraries copied. 632 */ 633 private File mAppLib32InstallDir; 634 635 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 636 // apps. 637 final File mDrmAppPrivateInstallDir; 638 639 // ---------------------------------------------------------------- 640 641 // Lock for state used when installing and doing other long running 642 // operations. Methods that must be called with this lock held have 643 // the suffix "LI". 644 final Object mInstallLock = new Object(); 645 646 // ---------------------------------------------------------------- 647 648 // Keys are String (package name), values are Package. This also serves 649 // as the lock for the global state. Methods that must be called with 650 // this lock held have the prefix "LP". 651 @GuardedBy("mPackages") 652 final ArrayMap<String, PackageParser.Package> mPackages = 653 new ArrayMap<String, PackageParser.Package>(); 654 655 final ArrayMap<String, Set<String>> mKnownCodebase = 656 new ArrayMap<String, Set<String>>(); 657 658 // Tracks available target package names -> overlay package paths. 659 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 660 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 661 662 /** 663 * Tracks new system packages [received in an OTA] that we expect to 664 * find updated user-installed versions. Keys are package name, values 665 * are package location. 666 */ 667 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 668 /** 669 * Tracks high priority intent filters for protected actions. During boot, certain 670 * filter actions are protected and should never be allowed to have a high priority 671 * intent filter for them. However, there is one, and only one exception -- the 672 * setup wizard. It must be able to define a high priority intent filter for these 673 * actions to ensure there are no escapes from the wizard. We need to delay processing 674 * of these during boot as we need to look at all of the system packages in order 675 * to know which component is the setup wizard. 676 */ 677 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 678 /** 679 * Whether or not processing protected filters should be deferred. 680 */ 681 private boolean mDeferProtectedFilters = true; 682 683 /** 684 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 685 */ 686 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 687 /** 688 * Whether or not system app permissions should be promoted from install to runtime. 689 */ 690 boolean mPromoteSystemApps; 691 692 @GuardedBy("mPackages") 693 final Settings mSettings; 694 695 /** 696 * Set of package names that are currently "frozen", which means active 697 * surgery is being done on the code/data for that package. The platform 698 * will refuse to launch frozen packages to avoid race conditions. 699 * 700 * @see PackageFreezer 701 */ 702 @GuardedBy("mPackages") 703 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 704 705 final ProtectedPackages mProtectedPackages; 706 707 boolean mFirstBoot; 708 709 PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy; 710 711 // System configuration read by SystemConfig. 712 final int[] mGlobalGids; 713 final SparseArray<ArraySet<String>> mSystemPermissions; 714 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 715 716 // If mac_permissions.xml was found for seinfo labeling. 717 boolean mFoundPolicyFile; 718 719 private final EphemeralApplicationRegistry mEphemeralApplicationRegistry; 720 721 public static final class SharedLibraryEntry { 722 public final String path; 723 public final String apk; 724 public final SharedLibraryInfo info; 725 726 SharedLibraryEntry(String _path, String _apk, String name, int version, int type, 727 String declaringPackageName, int declaringPackageVersionCode) { 728 path = _path; 729 apk = _apk; 730 info = new SharedLibraryInfo(name, version, type, new VersionedPackage( 731 declaringPackageName, declaringPackageVersionCode), null); 732 } 733 } 734 735 // Currently known shared libraries. 736 final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>(); 737 final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage = 738 new ArrayMap<>(); 739 740 // All available activities, for your resolving pleasure. 741 final ActivityIntentResolver mActivities = 742 new ActivityIntentResolver(); 743 744 // All available receivers, for your resolving pleasure. 745 final ActivityIntentResolver mReceivers = 746 new ActivityIntentResolver(); 747 748 // All available services, for your resolving pleasure. 749 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 750 751 // All available providers, for your resolving pleasure. 752 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 753 754 // Mapping from provider base names (first directory in content URI codePath) 755 // to the provider information. 756 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 757 new ArrayMap<String, PackageParser.Provider>(); 758 759 // Mapping from instrumentation class names to info about them. 760 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 761 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 762 763 // Mapping from permission names to info about them. 764 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 765 new ArrayMap<String, PackageParser.PermissionGroup>(); 766 767 // Packages whose data we have transfered into another package, thus 768 // should no longer exist. 769 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 770 771 // Broadcast actions that are only available to the system. 772 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 773 774 /** List of packages waiting for verification. */ 775 final SparseArray<PackageVerificationState> mPendingVerification 776 = new SparseArray<PackageVerificationState>(); 777 778 /** Set of packages associated with each app op permission. */ 779 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 780 781 final PackageInstallerService mInstallerService; 782 783 private final PackageDexOptimizer mPackageDexOptimizer; 784 // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package 785 // is used by other apps). 786 private final DexManager mDexManager; 787 788 private AtomicInteger mNextMoveId = new AtomicInteger(); 789 private final MoveCallbacks mMoveCallbacks; 790 791 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 792 793 // Cache of users who need badging. 794 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 795 796 /** Token for keys in mPendingVerification. */ 797 private int mPendingVerificationToken = 0; 798 799 volatile boolean mSystemReady; 800 volatile boolean mSafeMode; 801 volatile boolean mHasSystemUidErrors; 802 803 ApplicationInfo mAndroidApplication; 804 final ActivityInfo mResolveActivity = new ActivityInfo(); 805 final ResolveInfo mResolveInfo = new ResolveInfo(); 806 ComponentName mResolveComponentName; 807 PackageParser.Package mPlatformPackage; 808 ComponentName mCustomResolverComponentName; 809 810 boolean mResolverReplaced = false; 811 812 private final @Nullable ComponentName mIntentFilterVerifierComponent; 813 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 814 815 private int mIntentFilterVerificationToken = 0; 816 817 /** The service connection to the ephemeral resolver */ 818 final EphemeralResolverConnection mEphemeralResolverConnection; 819 820 /** Component used to install ephemeral applications */ 821 ComponentName mEphemeralInstallerComponent; 822 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 823 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 824 825 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 826 = new SparseArray<IntentFilterVerificationState>(); 827 828 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy; 829 830 // List of packages names to keep cached, even if they are uninstalled for all users 831 private List<String> mKeepUninstalledPackages; 832 833 private UserManagerInternal mUserManagerInternal; 834 835 private File mCacheDir; 836 837 private static class IFVerificationParams { 838 PackageParser.Package pkg; 839 boolean replacing; 840 int userId; 841 int verifierUid; 842 843 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 844 int _userId, int _verifierUid) { 845 pkg = _pkg; 846 replacing = _replacing; 847 userId = _userId; 848 replacing = _replacing; 849 verifierUid = _verifierUid; 850 } 851 } 852 853 private interface IntentFilterVerifier<T extends IntentFilter> { 854 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 855 T filter, String packageName); 856 void startVerifications(int userId); 857 void receiveVerificationResponse(int verificationId); 858 } 859 860 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 861 private Context mContext; 862 private ComponentName mIntentFilterVerifierComponent; 863 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 864 865 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 866 mContext = context; 867 mIntentFilterVerifierComponent = verifierComponent; 868 } 869 870 private String getDefaultScheme() { 871 return IntentFilter.SCHEME_HTTPS; 872 } 873 874 @Override 875 public void startVerifications(int userId) { 876 // Launch verifications requests 877 int count = mCurrentIntentFilterVerifications.size(); 878 for (int n=0; n<count; n++) { 879 int verificationId = mCurrentIntentFilterVerifications.get(n); 880 final IntentFilterVerificationState ivs = 881 mIntentFilterVerificationStates.get(verificationId); 882 883 String packageName = ivs.getPackageName(); 884 885 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 886 final int filterCount = filters.size(); 887 ArraySet<String> domainsSet = new ArraySet<>(); 888 for (int m=0; m<filterCount; m++) { 889 PackageParser.ActivityIntentInfo filter = filters.get(m); 890 domainsSet.addAll(filter.getHostsList()); 891 } 892 synchronized (mPackages) { 893 if (mSettings.createIntentFilterVerificationIfNeededLPw( 894 packageName, domainsSet) != null) { 895 scheduleWriteSettingsLocked(); 896 } 897 } 898 sendVerificationRequest(userId, verificationId, ivs); 899 } 900 mCurrentIntentFilterVerifications.clear(); 901 } 902 903 private void sendVerificationRequest(int userId, int verificationId, 904 IntentFilterVerificationState ivs) { 905 906 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 907 verificationIntent.putExtra( 908 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 909 verificationId); 910 verificationIntent.putExtra( 911 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 912 getDefaultScheme()); 913 verificationIntent.putExtra( 914 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 915 ivs.getHostsString()); 916 verificationIntent.putExtra( 917 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 918 ivs.getPackageName()); 919 verificationIntent.setComponent(mIntentFilterVerifierComponent); 920 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 921 922 UserHandle user = new UserHandle(userId); 923 mContext.sendBroadcastAsUser(verificationIntent, user); 924 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 925 "Sending IntentFilter verification broadcast"); 926 } 927 928 public void receiveVerificationResponse(int verificationId) { 929 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 930 931 final boolean verified = ivs.isVerified(); 932 933 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 934 final int count = filters.size(); 935 if (DEBUG_DOMAIN_VERIFICATION) { 936 Slog.i(TAG, "Received verification response " + verificationId 937 + " for " + count + " filters, verified=" + verified); 938 } 939 for (int n=0; n<count; n++) { 940 PackageParser.ActivityIntentInfo filter = filters.get(n); 941 filter.setVerified(verified); 942 943 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 944 + " verified with result:" + verified + " and hosts:" 945 + ivs.getHostsString()); 946 } 947 948 mIntentFilterVerificationStates.remove(verificationId); 949 950 final String packageName = ivs.getPackageName(); 951 IntentFilterVerificationInfo ivi = null; 952 953 synchronized (mPackages) { 954 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 955 } 956 if (ivi == null) { 957 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 958 + verificationId + " packageName:" + packageName); 959 return; 960 } 961 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 962 "Updating IntentFilterVerificationInfo for package " + packageName 963 +" verificationId:" + verificationId); 964 965 synchronized (mPackages) { 966 if (verified) { 967 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 968 } else { 969 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 970 } 971 scheduleWriteSettingsLocked(); 972 973 final int userId = ivs.getUserId(); 974 if (userId != UserHandle.USER_ALL) { 975 final int userStatus = 976 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 977 978 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 979 boolean needUpdate = false; 980 981 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 982 // already been set by the User thru the Disambiguation dialog 983 switch (userStatus) { 984 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 985 if (verified) { 986 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 987 } else { 988 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 989 } 990 needUpdate = true; 991 break; 992 993 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 994 if (verified) { 995 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 996 needUpdate = true; 997 } 998 break; 999 1000 default: 1001 // Nothing to do 1002 } 1003 1004 if (needUpdate) { 1005 mSettings.updateIntentFilterVerificationStatusLPw( 1006 packageName, updatedStatus, userId); 1007 scheduleWritePackageRestrictionsLocked(userId); 1008 } 1009 } 1010 } 1011 } 1012 1013 @Override 1014 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 1015 ActivityIntentInfo filter, String packageName) { 1016 if (!hasValidDomains(filter)) { 1017 return false; 1018 } 1019 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 1020 if (ivs == null) { 1021 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 1022 packageName); 1023 } 1024 if (DEBUG_DOMAIN_VERIFICATION) { 1025 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 1026 } 1027 ivs.addFilter(filter); 1028 return true; 1029 } 1030 1031 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 1032 int userId, int verificationId, String packageName) { 1033 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 1034 verifierUid, userId, packageName); 1035 ivs.setPendingState(); 1036 synchronized (mPackages) { 1037 mIntentFilterVerificationStates.append(verificationId, ivs); 1038 mCurrentIntentFilterVerifications.add(verificationId); 1039 } 1040 return ivs; 1041 } 1042 } 1043 1044 private static boolean hasValidDomains(ActivityIntentInfo filter) { 1045 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 1046 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 1047 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 1048 } 1049 1050 // Set of pending broadcasts for aggregating enable/disable of components. 1051 static class PendingPackageBroadcasts { 1052 // for each user id, a map of <package name -> components within that package> 1053 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 1054 1055 public PendingPackageBroadcasts() { 1056 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 1057 } 1058 1059 public ArrayList<String> get(int userId, String packageName) { 1060 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1061 return packages.get(packageName); 1062 } 1063 1064 public void put(int userId, String packageName, ArrayList<String> components) { 1065 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1066 packages.put(packageName, components); 1067 } 1068 1069 public void remove(int userId, String packageName) { 1070 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 1071 if (packages != null) { 1072 packages.remove(packageName); 1073 } 1074 } 1075 1076 public void remove(int userId) { 1077 mUidMap.remove(userId); 1078 } 1079 1080 public int userIdCount() { 1081 return mUidMap.size(); 1082 } 1083 1084 public int userIdAt(int n) { 1085 return mUidMap.keyAt(n); 1086 } 1087 1088 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 1089 return mUidMap.get(userId); 1090 } 1091 1092 public int size() { 1093 // total number of pending broadcast entries across all userIds 1094 int num = 0; 1095 for (int i = 0; i< mUidMap.size(); i++) { 1096 num += mUidMap.valueAt(i).size(); 1097 } 1098 return num; 1099 } 1100 1101 public void clear() { 1102 mUidMap.clear(); 1103 } 1104 1105 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1106 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1107 if (map == null) { 1108 map = new ArrayMap<String, ArrayList<String>>(); 1109 mUidMap.put(userId, map); 1110 } 1111 return map; 1112 } 1113 } 1114 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1115 1116 // Service Connection to remote media container service to copy 1117 // package uri's from external media onto secure containers 1118 // or internal storage. 1119 private IMediaContainerService mContainerService = null; 1120 1121 static final int SEND_PENDING_BROADCAST = 1; 1122 static final int MCS_BOUND = 3; 1123 static final int END_COPY = 4; 1124 static final int INIT_COPY = 5; 1125 static final int MCS_UNBIND = 6; 1126 static final int START_CLEANING_PACKAGE = 7; 1127 static final int FIND_INSTALL_LOC = 8; 1128 static final int POST_INSTALL = 9; 1129 static final int MCS_RECONNECT = 10; 1130 static final int MCS_GIVE_UP = 11; 1131 static final int UPDATED_MEDIA_STATUS = 12; 1132 static final int WRITE_SETTINGS = 13; 1133 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1134 static final int PACKAGE_VERIFIED = 15; 1135 static final int CHECK_PENDING_VERIFICATION = 16; 1136 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1137 static final int INTENT_FILTER_VERIFIED = 18; 1138 static final int WRITE_PACKAGE_LIST = 19; 1139 static final int EPHEMERAL_RESOLUTION_PHASE_TWO = 20; 1140 1141 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1142 1143 // Delay time in millisecs 1144 static final int BROADCAST_DELAY = 10 * 1000; 1145 1146 static UserManagerService sUserManager; 1147 1148 // Stores a list of users whose package restrictions file needs to be updated 1149 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1150 1151 final private DefaultContainerConnection mDefContainerConn = 1152 new DefaultContainerConnection(); 1153 class DefaultContainerConnection implements ServiceConnection { 1154 public void onServiceConnected(ComponentName name, IBinder service) { 1155 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1156 final IMediaContainerService imcs = IMediaContainerService.Stub 1157 .asInterface(Binder.allowBlocking(service)); 1158 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1159 } 1160 1161 public void onServiceDisconnected(ComponentName name) { 1162 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1163 } 1164 } 1165 1166 // Recordkeeping of restore-after-install operations that are currently in flight 1167 // between the Package Manager and the Backup Manager 1168 static class PostInstallData { 1169 public InstallArgs args; 1170 public PackageInstalledInfo res; 1171 1172 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1173 args = _a; 1174 res = _r; 1175 } 1176 } 1177 1178 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1179 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1180 1181 // XML tags for backup/restore of various bits of state 1182 private static final String TAG_PREFERRED_BACKUP = "pa"; 1183 private static final String TAG_DEFAULT_APPS = "da"; 1184 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1185 1186 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1187 private static final String TAG_ALL_GRANTS = "rt-grants"; 1188 private static final String TAG_GRANT = "grant"; 1189 private static final String ATTR_PACKAGE_NAME = "pkg"; 1190 1191 private static final String TAG_PERMISSION = "perm"; 1192 private static final String ATTR_PERMISSION_NAME = "name"; 1193 private static final String ATTR_IS_GRANTED = "g"; 1194 private static final String ATTR_USER_SET = "set"; 1195 private static final String ATTR_USER_FIXED = "fixed"; 1196 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1197 1198 // System/policy permission grants are not backed up 1199 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1200 FLAG_PERMISSION_POLICY_FIXED 1201 | FLAG_PERMISSION_SYSTEM_FIXED 1202 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1203 1204 // And we back up these user-adjusted states 1205 private static final int USER_RUNTIME_GRANT_MASK = 1206 FLAG_PERMISSION_USER_SET 1207 | FLAG_PERMISSION_USER_FIXED 1208 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1209 1210 final @Nullable String mRequiredVerifierPackage; 1211 final @NonNull String mRequiredInstallerPackage; 1212 final @NonNull String mRequiredUninstallerPackage; 1213 final @Nullable String mSetupWizardPackage; 1214 final @Nullable String mStorageManagerPackage; 1215 final @NonNull String mServicesSystemSharedLibraryPackageName; 1216 final @NonNull String mSharedSystemSharedLibraryPackageName; 1217 1218 final boolean mPermissionReviewRequired; 1219 1220 private final PackageUsage mPackageUsage = new PackageUsage(); 1221 private final CompilerStats mCompilerStats = new CompilerStats(); 1222 1223 class PackageHandler extends Handler { 1224 private boolean mBound = false; 1225 final ArrayList<HandlerParams> mPendingInstalls = 1226 new ArrayList<HandlerParams>(); 1227 1228 private boolean connectToService() { 1229 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1230 " DefaultContainerService"); 1231 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1232 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1233 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1234 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1235 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1236 mBound = true; 1237 return true; 1238 } 1239 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1240 return false; 1241 } 1242 1243 private void disconnectService() { 1244 mContainerService = null; 1245 mBound = false; 1246 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1247 mContext.unbindService(mDefContainerConn); 1248 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1249 } 1250 1251 PackageHandler(Looper looper) { 1252 super(looper); 1253 } 1254 1255 public void handleMessage(Message msg) { 1256 try { 1257 doHandleMessage(msg); 1258 } finally { 1259 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1260 } 1261 } 1262 1263 void doHandleMessage(Message msg) { 1264 switch (msg.what) { 1265 case INIT_COPY: { 1266 HandlerParams params = (HandlerParams) msg.obj; 1267 int idx = mPendingInstalls.size(); 1268 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1269 // If a bind was already initiated we dont really 1270 // need to do anything. The pending install 1271 // will be processed later on. 1272 if (!mBound) { 1273 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1274 System.identityHashCode(mHandler)); 1275 // If this is the only one pending we might 1276 // have to bind to the service again. 1277 if (!connectToService()) { 1278 Slog.e(TAG, "Failed to bind to media container service"); 1279 params.serviceError(); 1280 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1281 System.identityHashCode(mHandler)); 1282 if (params.traceMethod != null) { 1283 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1284 params.traceCookie); 1285 } 1286 return; 1287 } else { 1288 // Once we bind to the service, the first 1289 // pending request will be processed. 1290 mPendingInstalls.add(idx, params); 1291 } 1292 } else { 1293 mPendingInstalls.add(idx, params); 1294 // Already bound to the service. Just make 1295 // sure we trigger off processing the first request. 1296 if (idx == 0) { 1297 mHandler.sendEmptyMessage(MCS_BOUND); 1298 } 1299 } 1300 break; 1301 } 1302 case MCS_BOUND: { 1303 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1304 if (msg.obj != null) { 1305 mContainerService = (IMediaContainerService) msg.obj; 1306 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1307 System.identityHashCode(mHandler)); 1308 } 1309 if (mContainerService == null) { 1310 if (!mBound) { 1311 // Something seriously wrong since we are not bound and we are not 1312 // waiting for connection. Bail out. 1313 Slog.e(TAG, "Cannot bind to media container service"); 1314 for (HandlerParams params : mPendingInstalls) { 1315 // Indicate service bind error 1316 params.serviceError(); 1317 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1318 System.identityHashCode(params)); 1319 if (params.traceMethod != null) { 1320 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1321 params.traceMethod, params.traceCookie); 1322 } 1323 return; 1324 } 1325 mPendingInstalls.clear(); 1326 } else { 1327 Slog.w(TAG, "Waiting to connect to media container service"); 1328 } 1329 } else if (mPendingInstalls.size() > 0) { 1330 HandlerParams params = mPendingInstalls.get(0); 1331 if (params != null) { 1332 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1333 System.identityHashCode(params)); 1334 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1335 if (params.startCopy()) { 1336 // We are done... look for more work or to 1337 // go idle. 1338 if (DEBUG_SD_INSTALL) Log.i(TAG, 1339 "Checking for more work or unbind..."); 1340 // Delete pending install 1341 if (mPendingInstalls.size() > 0) { 1342 mPendingInstalls.remove(0); 1343 } 1344 if (mPendingInstalls.size() == 0) { 1345 if (mBound) { 1346 if (DEBUG_SD_INSTALL) Log.i(TAG, 1347 "Posting delayed MCS_UNBIND"); 1348 removeMessages(MCS_UNBIND); 1349 Message ubmsg = obtainMessage(MCS_UNBIND); 1350 // Unbind after a little delay, to avoid 1351 // continual thrashing. 1352 sendMessageDelayed(ubmsg, 10000); 1353 } 1354 } else { 1355 // There are more pending requests in queue. 1356 // Just post MCS_BOUND message to trigger processing 1357 // of next pending install. 1358 if (DEBUG_SD_INSTALL) Log.i(TAG, 1359 "Posting MCS_BOUND for next work"); 1360 mHandler.sendEmptyMessage(MCS_BOUND); 1361 } 1362 } 1363 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1364 } 1365 } else { 1366 // Should never happen ideally. 1367 Slog.w(TAG, "Empty queue"); 1368 } 1369 break; 1370 } 1371 case MCS_RECONNECT: { 1372 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1373 if (mPendingInstalls.size() > 0) { 1374 if (mBound) { 1375 disconnectService(); 1376 } 1377 if (!connectToService()) { 1378 Slog.e(TAG, "Failed to bind to media container service"); 1379 for (HandlerParams params : mPendingInstalls) { 1380 // Indicate service bind error 1381 params.serviceError(); 1382 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1383 System.identityHashCode(params)); 1384 } 1385 mPendingInstalls.clear(); 1386 } 1387 } 1388 break; 1389 } 1390 case MCS_UNBIND: { 1391 // If there is no actual work left, then time to unbind. 1392 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1393 1394 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1395 if (mBound) { 1396 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1397 1398 disconnectService(); 1399 } 1400 } else if (mPendingInstalls.size() > 0) { 1401 // There are more pending requests in queue. 1402 // Just post MCS_BOUND message to trigger processing 1403 // of next pending install. 1404 mHandler.sendEmptyMessage(MCS_BOUND); 1405 } 1406 1407 break; 1408 } 1409 case MCS_GIVE_UP: { 1410 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1411 HandlerParams params = mPendingInstalls.remove(0); 1412 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1413 System.identityHashCode(params)); 1414 break; 1415 } 1416 case SEND_PENDING_BROADCAST: { 1417 String packages[]; 1418 ArrayList<String> components[]; 1419 int size = 0; 1420 int uids[]; 1421 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1422 synchronized (mPackages) { 1423 if (mPendingBroadcasts == null) { 1424 return; 1425 } 1426 size = mPendingBroadcasts.size(); 1427 if (size <= 0) { 1428 // Nothing to be done. Just return 1429 return; 1430 } 1431 packages = new String[size]; 1432 components = new ArrayList[size]; 1433 uids = new int[size]; 1434 int i = 0; // filling out the above arrays 1435 1436 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1437 int packageUserId = mPendingBroadcasts.userIdAt(n); 1438 Iterator<Map.Entry<String, ArrayList<String>>> it 1439 = mPendingBroadcasts.packagesForUserId(packageUserId) 1440 .entrySet().iterator(); 1441 while (it.hasNext() && i < size) { 1442 Map.Entry<String, ArrayList<String>> ent = it.next(); 1443 packages[i] = ent.getKey(); 1444 components[i] = ent.getValue(); 1445 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1446 uids[i] = (ps != null) 1447 ? UserHandle.getUid(packageUserId, ps.appId) 1448 : -1; 1449 i++; 1450 } 1451 } 1452 size = i; 1453 mPendingBroadcasts.clear(); 1454 } 1455 // Send broadcasts 1456 for (int i = 0; i < size; i++) { 1457 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1458 } 1459 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1460 break; 1461 } 1462 case START_CLEANING_PACKAGE: { 1463 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1464 final String packageName = (String)msg.obj; 1465 final int userId = msg.arg1; 1466 final boolean andCode = msg.arg2 != 0; 1467 synchronized (mPackages) { 1468 if (userId == UserHandle.USER_ALL) { 1469 int[] users = sUserManager.getUserIds(); 1470 for (int user : users) { 1471 mSettings.addPackageToCleanLPw( 1472 new PackageCleanItem(user, packageName, andCode)); 1473 } 1474 } else { 1475 mSettings.addPackageToCleanLPw( 1476 new PackageCleanItem(userId, packageName, andCode)); 1477 } 1478 } 1479 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1480 startCleaningPackages(); 1481 } break; 1482 case POST_INSTALL: { 1483 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1484 1485 PostInstallData data = mRunningInstalls.get(msg.arg1); 1486 final boolean didRestore = (msg.arg2 != 0); 1487 mRunningInstalls.delete(msg.arg1); 1488 1489 if (data != null) { 1490 InstallArgs args = data.args; 1491 PackageInstalledInfo parentRes = data.res; 1492 1493 final boolean grantPermissions = (args.installFlags 1494 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1495 final boolean killApp = (args.installFlags 1496 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1497 final String[] grantedPermissions = args.installGrantPermissions; 1498 1499 // Handle the parent package 1500 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1501 grantedPermissions, didRestore, args.installerPackageName, 1502 args.observer); 1503 1504 // Handle the child packages 1505 final int childCount = (parentRes.addedChildPackages != null) 1506 ? parentRes.addedChildPackages.size() : 0; 1507 for (int i = 0; i < childCount; i++) { 1508 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1509 handlePackagePostInstall(childRes, grantPermissions, killApp, 1510 grantedPermissions, false, args.installerPackageName, 1511 args.observer); 1512 } 1513 1514 // Log tracing if needed 1515 if (args.traceMethod != null) { 1516 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1517 args.traceCookie); 1518 } 1519 } else { 1520 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1521 } 1522 1523 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1524 } break; 1525 case UPDATED_MEDIA_STATUS: { 1526 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1527 boolean reportStatus = msg.arg1 == 1; 1528 boolean doGc = msg.arg2 == 1; 1529 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1530 if (doGc) { 1531 // Force a gc to clear up stale containers. 1532 Runtime.getRuntime().gc(); 1533 } 1534 if (msg.obj != null) { 1535 @SuppressWarnings("unchecked") 1536 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1537 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1538 // Unload containers 1539 unloadAllContainers(args); 1540 } 1541 if (reportStatus) { 1542 try { 1543 if (DEBUG_SD_INSTALL) Log.i(TAG, 1544 "Invoking StorageManagerService call back"); 1545 PackageHelper.getStorageManager().finishMediaUpdate(); 1546 } catch (RemoteException e) { 1547 Log.e(TAG, "StorageManagerService not running?"); 1548 } 1549 } 1550 } break; 1551 case WRITE_SETTINGS: { 1552 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1553 synchronized (mPackages) { 1554 removeMessages(WRITE_SETTINGS); 1555 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1556 mSettings.writeLPr(); 1557 mDirtyUsers.clear(); 1558 } 1559 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1560 } break; 1561 case WRITE_PACKAGE_RESTRICTIONS: { 1562 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1563 synchronized (mPackages) { 1564 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1565 for (int userId : mDirtyUsers) { 1566 mSettings.writePackageRestrictionsLPr(userId); 1567 } 1568 mDirtyUsers.clear(); 1569 } 1570 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1571 } break; 1572 case WRITE_PACKAGE_LIST: { 1573 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1574 synchronized (mPackages) { 1575 removeMessages(WRITE_PACKAGE_LIST); 1576 mSettings.writePackageListLPr(msg.arg1); 1577 } 1578 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1579 } break; 1580 case CHECK_PENDING_VERIFICATION: { 1581 final int verificationId = msg.arg1; 1582 final PackageVerificationState state = mPendingVerification.get(verificationId); 1583 1584 if ((state != null) && !state.timeoutExtended()) { 1585 final InstallArgs args = state.getInstallArgs(); 1586 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1587 1588 Slog.i(TAG, "Verification timed out for " + originUri); 1589 mPendingVerification.remove(verificationId); 1590 1591 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1592 1593 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1594 Slog.i(TAG, "Continuing with installation of " + originUri); 1595 state.setVerifierResponse(Binder.getCallingUid(), 1596 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1597 broadcastPackageVerified(verificationId, originUri, 1598 PackageManager.VERIFICATION_ALLOW, 1599 state.getInstallArgs().getUser()); 1600 try { 1601 ret = args.copyApk(mContainerService, true); 1602 } catch (RemoteException e) { 1603 Slog.e(TAG, "Could not contact the ContainerService"); 1604 } 1605 } else { 1606 broadcastPackageVerified(verificationId, originUri, 1607 PackageManager.VERIFICATION_REJECT, 1608 state.getInstallArgs().getUser()); 1609 } 1610 1611 Trace.asyncTraceEnd( 1612 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1613 1614 processPendingInstall(args, ret); 1615 mHandler.sendEmptyMessage(MCS_UNBIND); 1616 } 1617 break; 1618 } 1619 case PACKAGE_VERIFIED: { 1620 final int verificationId = msg.arg1; 1621 1622 final PackageVerificationState state = mPendingVerification.get(verificationId); 1623 if (state == null) { 1624 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1625 break; 1626 } 1627 1628 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1629 1630 state.setVerifierResponse(response.callerUid, response.code); 1631 1632 if (state.isVerificationComplete()) { 1633 mPendingVerification.remove(verificationId); 1634 1635 final InstallArgs args = state.getInstallArgs(); 1636 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1637 1638 int ret; 1639 if (state.isInstallAllowed()) { 1640 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1641 broadcastPackageVerified(verificationId, originUri, 1642 response.code, state.getInstallArgs().getUser()); 1643 try { 1644 ret = args.copyApk(mContainerService, true); 1645 } catch (RemoteException e) { 1646 Slog.e(TAG, "Could not contact the ContainerService"); 1647 } 1648 } else { 1649 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1650 } 1651 1652 Trace.asyncTraceEnd( 1653 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1654 1655 processPendingInstall(args, ret); 1656 mHandler.sendEmptyMessage(MCS_UNBIND); 1657 } 1658 1659 break; 1660 } 1661 case START_INTENT_FILTER_VERIFICATIONS: { 1662 IFVerificationParams params = (IFVerificationParams) msg.obj; 1663 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1664 params.replacing, params.pkg); 1665 break; 1666 } 1667 case INTENT_FILTER_VERIFIED: { 1668 final int verificationId = msg.arg1; 1669 1670 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1671 verificationId); 1672 if (state == null) { 1673 Slog.w(TAG, "Invalid IntentFilter verification token " 1674 + verificationId + " received"); 1675 break; 1676 } 1677 1678 final int userId = state.getUserId(); 1679 1680 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1681 "Processing IntentFilter verification with token:" 1682 + verificationId + " and userId:" + userId); 1683 1684 final IntentFilterVerificationResponse response = 1685 (IntentFilterVerificationResponse) msg.obj; 1686 1687 state.setVerifierResponse(response.callerUid, response.code); 1688 1689 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1690 "IntentFilter verification with token:" + verificationId 1691 + " and userId:" + userId 1692 + " is settings verifier response with response code:" 1693 + response.code); 1694 1695 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1696 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1697 + response.getFailedDomainsString()); 1698 } 1699 1700 if (state.isVerificationComplete()) { 1701 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1702 } else { 1703 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1704 "IntentFilter verification with token:" + verificationId 1705 + " was not said to be complete"); 1706 } 1707 1708 break; 1709 } 1710 case EPHEMERAL_RESOLUTION_PHASE_TWO: { 1711 EphemeralResolver.doEphemeralResolutionPhaseTwo(mContext, 1712 mEphemeralResolverConnection, 1713 (EphemeralRequest) msg.obj, 1714 mEphemeralInstallerActivity, 1715 mHandler); 1716 } 1717 } 1718 } 1719 } 1720 1721 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1722 boolean killApp, String[] grantedPermissions, 1723 boolean launchedForRestore, String installerPackage, 1724 IPackageInstallObserver2 installObserver) { 1725 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1726 // Send the removed broadcasts 1727 if (res.removedInfo != null) { 1728 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1729 } 1730 1731 // Now that we successfully installed the package, grant runtime 1732 // permissions if requested before broadcasting the install. Also 1733 // for legacy apps in permission review mode we clear the permission 1734 // review flag which is used to emulate runtime permissions for 1735 // legacy apps. 1736 if (grantPermissions) { 1737 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1738 } 1739 1740 final boolean update = res.removedInfo != null 1741 && res.removedInfo.removedPackage != null; 1742 1743 // If this is the first time we have child packages for a disabled privileged 1744 // app that had no children, we grant requested runtime permissions to the new 1745 // children if the parent on the system image had them already granted. 1746 if (res.pkg.parentPackage != null) { 1747 synchronized (mPackages) { 1748 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1749 } 1750 } 1751 1752 synchronized (mPackages) { 1753 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1754 } 1755 1756 final String packageName = res.pkg.applicationInfo.packageName; 1757 1758 // Determine the set of users who are adding this package for 1759 // the first time vs. those who are seeing an update. 1760 int[] firstUsers = EMPTY_INT_ARRAY; 1761 int[] updateUsers = EMPTY_INT_ARRAY; 1762 if (res.origUsers == null || res.origUsers.length == 0) { 1763 firstUsers = res.newUsers; 1764 } else { 1765 for (int newUser : res.newUsers) { 1766 boolean isNew = true; 1767 for (int origUser : res.origUsers) { 1768 if (origUser == newUser) { 1769 isNew = false; 1770 break; 1771 } 1772 } 1773 if (isNew) { 1774 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1775 } else { 1776 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1777 } 1778 } 1779 } 1780 1781 // Send installed broadcasts if the install/update is not ephemeral 1782 // and the package is not a static shared lib. 1783 if (!isEphemeral(res.pkg) && res.pkg.staticSharedLibName == null) { 1784 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1785 1786 // Send added for users that see the package for the first time 1787 // sendPackageAddedForNewUsers also deals with system apps 1788 int appId = UserHandle.getAppId(res.uid); 1789 boolean isSystem = res.pkg.applicationInfo.isSystemApp(); 1790 sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers); 1791 1792 // Send added for users that don't see the package for the first time 1793 Bundle extras = new Bundle(1); 1794 extras.putInt(Intent.EXTRA_UID, res.uid); 1795 if (update) { 1796 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1797 } 1798 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1799 extras, 0 /*flags*/, null /*targetPackage*/, 1800 null /*finishedReceiver*/, updateUsers); 1801 1802 // Send replaced for users that don't see the package for the first time 1803 if (update) { 1804 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1805 packageName, extras, 0 /*flags*/, 1806 null /*targetPackage*/, null /*finishedReceiver*/, 1807 updateUsers); 1808 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1809 null /*package*/, null /*extras*/, 0 /*flags*/, 1810 packageName /*targetPackage*/, 1811 null /*finishedReceiver*/, updateUsers); 1812 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 1813 // First-install and we did a restore, so we're responsible for the 1814 // first-launch broadcast. 1815 if (DEBUG_BACKUP) { 1816 Slog.i(TAG, "Post-restore of " + packageName 1817 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers)); 1818 } 1819 sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers); 1820 } 1821 1822 // Send broadcast package appeared if forward locked/external for all users 1823 // treat asec-hosted packages like removable media on upgrade 1824 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1825 if (DEBUG_INSTALL) { 1826 Slog.i(TAG, "upgrading pkg " + res.pkg 1827 + " is ASEC-hosted -> AVAILABLE"); 1828 } 1829 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1830 ArrayList<String> pkgList = new ArrayList<>(1); 1831 pkgList.add(packageName); 1832 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1833 } 1834 } 1835 1836 // Work that needs to happen on first install within each user 1837 if (firstUsers != null && firstUsers.length > 0) { 1838 synchronized (mPackages) { 1839 for (int userId : firstUsers) { 1840 // If this app is a browser and it's newly-installed for some 1841 // users, clear any default-browser state in those users. The 1842 // app's nature doesn't depend on the user, so we can just check 1843 // its browser nature in any user and generalize. 1844 if (packageIsBrowser(packageName, userId)) { 1845 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1846 } 1847 1848 // We may also need to apply pending (restored) runtime 1849 // permission grants within these users. 1850 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1851 } 1852 } 1853 } 1854 1855 // Log current value of "unknown sources" setting 1856 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1857 getUnknownSourcesSettings()); 1858 1859 // Force a gc to clear up things 1860 Runtime.getRuntime().gc(); 1861 1862 // Remove the replaced package's older resources safely now 1863 // We delete after a gc for applications on sdcard. 1864 if (res.removedInfo != null && res.removedInfo.args != null) { 1865 synchronized (mInstallLock) { 1866 res.removedInfo.args.doPostDeleteLI(true); 1867 } 1868 } 1869 } 1870 1871 // If someone is watching installs - notify them 1872 if (installObserver != null) { 1873 try { 1874 Bundle extras = extrasForInstallResult(res); 1875 installObserver.onPackageInstalled(res.name, res.returnCode, 1876 res.returnMsg, extras); 1877 } catch (RemoteException e) { 1878 Slog.i(TAG, "Observer no longer exists."); 1879 } 1880 } 1881 } 1882 1883 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1884 PackageParser.Package pkg) { 1885 if (pkg.parentPackage == null) { 1886 return; 1887 } 1888 if (pkg.requestedPermissions == null) { 1889 return; 1890 } 1891 final PackageSetting disabledSysParentPs = mSettings 1892 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1893 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1894 || !disabledSysParentPs.isPrivileged() 1895 || (disabledSysParentPs.childPackageNames != null 1896 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1897 return; 1898 } 1899 final int[] allUserIds = sUserManager.getUserIds(); 1900 final int permCount = pkg.requestedPermissions.size(); 1901 for (int i = 0; i < permCount; i++) { 1902 String permission = pkg.requestedPermissions.get(i); 1903 BasePermission bp = mSettings.mPermissions.get(permission); 1904 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1905 continue; 1906 } 1907 for (int userId : allUserIds) { 1908 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1909 permission, userId)) { 1910 grantRuntimePermission(pkg.packageName, permission, userId); 1911 } 1912 } 1913 } 1914 } 1915 1916 private StorageEventListener mStorageListener = new StorageEventListener() { 1917 @Override 1918 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1919 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1920 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1921 final String volumeUuid = vol.getFsUuid(); 1922 1923 // Clean up any users or apps that were removed or recreated 1924 // while this volume was missing 1925 reconcileUsers(volumeUuid); 1926 reconcileApps(volumeUuid); 1927 1928 // Clean up any install sessions that expired or were 1929 // cancelled while this volume was missing 1930 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1931 1932 loadPrivatePackages(vol); 1933 1934 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1935 unloadPrivatePackages(vol); 1936 } 1937 } 1938 1939 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1940 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1941 updateExternalMediaStatus(true, false); 1942 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1943 updateExternalMediaStatus(false, false); 1944 } 1945 } 1946 } 1947 1948 @Override 1949 public void onVolumeForgotten(String fsUuid) { 1950 if (TextUtils.isEmpty(fsUuid)) { 1951 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1952 return; 1953 } 1954 1955 // Remove any apps installed on the forgotten volume 1956 synchronized (mPackages) { 1957 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1958 for (PackageSetting ps : packages) { 1959 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1960 deletePackageVersioned(new VersionedPackage(ps.name, 1961 PackageManager.VERSION_CODE_HIGHEST), 1962 new LegacyPackageDeleteObserver(null).getBinder(), 1963 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 1964 // Try very hard to release any references to this package 1965 // so we don't risk the system server being killed due to 1966 // open FDs 1967 AttributeCache.instance().removePackage(ps.name); 1968 } 1969 1970 mSettings.onVolumeForgotten(fsUuid); 1971 mSettings.writeLPr(); 1972 } 1973 } 1974 }; 1975 1976 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 1977 String[] grantedPermissions) { 1978 for (int userId : userIds) { 1979 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1980 } 1981 } 1982 1983 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1984 String[] grantedPermissions) { 1985 SettingBase sb = (SettingBase) pkg.mExtras; 1986 if (sb == null) { 1987 return; 1988 } 1989 1990 PermissionsState permissionsState = sb.getPermissionsState(); 1991 1992 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 1993 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 1994 1995 final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 1996 >= Build.VERSION_CODES.M; 1997 1998 for (String permission : pkg.requestedPermissions) { 1999 final BasePermission bp; 2000 synchronized (mPackages) { 2001 bp = mSettings.mPermissions.get(permission); 2002 } 2003 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 2004 && (grantedPermissions == null 2005 || ArrayUtils.contains(grantedPermissions, permission))) { 2006 final int flags = permissionsState.getPermissionFlags(permission, userId); 2007 if (supportsRuntimePermissions) { 2008 // Installer cannot change immutable permissions. 2009 if ((flags & immutableFlags) == 0) { 2010 grantRuntimePermission(pkg.packageName, permission, userId); 2011 } 2012 } else if (mPermissionReviewRequired) { 2013 // In permission review mode we clear the review flag when we 2014 // are asked to install the app with all permissions granted. 2015 if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 2016 updatePermissionFlags(permission, pkg.packageName, 2017 PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId); 2018 } 2019 } 2020 } 2021 } 2022 } 2023 2024 Bundle extrasForInstallResult(PackageInstalledInfo res) { 2025 Bundle extras = null; 2026 switch (res.returnCode) { 2027 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 2028 extras = new Bundle(); 2029 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 2030 res.origPermission); 2031 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 2032 res.origPackage); 2033 break; 2034 } 2035 case PackageManager.INSTALL_SUCCEEDED: { 2036 extras = new Bundle(); 2037 extras.putBoolean(Intent.EXTRA_REPLACING, 2038 res.removedInfo != null && res.removedInfo.removedPackage != null); 2039 break; 2040 } 2041 } 2042 return extras; 2043 } 2044 2045 void scheduleWriteSettingsLocked() { 2046 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2047 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2048 } 2049 } 2050 2051 void scheduleWritePackageListLocked(int userId) { 2052 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) { 2053 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST); 2054 msg.arg1 = userId; 2055 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY); 2056 } 2057 } 2058 2059 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2060 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2061 scheduleWritePackageRestrictionsLocked(userId); 2062 } 2063 2064 void scheduleWritePackageRestrictionsLocked(int userId) { 2065 final int[] userIds = (userId == UserHandle.USER_ALL) 2066 ? sUserManager.getUserIds() : new int[]{userId}; 2067 for (int nextUserId : userIds) { 2068 if (!sUserManager.exists(nextUserId)) return; 2069 mDirtyUsers.add(nextUserId); 2070 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2071 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2072 } 2073 } 2074 } 2075 2076 public static PackageManagerService main(Context context, Installer installer, 2077 boolean factoryTest, boolean onlyCore) { 2078 // Self-check for initial settings. 2079 PackageManagerServiceCompilerMapping.checkProperties(); 2080 2081 PackageManagerService m = new PackageManagerService(context, installer, 2082 factoryTest, onlyCore); 2083 m.enableSystemUserPackages(); 2084 ServiceManager.addService("package", m); 2085 return m; 2086 } 2087 2088 private void enableSystemUserPackages() { 2089 if (!UserManager.isSplitSystemUser()) { 2090 return; 2091 } 2092 // For system user, enable apps based on the following conditions: 2093 // - app is whitelisted or belong to one of these groups: 2094 // -- system app which has no launcher icons 2095 // -- system app which has INTERACT_ACROSS_USERS permission 2096 // -- system IME app 2097 // - app is not in the blacklist 2098 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2099 Set<String> enableApps = new ArraySet<>(); 2100 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2101 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2102 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2103 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2104 enableApps.addAll(wlApps); 2105 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2106 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2107 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2108 enableApps.removeAll(blApps); 2109 Log.i(TAG, "Applications installed for system user: " + enableApps); 2110 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2111 UserHandle.SYSTEM); 2112 final int allAppsSize = allAps.size(); 2113 synchronized (mPackages) { 2114 for (int i = 0; i < allAppsSize; i++) { 2115 String pName = allAps.get(i); 2116 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2117 // Should not happen, but we shouldn't be failing if it does 2118 if (pkgSetting == null) { 2119 continue; 2120 } 2121 boolean install = enableApps.contains(pName); 2122 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2123 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2124 + " for system user"); 2125 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2126 } 2127 } 2128 } 2129 } 2130 2131 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2132 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2133 Context.DISPLAY_SERVICE); 2134 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2135 } 2136 2137 /** 2138 * Requests that files preopted on a secondary system partition be copied to the data partition 2139 * if possible. Note that the actual copying of the files is accomplished by init for security 2140 * reasons. This simply requests that the copy takes place and awaits confirmation of its 2141 * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy. 2142 */ 2143 private static void requestCopyPreoptedFiles() { 2144 final int WAIT_TIME_MS = 100; 2145 final String CP_PREOPT_PROPERTY = "sys.cppreopt"; 2146 if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) { 2147 SystemProperties.set(CP_PREOPT_PROPERTY, "requested"); 2148 // We will wait for up to 100 seconds. 2149 final long timeEnd = SystemClock.uptimeMillis() + 100 * 1000; 2150 while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) { 2151 try { 2152 Thread.sleep(WAIT_TIME_MS); 2153 } catch (InterruptedException e) { 2154 // Do nothing 2155 } 2156 if (SystemClock.uptimeMillis() > timeEnd) { 2157 SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out"); 2158 Slog.wtf(TAG, "cppreopt did not finish!"); 2159 break; 2160 } 2161 } 2162 } 2163 } 2164 2165 public PackageManagerService(Context context, Installer installer, 2166 boolean factoryTest, boolean onlyCore) { 2167 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager"); 2168 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2169 SystemClock.uptimeMillis()); 2170 2171 if (mSdkVersion <= 0) { 2172 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2173 } 2174 2175 mContext = context; 2176 2177 mPermissionReviewRequired = context.getResources().getBoolean( 2178 R.bool.config_permissionReviewRequired); 2179 2180 mFactoryTest = factoryTest; 2181 mOnlyCore = onlyCore; 2182 mMetrics = new DisplayMetrics(); 2183 mSettings = new Settings(mPackages); 2184 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2185 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2186 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2187 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2188 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2189 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2190 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2191 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2192 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2193 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2194 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2195 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2196 2197 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2198 if (separateProcesses != null && separateProcesses.length() > 0) { 2199 if ("*".equals(separateProcesses)) { 2200 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2201 mSeparateProcesses = null; 2202 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2203 } else { 2204 mDefParseFlags = 0; 2205 mSeparateProcesses = separateProcesses.split(","); 2206 Slog.w(TAG, "Running with debug.separate_processes: " 2207 + separateProcesses); 2208 } 2209 } else { 2210 mDefParseFlags = 0; 2211 mSeparateProcesses = null; 2212 } 2213 2214 mInstaller = installer; 2215 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2216 "*dexopt*"); 2217 mDexManager = new DexManager(); 2218 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2219 2220 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2221 FgThread.get().getLooper()); 2222 2223 getDefaultDisplayMetrics(context, mMetrics); 2224 2225 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config"); 2226 SystemConfig systemConfig = SystemConfig.getInstance(); 2227 mGlobalGids = systemConfig.getGlobalGids(); 2228 mSystemPermissions = systemConfig.getSystemPermissions(); 2229 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2230 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2231 2232 mProtectedPackages = new ProtectedPackages(mContext); 2233 2234 synchronized (mInstallLock) { 2235 // writer 2236 synchronized (mPackages) { 2237 mHandlerThread = new ServiceThread(TAG, 2238 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2239 mHandlerThread.start(); 2240 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2241 mProcessLoggingHandler = new ProcessLoggingHandler(); 2242 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2243 2244 mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this); 2245 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2246 2247 File dataDir = Environment.getDataDirectory(); 2248 mAppInstallDir = new File(dataDir, "app"); 2249 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2250 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2251 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2252 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2253 2254 sUserManager = new UserManagerService(context, this, mPackages); 2255 2256 // Propagate permission configuration in to package manager. 2257 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2258 = systemConfig.getPermissions(); 2259 for (int i=0; i<permConfig.size(); i++) { 2260 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2261 BasePermission bp = mSettings.mPermissions.get(perm.name); 2262 if (bp == null) { 2263 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2264 mSettings.mPermissions.put(perm.name, bp); 2265 } 2266 if (perm.gids != null) { 2267 bp.setGids(perm.gids, perm.perUser); 2268 } 2269 } 2270 2271 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2272 final int builtInLibCount = libConfig.size(); 2273 for (int i = 0; i < builtInLibCount; i++) { 2274 String name = libConfig.keyAt(i); 2275 String path = libConfig.valueAt(i); 2276 addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED, 2277 SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0); 2278 } 2279 2280 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2281 2282 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings"); 2283 mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false)); 2284 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2285 2286 // Clean up orphaned packages for which the code path doesn't exist 2287 // and they are an update to a system app - caused by bug/32321269 2288 final int packageSettingCount = mSettings.mPackages.size(); 2289 for (int i = packageSettingCount - 1; i >= 0; i--) { 2290 PackageSetting ps = mSettings.mPackages.valueAt(i); 2291 if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists()) 2292 && mSettings.getDisabledSystemPkgLPr(ps.name) != null) { 2293 mSettings.mPackages.removeAt(i); 2294 mSettings.enableSystemPackageLPw(ps.name); 2295 } 2296 } 2297 2298 if (mFirstBoot) { 2299 requestCopyPreoptedFiles(); 2300 } 2301 2302 String customResolverActivity = Resources.getSystem().getString( 2303 R.string.config_customResolverActivity); 2304 if (TextUtils.isEmpty(customResolverActivity)) { 2305 customResolverActivity = null; 2306 } else { 2307 mCustomResolverComponentName = ComponentName.unflattenFromString( 2308 customResolverActivity); 2309 } 2310 2311 long startTime = SystemClock.uptimeMillis(); 2312 2313 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2314 startTime); 2315 2316 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2317 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2318 2319 if (bootClassPath == null) { 2320 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2321 } 2322 2323 if (systemServerClassPath == null) { 2324 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2325 } 2326 2327 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2328 final String[] dexCodeInstructionSets = 2329 getDexCodeInstructionSets( 2330 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2331 2332 /** 2333 * Ensure all external libraries have had dexopt run on them. 2334 */ 2335 if (mSharedLibraries.size() > 0) { 2336 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 2337 // NOTE: For now, we're compiling these system "shared libraries" 2338 // (and framework jars) into all available architectures. It's possible 2339 // to compile them only when we come across an app that uses them (there's 2340 // already logic for that in scanPackageLI) but that adds some complexity. 2341 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2342 final int libCount = mSharedLibraries.size(); 2343 for (int i = 0; i < libCount; i++) { 2344 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 2345 final int versionCount = versionedLib.size(); 2346 for (int j = 0; j < versionCount; j++) { 2347 SharedLibraryEntry libEntry = versionedLib.valueAt(j); 2348 final String libPath = libEntry.path != null 2349 ? libEntry.path : libEntry.apk; 2350 if (libPath == null) { 2351 continue; 2352 } 2353 try { 2354 // Shared libraries do not have profiles so we perform a full 2355 // AOT compilation (if needed). 2356 int dexoptNeeded = DexFile.getDexOptNeeded( 2357 libPath, dexCodeInstructionSet, 2358 getCompilerFilterForReason(REASON_SHARED_APK), 2359 false /* newProfile */); 2360 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2361 mInstaller.dexopt(libPath, Process.SYSTEM_UID, "*", 2362 dexCodeInstructionSet, dexoptNeeded, null, 2363 DEXOPT_PUBLIC, 2364 getCompilerFilterForReason(REASON_SHARED_APK), 2365 StorageManager.UUID_PRIVATE_INTERNAL, 2366 SKIP_SHARED_LIBRARY_CHECK); 2367 } 2368 } catch (FileNotFoundException e) { 2369 Slog.w(TAG, "Library not found: " + libPath); 2370 } catch (IOException | InstallerException e) { 2371 Slog.w(TAG, "Cannot dexopt " + libPath + "; is it an APK or JAR? " 2372 + e.getMessage()); 2373 } 2374 } 2375 } 2376 } 2377 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2378 } 2379 2380 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2381 2382 final VersionInfo ver = mSettings.getInternalVersion(); 2383 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2384 2385 // when upgrading from pre-M, promote system app permissions from install to runtime 2386 mPromoteSystemApps = 2387 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2388 2389 // When upgrading from pre-N, we need to handle package extraction like first boot, 2390 // as there is no profiling data available. 2391 mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N; 2392 2393 mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1; 2394 2395 // save off the names of pre-existing system packages prior to scanning; we don't 2396 // want to automatically grant runtime permissions for new system apps 2397 if (mPromoteSystemApps) { 2398 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2399 while (pkgSettingIter.hasNext()) { 2400 PackageSetting ps = pkgSettingIter.next(); 2401 if (isSystemApp(ps)) { 2402 mExistingSystemPackages.add(ps.name); 2403 } 2404 } 2405 } 2406 2407 mCacheDir = preparePackageParserCache(mIsUpgrade); 2408 2409 // Set flag to monitor and not change apk file paths when 2410 // scanning install directories. 2411 int scanFlags = SCAN_BOOTING | SCAN_INITIAL; 2412 2413 if (mIsUpgrade || mFirstBoot) { 2414 scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE; 2415 } 2416 2417 // Collect vendor overlay packages. (Do this before scanning any apps.) 2418 // For security and version matching reason, only consider 2419 // overlay packages if they reside in the right directory. 2420 String overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PERSIST_PROPERTY); 2421 if (overlayThemeDir.isEmpty()) { 2422 overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PROPERTY); 2423 } 2424 if (!overlayThemeDir.isEmpty()) { 2425 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR, overlayThemeDir), mDefParseFlags 2426 | PackageParser.PARSE_IS_SYSTEM 2427 | PackageParser.PARSE_IS_SYSTEM_DIR 2428 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2429 } 2430 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags 2431 | PackageParser.PARSE_IS_SYSTEM 2432 | PackageParser.PARSE_IS_SYSTEM_DIR 2433 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2434 2435 // Find base frameworks (resource packages without code). 2436 scanDirTracedLI(frameworkDir, mDefParseFlags 2437 | PackageParser.PARSE_IS_SYSTEM 2438 | PackageParser.PARSE_IS_SYSTEM_DIR 2439 | PackageParser.PARSE_IS_PRIVILEGED, 2440 scanFlags | SCAN_NO_DEX, 0); 2441 2442 // Collected privileged system packages. 2443 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2444 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2445 | PackageParser.PARSE_IS_SYSTEM 2446 | PackageParser.PARSE_IS_SYSTEM_DIR 2447 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2448 2449 // Collect ordinary system packages. 2450 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2451 scanDirTracedLI(systemAppDir, mDefParseFlags 2452 | PackageParser.PARSE_IS_SYSTEM 2453 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2454 2455 // Collect all vendor packages. 2456 File vendorAppDir = new File("/vendor/app"); 2457 try { 2458 vendorAppDir = vendorAppDir.getCanonicalFile(); 2459 } catch (IOException e) { 2460 // failed to look up canonical path, continue with original one 2461 } 2462 scanDirTracedLI(vendorAppDir, mDefParseFlags 2463 | PackageParser.PARSE_IS_SYSTEM 2464 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2465 2466 // Collect all OEM packages. 2467 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2468 scanDirTracedLI(oemAppDir, mDefParseFlags 2469 | PackageParser.PARSE_IS_SYSTEM 2470 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2471 2472 // Prune any system packages that no longer exist. 2473 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2474 if (!mOnlyCore) { 2475 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2476 while (psit.hasNext()) { 2477 PackageSetting ps = psit.next(); 2478 2479 /* 2480 * If this is not a system app, it can't be a 2481 * disable system app. 2482 */ 2483 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2484 continue; 2485 } 2486 2487 /* 2488 * If the package is scanned, it's not erased. 2489 */ 2490 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2491 if (scannedPkg != null) { 2492 /* 2493 * If the system app is both scanned and in the 2494 * disabled packages list, then it must have been 2495 * added via OTA. Remove it from the currently 2496 * scanned package so the previously user-installed 2497 * application can be scanned. 2498 */ 2499 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2500 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2501 + ps.name + "; removing system app. Last known codePath=" 2502 + ps.codePathString + ", installStatus=" + ps.installStatus 2503 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2504 + scannedPkg.mVersionCode); 2505 removePackageLI(scannedPkg, true); 2506 mExpectingBetter.put(ps.name, ps.codePath); 2507 } 2508 2509 continue; 2510 } 2511 2512 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2513 psit.remove(); 2514 logCriticalInfo(Log.WARN, "System package " + ps.name 2515 + " no longer exists; it's data will be wiped"); 2516 // Actual deletion of code and data will be handled by later 2517 // reconciliation step 2518 } else { 2519 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2520 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2521 possiblyDeletedUpdatedSystemApps.add(ps.name); 2522 } 2523 } 2524 } 2525 } 2526 2527 //look for any incomplete package installations 2528 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2529 for (int i = 0; i < deletePkgsList.size(); i++) { 2530 // Actual deletion of code and data will be handled by later 2531 // reconciliation step 2532 final String packageName = deletePkgsList.get(i).name; 2533 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2534 synchronized (mPackages) { 2535 mSettings.removePackageLPw(packageName); 2536 } 2537 } 2538 2539 //delete tmp files 2540 deleteTempPackageFiles(); 2541 2542 // Remove any shared userIDs that have no associated packages 2543 mSettings.pruneSharedUsersLPw(); 2544 2545 if (!mOnlyCore) { 2546 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2547 SystemClock.uptimeMillis()); 2548 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2549 2550 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2551 | PackageParser.PARSE_FORWARD_LOCK, 2552 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2553 2554 scanDirLI(mEphemeralInstallDir, mDefParseFlags 2555 | PackageParser.PARSE_IS_EPHEMERAL, 2556 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2557 2558 /** 2559 * Remove disable package settings for any updated system 2560 * apps that were removed via an OTA. If they're not a 2561 * previously-updated app, remove them completely. 2562 * Otherwise, just revoke their system-level permissions. 2563 */ 2564 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2565 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2566 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2567 2568 String msg; 2569 if (deletedPkg == null) { 2570 msg = "Updated system package " + deletedAppName 2571 + " no longer exists; it's data will be wiped"; 2572 // Actual deletion of code and data will be handled by later 2573 // reconciliation step 2574 } else { 2575 msg = "Updated system app + " + deletedAppName 2576 + " no longer present; removing system privileges for " 2577 + deletedAppName; 2578 2579 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2580 2581 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2582 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2583 } 2584 logCriticalInfo(Log.WARN, msg); 2585 } 2586 2587 /** 2588 * Make sure all system apps that we expected to appear on 2589 * the userdata partition actually showed up. If they never 2590 * appeared, crawl back and revive the system version. 2591 */ 2592 for (int i = 0; i < mExpectingBetter.size(); i++) { 2593 final String packageName = mExpectingBetter.keyAt(i); 2594 if (!mPackages.containsKey(packageName)) { 2595 final File scanFile = mExpectingBetter.valueAt(i); 2596 2597 logCriticalInfo(Log.WARN, "Expected better " + packageName 2598 + " but never showed up; reverting to system"); 2599 2600 int reparseFlags = mDefParseFlags; 2601 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2602 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2603 | PackageParser.PARSE_IS_SYSTEM_DIR 2604 | PackageParser.PARSE_IS_PRIVILEGED; 2605 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2606 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2607 | PackageParser.PARSE_IS_SYSTEM_DIR; 2608 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2609 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2610 | PackageParser.PARSE_IS_SYSTEM_DIR; 2611 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2612 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2613 | PackageParser.PARSE_IS_SYSTEM_DIR; 2614 } else { 2615 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2616 continue; 2617 } 2618 2619 mSettings.enableSystemPackageLPw(packageName); 2620 2621 try { 2622 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2623 } catch (PackageManagerException e) { 2624 Slog.e(TAG, "Failed to parse original system package: " 2625 + e.getMessage()); 2626 } 2627 } 2628 } 2629 } 2630 mExpectingBetter.clear(); 2631 2632 // Resolve the storage manager. 2633 mStorageManagerPackage = getStorageManagerPackageName(); 2634 2635 // Resolve protected action filters. Only the setup wizard is allowed to 2636 // have a high priority filter for these actions. 2637 mSetupWizardPackage = getSetupWizardPackageName(); 2638 if (mProtectedFilters.size() > 0) { 2639 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2640 Slog.i(TAG, "No setup wizard;" 2641 + " All protected intents capped to priority 0"); 2642 } 2643 for (ActivityIntentInfo filter : mProtectedFilters) { 2644 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2645 if (DEBUG_FILTERS) { 2646 Slog.i(TAG, "Found setup wizard;" 2647 + " allow priority " + filter.getPriority() + ";" 2648 + " package: " + filter.activity.info.packageName 2649 + " activity: " + filter.activity.className 2650 + " priority: " + filter.getPriority()); 2651 } 2652 // skip setup wizard; allow it to keep the high priority filter 2653 continue; 2654 } 2655 Slog.w(TAG, "Protected action; cap priority to 0;" 2656 + " package: " + filter.activity.info.packageName 2657 + " activity: " + filter.activity.className 2658 + " origPrio: " + filter.getPriority()); 2659 filter.setPriority(0); 2660 } 2661 } 2662 mDeferProtectedFilters = false; 2663 mProtectedFilters.clear(); 2664 2665 // Now that we know all of the shared libraries, update all clients to have 2666 // the correct library paths. 2667 updateAllSharedLibrariesLPw(null); 2668 2669 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2670 // NOTE: We ignore potential failures here during a system scan (like 2671 // the rest of the commands above) because there's precious little we 2672 // can do about it. A settings error is reported, though. 2673 adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/); 2674 } 2675 2676 // Now that we know all the packages we are keeping, 2677 // read and update their last usage times. 2678 mPackageUsage.read(mPackages); 2679 mCompilerStats.read(); 2680 2681 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2682 SystemClock.uptimeMillis()); 2683 Slog.i(TAG, "Time to scan packages: " 2684 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2685 + " seconds"); 2686 2687 // If the platform SDK has changed since the last time we booted, 2688 // we need to re-grant app permission to catch any new ones that 2689 // appear. This is really a hack, and means that apps can in some 2690 // cases get permissions that the user didn't initially explicitly 2691 // allow... it would be nice to have some better way to handle 2692 // this situation. 2693 int updateFlags = UPDATE_PERMISSIONS_ALL; 2694 if (ver.sdkVersion != mSdkVersion) { 2695 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2696 + mSdkVersion + "; regranting permissions for internal storage"); 2697 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2698 } 2699 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2700 ver.sdkVersion = mSdkVersion; 2701 2702 // If this is the first boot or an update from pre-M, and it is a normal 2703 // boot, then we need to initialize the default preferred apps across 2704 // all defined users. 2705 if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) { 2706 for (UserInfo user : sUserManager.getUsers(true)) { 2707 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2708 applyFactoryDefaultBrowserLPw(user.id); 2709 primeDomainVerificationsLPw(user.id); 2710 } 2711 } 2712 2713 // Prepare storage for system user really early during boot, 2714 // since core system apps like SettingsProvider and SystemUI 2715 // can't wait for user to start 2716 final int storageFlags; 2717 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2718 storageFlags = StorageManager.FLAG_STORAGE_DE; 2719 } else { 2720 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2721 } 2722 reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2723 storageFlags, true /* migrateAppData */); 2724 2725 // If this is first boot after an OTA, and a normal boot, then 2726 // we need to clear code cache directories. 2727 // Note that we do *not* clear the application profiles. These remain valid 2728 // across OTAs and are used to drive profile verification (post OTA) and 2729 // profile compilation (without waiting to collect a fresh set of profiles). 2730 if (mIsUpgrade && !onlyCore) { 2731 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2732 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2733 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2734 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2735 // No apps are running this early, so no need to freeze 2736 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2737 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2738 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2739 } 2740 } 2741 ver.fingerprint = Build.FINGERPRINT; 2742 } 2743 2744 checkDefaultBrowser(); 2745 2746 // clear only after permissions and other defaults have been updated 2747 mExistingSystemPackages.clear(); 2748 mPromoteSystemApps = false; 2749 2750 // All the changes are done during package scanning. 2751 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2752 2753 // can downgrade to reader 2754 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings"); 2755 mSettings.writeLPr(); 2756 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2757 2758 // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty 2759 // early on (before the package manager declares itself as early) because other 2760 // components in the system server might ask for package contexts for these apps. 2761 // 2762 // Note that "onlyCore" in this context means the system is encrypted or encrypting 2763 // (i.e, that the data partition is unavailable). 2764 if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) { 2765 long start = System.nanoTime(); 2766 List<PackageParser.Package> coreApps = new ArrayList<>(); 2767 for (PackageParser.Package pkg : mPackages.values()) { 2768 if (pkg.coreApp) { 2769 coreApps.add(pkg); 2770 } 2771 } 2772 2773 int[] stats = performDexOptUpgrade(coreApps, false, 2774 getCompilerFilterForReason(REASON_CORE_APP)); 2775 2776 final int elapsedTimeSeconds = 2777 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start); 2778 MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds); 2779 2780 if (DEBUG_DEXOPT) { 2781 Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" + 2782 stats[0] + ", " + stats[1] + ", " + stats[2] + ")"); 2783 } 2784 2785 2786 // TODO: Should we log these stats to tron too ? 2787 // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]); 2788 // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]); 2789 // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]); 2790 // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size()); 2791 } 2792 2793 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2794 SystemClock.uptimeMillis()); 2795 2796 if (!mOnlyCore) { 2797 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2798 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2799 mRequiredUninstallerPackage = getRequiredUninstallerLPr(); 2800 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2801 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2802 mIntentFilterVerifierComponent); 2803 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2804 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES, 2805 SharedLibraryInfo.VERSION_UNDEFINED); 2806 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2807 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED, 2808 SharedLibraryInfo.VERSION_UNDEFINED); 2809 } else { 2810 mRequiredVerifierPackage = null; 2811 mRequiredInstallerPackage = null; 2812 mRequiredUninstallerPackage = null; 2813 mIntentFilterVerifierComponent = null; 2814 mIntentFilterVerifier = null; 2815 mServicesSystemSharedLibraryPackageName = null; 2816 mSharedSystemSharedLibraryPackageName = null; 2817 } 2818 2819 mInstallerService = new PackageInstallerService(context, this); 2820 2821 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2822 if (ephemeralResolverComponent != null) { 2823 if (DEBUG_EPHEMERAL) { 2824 Slog.i(TAG, "Ephemeral resolver: " + ephemeralResolverComponent); 2825 } 2826 mEphemeralResolverConnection = 2827 new EphemeralResolverConnection(mContext, ephemeralResolverComponent); 2828 } else { 2829 mEphemeralResolverConnection = null; 2830 } 2831 mEphemeralInstallerComponent = getEphemeralInstallerLPr(); 2832 if (mEphemeralInstallerComponent != null) { 2833 if (DEBUG_EPHEMERAL) { 2834 Slog.i(TAG, "Ephemeral installer: " + mEphemeralInstallerComponent); 2835 } 2836 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2837 } 2838 2839 // Read and update the usage of dex files. 2840 // Do this at the end of PM init so that all the packages have their 2841 // data directory reconciled. 2842 // At this point we know the code paths of the packages, so we can validate 2843 // the disk file and build the internal cache. 2844 // The usage file is expected to be small so loading and verifying it 2845 // should take a fairly small time compare to the other activities (e.g. package 2846 // scanning). 2847 final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>(); 2848 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 2849 for (int userId : currentUserIds) { 2850 userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList()); 2851 } 2852 mDexManager.load(userPackages); 2853 } // synchronized (mPackages) 2854 } // synchronized (mInstallLock) 2855 2856 // Now after opening every single application zip, make sure they 2857 // are all flushed. Not really needed, but keeps things nice and 2858 // tidy. 2859 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC"); 2860 Runtime.getRuntime().gc(); 2861 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2862 2863 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks"); 2864 FallbackCategoryProvider.loadFallbacks(); 2865 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2866 2867 // The initial scanning above does many calls into installd while 2868 // holding the mPackages lock, but we're mostly interested in yelling 2869 // once we have a booted system. 2870 mInstaller.setWarnIfHeld(mPackages); 2871 2872 // Expose private service for system components to use. 2873 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2874 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2875 } 2876 2877 private static File preparePackageParserCache(boolean isUpgrade) { 2878 if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) { 2879 return null; 2880 } 2881 2882 // Disable package parsing on eng builds to allow for faster incremental development. 2883 if ("eng".equals(Build.TYPE)) { 2884 return null; 2885 } 2886 2887 if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) { 2888 Slog.i(TAG, "Disabling package parser cache due to system property."); 2889 return null; 2890 } 2891 2892 // The base directory for the package parser cache lives under /data/system/. 2893 final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(), 2894 "package_cache"); 2895 if (cacheBaseDir == null) { 2896 return null; 2897 } 2898 2899 // If this is a system upgrade scenario, delete the contents of the package cache dir. 2900 // This also serves to "GC" unused entries when the package cache version changes (which 2901 // can only happen during upgrades). 2902 if (isUpgrade) { 2903 FileUtils.deleteContents(cacheBaseDir); 2904 } 2905 2906 2907 // Return the versioned package cache directory. This is something like 2908 // "/data/system/package_cache/1" 2909 File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION); 2910 2911 // The following is a workaround to aid development on non-numbered userdebug 2912 // builds or cases where "adb sync" is used on userdebug builds. If we detect that 2913 // the system partition is newer. 2914 // 2915 // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build 2916 // that starts with "eng." to signify that this is an engineering build and not 2917 // destined for release. 2918 if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) { 2919 Slog.w(TAG, "Wiping cache directory because the system partition changed."); 2920 2921 // Heuristic: If the /system directory has been modified recently due to an "adb sync" 2922 // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable 2923 // in general and should not be used for production changes. In this specific case, 2924 // we know that they will work. 2925 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2926 if (cacheDir.lastModified() < frameworkDir.lastModified()) { 2927 FileUtils.deleteContents(cacheBaseDir); 2928 cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION); 2929 } 2930 } 2931 2932 return cacheDir; 2933 } 2934 2935 @Override 2936 public boolean isFirstBoot() { 2937 return mFirstBoot; 2938 } 2939 2940 @Override 2941 public boolean isOnlyCoreApps() { 2942 return mOnlyCore; 2943 } 2944 2945 @Override 2946 public boolean isUpgrade() { 2947 return mIsUpgrade; 2948 } 2949 2950 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2951 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2952 2953 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2954 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2955 UserHandle.USER_SYSTEM); 2956 if (matches.size() == 1) { 2957 return matches.get(0).getComponentInfo().packageName; 2958 } else if (matches.size() == 0) { 2959 Log.e(TAG, "There should probably be a verifier, but, none were found"); 2960 return null; 2961 } 2962 throw new RuntimeException("There must be exactly one verifier; found " + matches); 2963 } 2964 2965 private @NonNull String getRequiredSharedLibraryLPr(String name, int version) { 2966 synchronized (mPackages) { 2967 SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version); 2968 if (libraryEntry == null) { 2969 throw new IllegalStateException("Missing required shared library:" + name); 2970 } 2971 return libraryEntry.apk; 2972 } 2973 } 2974 2975 private @NonNull String getRequiredInstallerLPr() { 2976 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2977 intent.addCategory(Intent.CATEGORY_DEFAULT); 2978 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2979 2980 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2981 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2982 UserHandle.USER_SYSTEM); 2983 if (matches.size() == 1) { 2984 ResolveInfo resolveInfo = matches.get(0); 2985 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 2986 throw new RuntimeException("The installer must be a privileged app"); 2987 } 2988 return matches.get(0).getComponentInfo().packageName; 2989 } else { 2990 throw new RuntimeException("There must be exactly one installer; found " + matches); 2991 } 2992 } 2993 2994 private @NonNull String getRequiredUninstallerLPr() { 2995 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 2996 intent.addCategory(Intent.CATEGORY_DEFAULT); 2997 intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null)); 2998 2999 final ResolveInfo resolveInfo = resolveIntent(intent, null, 3000 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3001 UserHandle.USER_SYSTEM); 3002 if (resolveInfo == null || 3003 mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) { 3004 throw new RuntimeException("There must be exactly one uninstaller; found " 3005 + resolveInfo); 3006 } 3007 return resolveInfo.getComponentInfo().packageName; 3008 } 3009 3010 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 3011 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 3012 3013 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 3014 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3015 UserHandle.USER_SYSTEM); 3016 ResolveInfo best = null; 3017 final int N = matches.size(); 3018 for (int i = 0; i < N; i++) { 3019 final ResolveInfo cur = matches.get(i); 3020 final String packageName = cur.getComponentInfo().packageName; 3021 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 3022 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 3023 continue; 3024 } 3025 3026 if (best == null || cur.priority > best.priority) { 3027 best = cur; 3028 } 3029 } 3030 3031 if (best != null) { 3032 return best.getComponentInfo().getComponentName(); 3033 } else { 3034 throw new RuntimeException("There must be at least one intent filter verifier"); 3035 } 3036 } 3037 3038 private @Nullable ComponentName getEphemeralResolverLPr() { 3039 final String[] packageArray = 3040 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 3041 if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) { 3042 if (DEBUG_EPHEMERAL) { 3043 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 3044 } 3045 return null; 3046 } 3047 3048 final int resolveFlags = 3049 MATCH_DIRECT_BOOT_AWARE 3050 | MATCH_DIRECT_BOOT_UNAWARE 3051 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3052 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 3053 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 3054 resolveFlags, UserHandle.USER_SYSTEM); 3055 3056 final int N = resolvers.size(); 3057 if (N == 0) { 3058 if (DEBUG_EPHEMERAL) { 3059 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 3060 } 3061 return null; 3062 } 3063 3064 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 3065 for (int i = 0; i < N; i++) { 3066 final ResolveInfo info = resolvers.get(i); 3067 3068 if (info.serviceInfo == null) { 3069 continue; 3070 } 3071 3072 final String packageName = info.serviceInfo.packageName; 3073 if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) { 3074 if (DEBUG_EPHEMERAL) { 3075 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 3076 + " pkg: " + packageName + ", info:" + info); 3077 } 3078 continue; 3079 } 3080 3081 if (DEBUG_EPHEMERAL) { 3082 Slog.v(TAG, "Ephemeral resolver found;" 3083 + " pkg: " + packageName + ", info:" + info); 3084 } 3085 return new ComponentName(packageName, info.serviceInfo.name); 3086 } 3087 if (DEBUG_EPHEMERAL) { 3088 Slog.v(TAG, "Ephemeral resolver NOT found"); 3089 } 3090 return null; 3091 } 3092 3093 private @Nullable ComponentName getEphemeralInstallerLPr() { 3094 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 3095 intent.addCategory(Intent.CATEGORY_DEFAULT); 3096 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 3097 3098 final int resolveFlags = 3099 MATCH_DIRECT_BOOT_AWARE 3100 | MATCH_DIRECT_BOOT_UNAWARE 3101 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3102 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3103 resolveFlags, UserHandle.USER_SYSTEM); 3104 Iterator<ResolveInfo> iter = matches.iterator(); 3105 while (iter.hasNext()) { 3106 final ResolveInfo rInfo = iter.next(); 3107 final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName); 3108 if (ps != null) { 3109 final PermissionsState permissionsState = ps.getPermissionsState(); 3110 if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) { 3111 continue; 3112 } 3113 } 3114 iter.remove(); 3115 } 3116 if (matches.size() == 0) { 3117 return null; 3118 } else if (matches.size() == 1) { 3119 return matches.get(0).getComponentInfo().getComponentName(); 3120 } else { 3121 throw new RuntimeException( 3122 "There must be at most one ephemeral installer; found " + matches); 3123 } 3124 } 3125 3126 private void primeDomainVerificationsLPw(int userId) { 3127 if (DEBUG_DOMAIN_VERIFICATION) { 3128 Slog.d(TAG, "Priming domain verifications in user " + userId); 3129 } 3130 3131 SystemConfig systemConfig = SystemConfig.getInstance(); 3132 ArraySet<String> packages = systemConfig.getLinkedApps(); 3133 3134 for (String packageName : packages) { 3135 PackageParser.Package pkg = mPackages.get(packageName); 3136 if (pkg != null) { 3137 if (!pkg.isSystemApp()) { 3138 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 3139 continue; 3140 } 3141 3142 ArraySet<String> domains = null; 3143 for (PackageParser.Activity a : pkg.activities) { 3144 for (ActivityIntentInfo filter : a.intents) { 3145 if (hasValidDomains(filter)) { 3146 if (domains == null) { 3147 domains = new ArraySet<String>(); 3148 } 3149 domains.addAll(filter.getHostsList()); 3150 } 3151 } 3152 } 3153 3154 if (domains != null && domains.size() > 0) { 3155 if (DEBUG_DOMAIN_VERIFICATION) { 3156 Slog.v(TAG, " + " + packageName); 3157 } 3158 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 3159 // state w.r.t. the formal app-linkage "no verification attempted" state; 3160 // and then 'always' in the per-user state actually used for intent resolution. 3161 final IntentFilterVerificationInfo ivi; 3162 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains); 3163 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 3164 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 3165 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 3166 } else { 3167 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 3168 + "' does not handle web links"); 3169 } 3170 } else { 3171 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 3172 } 3173 } 3174 3175 scheduleWritePackageRestrictionsLocked(userId); 3176 scheduleWriteSettingsLocked(); 3177 } 3178 3179 private void applyFactoryDefaultBrowserLPw(int userId) { 3180 // The default browser app's package name is stored in a string resource, 3181 // with a product-specific overlay used for vendor customization. 3182 String browserPkg = mContext.getResources().getString( 3183 com.android.internal.R.string.default_browser); 3184 if (!TextUtils.isEmpty(browserPkg)) { 3185 // non-empty string => required to be a known package 3186 PackageSetting ps = mSettings.mPackages.get(browserPkg); 3187 if (ps == null) { 3188 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 3189 browserPkg = null; 3190 } else { 3191 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3192 } 3193 } 3194 3195 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3196 // default. If there's more than one, just leave everything alone. 3197 if (browserPkg == null) { 3198 calculateDefaultBrowserLPw(userId); 3199 } 3200 } 3201 3202 private void calculateDefaultBrowserLPw(int userId) { 3203 List<String> allBrowsers = resolveAllBrowserApps(userId); 3204 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3205 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3206 } 3207 3208 private List<String> resolveAllBrowserApps(int userId) { 3209 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3210 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3211 PackageManager.MATCH_ALL, userId); 3212 3213 final int count = list.size(); 3214 List<String> result = new ArrayList<String>(count); 3215 for (int i=0; i<count; i++) { 3216 ResolveInfo info = list.get(i); 3217 if (info.activityInfo == null 3218 || !info.handleAllWebDataURI 3219 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3220 || result.contains(info.activityInfo.packageName)) { 3221 continue; 3222 } 3223 result.add(info.activityInfo.packageName); 3224 } 3225 3226 return result; 3227 } 3228 3229 private boolean packageIsBrowser(String packageName, int userId) { 3230 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3231 PackageManager.MATCH_ALL, userId); 3232 final int N = list.size(); 3233 for (int i = 0; i < N; i++) { 3234 ResolveInfo info = list.get(i); 3235 if (packageName.equals(info.activityInfo.packageName)) { 3236 return true; 3237 } 3238 } 3239 return false; 3240 } 3241 3242 private void checkDefaultBrowser() { 3243 final int myUserId = UserHandle.myUserId(); 3244 final String packageName = getDefaultBrowserPackageName(myUserId); 3245 if (packageName != null) { 3246 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3247 if (info == null) { 3248 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3249 synchronized (mPackages) { 3250 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3251 } 3252 } 3253 } 3254 } 3255 3256 @Override 3257 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3258 throws RemoteException { 3259 try { 3260 return super.onTransact(code, data, reply, flags); 3261 } catch (RuntimeException e) { 3262 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3263 Slog.wtf(TAG, "Package Manager Crash", e); 3264 } 3265 throw e; 3266 } 3267 } 3268 3269 static int[] appendInts(int[] cur, int[] add) { 3270 if (add == null) return cur; 3271 if (cur == null) return add; 3272 final int N = add.length; 3273 for (int i=0; i<N; i++) { 3274 cur = appendInt(cur, add[i]); 3275 } 3276 return cur; 3277 } 3278 3279 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3280 if (!sUserManager.exists(userId)) return null; 3281 if (ps == null) { 3282 return null; 3283 } 3284 final PackageParser.Package p = ps.pkg; 3285 if (p == null) { 3286 return null; 3287 } 3288 // Filter out ephemeral app metadata: 3289 // * The system/shell/root can see metadata for any app 3290 // * An installed app can see metadata for 1) other installed apps 3291 // and 2) ephemeral apps that have explicitly interacted with it 3292 // * Ephemeral apps can only see their own metadata 3293 final int callingAppId = UserHandle.getAppId(Binder.getCallingUid()); 3294 if (callingAppId != Process.SYSTEM_UID 3295 && callingAppId != Process.SHELL_UID 3296 && callingAppId != Process.ROOT_UID) { 3297 final String ephemeralPackageName = getEphemeralPackageName(Binder.getCallingUid()); 3298 if (ephemeralPackageName != null) { 3299 // ephemeral apps can only get information on themselves 3300 if (!ephemeralPackageName.equals(p.packageName)) { 3301 return null; 3302 } 3303 } else { 3304 if (p.applicationInfo.isEphemeralApp()) { 3305 // only get access to the ephemeral app if we've been granted access 3306 if (!mEphemeralApplicationRegistry.isEphemeralAccessGranted( 3307 userId, callingAppId, ps.appId)) { 3308 return null; 3309 } 3310 } 3311 } 3312 } 3313 3314 final PermissionsState permissionsState = ps.getPermissionsState(); 3315 3316 // Compute GIDs only if requested 3317 final int[] gids = (flags & PackageManager.GET_GIDS) == 0 3318 ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId); 3319 // Compute granted permissions only if package has requested permissions 3320 final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions) 3321 ? Collections.<String>emptySet() : permissionsState.getPermissions(userId); 3322 final PackageUserState state = ps.readUserState(userId); 3323 3324 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0 3325 && ps.isSystem()) { 3326 flags |= MATCH_ANY_USER; 3327 } 3328 3329 PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags, 3330 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3331 3332 if (packageInfo == null) { 3333 return null; 3334 } 3335 3336 packageInfo.packageName = packageInfo.applicationInfo.packageName = 3337 resolveExternalPackageNameLPr(p); 3338 3339 return packageInfo; 3340 } 3341 3342 @Override 3343 public void checkPackageStartable(String packageName, int userId) { 3344 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3345 3346 synchronized (mPackages) { 3347 final PackageSetting ps = mSettings.mPackages.get(packageName); 3348 if (ps == null) { 3349 throw new SecurityException("Package " + packageName + " was not found!"); 3350 } 3351 3352 if (!ps.getInstalled(userId)) { 3353 throw new SecurityException( 3354 "Package " + packageName + " was not installed for user " + userId + "!"); 3355 } 3356 3357 if (mSafeMode && !ps.isSystem()) { 3358 throw new SecurityException("Package " + packageName + " not a system app!"); 3359 } 3360 3361 if (mFrozenPackages.contains(packageName)) { 3362 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3363 } 3364 3365 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3366 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3367 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3368 } 3369 } 3370 } 3371 3372 @Override 3373 public boolean isPackageAvailable(String packageName, int userId) { 3374 if (!sUserManager.exists(userId)) return false; 3375 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3376 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3377 synchronized (mPackages) { 3378 PackageParser.Package p = mPackages.get(packageName); 3379 if (p != null) { 3380 final PackageSetting ps = (PackageSetting) p.mExtras; 3381 if (ps != null) { 3382 final PackageUserState state = ps.readUserState(userId); 3383 if (state != null) { 3384 return PackageParser.isAvailable(state); 3385 } 3386 } 3387 } 3388 } 3389 return false; 3390 } 3391 3392 @Override 3393 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3394 return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST, 3395 flags, userId); 3396 } 3397 3398 @Override 3399 public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage, 3400 int flags, int userId) { 3401 return getPackageInfoInternal(versionedPackage.getPackageName(), 3402 // TODO: We will change version code to long, so in the new API it is long 3403 (int) versionedPackage.getVersionCode(), flags, userId); 3404 } 3405 3406 private PackageInfo getPackageInfoInternal(String packageName, int versionCode, 3407 int flags, int userId) { 3408 if (!sUserManager.exists(userId)) return null; 3409 flags = updateFlagsForPackage(flags, userId, packageName); 3410 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3411 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3412 3413 // reader 3414 synchronized (mPackages) { 3415 // Normalize package name to handle renamed packages and static libs 3416 packageName = resolveInternalPackageNameLPr(packageName, versionCode); 3417 3418 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3419 if (matchFactoryOnly) { 3420 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3421 if (ps != null) { 3422 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 3423 return null; 3424 } 3425 return generatePackageInfo(ps, flags, userId); 3426 } 3427 } 3428 3429 PackageParser.Package p = mPackages.get(packageName); 3430 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3431 return null; 3432 } 3433 if (DEBUG_PACKAGE_INFO) 3434 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3435 if (p != null) { 3436 if (filterSharedLibPackageLPr((PackageSetting) p.mExtras, 3437 Binder.getCallingUid(), userId)) { 3438 return null; 3439 } 3440 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3441 } 3442 if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) { 3443 final PackageSetting ps = mSettings.mPackages.get(packageName); 3444 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 3445 return null; 3446 } 3447 return generatePackageInfo(ps, flags, userId); 3448 } 3449 } 3450 return null; 3451 } 3452 3453 3454 private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId) { 3455 // System/shell/root get to see all static libs 3456 final int appId = UserHandle.getAppId(uid); 3457 if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID 3458 || appId == Process.ROOT_UID) { 3459 return false; 3460 } 3461 3462 // No package means no static lib as it is always on internal storage 3463 if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) { 3464 return false; 3465 } 3466 3467 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName, 3468 ps.pkg.staticSharedLibVersion); 3469 if (libEntry == null) { 3470 return false; 3471 } 3472 3473 final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid)); 3474 final String[] uidPackageNames = getPackagesForUid(resolvedUid); 3475 if (uidPackageNames == null) { 3476 return true; 3477 } 3478 3479 for (String uidPackageName : uidPackageNames) { 3480 if (ps.name.equals(uidPackageName)) { 3481 return false; 3482 } 3483 PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName); 3484 if (uidPs != null) { 3485 final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries, 3486 libEntry.info.getName()); 3487 if (index < 0) { 3488 continue; 3489 } 3490 if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) { 3491 return false; 3492 } 3493 } 3494 } 3495 return true; 3496 } 3497 3498 @Override 3499 public String[] currentToCanonicalPackageNames(String[] names) { 3500 String[] out = new String[names.length]; 3501 // reader 3502 synchronized (mPackages) { 3503 for (int i=names.length-1; i>=0; i--) { 3504 PackageSetting ps = mSettings.mPackages.get(names[i]); 3505 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3506 } 3507 } 3508 return out; 3509 } 3510 3511 @Override 3512 public String[] canonicalToCurrentPackageNames(String[] names) { 3513 String[] out = new String[names.length]; 3514 // reader 3515 synchronized (mPackages) { 3516 for (int i=names.length-1; i>=0; i--) { 3517 String cur = mSettings.getRenamedPackageLPr(names[i]); 3518 out[i] = cur != null ? cur : names[i]; 3519 } 3520 } 3521 return out; 3522 } 3523 3524 @Override 3525 public int getPackageUid(String packageName, int flags, int userId) { 3526 if (!sUserManager.exists(userId)) return -1; 3527 flags = updateFlagsForPackage(flags, userId, packageName); 3528 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3529 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3530 3531 // reader 3532 synchronized (mPackages) { 3533 final PackageParser.Package p = mPackages.get(packageName); 3534 if (p != null && p.isMatch(flags)) { 3535 return UserHandle.getUid(userId, p.applicationInfo.uid); 3536 } 3537 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3538 final PackageSetting ps = mSettings.mPackages.get(packageName); 3539 if (ps != null && ps.isMatch(flags)) { 3540 return UserHandle.getUid(userId, ps.appId); 3541 } 3542 } 3543 } 3544 3545 return -1; 3546 } 3547 3548 @Override 3549 public int[] getPackageGids(String packageName, int flags, int userId) { 3550 if (!sUserManager.exists(userId)) return null; 3551 flags = updateFlagsForPackage(flags, userId, packageName); 3552 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3553 false /* requireFullPermission */, false /* checkShell */, 3554 "getPackageGids"); 3555 3556 // reader 3557 synchronized (mPackages) { 3558 final PackageParser.Package p = mPackages.get(packageName); 3559 if (p != null && p.isMatch(flags)) { 3560 PackageSetting ps = (PackageSetting) p.mExtras; 3561 // TODO: Shouldn't this be checking for package installed state for userId and 3562 // return null? 3563 return ps.getPermissionsState().computeGids(userId); 3564 } 3565 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3566 final PackageSetting ps = mSettings.mPackages.get(packageName); 3567 if (ps != null && ps.isMatch(flags)) { 3568 return ps.getPermissionsState().computeGids(userId); 3569 } 3570 } 3571 } 3572 3573 return null; 3574 } 3575 3576 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3577 if (bp.perm != null) { 3578 return PackageParser.generatePermissionInfo(bp.perm, flags); 3579 } 3580 PermissionInfo pi = new PermissionInfo(); 3581 pi.name = bp.name; 3582 pi.packageName = bp.sourcePackage; 3583 pi.nonLocalizedLabel = bp.name; 3584 pi.protectionLevel = bp.protectionLevel; 3585 return pi; 3586 } 3587 3588 @Override 3589 public PermissionInfo getPermissionInfo(String name, int flags) { 3590 // reader 3591 synchronized (mPackages) { 3592 final BasePermission p = mSettings.mPermissions.get(name); 3593 if (p != null) { 3594 return generatePermissionInfo(p, flags); 3595 } 3596 return null; 3597 } 3598 } 3599 3600 @Override 3601 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3602 int flags) { 3603 // reader 3604 synchronized (mPackages) { 3605 if (group != null && !mPermissionGroups.containsKey(group)) { 3606 // This is thrown as NameNotFoundException 3607 return null; 3608 } 3609 3610 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3611 for (BasePermission p : mSettings.mPermissions.values()) { 3612 if (group == null) { 3613 if (p.perm == null || p.perm.info.group == null) { 3614 out.add(generatePermissionInfo(p, flags)); 3615 } 3616 } else { 3617 if (p.perm != null && group.equals(p.perm.info.group)) { 3618 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3619 } 3620 } 3621 } 3622 return new ParceledListSlice<>(out); 3623 } 3624 } 3625 3626 @Override 3627 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3628 // reader 3629 synchronized (mPackages) { 3630 return PackageParser.generatePermissionGroupInfo( 3631 mPermissionGroups.get(name), flags); 3632 } 3633 } 3634 3635 @Override 3636 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3637 // reader 3638 synchronized (mPackages) { 3639 final int N = mPermissionGroups.size(); 3640 ArrayList<PermissionGroupInfo> out 3641 = new ArrayList<PermissionGroupInfo>(N); 3642 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3643 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3644 } 3645 return new ParceledListSlice<>(out); 3646 } 3647 } 3648 3649 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3650 int uid, int userId) { 3651 if (!sUserManager.exists(userId)) return null; 3652 PackageSetting ps = mSettings.mPackages.get(packageName); 3653 if (ps != null) { 3654 if (filterSharedLibPackageLPr(ps, uid, userId)) { 3655 return null; 3656 } 3657 if (ps.pkg == null) { 3658 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3659 if (pInfo != null) { 3660 return pInfo.applicationInfo; 3661 } 3662 return null; 3663 } 3664 ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 3665 ps.readUserState(userId), userId); 3666 if (ai != null) { 3667 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 3668 } 3669 return ai; 3670 } 3671 return null; 3672 } 3673 3674 @Override 3675 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3676 if (!sUserManager.exists(userId)) return null; 3677 flags = updateFlagsForApplication(flags, userId, packageName); 3678 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3679 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3680 3681 // writer 3682 synchronized (mPackages) { 3683 // Normalize package name to handle renamed packages and static libs 3684 packageName = resolveInternalPackageNameLPr(packageName, 3685 PackageManager.VERSION_CODE_HIGHEST); 3686 3687 PackageParser.Package p = mPackages.get(packageName); 3688 if (DEBUG_PACKAGE_INFO) Log.v( 3689 TAG, "getApplicationInfo " + packageName 3690 + ": " + p); 3691 if (p != null) { 3692 PackageSetting ps = mSettings.mPackages.get(packageName); 3693 if (ps == null) return null; 3694 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 3695 return null; 3696 } 3697 // Note: isEnabledLP() does not apply here - always return info 3698 ApplicationInfo ai = PackageParser.generateApplicationInfo( 3699 p, flags, ps.readUserState(userId), userId); 3700 if (ai != null) { 3701 ai.packageName = resolveExternalPackageNameLPr(p); 3702 } 3703 return ai; 3704 } 3705 if ("android".equals(packageName)||"system".equals(packageName)) { 3706 return mAndroidApplication; 3707 } 3708 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3709 // Already generates the external package name 3710 return generateApplicationInfoFromSettingsLPw(packageName, 3711 Binder.getCallingUid(), flags, userId); 3712 } 3713 } 3714 return null; 3715 } 3716 3717 private String normalizePackageNameLPr(String packageName) { 3718 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 3719 return normalizedPackageName != null ? normalizedPackageName : packageName; 3720 } 3721 3722 @Override 3723 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3724 final IPackageDataObserver observer) { 3725 mContext.enforceCallingOrSelfPermission( 3726 android.Manifest.permission.CLEAR_APP_CACHE, null); 3727 // Queue up an async operation since clearing cache may take a little while. 3728 mHandler.post(new Runnable() { 3729 public void run() { 3730 mHandler.removeCallbacks(this); 3731 boolean success = true; 3732 synchronized (mInstallLock) { 3733 try { 3734 mInstaller.freeCache(volumeUuid, freeStorageSize, 0); 3735 } catch (InstallerException e) { 3736 Slog.w(TAG, "Couldn't clear application caches: " + e); 3737 success = false; 3738 } 3739 } 3740 if (observer != null) { 3741 try { 3742 observer.onRemoveCompleted(null, success); 3743 } catch (RemoteException e) { 3744 Slog.w(TAG, "RemoveException when invoking call back"); 3745 } 3746 } 3747 } 3748 }); 3749 } 3750 3751 @Override 3752 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3753 final IntentSender pi) { 3754 mContext.enforceCallingOrSelfPermission( 3755 android.Manifest.permission.CLEAR_APP_CACHE, null); 3756 // Queue up an async operation since clearing cache may take a little while. 3757 mHandler.post(new Runnable() { 3758 public void run() { 3759 mHandler.removeCallbacks(this); 3760 boolean success = true; 3761 synchronized (mInstallLock) { 3762 try { 3763 mInstaller.freeCache(volumeUuid, freeStorageSize, 0); 3764 } catch (InstallerException e) { 3765 Slog.w(TAG, "Couldn't clear application caches: " + e); 3766 success = false; 3767 } 3768 } 3769 if(pi != null) { 3770 try { 3771 // Callback via pending intent 3772 int code = success ? 1 : 0; 3773 pi.sendIntent(null, code, null, 3774 null, null); 3775 } catch (SendIntentException e1) { 3776 Slog.i(TAG, "Failed to send pending intent"); 3777 } 3778 } 3779 } 3780 }); 3781 } 3782 3783 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3784 synchronized (mInstallLock) { 3785 try { 3786 mInstaller.freeCache(volumeUuid, freeStorageSize, 0); 3787 } catch (InstallerException e) { 3788 throw new IOException("Failed to free enough space", e); 3789 } 3790 } 3791 } 3792 3793 /** 3794 * Update given flags based on encryption status of current user. 3795 */ 3796 private int updateFlags(int flags, int userId) { 3797 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3798 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3799 // Caller expressed an explicit opinion about what encryption 3800 // aware/unaware components they want to see, so fall through and 3801 // give them what they want 3802 } else { 3803 // Caller expressed no opinion, so match based on user state 3804 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 3805 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3806 } else { 3807 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3808 } 3809 } 3810 return flags; 3811 } 3812 3813 private UserManagerInternal getUserManagerInternal() { 3814 if (mUserManagerInternal == null) { 3815 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 3816 } 3817 return mUserManagerInternal; 3818 } 3819 3820 /** 3821 * Update given flags when being used to request {@link PackageInfo}. 3822 */ 3823 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3824 final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM; 3825 boolean triaged = true; 3826 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3827 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3828 // Caller is asking for component details, so they'd better be 3829 // asking for specific encryption matching behavior, or be triaged 3830 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3831 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3832 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3833 triaged = false; 3834 } 3835 } 3836 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3837 | PackageManager.MATCH_SYSTEM_ONLY 3838 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3839 triaged = false; 3840 } 3841 if ((flags & PackageManager.MATCH_ANY_USER) != 0) { 3842 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 3843 "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at " 3844 + Debug.getCallers(5)); 3845 } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser 3846 && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) { 3847 // If the caller wants all packages and has a restricted profile associated with it, 3848 // then match all users. This is to make sure that launchers that need to access work 3849 // profile apps don't start breaking. TODO: Remove this hack when launchers stop using 3850 // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380 3851 flags |= PackageManager.MATCH_ANY_USER; 3852 } 3853 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3854 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3855 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3856 } 3857 return updateFlags(flags, userId); 3858 } 3859 3860 /** 3861 * Update given flags when being used to request {@link ApplicationInfo}. 3862 */ 3863 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3864 return updateFlagsForPackage(flags, userId, cookie); 3865 } 3866 3867 /** 3868 * Update given flags when being used to request {@link ComponentInfo}. 3869 */ 3870 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3871 if (cookie instanceof Intent) { 3872 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3873 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3874 } 3875 } 3876 3877 boolean triaged = true; 3878 // Caller is asking for component details, so they'd better be 3879 // asking for specific encryption matching behavior, or be triaged 3880 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3881 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3882 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3883 triaged = false; 3884 } 3885 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3886 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3887 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3888 } 3889 3890 return updateFlags(flags, userId); 3891 } 3892 3893 /** 3894 * Update given intent when being used to request {@link ResolveInfo}. 3895 */ 3896 private Intent updateIntentForResolve(Intent intent) { 3897 if (intent.getSelector() != null) { 3898 intent = intent.getSelector(); 3899 } 3900 if (DEBUG_PREFERRED) { 3901 intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3902 } 3903 return intent; 3904 } 3905 3906 /** 3907 * Update given flags when being used to request {@link ResolveInfo}. 3908 */ 3909 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3910 // Safe mode means we shouldn't match any third-party components 3911 if (mSafeMode) { 3912 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3913 } 3914 final int callingUid = Binder.getCallingUid(); 3915 if (callingUid == Process.SYSTEM_UID || callingUid == 0) { 3916 // The system sees all components 3917 flags |= PackageManager.MATCH_EPHEMERAL; 3918 } else if (getEphemeralPackageName(callingUid) != null) { 3919 // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components 3920 flags |= PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY; 3921 flags |= PackageManager.MATCH_EPHEMERAL; 3922 } else { 3923 // Otherwise, prevent leaking ephemeral components 3924 flags &= ~PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY; 3925 flags &= ~PackageManager.MATCH_EPHEMERAL; 3926 } 3927 return updateFlagsForComponent(flags, userId, cookie); 3928 } 3929 3930 @Override 3931 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3932 if (!sUserManager.exists(userId)) return null; 3933 flags = updateFlagsForComponent(flags, userId, component); 3934 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3935 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 3936 synchronized (mPackages) { 3937 PackageParser.Activity a = mActivities.mActivities.get(component); 3938 3939 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3940 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3941 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3942 if (ps == null) return null; 3943 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3944 userId); 3945 } 3946 if (mResolveComponentName.equals(component)) { 3947 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3948 new PackageUserState(), userId); 3949 } 3950 } 3951 return null; 3952 } 3953 3954 @Override 3955 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3956 String resolvedType) { 3957 synchronized (mPackages) { 3958 if (component.equals(mResolveComponentName)) { 3959 // The resolver supports EVERYTHING! 3960 return true; 3961 } 3962 PackageParser.Activity a = mActivities.mActivities.get(component); 3963 if (a == null) { 3964 return false; 3965 } 3966 for (int i=0; i<a.intents.size(); i++) { 3967 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3968 intent.getData(), intent.getCategories(), TAG) >= 0) { 3969 return true; 3970 } 3971 } 3972 return false; 3973 } 3974 } 3975 3976 @Override 3977 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3978 if (!sUserManager.exists(userId)) return null; 3979 flags = updateFlagsForComponent(flags, userId, component); 3980 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3981 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 3982 synchronized (mPackages) { 3983 PackageParser.Activity a = mReceivers.mActivities.get(component); 3984 if (DEBUG_PACKAGE_INFO) Log.v( 3985 TAG, "getReceiverInfo " + component + ": " + a); 3986 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3987 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3988 if (ps == null) return null; 3989 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3990 userId); 3991 } 3992 } 3993 return null; 3994 } 3995 3996 @Override 3997 public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(int flags, int userId) { 3998 if (!sUserManager.exists(userId)) return null; 3999 Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0"); 4000 4001 flags = updateFlagsForPackage(flags, userId, null); 4002 4003 final boolean canSeeStaticLibraries = 4004 mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES) 4005 == PERMISSION_GRANTED 4006 || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES) 4007 == PERMISSION_GRANTED 4008 || mContext.checkCallingOrSelfPermission(REQUEST_INSTALL_PACKAGES) 4009 == PERMISSION_GRANTED 4010 || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES) 4011 == PERMISSION_GRANTED; 4012 4013 synchronized (mPackages) { 4014 List<SharedLibraryInfo> result = null; 4015 4016 final int libCount = mSharedLibraries.size(); 4017 for (int i = 0; i < libCount; i++) { 4018 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 4019 if (versionedLib == null) { 4020 continue; 4021 } 4022 4023 final int versionCount = versionedLib.size(); 4024 for (int j = 0; j < versionCount; j++) { 4025 SharedLibraryInfo libInfo = versionedLib.valueAt(j).info; 4026 if (!canSeeStaticLibraries && libInfo.isStatic()) { 4027 break; 4028 } 4029 final long identity = Binder.clearCallingIdentity(); 4030 try { 4031 // TODO: We will change version code to long, so in the new API it is long 4032 PackageInfo packageInfo = getPackageInfoVersioned( 4033 libInfo.getDeclaringPackage(), flags, userId); 4034 if (packageInfo == null) { 4035 continue; 4036 } 4037 } finally { 4038 Binder.restoreCallingIdentity(identity); 4039 } 4040 4041 SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(), 4042 libInfo.getVersion(), libInfo.getType(), libInfo.getDeclaringPackage(), 4043 getPackagesUsingSharedLibraryLPr(libInfo, flags, userId)); 4044 4045 if (result == null) { 4046 result = new ArrayList<>(); 4047 } 4048 result.add(resLibInfo); 4049 } 4050 } 4051 4052 return result != null ? new ParceledListSlice<>(result) : null; 4053 } 4054 } 4055 4056 private List<VersionedPackage> getPackagesUsingSharedLibraryLPr( 4057 SharedLibraryInfo libInfo, int flags, int userId) { 4058 List<VersionedPackage> versionedPackages = null; 4059 final int packageCount = mSettings.mPackages.size(); 4060 for (int i = 0; i < packageCount; i++) { 4061 PackageSetting ps = mSettings.mPackages.valueAt(i); 4062 4063 if (ps == null) { 4064 continue; 4065 } 4066 4067 if (!ps.getUserState().get(userId).isAvailable(flags)) { 4068 continue; 4069 } 4070 4071 final String libName = libInfo.getName(); 4072 if (libInfo.isStatic()) { 4073 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 4074 if (libIdx < 0) { 4075 continue; 4076 } 4077 if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) { 4078 continue; 4079 } 4080 if (versionedPackages == null) { 4081 versionedPackages = new ArrayList<>(); 4082 } 4083 // If the dependent is a static shared lib, use the public package name 4084 String dependentPackageName = ps.name; 4085 if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) { 4086 dependentPackageName = ps.pkg.manifestPackageName; 4087 } 4088 versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode)); 4089 } else if (ps.pkg != null) { 4090 if (ArrayUtils.contains(ps.pkg.usesLibraries, libName) 4091 || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) { 4092 if (versionedPackages == null) { 4093 versionedPackages = new ArrayList<>(); 4094 } 4095 versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode)); 4096 } 4097 } 4098 } 4099 4100 return versionedPackages; 4101 } 4102 4103 @Override 4104 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 4105 if (!sUserManager.exists(userId)) return null; 4106 flags = updateFlagsForComponent(flags, userId, component); 4107 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4108 false /* requireFullPermission */, false /* checkShell */, "get service info"); 4109 synchronized (mPackages) { 4110 PackageParser.Service s = mServices.mServices.get(component); 4111 if (DEBUG_PACKAGE_INFO) Log.v( 4112 TAG, "getServiceInfo " + component + ": " + s); 4113 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 4114 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4115 if (ps == null) return null; 4116 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 4117 userId); 4118 } 4119 } 4120 return null; 4121 } 4122 4123 @Override 4124 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 4125 if (!sUserManager.exists(userId)) return null; 4126 flags = updateFlagsForComponent(flags, userId, component); 4127 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4128 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 4129 synchronized (mPackages) { 4130 PackageParser.Provider p = mProviders.mProviders.get(component); 4131 if (DEBUG_PACKAGE_INFO) Log.v( 4132 TAG, "getProviderInfo " + component + ": " + p); 4133 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 4134 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4135 if (ps == null) return null; 4136 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 4137 userId); 4138 } 4139 } 4140 return null; 4141 } 4142 4143 @Override 4144 public String[] getSystemSharedLibraryNames() { 4145 synchronized (mPackages) { 4146 Set<String> libs = null; 4147 final int libCount = mSharedLibraries.size(); 4148 for (int i = 0; i < libCount; i++) { 4149 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 4150 if (versionedLib == null) { 4151 continue; 4152 } 4153 final int versionCount = versionedLib.size(); 4154 for (int j = 0; j < versionCount; j++) { 4155 SharedLibraryEntry libEntry = versionedLib.valueAt(j); 4156 if (!libEntry.info.isStatic()) { 4157 if (libs == null) { 4158 libs = new ArraySet<>(); 4159 } 4160 libs.add(libEntry.info.getName()); 4161 break; 4162 } 4163 PackageSetting ps = mSettings.getPackageLPr(libEntry.apk); 4164 if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(), 4165 UserHandle.getUserId(Binder.getCallingUid()))) { 4166 if (libs == null) { 4167 libs = new ArraySet<>(); 4168 } 4169 libs.add(libEntry.info.getName()); 4170 break; 4171 } 4172 } 4173 } 4174 4175 if (libs != null) { 4176 String[] libsArray = new String[libs.size()]; 4177 libs.toArray(libsArray); 4178 return libsArray; 4179 } 4180 4181 return null; 4182 } 4183 } 4184 4185 @Override 4186 public @NonNull String getServicesSystemSharedLibraryPackageName() { 4187 synchronized (mPackages) { 4188 return mServicesSystemSharedLibraryPackageName; 4189 } 4190 } 4191 4192 @Override 4193 public @NonNull String getSharedSystemSharedLibraryPackageName() { 4194 synchronized (mPackages) { 4195 return mSharedSystemSharedLibraryPackageName; 4196 } 4197 } 4198 4199 @Override 4200 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 4201 synchronized (mPackages) { 4202 final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values()); 4203 4204 final FeatureInfo fi = new FeatureInfo(); 4205 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 4206 FeatureInfo.GL_ES_VERSION_UNDEFINED); 4207 res.add(fi); 4208 4209 return new ParceledListSlice<>(res); 4210 } 4211 } 4212 4213 @Override 4214 public boolean hasSystemFeature(String name, int version) { 4215 synchronized (mPackages) { 4216 final FeatureInfo feat = mAvailableFeatures.get(name); 4217 if (feat == null) { 4218 return false; 4219 } else { 4220 return feat.version >= version; 4221 } 4222 } 4223 } 4224 4225 @Override 4226 public int checkPermission(String permName, String pkgName, int userId) { 4227 if (!sUserManager.exists(userId)) { 4228 return PackageManager.PERMISSION_DENIED; 4229 } 4230 4231 synchronized (mPackages) { 4232 final PackageParser.Package p = mPackages.get(pkgName); 4233 if (p != null && p.mExtras != null) { 4234 final PackageSetting ps = (PackageSetting) p.mExtras; 4235 final PermissionsState permissionsState = ps.getPermissionsState(); 4236 if (permissionsState.hasPermission(permName, userId)) { 4237 return PackageManager.PERMISSION_GRANTED; 4238 } 4239 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 4240 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 4241 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 4242 return PackageManager.PERMISSION_GRANTED; 4243 } 4244 } 4245 } 4246 4247 return PackageManager.PERMISSION_DENIED; 4248 } 4249 4250 @Override 4251 public int checkUidPermission(String permName, int uid) { 4252 final int userId = UserHandle.getUserId(uid); 4253 4254 if (!sUserManager.exists(userId)) { 4255 return PackageManager.PERMISSION_DENIED; 4256 } 4257 4258 synchronized (mPackages) { 4259 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4260 if (obj != null) { 4261 final SettingBase ps = (SettingBase) obj; 4262 final PermissionsState permissionsState = ps.getPermissionsState(); 4263 if (permissionsState.hasPermission(permName, userId)) { 4264 return PackageManager.PERMISSION_GRANTED; 4265 } 4266 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 4267 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 4268 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 4269 return PackageManager.PERMISSION_GRANTED; 4270 } 4271 } else { 4272 ArraySet<String> perms = mSystemPermissions.get(uid); 4273 if (perms != null) { 4274 if (perms.contains(permName)) { 4275 return PackageManager.PERMISSION_GRANTED; 4276 } 4277 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 4278 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 4279 return PackageManager.PERMISSION_GRANTED; 4280 } 4281 } 4282 } 4283 } 4284 4285 return PackageManager.PERMISSION_DENIED; 4286 } 4287 4288 @Override 4289 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 4290 if (UserHandle.getCallingUserId() != userId) { 4291 mContext.enforceCallingPermission( 4292 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4293 "isPermissionRevokedByPolicy for user " + userId); 4294 } 4295 4296 if (checkPermission(permission, packageName, userId) 4297 == PackageManager.PERMISSION_GRANTED) { 4298 return false; 4299 } 4300 4301 final long identity = Binder.clearCallingIdentity(); 4302 try { 4303 final int flags = getPermissionFlags(permission, packageName, userId); 4304 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 4305 } finally { 4306 Binder.restoreCallingIdentity(identity); 4307 } 4308 } 4309 4310 @Override 4311 public String getPermissionControllerPackageName() { 4312 synchronized (mPackages) { 4313 return mRequiredInstallerPackage; 4314 } 4315 } 4316 4317 /** 4318 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 4319 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 4320 * @param checkShell whether to prevent shell from access if there's a debugging restriction 4321 * @param message the message to log on security exception 4322 */ 4323 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 4324 boolean checkShell, String message) { 4325 if (userId < 0) { 4326 throw new IllegalArgumentException("Invalid userId " + userId); 4327 } 4328 if (checkShell) { 4329 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 4330 } 4331 if (userId == UserHandle.getUserId(callingUid)) return; 4332 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4333 if (requireFullPermission) { 4334 mContext.enforceCallingOrSelfPermission( 4335 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 4336 } else { 4337 try { 4338 mContext.enforceCallingOrSelfPermission( 4339 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 4340 } catch (SecurityException se) { 4341 mContext.enforceCallingOrSelfPermission( 4342 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 4343 } 4344 } 4345 } 4346 } 4347 4348 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 4349 if (callingUid == Process.SHELL_UID) { 4350 if (userHandle >= 0 4351 && sUserManager.hasUserRestriction(restriction, userHandle)) { 4352 throw new SecurityException("Shell does not have permission to access user " 4353 + userHandle); 4354 } else if (userHandle < 0) { 4355 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 4356 + Debug.getCallers(3)); 4357 } 4358 } 4359 } 4360 4361 private BasePermission findPermissionTreeLP(String permName) { 4362 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 4363 if (permName.startsWith(bp.name) && 4364 permName.length() > bp.name.length() && 4365 permName.charAt(bp.name.length()) == '.') { 4366 return bp; 4367 } 4368 } 4369 return null; 4370 } 4371 4372 private BasePermission checkPermissionTreeLP(String permName) { 4373 if (permName != null) { 4374 BasePermission bp = findPermissionTreeLP(permName); 4375 if (bp != null) { 4376 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 4377 return bp; 4378 } 4379 throw new SecurityException("Calling uid " 4380 + Binder.getCallingUid() 4381 + " is not allowed to add to permission tree " 4382 + bp.name + " owned by uid " + bp.uid); 4383 } 4384 } 4385 throw new SecurityException("No permission tree found for " + permName); 4386 } 4387 4388 static boolean compareStrings(CharSequence s1, CharSequence s2) { 4389 if (s1 == null) { 4390 return s2 == null; 4391 } 4392 if (s2 == null) { 4393 return false; 4394 } 4395 if (s1.getClass() != s2.getClass()) { 4396 return false; 4397 } 4398 return s1.equals(s2); 4399 } 4400 4401 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 4402 if (pi1.icon != pi2.icon) return false; 4403 if (pi1.logo != pi2.logo) return false; 4404 if (pi1.protectionLevel != pi2.protectionLevel) return false; 4405 if (!compareStrings(pi1.name, pi2.name)) return false; 4406 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 4407 // We'll take care of setting this one. 4408 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 4409 // These are not currently stored in settings. 4410 //if (!compareStrings(pi1.group, pi2.group)) return false; 4411 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 4412 //if (pi1.labelRes != pi2.labelRes) return false; 4413 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 4414 return true; 4415 } 4416 4417 int permissionInfoFootprint(PermissionInfo info) { 4418 int size = info.name.length(); 4419 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 4420 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 4421 return size; 4422 } 4423 4424 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 4425 int size = 0; 4426 for (BasePermission perm : mSettings.mPermissions.values()) { 4427 if (perm.uid == tree.uid) { 4428 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 4429 } 4430 } 4431 return size; 4432 } 4433 4434 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 4435 // We calculate the max size of permissions defined by this uid and throw 4436 // if that plus the size of 'info' would exceed our stated maximum. 4437 if (tree.uid != Process.SYSTEM_UID) { 4438 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 4439 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 4440 throw new SecurityException("Permission tree size cap exceeded"); 4441 } 4442 } 4443 } 4444 4445 boolean addPermissionLocked(PermissionInfo info, boolean async) { 4446 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 4447 throw new SecurityException("Label must be specified in permission"); 4448 } 4449 BasePermission tree = checkPermissionTreeLP(info.name); 4450 BasePermission bp = mSettings.mPermissions.get(info.name); 4451 boolean added = bp == null; 4452 boolean changed = true; 4453 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 4454 if (added) { 4455 enforcePermissionCapLocked(info, tree); 4456 bp = new BasePermission(info.name, tree.sourcePackage, 4457 BasePermission.TYPE_DYNAMIC); 4458 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 4459 throw new SecurityException( 4460 "Not allowed to modify non-dynamic permission " 4461 + info.name); 4462 } else { 4463 if (bp.protectionLevel == fixedLevel 4464 && bp.perm.owner.equals(tree.perm.owner) 4465 && bp.uid == tree.uid 4466 && comparePermissionInfos(bp.perm.info, info)) { 4467 changed = false; 4468 } 4469 } 4470 bp.protectionLevel = fixedLevel; 4471 info = new PermissionInfo(info); 4472 info.protectionLevel = fixedLevel; 4473 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 4474 bp.perm.info.packageName = tree.perm.info.packageName; 4475 bp.uid = tree.uid; 4476 if (added) { 4477 mSettings.mPermissions.put(info.name, bp); 4478 } 4479 if (changed) { 4480 if (!async) { 4481 mSettings.writeLPr(); 4482 } else { 4483 scheduleWriteSettingsLocked(); 4484 } 4485 } 4486 return added; 4487 } 4488 4489 @Override 4490 public boolean addPermission(PermissionInfo info) { 4491 synchronized (mPackages) { 4492 return addPermissionLocked(info, false); 4493 } 4494 } 4495 4496 @Override 4497 public boolean addPermissionAsync(PermissionInfo info) { 4498 synchronized (mPackages) { 4499 return addPermissionLocked(info, true); 4500 } 4501 } 4502 4503 @Override 4504 public void removePermission(String name) { 4505 synchronized (mPackages) { 4506 checkPermissionTreeLP(name); 4507 BasePermission bp = mSettings.mPermissions.get(name); 4508 if (bp != null) { 4509 if (bp.type != BasePermission.TYPE_DYNAMIC) { 4510 throw new SecurityException( 4511 "Not allowed to modify non-dynamic permission " 4512 + name); 4513 } 4514 mSettings.mPermissions.remove(name); 4515 mSettings.writeLPr(); 4516 } 4517 } 4518 } 4519 4520 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 4521 BasePermission bp) { 4522 int index = pkg.requestedPermissions.indexOf(bp.name); 4523 if (index == -1) { 4524 throw new SecurityException("Package " + pkg.packageName 4525 + " has not requested permission " + bp.name); 4526 } 4527 if (!bp.isRuntime() && !bp.isDevelopment()) { 4528 throw new SecurityException("Permission " + bp.name 4529 + " is not a changeable permission type"); 4530 } 4531 } 4532 4533 @Override 4534 public void grantRuntimePermission(String packageName, String name, final int userId) { 4535 grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */); 4536 } 4537 4538 private void grantRuntimePermission(String packageName, String name, final int userId, 4539 boolean overridePolicy) { 4540 if (!sUserManager.exists(userId)) { 4541 Log.e(TAG, "No such user:" + userId); 4542 return; 4543 } 4544 4545 mContext.enforceCallingOrSelfPermission( 4546 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 4547 "grantRuntimePermission"); 4548 4549 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4550 true /* requireFullPermission */, true /* checkShell */, 4551 "grantRuntimePermission"); 4552 4553 final int uid; 4554 final SettingBase sb; 4555 4556 synchronized (mPackages) { 4557 final PackageParser.Package pkg = mPackages.get(packageName); 4558 if (pkg == null) { 4559 throw new IllegalArgumentException("Unknown package: " + packageName); 4560 } 4561 4562 final BasePermission bp = mSettings.mPermissions.get(name); 4563 if (bp == null) { 4564 throw new IllegalArgumentException("Unknown permission: " + name); 4565 } 4566 4567 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4568 4569 // If a permission review is required for legacy apps we represent 4570 // their permissions as always granted runtime ones since we need 4571 // to keep the review required permission flag per user while an 4572 // install permission's state is shared across all users. 4573 if (mPermissionReviewRequired 4574 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4575 && bp.isRuntime()) { 4576 return; 4577 } 4578 4579 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 4580 sb = (SettingBase) pkg.mExtras; 4581 if (sb == null) { 4582 throw new IllegalArgumentException("Unknown package: " + packageName); 4583 } 4584 4585 final PermissionsState permissionsState = sb.getPermissionsState(); 4586 4587 final int flags = permissionsState.getPermissionFlags(name, userId); 4588 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4589 throw new SecurityException("Cannot grant system fixed permission " 4590 + name + " for package " + packageName); 4591 } 4592 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) { 4593 throw new SecurityException("Cannot grant policy fixed permission " 4594 + name + " for package " + packageName); 4595 } 4596 4597 if (bp.isDevelopment()) { 4598 // Development permissions must be handled specially, since they are not 4599 // normal runtime permissions. For now they apply to all users. 4600 if (permissionsState.grantInstallPermission(bp) != 4601 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4602 scheduleWriteSettingsLocked(); 4603 } 4604 return; 4605 } 4606 4607 if (pkg.applicationInfo.isEphemeralApp() && !bp.isEphemeral()) { 4608 throw new SecurityException("Cannot grant non-ephemeral permission" 4609 + name + " for package " + packageName); 4610 } 4611 4612 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4613 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4614 return; 4615 } 4616 4617 final int result = permissionsState.grantRuntimePermission(bp, userId); 4618 switch (result) { 4619 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4620 return; 4621 } 4622 4623 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4624 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4625 mHandler.post(new Runnable() { 4626 @Override 4627 public void run() { 4628 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4629 } 4630 }); 4631 } 4632 break; 4633 } 4634 4635 if (bp.isRuntime()) { 4636 logPermissionGranted(mContext, name, packageName); 4637 } 4638 4639 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4640 4641 // Not critical if that is lost - app has to request again. 4642 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4643 } 4644 4645 // Only need to do this if user is initialized. Otherwise it's a new user 4646 // and there are no processes running as the user yet and there's no need 4647 // to make an expensive call to remount processes for the changed permissions. 4648 if (READ_EXTERNAL_STORAGE.equals(name) 4649 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4650 final long token = Binder.clearCallingIdentity(); 4651 try { 4652 if (sUserManager.isInitialized(userId)) { 4653 StorageManagerInternal storageManagerInternal = LocalServices.getService( 4654 StorageManagerInternal.class); 4655 storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName); 4656 } 4657 } finally { 4658 Binder.restoreCallingIdentity(token); 4659 } 4660 } 4661 } 4662 4663 @Override 4664 public void revokeRuntimePermission(String packageName, String name, int userId) { 4665 revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */); 4666 } 4667 4668 private void revokeRuntimePermission(String packageName, String name, int userId, 4669 boolean overridePolicy) { 4670 if (!sUserManager.exists(userId)) { 4671 Log.e(TAG, "No such user:" + userId); 4672 return; 4673 } 4674 4675 mContext.enforceCallingOrSelfPermission( 4676 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4677 "revokeRuntimePermission"); 4678 4679 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4680 true /* requireFullPermission */, true /* checkShell */, 4681 "revokeRuntimePermission"); 4682 4683 final int appId; 4684 4685 synchronized (mPackages) { 4686 final PackageParser.Package pkg = mPackages.get(packageName); 4687 if (pkg == null) { 4688 throw new IllegalArgumentException("Unknown package: " + packageName); 4689 } 4690 4691 final BasePermission bp = mSettings.mPermissions.get(name); 4692 if (bp == null) { 4693 throw new IllegalArgumentException("Unknown permission: " + name); 4694 } 4695 4696 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4697 4698 // If a permission review is required for legacy apps we represent 4699 // their permissions as always granted runtime ones since we need 4700 // to keep the review required permission flag per user while an 4701 // install permission's state is shared across all users. 4702 if (mPermissionReviewRequired 4703 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4704 && bp.isRuntime()) { 4705 return; 4706 } 4707 4708 SettingBase sb = (SettingBase) pkg.mExtras; 4709 if (sb == null) { 4710 throw new IllegalArgumentException("Unknown package: " + packageName); 4711 } 4712 4713 final PermissionsState permissionsState = sb.getPermissionsState(); 4714 4715 final int flags = permissionsState.getPermissionFlags(name, userId); 4716 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4717 throw new SecurityException("Cannot revoke system fixed permission " 4718 + name + " for package " + packageName); 4719 } 4720 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) { 4721 throw new SecurityException("Cannot revoke policy fixed permission " 4722 + name + " for package " + packageName); 4723 } 4724 4725 if (bp.isDevelopment()) { 4726 // Development permissions must be handled specially, since they are not 4727 // normal runtime permissions. For now they apply to all users. 4728 if (permissionsState.revokeInstallPermission(bp) != 4729 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4730 scheduleWriteSettingsLocked(); 4731 } 4732 return; 4733 } 4734 4735 if (permissionsState.revokeRuntimePermission(bp, userId) == 4736 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4737 return; 4738 } 4739 4740 if (bp.isRuntime()) { 4741 logPermissionRevoked(mContext, name, packageName); 4742 } 4743 4744 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4745 4746 // Critical, after this call app should never have the permission. 4747 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4748 4749 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4750 } 4751 4752 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4753 } 4754 4755 /** 4756 * Get the first event id for the permission. 4757 * 4758 * <p>There are four events for each permission: <ul> 4759 * <li>Request permission: first id + 0</li> 4760 * <li>Grant permission: first id + 1</li> 4761 * <li>Request for permission denied: first id + 2</li> 4762 * <li>Revoke permission: first id + 3</li> 4763 * </ul></p> 4764 * 4765 * @param name name of the permission 4766 * 4767 * @return The first event id for the permission 4768 */ 4769 private static int getBaseEventId(@NonNull String name) { 4770 int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name); 4771 4772 if (eventIdIndex == -1) { 4773 if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE 4774 || "user".equals(Build.TYPE)) { 4775 Log.i(TAG, "Unknown permission " + name); 4776 4777 return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN; 4778 } else { 4779 // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated. 4780 // 4781 // Also update 4782 // - EventLogger#ALL_DANGEROUS_PERMISSIONS 4783 // - metrics_constants.proto 4784 throw new IllegalStateException("Unknown permission " + name); 4785 } 4786 } 4787 4788 return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4; 4789 } 4790 4791 /** 4792 * Log that a permission was revoked. 4793 * 4794 * @param context Context of the caller 4795 * @param name name of the permission 4796 * @param packageName package permission if for 4797 */ 4798 private static void logPermissionRevoked(@NonNull Context context, @NonNull String name, 4799 @NonNull String packageName) { 4800 MetricsLogger.action(context, getBaseEventId(name) + 3, packageName); 4801 } 4802 4803 /** 4804 * Log that a permission request was granted. 4805 * 4806 * @param context Context of the caller 4807 * @param name name of the permission 4808 * @param packageName package permission if for 4809 */ 4810 private static void logPermissionGranted(@NonNull Context context, @NonNull String name, 4811 @NonNull String packageName) { 4812 MetricsLogger.action(context, getBaseEventId(name) + 1, packageName); 4813 } 4814 4815 @Override 4816 public void resetRuntimePermissions() { 4817 mContext.enforceCallingOrSelfPermission( 4818 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4819 "revokeRuntimePermission"); 4820 4821 int callingUid = Binder.getCallingUid(); 4822 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4823 mContext.enforceCallingOrSelfPermission( 4824 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4825 "resetRuntimePermissions"); 4826 } 4827 4828 synchronized (mPackages) { 4829 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4830 for (int userId : UserManagerService.getInstance().getUserIds()) { 4831 final int packageCount = mPackages.size(); 4832 for (int i = 0; i < packageCount; i++) { 4833 PackageParser.Package pkg = mPackages.valueAt(i); 4834 if (!(pkg.mExtras instanceof PackageSetting)) { 4835 continue; 4836 } 4837 PackageSetting ps = (PackageSetting) pkg.mExtras; 4838 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4839 } 4840 } 4841 } 4842 } 4843 4844 @Override 4845 public int getPermissionFlags(String name, String packageName, int userId) { 4846 if (!sUserManager.exists(userId)) { 4847 return 0; 4848 } 4849 4850 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4851 4852 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4853 true /* requireFullPermission */, false /* checkShell */, 4854 "getPermissionFlags"); 4855 4856 synchronized (mPackages) { 4857 final PackageParser.Package pkg = mPackages.get(packageName); 4858 if (pkg == null) { 4859 return 0; 4860 } 4861 4862 final BasePermission bp = mSettings.mPermissions.get(name); 4863 if (bp == null) { 4864 return 0; 4865 } 4866 4867 SettingBase sb = (SettingBase) pkg.mExtras; 4868 if (sb == null) { 4869 return 0; 4870 } 4871 4872 PermissionsState permissionsState = sb.getPermissionsState(); 4873 return permissionsState.getPermissionFlags(name, userId); 4874 } 4875 } 4876 4877 @Override 4878 public void updatePermissionFlags(String name, String packageName, int flagMask, 4879 int flagValues, int userId) { 4880 if (!sUserManager.exists(userId)) { 4881 return; 4882 } 4883 4884 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4885 4886 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4887 true /* requireFullPermission */, true /* checkShell */, 4888 "updatePermissionFlags"); 4889 4890 // Only the system can change these flags and nothing else. 4891 if (getCallingUid() != Process.SYSTEM_UID) { 4892 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4893 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4894 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4895 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4896 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4897 } 4898 4899 synchronized (mPackages) { 4900 final PackageParser.Package pkg = mPackages.get(packageName); 4901 if (pkg == null) { 4902 throw new IllegalArgumentException("Unknown package: " + packageName); 4903 } 4904 4905 final BasePermission bp = mSettings.mPermissions.get(name); 4906 if (bp == null) { 4907 throw new IllegalArgumentException("Unknown permission: " + name); 4908 } 4909 4910 SettingBase sb = (SettingBase) pkg.mExtras; 4911 if (sb == null) { 4912 throw new IllegalArgumentException("Unknown package: " + packageName); 4913 } 4914 4915 PermissionsState permissionsState = sb.getPermissionsState(); 4916 4917 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4918 4919 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4920 // Install and runtime permissions are stored in different places, 4921 // so figure out what permission changed and persist the change. 4922 if (permissionsState.getInstallPermissionState(name) != null) { 4923 scheduleWriteSettingsLocked(); 4924 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4925 || hadState) { 4926 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4927 } 4928 } 4929 } 4930 } 4931 4932 /** 4933 * Update the permission flags for all packages and runtime permissions of a user in order 4934 * to allow device or profile owner to remove POLICY_FIXED. 4935 */ 4936 @Override 4937 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4938 if (!sUserManager.exists(userId)) { 4939 return; 4940 } 4941 4942 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4943 4944 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4945 true /* requireFullPermission */, true /* checkShell */, 4946 "updatePermissionFlagsForAllApps"); 4947 4948 // Only the system can change system fixed flags. 4949 if (getCallingUid() != Process.SYSTEM_UID) { 4950 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4951 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4952 } 4953 4954 synchronized (mPackages) { 4955 boolean changed = false; 4956 final int packageCount = mPackages.size(); 4957 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4958 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4959 SettingBase sb = (SettingBase) pkg.mExtras; 4960 if (sb == null) { 4961 continue; 4962 } 4963 PermissionsState permissionsState = sb.getPermissionsState(); 4964 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4965 userId, flagMask, flagValues); 4966 } 4967 if (changed) { 4968 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4969 } 4970 } 4971 } 4972 4973 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4974 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4975 != PackageManager.PERMISSION_GRANTED 4976 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4977 != PackageManager.PERMISSION_GRANTED) { 4978 throw new SecurityException(message + " requires " 4979 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4980 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4981 } 4982 } 4983 4984 @Override 4985 public boolean shouldShowRequestPermissionRationale(String permissionName, 4986 String packageName, int userId) { 4987 if (UserHandle.getCallingUserId() != userId) { 4988 mContext.enforceCallingPermission( 4989 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4990 "canShowRequestPermissionRationale for user " + userId); 4991 } 4992 4993 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4994 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4995 return false; 4996 } 4997 4998 if (checkPermission(permissionName, packageName, userId) 4999 == PackageManager.PERMISSION_GRANTED) { 5000 return false; 5001 } 5002 5003 final int flags; 5004 5005 final long identity = Binder.clearCallingIdentity(); 5006 try { 5007 flags = getPermissionFlags(permissionName, 5008 packageName, userId); 5009 } finally { 5010 Binder.restoreCallingIdentity(identity); 5011 } 5012 5013 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 5014 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 5015 | PackageManager.FLAG_PERMISSION_USER_FIXED; 5016 5017 if ((flags & fixedFlags) != 0) { 5018 return false; 5019 } 5020 5021 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 5022 } 5023 5024 @Override 5025 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 5026 mContext.enforceCallingOrSelfPermission( 5027 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 5028 "addOnPermissionsChangeListener"); 5029 5030 synchronized (mPackages) { 5031 mOnPermissionChangeListeners.addListenerLocked(listener); 5032 } 5033 } 5034 5035 @Override 5036 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 5037 synchronized (mPackages) { 5038 mOnPermissionChangeListeners.removeListenerLocked(listener); 5039 } 5040 } 5041 5042 @Override 5043 public boolean isProtectedBroadcast(String actionName) { 5044 synchronized (mPackages) { 5045 if (mProtectedBroadcasts.contains(actionName)) { 5046 return true; 5047 } else if (actionName != null) { 5048 // TODO: remove these terrible hacks 5049 if (actionName.startsWith("android.net.netmon.lingerExpired") 5050 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 5051 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 5052 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 5053 return true; 5054 } 5055 } 5056 } 5057 return false; 5058 } 5059 5060 @Override 5061 public int checkSignatures(String pkg1, String pkg2) { 5062 synchronized (mPackages) { 5063 final PackageParser.Package p1 = mPackages.get(pkg1); 5064 final PackageParser.Package p2 = mPackages.get(pkg2); 5065 if (p1 == null || p1.mExtras == null 5066 || p2 == null || p2.mExtras == null) { 5067 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5068 } 5069 return compareSignatures(p1.mSignatures, p2.mSignatures); 5070 } 5071 } 5072 5073 @Override 5074 public int checkUidSignatures(int uid1, int uid2) { 5075 // Map to base uids. 5076 uid1 = UserHandle.getAppId(uid1); 5077 uid2 = UserHandle.getAppId(uid2); 5078 // reader 5079 synchronized (mPackages) { 5080 Signature[] s1; 5081 Signature[] s2; 5082 Object obj = mSettings.getUserIdLPr(uid1); 5083 if (obj != null) { 5084 if (obj instanceof SharedUserSetting) { 5085 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 5086 } else if (obj instanceof PackageSetting) { 5087 s1 = ((PackageSetting)obj).signatures.mSignatures; 5088 } else { 5089 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5090 } 5091 } else { 5092 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5093 } 5094 obj = mSettings.getUserIdLPr(uid2); 5095 if (obj != null) { 5096 if (obj instanceof SharedUserSetting) { 5097 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 5098 } else if (obj instanceof PackageSetting) { 5099 s2 = ((PackageSetting)obj).signatures.mSignatures; 5100 } else { 5101 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5102 } 5103 } else { 5104 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5105 } 5106 return compareSignatures(s1, s2); 5107 } 5108 } 5109 5110 /** 5111 * This method should typically only be used when granting or revoking 5112 * permissions, since the app may immediately restart after this call. 5113 * <p> 5114 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 5115 * guard your work against the app being relaunched. 5116 */ 5117 private void killUid(int appId, int userId, String reason) { 5118 final long identity = Binder.clearCallingIdentity(); 5119 try { 5120 IActivityManager am = ActivityManager.getService(); 5121 if (am != null) { 5122 try { 5123 am.killUid(appId, userId, reason); 5124 } catch (RemoteException e) { 5125 /* ignore - same process */ 5126 } 5127 } 5128 } finally { 5129 Binder.restoreCallingIdentity(identity); 5130 } 5131 } 5132 5133 /** 5134 * Compares two sets of signatures. Returns: 5135 * <br /> 5136 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 5137 * <br /> 5138 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 5139 * <br /> 5140 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 5141 * <br /> 5142 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 5143 * <br /> 5144 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 5145 */ 5146 static int compareSignatures(Signature[] s1, Signature[] s2) { 5147 if (s1 == null) { 5148 return s2 == null 5149 ? PackageManager.SIGNATURE_NEITHER_SIGNED 5150 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 5151 } 5152 5153 if (s2 == null) { 5154 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 5155 } 5156 5157 if (s1.length != s2.length) { 5158 return PackageManager.SIGNATURE_NO_MATCH; 5159 } 5160 5161 // Since both signature sets are of size 1, we can compare without HashSets. 5162 if (s1.length == 1) { 5163 return s1[0].equals(s2[0]) ? 5164 PackageManager.SIGNATURE_MATCH : 5165 PackageManager.SIGNATURE_NO_MATCH; 5166 } 5167 5168 ArraySet<Signature> set1 = new ArraySet<Signature>(); 5169 for (Signature sig : s1) { 5170 set1.add(sig); 5171 } 5172 ArraySet<Signature> set2 = new ArraySet<Signature>(); 5173 for (Signature sig : s2) { 5174 set2.add(sig); 5175 } 5176 // Make sure s2 contains all signatures in s1. 5177 if (set1.equals(set2)) { 5178 return PackageManager.SIGNATURE_MATCH; 5179 } 5180 return PackageManager.SIGNATURE_NO_MATCH; 5181 } 5182 5183 /** 5184 * If the database version for this type of package (internal storage or 5185 * external storage) is less than the version where package signatures 5186 * were updated, return true. 5187 */ 5188 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 5189 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 5190 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 5191 } 5192 5193 /** 5194 * Used for backward compatibility to make sure any packages with 5195 * certificate chains get upgraded to the new style. {@code existingSigs} 5196 * will be in the old format (since they were stored on disk from before the 5197 * system upgrade) and {@code scannedSigs} will be in the newer format. 5198 */ 5199 private int compareSignaturesCompat(PackageSignatures existingSigs, 5200 PackageParser.Package scannedPkg) { 5201 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 5202 return PackageManager.SIGNATURE_NO_MATCH; 5203 } 5204 5205 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 5206 for (Signature sig : existingSigs.mSignatures) { 5207 existingSet.add(sig); 5208 } 5209 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 5210 for (Signature sig : scannedPkg.mSignatures) { 5211 try { 5212 Signature[] chainSignatures = sig.getChainSignatures(); 5213 for (Signature chainSig : chainSignatures) { 5214 scannedCompatSet.add(chainSig); 5215 } 5216 } catch (CertificateEncodingException e) { 5217 scannedCompatSet.add(sig); 5218 } 5219 } 5220 /* 5221 * Make sure the expanded scanned set contains all signatures in the 5222 * existing one. 5223 */ 5224 if (scannedCompatSet.equals(existingSet)) { 5225 // Migrate the old signatures to the new scheme. 5226 existingSigs.assignSignatures(scannedPkg.mSignatures); 5227 // The new KeySets will be re-added later in the scanning process. 5228 synchronized (mPackages) { 5229 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 5230 } 5231 return PackageManager.SIGNATURE_MATCH; 5232 } 5233 return PackageManager.SIGNATURE_NO_MATCH; 5234 } 5235 5236 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 5237 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 5238 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 5239 } 5240 5241 private int compareSignaturesRecover(PackageSignatures existingSigs, 5242 PackageParser.Package scannedPkg) { 5243 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 5244 return PackageManager.SIGNATURE_NO_MATCH; 5245 } 5246 5247 String msg = null; 5248 try { 5249 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 5250 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 5251 + scannedPkg.packageName); 5252 return PackageManager.SIGNATURE_MATCH; 5253 } 5254 } catch (CertificateException e) { 5255 msg = e.getMessage(); 5256 } 5257 5258 logCriticalInfo(Log.INFO, 5259 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 5260 return PackageManager.SIGNATURE_NO_MATCH; 5261 } 5262 5263 @Override 5264 public List<String> getAllPackages() { 5265 synchronized (mPackages) { 5266 return new ArrayList<String>(mPackages.keySet()); 5267 } 5268 } 5269 5270 @Override 5271 public String[] getPackagesForUid(int uid) { 5272 final int userId = UserHandle.getUserId(uid); 5273 uid = UserHandle.getAppId(uid); 5274 // reader 5275 synchronized (mPackages) { 5276 Object obj = mSettings.getUserIdLPr(uid); 5277 if (obj instanceof SharedUserSetting) { 5278 final SharedUserSetting sus = (SharedUserSetting) obj; 5279 final int N = sus.packages.size(); 5280 String[] res = new String[N]; 5281 final Iterator<PackageSetting> it = sus.packages.iterator(); 5282 int i = 0; 5283 while (it.hasNext()) { 5284 PackageSetting ps = it.next(); 5285 if (ps.getInstalled(userId)) { 5286 res[i++] = ps.name; 5287 } else { 5288 res = ArrayUtils.removeElement(String.class, res, res[i]); 5289 } 5290 } 5291 return res; 5292 } else if (obj instanceof PackageSetting) { 5293 final PackageSetting ps = (PackageSetting) obj; 5294 if (ps.getInstalled(userId)) { 5295 return new String[]{ps.name}; 5296 } 5297 } 5298 } 5299 return null; 5300 } 5301 5302 @Override 5303 public String getNameForUid(int uid) { 5304 // reader 5305 synchronized (mPackages) { 5306 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5307 if (obj instanceof SharedUserSetting) { 5308 final SharedUserSetting sus = (SharedUserSetting) obj; 5309 return sus.name + ":" + sus.userId; 5310 } else if (obj instanceof PackageSetting) { 5311 final PackageSetting ps = (PackageSetting) obj; 5312 return ps.name; 5313 } 5314 } 5315 return null; 5316 } 5317 5318 @Override 5319 public int getUidForSharedUser(String sharedUserName) { 5320 if(sharedUserName == null) { 5321 return -1; 5322 } 5323 // reader 5324 synchronized (mPackages) { 5325 SharedUserSetting suid; 5326 try { 5327 suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 5328 if (suid != null) { 5329 return suid.userId; 5330 } 5331 } catch (PackageManagerException ignore) { 5332 // can't happen, but, still need to catch it 5333 } 5334 return -1; 5335 } 5336 } 5337 5338 @Override 5339 public int getFlagsForUid(int uid) { 5340 synchronized (mPackages) { 5341 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5342 if (obj instanceof SharedUserSetting) { 5343 final SharedUserSetting sus = (SharedUserSetting) obj; 5344 return sus.pkgFlags; 5345 } else if (obj instanceof PackageSetting) { 5346 final PackageSetting ps = (PackageSetting) obj; 5347 return ps.pkgFlags; 5348 } 5349 } 5350 return 0; 5351 } 5352 5353 @Override 5354 public int getPrivateFlagsForUid(int uid) { 5355 synchronized (mPackages) { 5356 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5357 if (obj instanceof SharedUserSetting) { 5358 final SharedUserSetting sus = (SharedUserSetting) obj; 5359 return sus.pkgPrivateFlags; 5360 } else if (obj instanceof PackageSetting) { 5361 final PackageSetting ps = (PackageSetting) obj; 5362 return ps.pkgPrivateFlags; 5363 } 5364 } 5365 return 0; 5366 } 5367 5368 @Override 5369 public boolean isUidPrivileged(int uid) { 5370 uid = UserHandle.getAppId(uid); 5371 // reader 5372 synchronized (mPackages) { 5373 Object obj = mSettings.getUserIdLPr(uid); 5374 if (obj instanceof SharedUserSetting) { 5375 final SharedUserSetting sus = (SharedUserSetting) obj; 5376 final Iterator<PackageSetting> it = sus.packages.iterator(); 5377 while (it.hasNext()) { 5378 if (it.next().isPrivileged()) { 5379 return true; 5380 } 5381 } 5382 } else if (obj instanceof PackageSetting) { 5383 final PackageSetting ps = (PackageSetting) obj; 5384 return ps.isPrivileged(); 5385 } 5386 } 5387 return false; 5388 } 5389 5390 @Override 5391 public String[] getAppOpPermissionPackages(String permissionName) { 5392 synchronized (mPackages) { 5393 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 5394 if (pkgs == null) { 5395 return null; 5396 } 5397 return pkgs.toArray(new String[pkgs.size()]); 5398 } 5399 } 5400 5401 @Override 5402 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 5403 int flags, int userId) { 5404 try { 5405 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 5406 5407 if (!sUserManager.exists(userId)) return null; 5408 flags = updateFlagsForResolve(flags, userId, intent); 5409 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5410 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 5411 5412 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5413 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 5414 flags, userId); 5415 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5416 5417 final ResolveInfo bestChoice = 5418 chooseBestActivity(intent, resolvedType, flags, query, userId); 5419 return bestChoice; 5420 } finally { 5421 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5422 } 5423 } 5424 5425 @Override 5426 public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) { 5427 if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) { 5428 throw new SecurityException( 5429 "findPersistentPreferredActivity can only be run by the system"); 5430 } 5431 if (!sUserManager.exists(userId)) { 5432 return null; 5433 } 5434 intent = updateIntentForResolve(intent); 5435 final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver()); 5436 final int flags = updateFlagsForResolve(0, userId, intent); 5437 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5438 userId); 5439 synchronized (mPackages) { 5440 return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false, 5441 userId); 5442 } 5443 } 5444 5445 @Override 5446 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 5447 IntentFilter filter, int match, ComponentName activity) { 5448 final int userId = UserHandle.getCallingUserId(); 5449 if (DEBUG_PREFERRED) { 5450 Log.v(TAG, "setLastChosenActivity intent=" + intent 5451 + " resolvedType=" + resolvedType 5452 + " flags=" + flags 5453 + " filter=" + filter 5454 + " match=" + match 5455 + " activity=" + activity); 5456 filter.dump(new PrintStreamPrinter(System.out), " "); 5457 } 5458 intent.setComponent(null); 5459 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5460 userId); 5461 // Find any earlier preferred or last chosen entries and nuke them 5462 findPreferredActivity(intent, resolvedType, 5463 flags, query, 0, false, true, false, userId); 5464 // Add the new activity as the last chosen for this filter 5465 addPreferredActivityInternal(filter, match, null, activity, false, userId, 5466 "Setting last chosen"); 5467 } 5468 5469 @Override 5470 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 5471 final int userId = UserHandle.getCallingUserId(); 5472 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 5473 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5474 userId); 5475 return findPreferredActivity(intent, resolvedType, flags, query, 0, 5476 false, false, false, userId); 5477 } 5478 5479 private boolean isEphemeralDisabled() { 5480 // ephemeral apps have been disabled across the board 5481 if (DISABLE_EPHEMERAL_APPS) { 5482 return true; 5483 } 5484 // system isn't up yet; can't read settings, so, assume no ephemeral apps 5485 if (!mSystemReady) { 5486 return true; 5487 } 5488 // we can't get a content resolver until the system is ready; these checks must happen last 5489 final ContentResolver resolver = mContext.getContentResolver(); 5490 if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) { 5491 return true; 5492 } 5493 return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0; 5494 } 5495 5496 private boolean isEphemeralAllowed( 5497 Intent intent, List<ResolveInfo> resolvedActivities, int userId, 5498 boolean skipPackageCheck) { 5499 // Short circuit and return early if possible. 5500 if (isEphemeralDisabled()) { 5501 return false; 5502 } 5503 final int callingUser = UserHandle.getCallingUserId(); 5504 if (callingUser != UserHandle.USER_SYSTEM) { 5505 return false; 5506 } 5507 if (mEphemeralResolverConnection == null) { 5508 return false; 5509 } 5510 if (mEphemeralInstallerComponent == null) { 5511 return false; 5512 } 5513 if (intent.getComponent() != null) { 5514 return false; 5515 } 5516 if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) { 5517 return false; 5518 } 5519 if (!skipPackageCheck && intent.getPackage() != null) { 5520 return false; 5521 } 5522 final boolean isWebUri = hasWebURI(intent); 5523 if (!isWebUri || intent.getData().getHost() == null) { 5524 return false; 5525 } 5526 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 5527 synchronized (mPackages) { 5528 final int count = (resolvedActivities == null ? 0 : resolvedActivities.size()); 5529 for (int n = 0; n < count; n++) { 5530 ResolveInfo info = resolvedActivities.get(n); 5531 String packageName = info.activityInfo.packageName; 5532 PackageSetting ps = mSettings.mPackages.get(packageName); 5533 if (ps != null) { 5534 // Try to get the status from User settings first 5535 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5536 int status = (int) (packedStatus >> 32); 5537 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 5538 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5539 if (DEBUG_EPHEMERAL) { 5540 Slog.v(TAG, "DENY ephemeral apps;" 5541 + " pkg: " + packageName + ", status: " + status); 5542 } 5543 return false; 5544 } 5545 } 5546 } 5547 } 5548 // We've exhausted all ways to deny ephemeral application; let the system look for them. 5549 return true; 5550 } 5551 5552 private void requestEphemeralResolutionPhaseTwo(EphemeralResponse responseObj, 5553 Intent origIntent, String resolvedType, Intent launchIntent, String callingPackage, 5554 int userId) { 5555 final Message msg = mHandler.obtainMessage(EPHEMERAL_RESOLUTION_PHASE_TWO, 5556 new EphemeralRequest(responseObj, origIntent, resolvedType, launchIntent, 5557 callingPackage, userId)); 5558 mHandler.sendMessage(msg); 5559 } 5560 5561 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 5562 int flags, List<ResolveInfo> query, int userId) { 5563 if (query != null) { 5564 final int N = query.size(); 5565 if (N == 1) { 5566 return query.get(0); 5567 } else if (N > 1) { 5568 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 5569 // If there is more than one activity with the same priority, 5570 // then let the user decide between them. 5571 ResolveInfo r0 = query.get(0); 5572 ResolveInfo r1 = query.get(1); 5573 if (DEBUG_INTENT_MATCHING || debug) { 5574 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 5575 + r1.activityInfo.name + "=" + r1.priority); 5576 } 5577 // If the first activity has a higher priority, or a different 5578 // default, then it is always desirable to pick it. 5579 if (r0.priority != r1.priority 5580 || r0.preferredOrder != r1.preferredOrder 5581 || r0.isDefault != r1.isDefault) { 5582 return query.get(0); 5583 } 5584 // If we have saved a preference for a preferred activity for 5585 // this Intent, use that. 5586 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 5587 flags, query, r0.priority, true, false, debug, userId); 5588 if (ri != null) { 5589 return ri; 5590 } 5591 ri = new ResolveInfo(mResolveInfo); 5592 ri.activityInfo = new ActivityInfo(ri.activityInfo); 5593 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 5594 // If all of the options come from the same package, show the application's 5595 // label and icon instead of the generic resolver's. 5596 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 5597 // and then throw away the ResolveInfo itself, meaning that the caller loses 5598 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 5599 // a fallback for this case; we only set the target package's resources on 5600 // the ResolveInfo, not the ActivityInfo. 5601 final String intentPackage = intent.getPackage(); 5602 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 5603 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 5604 ri.resolvePackageName = intentPackage; 5605 if (userNeedsBadging(userId)) { 5606 ri.noResourceId = true; 5607 } else { 5608 ri.icon = appi.icon; 5609 } 5610 ri.iconResourceId = appi.icon; 5611 ri.labelRes = appi.labelRes; 5612 } 5613 ri.activityInfo.applicationInfo = new ApplicationInfo( 5614 ri.activityInfo.applicationInfo); 5615 if (userId != 0) { 5616 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 5617 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 5618 } 5619 // Make sure that the resolver is displayable in car mode 5620 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 5621 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 5622 return ri; 5623 } 5624 } 5625 return null; 5626 } 5627 5628 /** 5629 * Return true if the given list is not empty and all of its contents have 5630 * an activityInfo with the given package name. 5631 */ 5632 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 5633 if (ArrayUtils.isEmpty(list)) { 5634 return false; 5635 } 5636 for (int i = 0, N = list.size(); i < N; i++) { 5637 final ResolveInfo ri = list.get(i); 5638 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 5639 if (ai == null || !packageName.equals(ai.packageName)) { 5640 return false; 5641 } 5642 } 5643 return true; 5644 } 5645 5646 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 5647 int flags, List<ResolveInfo> query, boolean debug, int userId) { 5648 final int N = query.size(); 5649 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 5650 .get(userId); 5651 // Get the list of persistent preferred activities that handle the intent 5652 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 5653 List<PersistentPreferredActivity> pprefs = ppir != null 5654 ? ppir.queryIntent(intent, resolvedType, 5655 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 5656 (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0, 5657 (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId) 5658 : null; 5659 if (pprefs != null && pprefs.size() > 0) { 5660 final int M = pprefs.size(); 5661 for (int i=0; i<M; i++) { 5662 final PersistentPreferredActivity ppa = pprefs.get(i); 5663 if (DEBUG_PREFERRED || debug) { 5664 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 5665 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 5666 + "\n component=" + ppa.mComponent); 5667 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5668 } 5669 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 5670 flags | MATCH_DISABLED_COMPONENTS, userId); 5671 if (DEBUG_PREFERRED || debug) { 5672 Slog.v(TAG, "Found persistent preferred activity:"); 5673 if (ai != null) { 5674 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5675 } else { 5676 Slog.v(TAG, " null"); 5677 } 5678 } 5679 if (ai == null) { 5680 // This previously registered persistent preferred activity 5681 // component is no longer known. Ignore it and do NOT remove it. 5682 continue; 5683 } 5684 for (int j=0; j<N; j++) { 5685 final ResolveInfo ri = query.get(j); 5686 if (!ri.activityInfo.applicationInfo.packageName 5687 .equals(ai.applicationInfo.packageName)) { 5688 continue; 5689 } 5690 if (!ri.activityInfo.name.equals(ai.name)) { 5691 continue; 5692 } 5693 // Found a persistent preference that can handle the intent. 5694 if (DEBUG_PREFERRED || debug) { 5695 Slog.v(TAG, "Returning persistent preferred activity: " + 5696 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5697 } 5698 return ri; 5699 } 5700 } 5701 } 5702 return null; 5703 } 5704 5705 // TODO: handle preferred activities missing while user has amnesia 5706 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5707 List<ResolveInfo> query, int priority, boolean always, 5708 boolean removeMatches, boolean debug, int userId) { 5709 if (!sUserManager.exists(userId)) return null; 5710 flags = updateFlagsForResolve(flags, userId, intent); 5711 intent = updateIntentForResolve(intent); 5712 // writer 5713 synchronized (mPackages) { 5714 // Try to find a matching persistent preferred activity. 5715 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5716 debug, userId); 5717 5718 // If a persistent preferred activity matched, use it. 5719 if (pri != null) { 5720 return pri; 5721 } 5722 5723 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5724 // Get the list of preferred activities that handle the intent 5725 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5726 List<PreferredActivity> prefs = pir != null 5727 ? pir.queryIntent(intent, resolvedType, 5728 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 5729 (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0, 5730 (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId) 5731 : null; 5732 if (prefs != null && prefs.size() > 0) { 5733 boolean changed = false; 5734 try { 5735 // First figure out how good the original match set is. 5736 // We will only allow preferred activities that came 5737 // from the same match quality. 5738 int match = 0; 5739 5740 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5741 5742 final int N = query.size(); 5743 for (int j=0; j<N; j++) { 5744 final ResolveInfo ri = query.get(j); 5745 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5746 + ": 0x" + Integer.toHexString(match)); 5747 if (ri.match > match) { 5748 match = ri.match; 5749 } 5750 } 5751 5752 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5753 + Integer.toHexString(match)); 5754 5755 match &= IntentFilter.MATCH_CATEGORY_MASK; 5756 final int M = prefs.size(); 5757 for (int i=0; i<M; i++) { 5758 final PreferredActivity pa = prefs.get(i); 5759 if (DEBUG_PREFERRED || debug) { 5760 Slog.v(TAG, "Checking PreferredActivity ds=" 5761 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5762 + "\n component=" + pa.mPref.mComponent); 5763 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5764 } 5765 if (pa.mPref.mMatch != match) { 5766 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5767 + Integer.toHexString(pa.mPref.mMatch)); 5768 continue; 5769 } 5770 // If it's not an "always" type preferred activity and that's what we're 5771 // looking for, skip it. 5772 if (always && !pa.mPref.mAlways) { 5773 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5774 continue; 5775 } 5776 final ActivityInfo ai = getActivityInfo( 5777 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5778 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5779 userId); 5780 if (DEBUG_PREFERRED || debug) { 5781 Slog.v(TAG, "Found preferred activity:"); 5782 if (ai != null) { 5783 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5784 } else { 5785 Slog.v(TAG, " null"); 5786 } 5787 } 5788 if (ai == null) { 5789 // This previously registered preferred activity 5790 // component is no longer known. Most likely an update 5791 // to the app was installed and in the new version this 5792 // component no longer exists. Clean it up by removing 5793 // it from the preferred activities list, and skip it. 5794 Slog.w(TAG, "Removing dangling preferred activity: " 5795 + pa.mPref.mComponent); 5796 pir.removeFilter(pa); 5797 changed = true; 5798 continue; 5799 } 5800 for (int j=0; j<N; j++) { 5801 final ResolveInfo ri = query.get(j); 5802 if (!ri.activityInfo.applicationInfo.packageName 5803 .equals(ai.applicationInfo.packageName)) { 5804 continue; 5805 } 5806 if (!ri.activityInfo.name.equals(ai.name)) { 5807 continue; 5808 } 5809 5810 if (removeMatches) { 5811 pir.removeFilter(pa); 5812 changed = true; 5813 if (DEBUG_PREFERRED) { 5814 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 5815 } 5816 break; 5817 } 5818 5819 // Okay we found a previously set preferred or last chosen app. 5820 // If the result set is different from when this 5821 // was created, we need to clear it and re-ask the 5822 // user their preference, if we're looking for an "always" type entry. 5823 if (always && !pa.mPref.sameSet(query)) { 5824 Slog.i(TAG, "Result set changed, dropping preferred activity for " 5825 + intent + " type " + resolvedType); 5826 if (DEBUG_PREFERRED) { 5827 Slog.v(TAG, "Removing preferred activity since set changed " 5828 + pa.mPref.mComponent); 5829 } 5830 pir.removeFilter(pa); 5831 // Re-add the filter as a "last chosen" entry (!always) 5832 PreferredActivity lastChosen = new PreferredActivity( 5833 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 5834 pir.addFilter(lastChosen); 5835 changed = true; 5836 return null; 5837 } 5838 5839 // Yay! Either the set matched or we're looking for the last chosen 5840 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 5841 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5842 return ri; 5843 } 5844 } 5845 } finally { 5846 if (changed) { 5847 if (DEBUG_PREFERRED) { 5848 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 5849 } 5850 scheduleWritePackageRestrictionsLocked(userId); 5851 } 5852 } 5853 } 5854 } 5855 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 5856 return null; 5857 } 5858 5859 /* 5860 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 5861 */ 5862 @Override 5863 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 5864 int targetUserId) { 5865 mContext.enforceCallingOrSelfPermission( 5866 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 5867 List<CrossProfileIntentFilter> matches = 5868 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 5869 if (matches != null) { 5870 int size = matches.size(); 5871 for (int i = 0; i < size; i++) { 5872 if (matches.get(i).getTargetUserId() == targetUserId) return true; 5873 } 5874 } 5875 if (hasWebURI(intent)) { 5876 // cross-profile app linking works only towards the parent. 5877 final UserInfo parent = getProfileParent(sourceUserId); 5878 synchronized(mPackages) { 5879 int flags = updateFlagsForResolve(0, parent.id, intent); 5880 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5881 intent, resolvedType, flags, sourceUserId, parent.id); 5882 return xpDomainInfo != null; 5883 } 5884 } 5885 return false; 5886 } 5887 5888 private UserInfo getProfileParent(int userId) { 5889 final long identity = Binder.clearCallingIdentity(); 5890 try { 5891 return sUserManager.getProfileParent(userId); 5892 } finally { 5893 Binder.restoreCallingIdentity(identity); 5894 } 5895 } 5896 5897 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5898 String resolvedType, int userId) { 5899 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5900 if (resolver != null) { 5901 return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, 5902 false /*visibleToEphemeral*/, false /*isEphemeral*/, userId); 5903 } 5904 return null; 5905 } 5906 5907 @Override 5908 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 5909 String resolvedType, int flags, int userId) { 5910 try { 5911 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5912 5913 return new ParceledListSlice<>( 5914 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 5915 } finally { 5916 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5917 } 5918 } 5919 5920 /** 5921 * Returns the package name of the calling Uid if it's an ephemeral app. If it isn't 5922 * ephemeral, returns {@code null}. 5923 */ 5924 private String getEphemeralPackageName(int callingUid) { 5925 final int appId = UserHandle.getAppId(callingUid); 5926 synchronized (mPackages) { 5927 final Object obj = mSettings.getUserIdLPr(appId); 5928 if (obj instanceof PackageSetting) { 5929 final PackageSetting ps = (PackageSetting) obj; 5930 return ps.pkg.applicationInfo.isEphemeralApp() ? ps.pkg.packageName : null; 5931 } 5932 } 5933 return null; 5934 } 5935 5936 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 5937 String resolvedType, int flags, int userId) { 5938 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5939 final String ephemeralPkgName = getEphemeralPackageName(Binder.getCallingUid()); 5940 flags = updateFlagsForResolve(flags, userId, intent); 5941 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5942 false /* requireFullPermission */, false /* checkShell */, 5943 "query intent activities"); 5944 ComponentName comp = intent.getComponent(); 5945 if (comp == null) { 5946 if (intent.getSelector() != null) { 5947 intent = intent.getSelector(); 5948 comp = intent.getComponent(); 5949 } 5950 } 5951 5952 if (comp != null) { 5953 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5954 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5955 if (ai != null) { 5956 // When specifying an explicit component, we prevent the activity from being 5957 // used when either 1) the calling package is normal and the activity is within 5958 // an ephemeral application or 2) the calling package is ephemeral and the 5959 // activity is not visible to ephemeral applications. 5960 boolean matchEphemeral = 5961 (flags & PackageManager.MATCH_EPHEMERAL) != 0; 5962 boolean ephemeralVisibleOnly = 5963 (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0; 5964 boolean blockResolution = 5965 (!matchEphemeral && ephemeralPkgName == null 5966 && (ai.applicationInfo.privateFlags 5967 & ApplicationInfo.PRIVATE_FLAG_EPHEMERAL) != 0) 5968 || (ephemeralVisibleOnly && ephemeralPkgName != null 5969 && (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0); 5970 if (!blockResolution) { 5971 final ResolveInfo ri = new ResolveInfo(); 5972 ri.activityInfo = ai; 5973 list.add(ri); 5974 } 5975 } 5976 return list; 5977 } 5978 5979 // reader 5980 boolean sortResult = false; 5981 boolean addEphemeral = false; 5982 List<ResolveInfo> result; 5983 final String pkgName = intent.getPackage(); 5984 synchronized (mPackages) { 5985 if (pkgName == null) { 5986 List<CrossProfileIntentFilter> matchingFilters = 5987 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5988 // Check for results that need to skip the current profile. 5989 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5990 resolvedType, flags, userId); 5991 if (xpResolveInfo != null) { 5992 List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1); 5993 xpResult.add(xpResolveInfo); 5994 return filterForEphemeral( 5995 filterIfNotSystemUser(xpResult, userId), ephemeralPkgName); 5996 } 5997 5998 // Check for results in the current profile. 5999 result = filterIfNotSystemUser(mActivities.queryIntent( 6000 intent, resolvedType, flags, userId), userId); 6001 addEphemeral = 6002 isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/); 6003 6004 // Check for cross profile results. 6005 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 6006 xpResolveInfo = queryCrossProfileIntents( 6007 matchingFilters, intent, resolvedType, flags, userId, 6008 hasNonNegativePriorityResult); 6009 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 6010 boolean isVisibleToUser = filterIfNotSystemUser( 6011 Collections.singletonList(xpResolveInfo), userId).size() > 0; 6012 if (isVisibleToUser) { 6013 result.add(xpResolveInfo); 6014 sortResult = true; 6015 } 6016 } 6017 if (hasWebURI(intent)) { 6018 CrossProfileDomainInfo xpDomainInfo = null; 6019 final UserInfo parent = getProfileParent(userId); 6020 if (parent != null) { 6021 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 6022 flags, userId, parent.id); 6023 } 6024 if (xpDomainInfo != null) { 6025 if (xpResolveInfo != null) { 6026 // If we didn't remove it, the cross-profile ResolveInfo would be twice 6027 // in the result. 6028 result.remove(xpResolveInfo); 6029 } 6030 if (result.size() == 0 && !addEphemeral) { 6031 // No result in current profile, but found candidate in parent user. 6032 // And we are not going to add emphemeral app, so we can return the 6033 // result straight away. 6034 result.add(xpDomainInfo.resolveInfo); 6035 return filterForEphemeral(result, ephemeralPkgName); 6036 } 6037 } else if (result.size() <= 1 && !addEphemeral) { 6038 // No result in parent user and <= 1 result in current profile, and we 6039 // are not going to add emphemeral app, so we can return the result without 6040 // further processing. 6041 return filterForEphemeral(result, ephemeralPkgName); 6042 } 6043 // We have more than one candidate (combining results from current and parent 6044 // profile), so we need filtering and sorting. 6045 result = filterCandidatesWithDomainPreferredActivitiesLPr( 6046 intent, flags, result, xpDomainInfo, userId); 6047 sortResult = true; 6048 } 6049 } else { 6050 final PackageParser.Package pkg = mPackages.get(pkgName); 6051 if (pkg != null) { 6052 result = filterForEphemeral(filterIfNotSystemUser( 6053 mActivities.queryIntentForPackage( 6054 intent, resolvedType, flags, pkg.activities, userId), 6055 userId), ephemeralPkgName); 6056 } else { 6057 // the caller wants to resolve for a particular package; however, there 6058 // were no installed results, so, try to find an ephemeral result 6059 addEphemeral = isEphemeralAllowed( 6060 intent, null /*result*/, userId, true /*skipPackageCheck*/); 6061 result = new ArrayList<ResolveInfo>(); 6062 } 6063 } 6064 } 6065 if (addEphemeral) { 6066 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 6067 final EphemeralRequest requestObject = new EphemeralRequest( 6068 null /*responseObj*/, intent /*origIntent*/, resolvedType, 6069 null /*launchIntent*/, null /*callingPackage*/, userId); 6070 final EphemeralResponse intentInfo = EphemeralResolver.doEphemeralResolutionPhaseOne( 6071 mContext, mEphemeralResolverConnection, requestObject); 6072 if (intentInfo != null) { 6073 if (DEBUG_EPHEMERAL) { 6074 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 6075 } 6076 final ResolveInfo ephemeralInstaller = new ResolveInfo(mEphemeralInstallerInfo); 6077 ephemeralInstaller.ephemeralResponse = intentInfo; 6078 // make sure this resolver is the default 6079 ephemeralInstaller.isDefault = true; 6080 ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 6081 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 6082 // add a non-generic filter 6083 ephemeralInstaller.filter = new IntentFilter(intent.getAction()); 6084 ephemeralInstaller.filter.addDataPath( 6085 intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL); 6086 result.add(ephemeralInstaller); 6087 } 6088 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6089 } 6090 if (sortResult) { 6091 Collections.sort(result, mResolvePrioritySorter); 6092 } 6093 return filterForEphemeral(result, ephemeralPkgName); 6094 } 6095 6096 private static class CrossProfileDomainInfo { 6097 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 6098 ResolveInfo resolveInfo; 6099 /* Best domain verification status of the activities found in the other profile */ 6100 int bestDomainVerificationStatus; 6101 } 6102 6103 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 6104 String resolvedType, int flags, int sourceUserId, int parentUserId) { 6105 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 6106 sourceUserId)) { 6107 return null; 6108 } 6109 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 6110 resolvedType, flags, parentUserId); 6111 6112 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 6113 return null; 6114 } 6115 CrossProfileDomainInfo result = null; 6116 int size = resultTargetUser.size(); 6117 for (int i = 0; i < size; i++) { 6118 ResolveInfo riTargetUser = resultTargetUser.get(i); 6119 // Intent filter verification is only for filters that specify a host. So don't return 6120 // those that handle all web uris. 6121 if (riTargetUser.handleAllWebDataURI) { 6122 continue; 6123 } 6124 String packageName = riTargetUser.activityInfo.packageName; 6125 PackageSetting ps = mSettings.mPackages.get(packageName); 6126 if (ps == null) { 6127 continue; 6128 } 6129 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 6130 int status = (int)(verificationState >> 32); 6131 if (result == null) { 6132 result = new CrossProfileDomainInfo(); 6133 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 6134 sourceUserId, parentUserId); 6135 result.bestDomainVerificationStatus = status; 6136 } else { 6137 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 6138 result.bestDomainVerificationStatus); 6139 } 6140 } 6141 // Don't consider matches with status NEVER across profiles. 6142 if (result != null && result.bestDomainVerificationStatus 6143 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6144 return null; 6145 } 6146 return result; 6147 } 6148 6149 /** 6150 * Verification statuses are ordered from the worse to the best, except for 6151 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 6152 */ 6153 private int bestDomainVerificationStatus(int status1, int status2) { 6154 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6155 return status2; 6156 } 6157 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6158 return status1; 6159 } 6160 return (int) MathUtils.max(status1, status2); 6161 } 6162 6163 private boolean isUserEnabled(int userId) { 6164 long callingId = Binder.clearCallingIdentity(); 6165 try { 6166 UserInfo userInfo = sUserManager.getUserInfo(userId); 6167 return userInfo != null && userInfo.isEnabled(); 6168 } finally { 6169 Binder.restoreCallingIdentity(callingId); 6170 } 6171 } 6172 6173 /** 6174 * Filter out activities with systemUserOnly flag set, when current user is not System. 6175 * 6176 * @return filtered list 6177 */ 6178 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 6179 if (userId == UserHandle.USER_SYSTEM) { 6180 return resolveInfos; 6181 } 6182 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 6183 ResolveInfo info = resolveInfos.get(i); 6184 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 6185 resolveInfos.remove(i); 6186 } 6187 } 6188 return resolveInfos; 6189 } 6190 6191 /** 6192 * Filters out ephemeral activities. 6193 * <p>When resolving for an ephemeral app, only activities that 1) are defined in the 6194 * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned. 6195 * 6196 * @param resolveInfos The pre-filtered list of resolved activities 6197 * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering 6198 * is performed. 6199 * @return A filtered list of resolved activities. 6200 */ 6201 private List<ResolveInfo> filterForEphemeral(List<ResolveInfo> resolveInfos, 6202 String ephemeralPkgName) { 6203 if (ephemeralPkgName == null) { 6204 return resolveInfos; 6205 } 6206 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 6207 ResolveInfo info = resolveInfos.get(i); 6208 final boolean isEphemeralApp = info.activityInfo.applicationInfo.isEphemeralApp(); 6209 // allow activities that are defined in the provided package 6210 if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) { 6211 continue; 6212 } 6213 // allow activities that have been explicitly exposed to ephemeral apps 6214 if (!isEphemeralApp 6215 && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) { 6216 continue; 6217 } 6218 resolveInfos.remove(i); 6219 } 6220 return resolveInfos; 6221 } 6222 6223 /** 6224 * @param resolveInfos list of resolve infos in descending priority order 6225 * @return if the list contains a resolve info with non-negative priority 6226 */ 6227 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 6228 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 6229 } 6230 6231 private static boolean hasWebURI(Intent intent) { 6232 if (intent.getData() == null) { 6233 return false; 6234 } 6235 final String scheme = intent.getScheme(); 6236 if (TextUtils.isEmpty(scheme)) { 6237 return false; 6238 } 6239 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 6240 } 6241 6242 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 6243 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 6244 int userId) { 6245 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 6246 6247 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 6248 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 6249 candidates.size()); 6250 } 6251 6252 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 6253 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 6254 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 6255 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 6256 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 6257 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 6258 6259 synchronized (mPackages) { 6260 final int count = candidates.size(); 6261 // First, try to use linked apps. Partition the candidates into four lists: 6262 // one for the final results, one for the "do not use ever", one for "undefined status" 6263 // and finally one for "browser app type". 6264 for (int n=0; n<count; n++) { 6265 ResolveInfo info = candidates.get(n); 6266 String packageName = info.activityInfo.packageName; 6267 PackageSetting ps = mSettings.mPackages.get(packageName); 6268 if (ps != null) { 6269 // Add to the special match all list (Browser use case) 6270 if (info.handleAllWebDataURI) { 6271 matchAllList.add(info); 6272 continue; 6273 } 6274 // Try to get the status from User settings first 6275 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 6276 int status = (int)(packedStatus >> 32); 6277 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 6278 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 6279 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6280 Slog.i(TAG, " + always: " + info.activityInfo.packageName 6281 + " : linkgen=" + linkGeneration); 6282 } 6283 // Use link-enabled generation as preferredOrder, i.e. 6284 // prefer newly-enabled over earlier-enabled. 6285 info.preferredOrder = linkGeneration; 6286 alwaysList.add(info); 6287 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6288 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6289 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 6290 } 6291 neverList.add(info); 6292 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 6293 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6294 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 6295 } 6296 alwaysAskList.add(info); 6297 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 6298 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 6299 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6300 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 6301 } 6302 undefinedList.add(info); 6303 } 6304 } 6305 } 6306 6307 // We'll want to include browser possibilities in a few cases 6308 boolean includeBrowser = false; 6309 6310 // First try to add the "always" resolution(s) for the current user, if any 6311 if (alwaysList.size() > 0) { 6312 result.addAll(alwaysList); 6313 } else { 6314 // Add all undefined apps as we want them to appear in the disambiguation dialog. 6315 result.addAll(undefinedList); 6316 // Maybe add one for the other profile. 6317 if (xpDomainInfo != null && ( 6318 xpDomainInfo.bestDomainVerificationStatus 6319 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 6320 result.add(xpDomainInfo.resolveInfo); 6321 } 6322 includeBrowser = true; 6323 } 6324 6325 // The presence of any 'always ask' alternatives means we'll also offer browsers. 6326 // If there were 'always' entries their preferred order has been set, so we also 6327 // back that off to make the alternatives equivalent 6328 if (alwaysAskList.size() > 0) { 6329 for (ResolveInfo i : result) { 6330 i.preferredOrder = 0; 6331 } 6332 result.addAll(alwaysAskList); 6333 includeBrowser = true; 6334 } 6335 6336 if (includeBrowser) { 6337 // Also add browsers (all of them or only the default one) 6338 if (DEBUG_DOMAIN_VERIFICATION) { 6339 Slog.v(TAG, " ...including browsers in candidate set"); 6340 } 6341 if ((matchFlags & MATCH_ALL) != 0) { 6342 result.addAll(matchAllList); 6343 } else { 6344 // Browser/generic handling case. If there's a default browser, go straight 6345 // to that (but only if there is no other higher-priority match). 6346 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 6347 int maxMatchPrio = 0; 6348 ResolveInfo defaultBrowserMatch = null; 6349 final int numCandidates = matchAllList.size(); 6350 for (int n = 0; n < numCandidates; n++) { 6351 ResolveInfo info = matchAllList.get(n); 6352 // track the highest overall match priority... 6353 if (info.priority > maxMatchPrio) { 6354 maxMatchPrio = info.priority; 6355 } 6356 // ...and the highest-priority default browser match 6357 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 6358 if (defaultBrowserMatch == null 6359 || (defaultBrowserMatch.priority < info.priority)) { 6360 if (debug) { 6361 Slog.v(TAG, "Considering default browser match " + info); 6362 } 6363 defaultBrowserMatch = info; 6364 } 6365 } 6366 } 6367 if (defaultBrowserMatch != null 6368 && defaultBrowserMatch.priority >= maxMatchPrio 6369 && !TextUtils.isEmpty(defaultBrowserPackageName)) 6370 { 6371 if (debug) { 6372 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 6373 } 6374 result.add(defaultBrowserMatch); 6375 } else { 6376 result.addAll(matchAllList); 6377 } 6378 } 6379 6380 // If there is nothing selected, add all candidates and remove the ones that the user 6381 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 6382 if (result.size() == 0) { 6383 result.addAll(candidates); 6384 result.removeAll(neverList); 6385 } 6386 } 6387 } 6388 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 6389 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 6390 result.size()); 6391 for (ResolveInfo info : result) { 6392 Slog.v(TAG, " + " + info.activityInfo); 6393 } 6394 } 6395 return result; 6396 } 6397 6398 // Returns a packed value as a long: 6399 // 6400 // high 'int'-sized word: link status: undefined/ask/never/always. 6401 // low 'int'-sized word: relative priority among 'always' results. 6402 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 6403 long result = ps.getDomainVerificationStatusForUser(userId); 6404 // if none available, get the master status 6405 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 6406 if (ps.getIntentFilterVerificationInfo() != null) { 6407 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 6408 } 6409 } 6410 return result; 6411 } 6412 6413 private ResolveInfo querySkipCurrentProfileIntents( 6414 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 6415 int flags, int sourceUserId) { 6416 if (matchingFilters != null) { 6417 int size = matchingFilters.size(); 6418 for (int i = 0; i < size; i ++) { 6419 CrossProfileIntentFilter filter = matchingFilters.get(i); 6420 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 6421 // Checking if there are activities in the target user that can handle the 6422 // intent. 6423 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 6424 resolvedType, flags, sourceUserId); 6425 if (resolveInfo != null) { 6426 return resolveInfo; 6427 } 6428 } 6429 } 6430 } 6431 return null; 6432 } 6433 6434 // Return matching ResolveInfo in target user if any. 6435 private ResolveInfo queryCrossProfileIntents( 6436 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 6437 int flags, int sourceUserId, boolean matchInCurrentProfile) { 6438 if (matchingFilters != null) { 6439 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 6440 // match the same intent. For performance reasons, it is better not to 6441 // run queryIntent twice for the same userId 6442 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 6443 int size = matchingFilters.size(); 6444 for (int i = 0; i < size; i++) { 6445 CrossProfileIntentFilter filter = matchingFilters.get(i); 6446 int targetUserId = filter.getTargetUserId(); 6447 boolean skipCurrentProfile = 6448 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 6449 boolean skipCurrentProfileIfNoMatchFound = 6450 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 6451 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 6452 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 6453 // Checking if there are activities in the target user that can handle the 6454 // intent. 6455 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 6456 resolvedType, flags, sourceUserId); 6457 if (resolveInfo != null) return resolveInfo; 6458 alreadyTriedUserIds.put(targetUserId, true); 6459 } 6460 } 6461 } 6462 return null; 6463 } 6464 6465 /** 6466 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 6467 * will forward the intent to the filter's target user. 6468 * Otherwise, returns null. 6469 */ 6470 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 6471 String resolvedType, int flags, int sourceUserId) { 6472 int targetUserId = filter.getTargetUserId(); 6473 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 6474 resolvedType, flags, targetUserId); 6475 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 6476 // If all the matches in the target profile are suspended, return null. 6477 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 6478 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 6479 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 6480 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 6481 targetUserId); 6482 } 6483 } 6484 } 6485 return null; 6486 } 6487 6488 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 6489 int sourceUserId, int targetUserId) { 6490 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 6491 long ident = Binder.clearCallingIdentity(); 6492 boolean targetIsProfile; 6493 try { 6494 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 6495 } finally { 6496 Binder.restoreCallingIdentity(ident); 6497 } 6498 String className; 6499 if (targetIsProfile) { 6500 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 6501 } else { 6502 className = FORWARD_INTENT_TO_PARENT; 6503 } 6504 ComponentName forwardingActivityComponentName = new ComponentName( 6505 mAndroidApplication.packageName, className); 6506 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 6507 sourceUserId); 6508 if (!targetIsProfile) { 6509 forwardingActivityInfo.showUserIcon = targetUserId; 6510 forwardingResolveInfo.noResourceId = true; 6511 } 6512 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 6513 forwardingResolveInfo.priority = 0; 6514 forwardingResolveInfo.preferredOrder = 0; 6515 forwardingResolveInfo.match = 0; 6516 forwardingResolveInfo.isDefault = true; 6517 forwardingResolveInfo.filter = filter; 6518 forwardingResolveInfo.targetUserId = targetUserId; 6519 return forwardingResolveInfo; 6520 } 6521 6522 @Override 6523 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 6524 Intent[] specifics, String[] specificTypes, Intent intent, 6525 String resolvedType, int flags, int userId) { 6526 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 6527 specificTypes, intent, resolvedType, flags, userId)); 6528 } 6529 6530 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 6531 Intent[] specifics, String[] specificTypes, Intent intent, 6532 String resolvedType, int flags, int userId) { 6533 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6534 flags = updateFlagsForResolve(flags, userId, intent); 6535 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6536 false /* requireFullPermission */, false /* checkShell */, 6537 "query intent activity options"); 6538 final String resultsAction = intent.getAction(); 6539 6540 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 6541 | PackageManager.GET_RESOLVED_FILTER, userId); 6542 6543 if (DEBUG_INTENT_MATCHING) { 6544 Log.v(TAG, "Query " + intent + ": " + results); 6545 } 6546 6547 int specificsPos = 0; 6548 int N; 6549 6550 // todo: note that the algorithm used here is O(N^2). This 6551 // isn't a problem in our current environment, but if we start running 6552 // into situations where we have more than 5 or 10 matches then this 6553 // should probably be changed to something smarter... 6554 6555 // First we go through and resolve each of the specific items 6556 // that were supplied, taking care of removing any corresponding 6557 // duplicate items in the generic resolve list. 6558 if (specifics != null) { 6559 for (int i=0; i<specifics.length; i++) { 6560 final Intent sintent = specifics[i]; 6561 if (sintent == null) { 6562 continue; 6563 } 6564 6565 if (DEBUG_INTENT_MATCHING) { 6566 Log.v(TAG, "Specific #" + i + ": " + sintent); 6567 } 6568 6569 String action = sintent.getAction(); 6570 if (resultsAction != null && resultsAction.equals(action)) { 6571 // If this action was explicitly requested, then don't 6572 // remove things that have it. 6573 action = null; 6574 } 6575 6576 ResolveInfo ri = null; 6577 ActivityInfo ai = null; 6578 6579 ComponentName comp = sintent.getComponent(); 6580 if (comp == null) { 6581 ri = resolveIntent( 6582 sintent, 6583 specificTypes != null ? specificTypes[i] : null, 6584 flags, userId); 6585 if (ri == null) { 6586 continue; 6587 } 6588 if (ri == mResolveInfo) { 6589 // ACK! Must do something better with this. 6590 } 6591 ai = ri.activityInfo; 6592 comp = new ComponentName(ai.applicationInfo.packageName, 6593 ai.name); 6594 } else { 6595 ai = getActivityInfo(comp, flags, userId); 6596 if (ai == null) { 6597 continue; 6598 } 6599 } 6600 6601 // Look for any generic query activities that are duplicates 6602 // of this specific one, and remove them from the results. 6603 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 6604 N = results.size(); 6605 int j; 6606 for (j=specificsPos; j<N; j++) { 6607 ResolveInfo sri = results.get(j); 6608 if ((sri.activityInfo.name.equals(comp.getClassName()) 6609 && sri.activityInfo.applicationInfo.packageName.equals( 6610 comp.getPackageName())) 6611 || (action != null && sri.filter.matchAction(action))) { 6612 results.remove(j); 6613 if (DEBUG_INTENT_MATCHING) Log.v( 6614 TAG, "Removing duplicate item from " + j 6615 + " due to specific " + specificsPos); 6616 if (ri == null) { 6617 ri = sri; 6618 } 6619 j--; 6620 N--; 6621 } 6622 } 6623 6624 // Add this specific item to its proper place. 6625 if (ri == null) { 6626 ri = new ResolveInfo(); 6627 ri.activityInfo = ai; 6628 } 6629 results.add(specificsPos, ri); 6630 ri.specificIndex = i; 6631 specificsPos++; 6632 } 6633 } 6634 6635 // Now we go through the remaining generic results and remove any 6636 // duplicate actions that are found here. 6637 N = results.size(); 6638 for (int i=specificsPos; i<N-1; i++) { 6639 final ResolveInfo rii = results.get(i); 6640 if (rii.filter == null) { 6641 continue; 6642 } 6643 6644 // Iterate over all of the actions of this result's intent 6645 // filter... typically this should be just one. 6646 final Iterator<String> it = rii.filter.actionsIterator(); 6647 if (it == null) { 6648 continue; 6649 } 6650 while (it.hasNext()) { 6651 final String action = it.next(); 6652 if (resultsAction != null && resultsAction.equals(action)) { 6653 // If this action was explicitly requested, then don't 6654 // remove things that have it. 6655 continue; 6656 } 6657 for (int j=i+1; j<N; j++) { 6658 final ResolveInfo rij = results.get(j); 6659 if (rij.filter != null && rij.filter.hasAction(action)) { 6660 results.remove(j); 6661 if (DEBUG_INTENT_MATCHING) Log.v( 6662 TAG, "Removing duplicate item from " + j 6663 + " due to action " + action + " at " + i); 6664 j--; 6665 N--; 6666 } 6667 } 6668 } 6669 6670 // If the caller didn't request filter information, drop it now 6671 // so we don't have to marshall/unmarshall it. 6672 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6673 rii.filter = null; 6674 } 6675 } 6676 6677 // Filter out the caller activity if so requested. 6678 if (caller != null) { 6679 N = results.size(); 6680 for (int i=0; i<N; i++) { 6681 ActivityInfo ainfo = results.get(i).activityInfo; 6682 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 6683 && caller.getClassName().equals(ainfo.name)) { 6684 results.remove(i); 6685 break; 6686 } 6687 } 6688 } 6689 6690 // If the caller didn't request filter information, 6691 // drop them now so we don't have to 6692 // marshall/unmarshall it. 6693 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6694 N = results.size(); 6695 for (int i=0; i<N; i++) { 6696 results.get(i).filter = null; 6697 } 6698 } 6699 6700 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 6701 return results; 6702 } 6703 6704 @Override 6705 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 6706 String resolvedType, int flags, int userId) { 6707 return new ParceledListSlice<>( 6708 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 6709 } 6710 6711 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 6712 String resolvedType, int flags, int userId) { 6713 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6714 flags = updateFlagsForResolve(flags, userId, intent); 6715 ComponentName comp = intent.getComponent(); 6716 if (comp == null) { 6717 if (intent.getSelector() != null) { 6718 intent = intent.getSelector(); 6719 comp = intent.getComponent(); 6720 } 6721 } 6722 if (comp != null) { 6723 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6724 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 6725 if (ai != null) { 6726 ResolveInfo ri = new ResolveInfo(); 6727 ri.activityInfo = ai; 6728 list.add(ri); 6729 } 6730 return list; 6731 } 6732 6733 // reader 6734 synchronized (mPackages) { 6735 String pkgName = intent.getPackage(); 6736 if (pkgName == null) { 6737 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 6738 } 6739 final PackageParser.Package pkg = mPackages.get(pkgName); 6740 if (pkg != null) { 6741 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 6742 userId); 6743 } 6744 return Collections.emptyList(); 6745 } 6746 } 6747 6748 @Override 6749 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 6750 if (!sUserManager.exists(userId)) return null; 6751 flags = updateFlagsForResolve(flags, userId, intent); 6752 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 6753 if (query != null) { 6754 if (query.size() >= 1) { 6755 // If there is more than one service with the same priority, 6756 // just arbitrarily pick the first one. 6757 return query.get(0); 6758 } 6759 } 6760 return null; 6761 } 6762 6763 @Override 6764 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 6765 String resolvedType, int flags, int userId) { 6766 return new ParceledListSlice<>( 6767 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 6768 } 6769 6770 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 6771 String resolvedType, int flags, int userId) { 6772 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6773 flags = updateFlagsForResolve(flags, userId, intent); 6774 ComponentName comp = intent.getComponent(); 6775 if (comp == null) { 6776 if (intent.getSelector() != null) { 6777 intent = intent.getSelector(); 6778 comp = intent.getComponent(); 6779 } 6780 } 6781 if (comp != null) { 6782 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6783 final ServiceInfo si = getServiceInfo(comp, flags, userId); 6784 if (si != null) { 6785 final ResolveInfo ri = new ResolveInfo(); 6786 ri.serviceInfo = si; 6787 list.add(ri); 6788 } 6789 return list; 6790 } 6791 6792 // reader 6793 synchronized (mPackages) { 6794 String pkgName = intent.getPackage(); 6795 if (pkgName == null) { 6796 return mServices.queryIntent(intent, resolvedType, flags, userId); 6797 } 6798 final PackageParser.Package pkg = mPackages.get(pkgName); 6799 if (pkg != null) { 6800 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 6801 userId); 6802 } 6803 return Collections.emptyList(); 6804 } 6805 } 6806 6807 @Override 6808 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 6809 String resolvedType, int flags, int userId) { 6810 return new ParceledListSlice<>( 6811 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 6812 } 6813 6814 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 6815 Intent intent, String resolvedType, int flags, int userId) { 6816 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6817 flags = updateFlagsForResolve(flags, userId, intent); 6818 ComponentName comp = intent.getComponent(); 6819 if (comp == null) { 6820 if (intent.getSelector() != null) { 6821 intent = intent.getSelector(); 6822 comp = intent.getComponent(); 6823 } 6824 } 6825 if (comp != null) { 6826 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6827 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 6828 if (pi != null) { 6829 final ResolveInfo ri = new ResolveInfo(); 6830 ri.providerInfo = pi; 6831 list.add(ri); 6832 } 6833 return list; 6834 } 6835 6836 // reader 6837 synchronized (mPackages) { 6838 String pkgName = intent.getPackage(); 6839 if (pkgName == null) { 6840 return mProviders.queryIntent(intent, resolvedType, flags, userId); 6841 } 6842 final PackageParser.Package pkg = mPackages.get(pkgName); 6843 if (pkg != null) { 6844 return mProviders.queryIntentForPackage( 6845 intent, resolvedType, flags, pkg.providers, userId); 6846 } 6847 return Collections.emptyList(); 6848 } 6849 } 6850 6851 @Override 6852 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 6853 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6854 flags = updateFlagsForPackage(flags, userId, null); 6855 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 6856 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6857 true /* requireFullPermission */, false /* checkShell */, 6858 "get installed packages"); 6859 6860 // writer 6861 synchronized (mPackages) { 6862 ArrayList<PackageInfo> list; 6863 if (listUninstalled) { 6864 list = new ArrayList<>(mSettings.mPackages.size()); 6865 for (PackageSetting ps : mSettings.mPackages.values()) { 6866 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 6867 continue; 6868 } 6869 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 6870 if (pi != null) { 6871 list.add(pi); 6872 } 6873 } 6874 } else { 6875 list = new ArrayList<>(mPackages.size()); 6876 for (PackageParser.Package p : mPackages.values()) { 6877 if (filterSharedLibPackageLPr((PackageSetting) p.mExtras, 6878 Binder.getCallingUid(), userId)) { 6879 continue; 6880 } 6881 final PackageInfo pi = generatePackageInfo((PackageSetting) 6882 p.mExtras, flags, userId); 6883 if (pi != null) { 6884 list.add(pi); 6885 } 6886 } 6887 } 6888 6889 return new ParceledListSlice<>(list); 6890 } 6891 } 6892 6893 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 6894 String[] permissions, boolean[] tmp, int flags, int userId) { 6895 int numMatch = 0; 6896 final PermissionsState permissionsState = ps.getPermissionsState(); 6897 for (int i=0; i<permissions.length; i++) { 6898 final String permission = permissions[i]; 6899 if (permissionsState.hasPermission(permission, userId)) { 6900 tmp[i] = true; 6901 numMatch++; 6902 } else { 6903 tmp[i] = false; 6904 } 6905 } 6906 if (numMatch == 0) { 6907 return; 6908 } 6909 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 6910 6911 // The above might return null in cases of uninstalled apps or install-state 6912 // skew across users/profiles. 6913 if (pi != null) { 6914 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 6915 if (numMatch == permissions.length) { 6916 pi.requestedPermissions = permissions; 6917 } else { 6918 pi.requestedPermissions = new String[numMatch]; 6919 numMatch = 0; 6920 for (int i=0; i<permissions.length; i++) { 6921 if (tmp[i]) { 6922 pi.requestedPermissions[numMatch] = permissions[i]; 6923 numMatch++; 6924 } 6925 } 6926 } 6927 } 6928 list.add(pi); 6929 } 6930 } 6931 6932 @Override 6933 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 6934 String[] permissions, int flags, int userId) { 6935 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6936 flags = updateFlagsForPackage(flags, userId, permissions); 6937 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6938 true /* requireFullPermission */, false /* checkShell */, 6939 "get packages holding permissions"); 6940 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 6941 6942 // writer 6943 synchronized (mPackages) { 6944 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 6945 boolean[] tmpBools = new boolean[permissions.length]; 6946 if (listUninstalled) { 6947 for (PackageSetting ps : mSettings.mPackages.values()) { 6948 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6949 userId); 6950 } 6951 } else { 6952 for (PackageParser.Package pkg : mPackages.values()) { 6953 PackageSetting ps = (PackageSetting)pkg.mExtras; 6954 if (ps != null) { 6955 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6956 userId); 6957 } 6958 } 6959 } 6960 6961 return new ParceledListSlice<PackageInfo>(list); 6962 } 6963 } 6964 6965 @Override 6966 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 6967 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6968 flags = updateFlagsForApplication(flags, userId, null); 6969 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 6970 6971 // writer 6972 synchronized (mPackages) { 6973 ArrayList<ApplicationInfo> list; 6974 if (listUninstalled) { 6975 list = new ArrayList<>(mSettings.mPackages.size()); 6976 for (PackageSetting ps : mSettings.mPackages.values()) { 6977 ApplicationInfo ai; 6978 int effectiveFlags = flags; 6979 if (ps.isSystem()) { 6980 effectiveFlags |= PackageManager.MATCH_ANY_USER; 6981 } 6982 if (ps.pkg != null) { 6983 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 6984 continue; 6985 } 6986 ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags, 6987 ps.readUserState(userId), userId); 6988 if (ai != null) { 6989 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 6990 } 6991 } else { 6992 // Shared lib filtering done in generateApplicationInfoFromSettingsLPw 6993 // and already converts to externally visible package name 6994 ai = generateApplicationInfoFromSettingsLPw(ps.name, 6995 Binder.getCallingUid(), effectiveFlags, userId); 6996 } 6997 if (ai != null) { 6998 list.add(ai); 6999 } 7000 } 7001 } else { 7002 list = new ArrayList<>(mPackages.size()); 7003 for (PackageParser.Package p : mPackages.values()) { 7004 if (p.mExtras != null) { 7005 PackageSetting ps = (PackageSetting) p.mExtras; 7006 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 7007 continue; 7008 } 7009 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 7010 ps.readUserState(userId), userId); 7011 if (ai != null) { 7012 ai.packageName = resolveExternalPackageNameLPr(p); 7013 list.add(ai); 7014 } 7015 } 7016 } 7017 } 7018 7019 return new ParceledListSlice<>(list); 7020 } 7021 } 7022 7023 @Override 7024 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 7025 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7026 return null; 7027 } 7028 7029 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 7030 "getEphemeralApplications"); 7031 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7032 true /* requireFullPermission */, false /* checkShell */, 7033 "getEphemeralApplications"); 7034 synchronized (mPackages) { 7035 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 7036 .getEphemeralApplicationsLPw(userId); 7037 if (ephemeralApps != null) { 7038 return new ParceledListSlice<>(ephemeralApps); 7039 } 7040 } 7041 return null; 7042 } 7043 7044 @Override 7045 public boolean isEphemeralApplication(String packageName, int userId) { 7046 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7047 true /* requireFullPermission */, false /* checkShell */, 7048 "isEphemeral"); 7049 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7050 return false; 7051 } 7052 7053 if (!isCallerSameApp(packageName)) { 7054 return false; 7055 } 7056 synchronized (mPackages) { 7057 PackageParser.Package pkg = mPackages.get(packageName); 7058 if (pkg != null) { 7059 return pkg.applicationInfo.isEphemeralApp(); 7060 } 7061 } 7062 return false; 7063 } 7064 7065 @Override 7066 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 7067 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7068 return null; 7069 } 7070 7071 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7072 true /* requireFullPermission */, false /* checkShell */, 7073 "getCookie"); 7074 if (!isCallerSameApp(packageName)) { 7075 return null; 7076 } 7077 synchronized (mPackages) { 7078 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 7079 packageName, userId); 7080 } 7081 } 7082 7083 @Override 7084 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 7085 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7086 return true; 7087 } 7088 7089 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7090 true /* requireFullPermission */, true /* checkShell */, 7091 "setCookie"); 7092 if (!isCallerSameApp(packageName)) { 7093 return false; 7094 } 7095 synchronized (mPackages) { 7096 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 7097 packageName, cookie, userId); 7098 } 7099 } 7100 7101 @Override 7102 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 7103 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7104 return null; 7105 } 7106 7107 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 7108 "getEphemeralApplicationIcon"); 7109 7110 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7111 true /* requireFullPermission */, false /* checkShell */, 7112 "getEphemeralApplicationIcon"); 7113 synchronized (mPackages) { 7114 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 7115 packageName, userId); 7116 } 7117 } 7118 7119 private boolean isCallerSameApp(String packageName) { 7120 PackageParser.Package pkg = mPackages.get(packageName); 7121 return pkg != null 7122 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 7123 } 7124 7125 @Override 7126 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 7127 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 7128 } 7129 7130 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 7131 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 7132 7133 // reader 7134 synchronized (mPackages) { 7135 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 7136 final int userId = UserHandle.getCallingUserId(); 7137 while (i.hasNext()) { 7138 final PackageParser.Package p = i.next(); 7139 if (p.applicationInfo == null) continue; 7140 7141 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 7142 && !p.applicationInfo.isDirectBootAware(); 7143 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 7144 && p.applicationInfo.isDirectBootAware(); 7145 7146 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 7147 && (!mSafeMode || isSystemApp(p)) 7148 && (matchesUnaware || matchesAware)) { 7149 PackageSetting ps = mSettings.mPackages.get(p.packageName); 7150 if (ps != null) { 7151 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 7152 ps.readUserState(userId), userId); 7153 if (ai != null) { 7154 finalList.add(ai); 7155 } 7156 } 7157 } 7158 } 7159 } 7160 7161 return finalList; 7162 } 7163 7164 @Override 7165 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 7166 if (!sUserManager.exists(userId)) return null; 7167 flags = updateFlagsForComponent(flags, userId, name); 7168 // reader 7169 synchronized (mPackages) { 7170 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 7171 PackageSetting ps = provider != null 7172 ? mSettings.mPackages.get(provider.owner.packageName) 7173 : null; 7174 return ps != null 7175 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 7176 ? PackageParser.generateProviderInfo(provider, flags, 7177 ps.readUserState(userId), userId) 7178 : null; 7179 } 7180 } 7181 7182 /** 7183 * @deprecated 7184 */ 7185 @Deprecated 7186 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 7187 // reader 7188 synchronized (mPackages) { 7189 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 7190 .entrySet().iterator(); 7191 final int userId = UserHandle.getCallingUserId(); 7192 while (i.hasNext()) { 7193 Map.Entry<String, PackageParser.Provider> entry = i.next(); 7194 PackageParser.Provider p = entry.getValue(); 7195 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 7196 7197 if (ps != null && p.syncable 7198 && (!mSafeMode || (p.info.applicationInfo.flags 7199 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 7200 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 7201 ps.readUserState(userId), userId); 7202 if (info != null) { 7203 outNames.add(entry.getKey()); 7204 outInfo.add(info); 7205 } 7206 } 7207 } 7208 } 7209 } 7210 7211 @Override 7212 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 7213 int uid, int flags) { 7214 final int userId = processName != null ? UserHandle.getUserId(uid) 7215 : UserHandle.getCallingUserId(); 7216 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7217 flags = updateFlagsForComponent(flags, userId, processName); 7218 7219 ArrayList<ProviderInfo> finalList = null; 7220 // reader 7221 synchronized (mPackages) { 7222 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 7223 while (i.hasNext()) { 7224 final PackageParser.Provider p = i.next(); 7225 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 7226 if (ps != null && p.info.authority != null 7227 && (processName == null 7228 || (p.info.processName.equals(processName) 7229 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 7230 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 7231 if (finalList == null) { 7232 finalList = new ArrayList<ProviderInfo>(3); 7233 } 7234 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 7235 ps.readUserState(userId), userId); 7236 if (info != null) { 7237 finalList.add(info); 7238 } 7239 } 7240 } 7241 } 7242 7243 if (finalList != null) { 7244 Collections.sort(finalList, mProviderInitOrderSorter); 7245 return new ParceledListSlice<ProviderInfo>(finalList); 7246 } 7247 7248 return ParceledListSlice.emptyList(); 7249 } 7250 7251 @Override 7252 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 7253 // reader 7254 synchronized (mPackages) { 7255 final PackageParser.Instrumentation i = mInstrumentation.get(name); 7256 return PackageParser.generateInstrumentationInfo(i, flags); 7257 } 7258 } 7259 7260 @Override 7261 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 7262 String targetPackage, int flags) { 7263 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 7264 } 7265 7266 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 7267 int flags) { 7268 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 7269 7270 // reader 7271 synchronized (mPackages) { 7272 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 7273 while (i.hasNext()) { 7274 final PackageParser.Instrumentation p = i.next(); 7275 if (targetPackage == null 7276 || targetPackage.equals(p.info.targetPackage)) { 7277 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 7278 flags); 7279 if (ii != null) { 7280 finalList.add(ii); 7281 } 7282 } 7283 } 7284 } 7285 7286 return finalList; 7287 } 7288 7289 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 7290 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 7291 if (overlays == null) { 7292 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 7293 return; 7294 } 7295 for (PackageParser.Package opkg : overlays.values()) { 7296 // Not much to do if idmap fails: we already logged the error 7297 // and we certainly don't want to abort installation of pkg simply 7298 // because an overlay didn't fit properly. For these reasons, 7299 // ignore the return value of createIdmapForPackagePairLI. 7300 createIdmapForPackagePairLI(pkg, opkg); 7301 } 7302 } 7303 7304 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 7305 PackageParser.Package opkg) { 7306 if (!opkg.mTrustedOverlay) { 7307 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 7308 opkg.baseCodePath + ": overlay not trusted"); 7309 return false; 7310 } 7311 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 7312 if (overlaySet == null) { 7313 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 7314 opkg.baseCodePath + " but target package has no known overlays"); 7315 return false; 7316 } 7317 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 7318 // TODO: generate idmap for split APKs 7319 try { 7320 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 7321 } catch (InstallerException e) { 7322 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 7323 + opkg.baseCodePath); 7324 return false; 7325 } 7326 PackageParser.Package[] overlayArray = 7327 overlaySet.values().toArray(new PackageParser.Package[0]); 7328 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 7329 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 7330 return p1.mOverlayPriority - p2.mOverlayPriority; 7331 } 7332 }; 7333 Arrays.sort(overlayArray, cmp); 7334 7335 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 7336 int i = 0; 7337 for (PackageParser.Package p : overlayArray) { 7338 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 7339 } 7340 return true; 7341 } 7342 7343 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 7344 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]"); 7345 try { 7346 scanDirLI(dir, parseFlags, scanFlags, currentTime); 7347 } finally { 7348 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7349 } 7350 } 7351 7352 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 7353 final File[] files = dir.listFiles(); 7354 if (ArrayUtils.isEmpty(files)) { 7355 Log.d(TAG, "No files in app dir " + dir); 7356 return; 7357 } 7358 7359 if (DEBUG_PACKAGE_SCANNING) { 7360 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 7361 + " flags=0x" + Integer.toHexString(parseFlags)); 7362 } 7363 ParallelPackageParser parallelPackageParser = new ParallelPackageParser( 7364 mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir); 7365 7366 // Submit files for parsing in parallel 7367 int fileCount = 0; 7368 for (File file : files) { 7369 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 7370 && !PackageInstallerService.isStageName(file.getName()); 7371 if (!isPackage) { 7372 // Ignore entries which are not packages 7373 continue; 7374 } 7375 parallelPackageParser.submit(file, parseFlags); 7376 fileCount++; 7377 } 7378 7379 // Process results one by one 7380 for (; fileCount > 0; fileCount--) { 7381 ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take(); 7382 Throwable throwable = parseResult.throwable; 7383 int errorCode = PackageManager.INSTALL_SUCCEEDED; 7384 7385 if (throwable == null) { 7386 // Static shared libraries have synthetic package names 7387 if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) { 7388 renameStaticSharedLibraryPackage(parseResult.pkg); 7389 } 7390 try { 7391 if (errorCode == PackageManager.INSTALL_SUCCEEDED) { 7392 scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags, 7393 currentTime, null); 7394 } 7395 } catch (PackageManagerException e) { 7396 errorCode = e.error; 7397 Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage()); 7398 } 7399 } else if (throwable instanceof PackageParser.PackageParserException) { 7400 PackageParser.PackageParserException e = (PackageParser.PackageParserException) 7401 throwable; 7402 errorCode = e.error; 7403 Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage()); 7404 } else { 7405 throw new IllegalStateException("Unexpected exception occurred while parsing " 7406 + parseResult.scanFile, throwable); 7407 } 7408 7409 // Delete invalid userdata apps 7410 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 7411 errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) { 7412 logCriticalInfo(Log.WARN, 7413 "Deleting invalid package at " + parseResult.scanFile); 7414 removeCodePathLI(parseResult.scanFile); 7415 } 7416 } 7417 parallelPackageParser.close(); 7418 } 7419 7420 private static File getSettingsProblemFile() { 7421 File dataDir = Environment.getDataDirectory(); 7422 File systemDir = new File(dataDir, "system"); 7423 File fname = new File(systemDir, "uiderrors.txt"); 7424 return fname; 7425 } 7426 7427 static void reportSettingsProblem(int priority, String msg) { 7428 logCriticalInfo(priority, msg); 7429 } 7430 7431 static void logCriticalInfo(int priority, String msg) { 7432 Slog.println(priority, TAG, msg); 7433 EventLogTags.writePmCriticalInfo(msg); 7434 try { 7435 File fname = getSettingsProblemFile(); 7436 FileOutputStream out = new FileOutputStream(fname, true); 7437 PrintWriter pw = new FastPrintWriter(out); 7438 SimpleDateFormat formatter = new SimpleDateFormat(); 7439 String dateString = formatter.format(new Date(System.currentTimeMillis())); 7440 pw.println(dateString + ": " + msg); 7441 pw.close(); 7442 FileUtils.setPermissions( 7443 fname.toString(), 7444 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 7445 -1, -1); 7446 } catch (java.io.IOException e) { 7447 } 7448 } 7449 7450 private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) { 7451 if (srcFile.isDirectory()) { 7452 final File baseFile = new File(pkg.baseCodePath); 7453 long maxModifiedTime = baseFile.lastModified(); 7454 if (pkg.splitCodePaths != null) { 7455 for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) { 7456 final File splitFile = new File(pkg.splitCodePaths[i]); 7457 maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified()); 7458 } 7459 } 7460 return maxModifiedTime; 7461 } 7462 return srcFile.lastModified(); 7463 } 7464 7465 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 7466 final int policyFlags) throws PackageManagerException { 7467 // When upgrading from pre-N MR1, verify the package time stamp using the package 7468 // directory and not the APK file. 7469 final long lastModifiedTime = mIsPreNMR1Upgrade 7470 ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile); 7471 if (ps != null 7472 && ps.codePath.equals(srcFile) 7473 && ps.timeStamp == lastModifiedTime 7474 && !isCompatSignatureUpdateNeeded(pkg) 7475 && !isRecoverSignatureUpdateNeeded(pkg)) { 7476 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 7477 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7478 ArraySet<PublicKey> signingKs; 7479 synchronized (mPackages) { 7480 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 7481 } 7482 if (ps.signatures.mSignatures != null 7483 && ps.signatures.mSignatures.length != 0 7484 && signingKs != null) { 7485 // Optimization: reuse the existing cached certificates 7486 // if the package appears to be unchanged. 7487 pkg.mSignatures = ps.signatures.mSignatures; 7488 pkg.mSigningKeys = signingKs; 7489 return; 7490 } 7491 7492 Slog.w(TAG, "PackageSetting for " + ps.name 7493 + " is missing signatures. Collecting certs again to recover them."); 7494 } else { 7495 Slog.i(TAG, srcFile.toString() + " changed; collecting certs"); 7496 } 7497 7498 try { 7499 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 7500 PackageParser.collectCertificates(pkg, policyFlags); 7501 } catch (PackageParserException e) { 7502 throw PackageManagerException.from(e); 7503 } finally { 7504 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7505 } 7506 } 7507 7508 /** 7509 * Traces a package scan. 7510 * @see #scanPackageLI(File, int, int, long, UserHandle) 7511 */ 7512 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 7513 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7514 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]"); 7515 try { 7516 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 7517 } finally { 7518 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7519 } 7520 } 7521 7522 /** 7523 * Scans a package and returns the newly parsed package. 7524 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 7525 */ 7526 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 7527 long currentTime, UserHandle user) throws PackageManagerException { 7528 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 7529 PackageParser pp = new PackageParser(); 7530 pp.setSeparateProcesses(mSeparateProcesses); 7531 pp.setOnlyCoreApps(mOnlyCore); 7532 pp.setDisplayMetrics(mMetrics); 7533 7534 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 7535 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 7536 } 7537 7538 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 7539 final PackageParser.Package pkg; 7540 try { 7541 pkg = pp.parsePackage(scanFile, parseFlags); 7542 } catch (PackageParserException e) { 7543 throw PackageManagerException.from(e); 7544 } finally { 7545 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7546 } 7547 7548 // Static shared libraries have synthetic package names 7549 if (pkg.applicationInfo.isStaticSharedLibrary()) { 7550 renameStaticSharedLibraryPackage(pkg); 7551 } 7552 7553 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 7554 } 7555 7556 /** 7557 * Scans a package and returns the newly parsed package. 7558 * @throws PackageManagerException on a parse error. 7559 */ 7560 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 7561 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 7562 throws PackageManagerException { 7563 // If the package has children and this is the first dive in the function 7564 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 7565 // packages (parent and children) would be successfully scanned before the 7566 // actual scan since scanning mutates internal state and we want to atomically 7567 // install the package and its children. 7568 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7569 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7570 scanFlags |= SCAN_CHECK_ONLY; 7571 } 7572 } else { 7573 scanFlags &= ~SCAN_CHECK_ONLY; 7574 } 7575 7576 // Scan the parent 7577 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 7578 scanFlags, currentTime, user); 7579 7580 // Scan the children 7581 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7582 for (int i = 0; i < childCount; i++) { 7583 PackageParser.Package childPackage = pkg.childPackages.get(i); 7584 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 7585 currentTime, user); 7586 } 7587 7588 7589 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7590 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 7591 } 7592 7593 return scannedPkg; 7594 } 7595 7596 /** 7597 * Scans a package and returns the newly parsed package. 7598 * @throws PackageManagerException on a parse error. 7599 */ 7600 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 7601 int policyFlags, int scanFlags, long currentTime, UserHandle user) 7602 throws PackageManagerException { 7603 PackageSetting ps = null; 7604 PackageSetting updatedPkg; 7605 // reader 7606 synchronized (mPackages) { 7607 // Look to see if we already know about this package. 7608 String oldName = mSettings.getRenamedPackageLPr(pkg.packageName); 7609 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 7610 // This package has been renamed to its original name. Let's 7611 // use that. 7612 ps = mSettings.getPackageLPr(oldName); 7613 } 7614 // If there was no original package, see one for the real package name. 7615 if (ps == null) { 7616 ps = mSettings.getPackageLPr(pkg.packageName); 7617 } 7618 // Check to see if this package could be hiding/updating a system 7619 // package. Must look for it either under the original or real 7620 // package name depending on our state. 7621 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 7622 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 7623 7624 // If this is a package we don't know about on the system partition, we 7625 // may need to remove disabled child packages on the system partition 7626 // or may need to not add child packages if the parent apk is updated 7627 // on the data partition and no longer defines this child package. 7628 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 7629 // If this is a parent package for an updated system app and this system 7630 // app got an OTA update which no longer defines some of the child packages 7631 // we have to prune them from the disabled system packages. 7632 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 7633 if (disabledPs != null) { 7634 final int scannedChildCount = (pkg.childPackages != null) 7635 ? pkg.childPackages.size() : 0; 7636 final int disabledChildCount = disabledPs.childPackageNames != null 7637 ? disabledPs.childPackageNames.size() : 0; 7638 for (int i = 0; i < disabledChildCount; i++) { 7639 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 7640 boolean disabledPackageAvailable = false; 7641 for (int j = 0; j < scannedChildCount; j++) { 7642 PackageParser.Package childPkg = pkg.childPackages.get(j); 7643 if (childPkg.packageName.equals(disabledChildPackageName)) { 7644 disabledPackageAvailable = true; 7645 break; 7646 } 7647 } 7648 if (!disabledPackageAvailable) { 7649 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 7650 } 7651 } 7652 } 7653 } 7654 } 7655 7656 boolean updatedPkgBetter = false; 7657 // First check if this is a system package that may involve an update 7658 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 7659 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 7660 // it needs to drop FLAG_PRIVILEGED. 7661 if (locationIsPrivileged(scanFile)) { 7662 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7663 } else { 7664 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7665 } 7666 7667 if (ps != null && !ps.codePath.equals(scanFile)) { 7668 // The path has changed from what was last scanned... check the 7669 // version of the new path against what we have stored to determine 7670 // what to do. 7671 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 7672 if (pkg.mVersionCode <= ps.versionCode) { 7673 // The system package has been updated and the code path does not match 7674 // Ignore entry. Skip it. 7675 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 7676 + " ignored: updated version " + ps.versionCode 7677 + " better than this " + pkg.mVersionCode); 7678 if (!updatedPkg.codePath.equals(scanFile)) { 7679 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 7680 + ps.name + " changing from " + updatedPkg.codePathString 7681 + " to " + scanFile); 7682 updatedPkg.codePath = scanFile; 7683 updatedPkg.codePathString = scanFile.toString(); 7684 updatedPkg.resourcePath = scanFile; 7685 updatedPkg.resourcePathString = scanFile.toString(); 7686 } 7687 updatedPkg.pkg = pkg; 7688 updatedPkg.versionCode = pkg.mVersionCode; 7689 7690 // Update the disabled system child packages to point to the package too. 7691 final int childCount = updatedPkg.childPackageNames != null 7692 ? updatedPkg.childPackageNames.size() : 0; 7693 for (int i = 0; i < childCount; i++) { 7694 String childPackageName = updatedPkg.childPackageNames.get(i); 7695 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 7696 childPackageName); 7697 if (updatedChildPkg != null) { 7698 updatedChildPkg.pkg = pkg; 7699 updatedChildPkg.versionCode = pkg.mVersionCode; 7700 } 7701 } 7702 7703 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 7704 + scanFile + " ignored: updated version " + ps.versionCode 7705 + " better than this " + pkg.mVersionCode); 7706 } else { 7707 // The current app on the system partition is better than 7708 // what we have updated to on the data partition; switch 7709 // back to the system partition version. 7710 // At this point, its safely assumed that package installation for 7711 // apps in system partition will go through. If not there won't be a working 7712 // version of the app 7713 // writer 7714 synchronized (mPackages) { 7715 // Just remove the loaded entries from package lists. 7716 mPackages.remove(ps.name); 7717 } 7718 7719 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7720 + " reverting from " + ps.codePathString 7721 + ": new version " + pkg.mVersionCode 7722 + " better than installed " + ps.versionCode); 7723 7724 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7725 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7726 synchronized (mInstallLock) { 7727 args.cleanUpResourcesLI(); 7728 } 7729 synchronized (mPackages) { 7730 mSettings.enableSystemPackageLPw(ps.name); 7731 } 7732 updatedPkgBetter = true; 7733 } 7734 } 7735 } 7736 7737 if (updatedPkg != null) { 7738 // An updated system app will not have the PARSE_IS_SYSTEM flag set 7739 // initially 7740 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 7741 7742 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 7743 // flag set initially 7744 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 7745 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 7746 } 7747 } 7748 7749 // Verify certificates against what was last scanned 7750 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 7751 7752 /* 7753 * A new system app appeared, but we already had a non-system one of the 7754 * same name installed earlier. 7755 */ 7756 boolean shouldHideSystemApp = false; 7757 if (updatedPkg == null && ps != null 7758 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 7759 /* 7760 * Check to make sure the signatures match first. If they don't, 7761 * wipe the installed application and its data. 7762 */ 7763 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 7764 != PackageManager.SIGNATURE_MATCH) { 7765 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 7766 + " signatures don't match existing userdata copy; removing"); 7767 try (PackageFreezer freezer = freezePackage(pkg.packageName, 7768 "scanPackageInternalLI")) { 7769 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 7770 } 7771 ps = null; 7772 } else { 7773 /* 7774 * If the newly-added system app is an older version than the 7775 * already installed version, hide it. It will be scanned later 7776 * and re-added like an update. 7777 */ 7778 if (pkg.mVersionCode <= ps.versionCode) { 7779 shouldHideSystemApp = true; 7780 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 7781 + " but new version " + pkg.mVersionCode + " better than installed " 7782 + ps.versionCode + "; hiding system"); 7783 } else { 7784 /* 7785 * The newly found system app is a newer version that the 7786 * one previously installed. Simply remove the 7787 * already-installed application and replace it with our own 7788 * while keeping the application data. 7789 */ 7790 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7791 + " reverting from " + ps.codePathString + ": new version " 7792 + pkg.mVersionCode + " better than installed " + ps.versionCode); 7793 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7794 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7795 synchronized (mInstallLock) { 7796 args.cleanUpResourcesLI(); 7797 } 7798 } 7799 } 7800 } 7801 7802 // The apk is forward locked (not public) if its code and resources 7803 // are kept in different files. (except for app in either system or 7804 // vendor path). 7805 // TODO grab this value from PackageSettings 7806 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7807 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 7808 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 7809 } 7810 } 7811 7812 // TODO: extend to support forward-locked splits 7813 String resourcePath = null; 7814 String baseResourcePath = null; 7815 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 7816 if (ps != null && ps.resourcePathString != null) { 7817 resourcePath = ps.resourcePathString; 7818 baseResourcePath = ps.resourcePathString; 7819 } else { 7820 // Should not happen at all. Just log an error. 7821 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 7822 } 7823 } else { 7824 resourcePath = pkg.codePath; 7825 baseResourcePath = pkg.baseCodePath; 7826 } 7827 7828 // Set application objects path explicitly. 7829 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 7830 pkg.setApplicationInfoCodePath(pkg.codePath); 7831 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 7832 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 7833 pkg.setApplicationInfoResourcePath(resourcePath); 7834 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 7835 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 7836 7837 // Note that we invoke the following method only if we are about to unpack an application 7838 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 7839 | SCAN_UPDATE_SIGNATURE, currentTime, user); 7840 7841 /* 7842 * If the system app should be overridden by a previously installed 7843 * data, hide the system app now and let the /data/app scan pick it up 7844 * again. 7845 */ 7846 if (shouldHideSystemApp) { 7847 synchronized (mPackages) { 7848 mSettings.disableSystemPackageLPw(pkg.packageName, true); 7849 } 7850 } 7851 7852 return scannedPkg; 7853 } 7854 7855 private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) { 7856 // Derive the new package synthetic package name 7857 pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER 7858 + pkg.staticSharedLibVersion); 7859 } 7860 7861 private static String fixProcessName(String defProcessName, 7862 String processName) { 7863 if (processName == null) { 7864 return defProcessName; 7865 } 7866 return processName; 7867 } 7868 7869 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 7870 throws PackageManagerException { 7871 if (pkgSetting.signatures.mSignatures != null) { 7872 // Already existing package. Make sure signatures match 7873 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 7874 == PackageManager.SIGNATURE_MATCH; 7875 if (!match) { 7876 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 7877 == PackageManager.SIGNATURE_MATCH; 7878 } 7879 if (!match) { 7880 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 7881 == PackageManager.SIGNATURE_MATCH; 7882 } 7883 if (!match) { 7884 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 7885 + pkg.packageName + " signatures do not match the " 7886 + "previously installed version; ignoring!"); 7887 } 7888 } 7889 7890 // Check for shared user signatures 7891 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 7892 // Already existing package. Make sure signatures match 7893 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7894 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 7895 if (!match) { 7896 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 7897 == PackageManager.SIGNATURE_MATCH; 7898 } 7899 if (!match) { 7900 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 7901 == PackageManager.SIGNATURE_MATCH; 7902 } 7903 if (!match) { 7904 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 7905 "Package " + pkg.packageName 7906 + " has no signatures that match those in shared user " 7907 + pkgSetting.sharedUser.name + "; ignoring!"); 7908 } 7909 } 7910 } 7911 7912 /** 7913 * Enforces that only the system UID or root's UID can call a method exposed 7914 * via Binder. 7915 * 7916 * @param message used as message if SecurityException is thrown 7917 * @throws SecurityException if the caller is not system or root 7918 */ 7919 private static final void enforceSystemOrRoot(String message) { 7920 final int uid = Binder.getCallingUid(); 7921 if (uid != Process.SYSTEM_UID && uid != 0) { 7922 throw new SecurityException(message); 7923 } 7924 } 7925 7926 @Override 7927 public void performFstrimIfNeeded() { 7928 enforceSystemOrRoot("Only the system can request fstrim"); 7929 7930 // Before everything else, see whether we need to fstrim. 7931 try { 7932 IStorageManager sm = PackageHelper.getStorageManager(); 7933 if (sm != null) { 7934 boolean doTrim = false; 7935 final long interval = android.provider.Settings.Global.getLong( 7936 mContext.getContentResolver(), 7937 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 7938 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 7939 if (interval > 0) { 7940 final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance(); 7941 if (timeSinceLast > interval) { 7942 doTrim = true; 7943 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 7944 + "; running immediately"); 7945 } 7946 } 7947 if (doTrim) { 7948 final boolean dexOptDialogShown; 7949 synchronized (mPackages) { 7950 dexOptDialogShown = mDexOptDialogShown; 7951 } 7952 if (!isFirstBoot() && dexOptDialogShown) { 7953 try { 7954 ActivityManager.getService().showBootMessage( 7955 mContext.getResources().getString( 7956 R.string.android_upgrading_fstrim), true); 7957 } catch (RemoteException e) { 7958 } 7959 } 7960 sm.runMaintenance(); 7961 } 7962 } else { 7963 Slog.e(TAG, "storageManager service unavailable!"); 7964 } 7965 } catch (RemoteException e) { 7966 // Can't happen; StorageManagerService is local 7967 } 7968 } 7969 7970 @Override 7971 public void updatePackagesIfNeeded() { 7972 enforceSystemOrRoot("Only the system can request package update"); 7973 7974 // We need to re-extract after an OTA. 7975 boolean causeUpgrade = isUpgrade(); 7976 7977 // First boot or factory reset. 7978 // Note: we also handle devices that are upgrading to N right now as if it is their 7979 // first boot, as they do not have profile data. 7980 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 7981 7982 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 7983 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 7984 7985 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 7986 return; 7987 } 7988 7989 List<PackageParser.Package> pkgs; 7990 synchronized (mPackages) { 7991 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 7992 } 7993 7994 final long startTime = System.nanoTime(); 7995 final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */, 7996 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT)); 7997 7998 final int elapsedTimeSeconds = 7999 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 8000 8001 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]); 8002 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]); 8003 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]); 8004 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 8005 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 8006 } 8007 8008 /** 8009 * Performs dexopt on the set of packages in {@code packages} and returns an int array 8010 * containing statistics about the invocation. The array consists of three elements, 8011 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped} 8012 * and {@code numberOfPackagesFailed}. 8013 */ 8014 private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog, 8015 String compilerFilter) { 8016 8017 int numberOfPackagesVisited = 0; 8018 int numberOfPackagesOptimized = 0; 8019 int numberOfPackagesSkipped = 0; 8020 int numberOfPackagesFailed = 0; 8021 final int numberOfPackagesToDexopt = pkgs.size(); 8022 8023 for (PackageParser.Package pkg : pkgs) { 8024 numberOfPackagesVisited++; 8025 8026 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 8027 if (DEBUG_DEXOPT) { 8028 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 8029 } 8030 numberOfPackagesSkipped++; 8031 continue; 8032 } 8033 8034 if (DEBUG_DEXOPT) { 8035 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 8036 numberOfPackagesToDexopt + ": " + pkg.packageName); 8037 } 8038 8039 if (showDialog) { 8040 try { 8041 ActivityManager.getService().showBootMessage( 8042 mContext.getResources().getString(R.string.android_upgrading_apk, 8043 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 8044 } catch (RemoteException e) { 8045 } 8046 synchronized (mPackages) { 8047 mDexOptDialogShown = true; 8048 } 8049 } 8050 8051 // If the OTA updates a system app which was previously preopted to a non-preopted state 8052 // the app might end up being verified at runtime. That's because by default the apps 8053 // are verify-profile but for preopted apps there's no profile. 8054 // Do a hacky check to ensure that if we have no profiles (a reasonable indication 8055 // that before the OTA the app was preopted) the app gets compiled with a non-profile 8056 // filter (by default interpret-only). 8057 // Note that at this stage unused apps are already filtered. 8058 if (isSystemApp(pkg) && 8059 DexFile.isProfileGuidedCompilerFilter(compilerFilter) && 8060 !Environment.getReferenceProfile(pkg.packageName).exists()) { 8061 compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter); 8062 } 8063 8064 // checkProfiles is false to avoid merging profiles during boot which 8065 // might interfere with background compilation (b/28612421). 8066 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 8067 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 8068 // trade-off worth doing to save boot time work. 8069 int dexOptStatus = performDexOptTraced(pkg.packageName, 8070 false /* checkProfiles */, 8071 compilerFilter, 8072 false /* force */); 8073 switch (dexOptStatus) { 8074 case PackageDexOptimizer.DEX_OPT_PERFORMED: 8075 numberOfPackagesOptimized++; 8076 break; 8077 case PackageDexOptimizer.DEX_OPT_SKIPPED: 8078 numberOfPackagesSkipped++; 8079 break; 8080 case PackageDexOptimizer.DEX_OPT_FAILED: 8081 numberOfPackagesFailed++; 8082 break; 8083 default: 8084 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus); 8085 break; 8086 } 8087 } 8088 8089 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped, 8090 numberOfPackagesFailed }; 8091 } 8092 8093 @Override 8094 public void notifyPackageUse(String packageName, int reason) { 8095 synchronized (mPackages) { 8096 PackageParser.Package p = mPackages.get(packageName); 8097 if (p == null) { 8098 return; 8099 } 8100 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 8101 } 8102 } 8103 8104 @Override 8105 public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) { 8106 int userId = UserHandle.getCallingUserId(); 8107 ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId); 8108 if (ai == null) { 8109 Slog.w(TAG, "Loading a package that does not exist for the calling user. package=" 8110 + loadingPackageName + ", user=" + userId); 8111 return; 8112 } 8113 mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId); 8114 } 8115 8116 // TODO: this is not used nor needed. Delete it. 8117 @Override 8118 public boolean performDexOptIfNeeded(String packageName) { 8119 int dexOptStatus = performDexOptTraced(packageName, 8120 false /* checkProfiles */, getFullCompilerFilter(), false /* force */); 8121 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 8122 } 8123 8124 @Override 8125 public boolean performDexOpt(String packageName, 8126 boolean checkProfiles, int compileReason, boolean force) { 8127 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 8128 getCompilerFilterForReason(compileReason), force); 8129 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 8130 } 8131 8132 @Override 8133 public boolean performDexOptMode(String packageName, 8134 boolean checkProfiles, String targetCompilerFilter, boolean force) { 8135 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 8136 targetCompilerFilter, force); 8137 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 8138 } 8139 8140 private int performDexOptTraced(String packageName, 8141 boolean checkProfiles, String targetCompilerFilter, boolean force) { 8142 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 8143 try { 8144 return performDexOptInternal(packageName, checkProfiles, 8145 targetCompilerFilter, force); 8146 } finally { 8147 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8148 } 8149 } 8150 8151 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 8152 // if the package can now be considered up to date for the given filter. 8153 private int performDexOptInternal(String packageName, 8154 boolean checkProfiles, String targetCompilerFilter, boolean force) { 8155 PackageParser.Package p; 8156 synchronized (mPackages) { 8157 p = mPackages.get(packageName); 8158 if (p == null) { 8159 // Package could not be found. Report failure. 8160 return PackageDexOptimizer.DEX_OPT_FAILED; 8161 } 8162 mPackageUsage.maybeWriteAsync(mPackages); 8163 mCompilerStats.maybeWriteAsync(); 8164 } 8165 long callingId = Binder.clearCallingIdentity(); 8166 try { 8167 synchronized (mInstallLock) { 8168 return performDexOptInternalWithDependenciesLI(p, checkProfiles, 8169 targetCompilerFilter, force); 8170 } 8171 } finally { 8172 Binder.restoreCallingIdentity(callingId); 8173 } 8174 } 8175 8176 public ArraySet<String> getOptimizablePackages() { 8177 ArraySet<String> pkgs = new ArraySet<String>(); 8178 synchronized (mPackages) { 8179 for (PackageParser.Package p : mPackages.values()) { 8180 if (PackageDexOptimizer.canOptimizePackage(p)) { 8181 pkgs.add(p.packageName); 8182 } 8183 } 8184 } 8185 return pkgs; 8186 } 8187 8188 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 8189 boolean checkProfiles, String targetCompilerFilter, 8190 boolean force) { 8191 // Select the dex optimizer based on the force parameter. 8192 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 8193 // allocate an object here. 8194 PackageDexOptimizer pdo = force 8195 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 8196 : mPackageDexOptimizer; 8197 8198 // Optimize all dependencies first. Note: we ignore the return value and march on 8199 // on errors. 8200 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 8201 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 8202 if (!deps.isEmpty()) { 8203 for (PackageParser.Package depPackage : deps) { 8204 // TODO: Analyze and investigate if we (should) profile libraries. 8205 // Currently this will do a full compilation of the library by default. 8206 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 8207 false /* checkProfiles */, 8208 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY), 8209 getOrCreateCompilerPackageStats(depPackage)); 8210 } 8211 } 8212 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 8213 targetCompilerFilter, getOrCreateCompilerPackageStats(p)); 8214 } 8215 8216 List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 8217 if (p.usesLibraries != null || p.usesOptionalLibraries != null 8218 || p.usesStaticLibraries != null) { 8219 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 8220 Set<String> collectedNames = new HashSet<>(); 8221 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 8222 8223 retValue.remove(p); 8224 8225 return retValue; 8226 } else { 8227 return Collections.emptyList(); 8228 } 8229 } 8230 8231 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 8232 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) { 8233 if (!collectedNames.contains(p.packageName)) { 8234 collectedNames.add(p.packageName); 8235 collected.add(p); 8236 8237 if (p.usesLibraries != null) { 8238 findSharedNonSystemLibrariesRecursive(p.usesLibraries, 8239 null, collected, collectedNames); 8240 } 8241 if (p.usesOptionalLibraries != null) { 8242 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, 8243 null, collected, collectedNames); 8244 } 8245 if (p.usesStaticLibraries != null) { 8246 findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries, 8247 p.usesStaticLibrariesVersions, collected, collectedNames); 8248 } 8249 } 8250 } 8251 8252 private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions, 8253 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) { 8254 final int libNameCount = libs.size(); 8255 for (int i = 0; i < libNameCount; i++) { 8256 String libName = libs.get(i); 8257 int version = (versions != null && versions.length == libNameCount) 8258 ? versions[i] : PackageManager.VERSION_CODE_HIGHEST; 8259 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version); 8260 if (libPkg != null) { 8261 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 8262 } 8263 } 8264 } 8265 8266 private PackageParser.Package findSharedNonSystemLibrary(String name, int version) { 8267 synchronized (mPackages) { 8268 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version); 8269 if (libEntry != null) { 8270 return mPackages.get(libEntry.apk); 8271 } 8272 return null; 8273 } 8274 } 8275 8276 private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) { 8277 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 8278 if (versionedLib == null) { 8279 return null; 8280 } 8281 return versionedLib.get(version); 8282 } 8283 8284 private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) { 8285 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get( 8286 pkg.staticSharedLibName); 8287 if (versionedLib == null) { 8288 return null; 8289 } 8290 int previousLibVersion = -1; 8291 final int versionCount = versionedLib.size(); 8292 for (int i = 0; i < versionCount; i++) { 8293 final int libVersion = versionedLib.keyAt(i); 8294 if (libVersion < pkg.staticSharedLibVersion) { 8295 previousLibVersion = Math.max(previousLibVersion, libVersion); 8296 } 8297 } 8298 if (previousLibVersion >= 0) { 8299 return versionedLib.get(previousLibVersion); 8300 } 8301 return null; 8302 } 8303 8304 public void shutdown() { 8305 mPackageUsage.writeNow(mPackages); 8306 mCompilerStats.writeNow(); 8307 } 8308 8309 @Override 8310 public void dumpProfiles(String packageName) { 8311 PackageParser.Package pkg; 8312 synchronized (mPackages) { 8313 pkg = mPackages.get(packageName); 8314 if (pkg == null) { 8315 throw new IllegalArgumentException("Unknown package: " + packageName); 8316 } 8317 } 8318 /* Only the shell, root, or the app user should be able to dump profiles. */ 8319 int callingUid = Binder.getCallingUid(); 8320 if (callingUid != Process.SHELL_UID && 8321 callingUid != Process.ROOT_UID && 8322 callingUid != pkg.applicationInfo.uid) { 8323 throw new SecurityException("dumpProfiles"); 8324 } 8325 8326 synchronized (mInstallLock) { 8327 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles"); 8328 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 8329 try { 8330 List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly(); 8331 String codePaths = TextUtils.join(";", allCodePaths); 8332 mInstaller.dumpProfiles(sharedGid, packageName, codePaths); 8333 } catch (InstallerException e) { 8334 Slog.w(TAG, "Failed to dump profiles", e); 8335 } 8336 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8337 } 8338 } 8339 8340 @Override 8341 public void forceDexOpt(String packageName) { 8342 enforceSystemOrRoot("forceDexOpt"); 8343 8344 PackageParser.Package pkg; 8345 synchronized (mPackages) { 8346 pkg = mPackages.get(packageName); 8347 if (pkg == null) { 8348 throw new IllegalArgumentException("Unknown package: " + packageName); 8349 } 8350 } 8351 8352 synchronized (mInstallLock) { 8353 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 8354 8355 // Whoever is calling forceDexOpt wants a fully compiled package. 8356 // Don't use profiles since that may cause compilation to be skipped. 8357 final int res = performDexOptInternalWithDependenciesLI(pkg, 8358 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 8359 true /* force */); 8360 8361 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8362 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 8363 throw new IllegalStateException("Failed to dexopt: " + res); 8364 } 8365 } 8366 } 8367 8368 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 8369 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 8370 Slog.w(TAG, "Unable to update from " + oldPkg.name 8371 + " to " + newPkg.packageName 8372 + ": old package not in system partition"); 8373 return false; 8374 } else if (mPackages.get(oldPkg.name) != null) { 8375 Slog.w(TAG, "Unable to update from " + oldPkg.name 8376 + " to " + newPkg.packageName 8377 + ": old package still exists"); 8378 return false; 8379 } 8380 return true; 8381 } 8382 8383 void removeCodePathLI(File codePath) { 8384 if (codePath.isDirectory()) { 8385 try { 8386 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 8387 } catch (InstallerException e) { 8388 Slog.w(TAG, "Failed to remove code path", e); 8389 } 8390 } else { 8391 codePath.delete(); 8392 } 8393 } 8394 8395 private int[] resolveUserIds(int userId) { 8396 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 8397 } 8398 8399 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 8400 if (pkg == null) { 8401 Slog.wtf(TAG, "Package was null!", new Throwable()); 8402 return; 8403 } 8404 clearAppDataLeafLIF(pkg, userId, flags); 8405 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8406 for (int i = 0; i < childCount; i++) { 8407 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 8408 } 8409 } 8410 8411 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 8412 final PackageSetting ps; 8413 synchronized (mPackages) { 8414 ps = mSettings.mPackages.get(pkg.packageName); 8415 } 8416 for (int realUserId : resolveUserIds(userId)) { 8417 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 8418 try { 8419 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 8420 ceDataInode); 8421 } catch (InstallerException e) { 8422 Slog.w(TAG, String.valueOf(e)); 8423 } 8424 } 8425 } 8426 8427 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 8428 if (pkg == null) { 8429 Slog.wtf(TAG, "Package was null!", new Throwable()); 8430 return; 8431 } 8432 destroyAppDataLeafLIF(pkg, userId, flags); 8433 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8434 for (int i = 0; i < childCount; i++) { 8435 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 8436 } 8437 } 8438 8439 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 8440 final PackageSetting ps; 8441 synchronized (mPackages) { 8442 ps = mSettings.mPackages.get(pkg.packageName); 8443 } 8444 for (int realUserId : resolveUserIds(userId)) { 8445 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 8446 try { 8447 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 8448 ceDataInode); 8449 } catch (InstallerException e) { 8450 Slog.w(TAG, String.valueOf(e)); 8451 } 8452 } 8453 } 8454 8455 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 8456 if (pkg == null) { 8457 Slog.wtf(TAG, "Package was null!", new Throwable()); 8458 return; 8459 } 8460 destroyAppProfilesLeafLIF(pkg); 8461 destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */); 8462 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8463 for (int i = 0; i < childCount; i++) { 8464 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 8465 destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId, 8466 true /* removeBaseMarker */); 8467 } 8468 } 8469 8470 private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId, 8471 boolean removeBaseMarker) { 8472 if (pkg.isForwardLocked()) { 8473 return; 8474 } 8475 8476 for (String path : pkg.getAllCodePathsExcludingResourceOnly()) { 8477 try { 8478 path = PackageManagerServiceUtils.realpath(new File(path)); 8479 } catch (IOException e) { 8480 // TODO: Should we return early here ? 8481 Slog.w(TAG, "Failed to get canonical path", e); 8482 continue; 8483 } 8484 8485 final String useMarker = path.replace('/', '@'); 8486 for (int realUserId : resolveUserIds(userId)) { 8487 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId); 8488 if (removeBaseMarker) { 8489 File foreignUseMark = new File(profileDir, useMarker); 8490 if (foreignUseMark.exists()) { 8491 if (!foreignUseMark.delete()) { 8492 Slog.w(TAG, "Unable to delete foreign user mark for package: " 8493 + pkg.packageName); 8494 } 8495 } 8496 } 8497 8498 File[] markers = profileDir.listFiles(); 8499 if (markers != null) { 8500 final String searchString = "@" + pkg.packageName + "@"; 8501 // We also delete all markers that contain the package name we're 8502 // uninstalling. These are associated with secondary dex-files belonging 8503 // to the package. Reconstructing the path of these dex files is messy 8504 // in general. 8505 for (File marker : markers) { 8506 if (marker.getName().indexOf(searchString) > 0) { 8507 if (!marker.delete()) { 8508 Slog.w(TAG, "Unable to delete foreign user mark for package: " 8509 + pkg.packageName); 8510 } 8511 } 8512 } 8513 } 8514 } 8515 } 8516 } 8517 8518 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 8519 try { 8520 mInstaller.destroyAppProfiles(pkg.packageName); 8521 } catch (InstallerException e) { 8522 Slog.w(TAG, String.valueOf(e)); 8523 } 8524 } 8525 8526 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 8527 if (pkg == null) { 8528 Slog.wtf(TAG, "Package was null!", new Throwable()); 8529 return; 8530 } 8531 clearAppProfilesLeafLIF(pkg); 8532 // We don't remove the base foreign use marker when clearing profiles because 8533 // we will rename it when the app is updated. Unlike the actual profile contents, 8534 // the foreign use marker is good across installs. 8535 destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */); 8536 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8537 for (int i = 0; i < childCount; i++) { 8538 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 8539 } 8540 } 8541 8542 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 8543 try { 8544 mInstaller.clearAppProfiles(pkg.packageName); 8545 } catch (InstallerException e) { 8546 Slog.w(TAG, String.valueOf(e)); 8547 } 8548 } 8549 8550 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 8551 long lastUpdateTime) { 8552 // Set parent install/update time 8553 PackageSetting ps = (PackageSetting) pkg.mExtras; 8554 if (ps != null) { 8555 ps.firstInstallTime = firstInstallTime; 8556 ps.lastUpdateTime = lastUpdateTime; 8557 } 8558 // Set children install/update time 8559 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8560 for (int i = 0; i < childCount; i++) { 8561 PackageParser.Package childPkg = pkg.childPackages.get(i); 8562 ps = (PackageSetting) childPkg.mExtras; 8563 if (ps != null) { 8564 ps.firstInstallTime = firstInstallTime; 8565 ps.lastUpdateTime = lastUpdateTime; 8566 } 8567 } 8568 } 8569 8570 private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 8571 PackageParser.Package changingLib) { 8572 if (file.path != null) { 8573 usesLibraryFiles.add(file.path); 8574 return; 8575 } 8576 PackageParser.Package p = mPackages.get(file.apk); 8577 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 8578 // If we are doing this while in the middle of updating a library apk, 8579 // then we need to make sure to use that new apk for determining the 8580 // dependencies here. (We haven't yet finished committing the new apk 8581 // to the package manager state.) 8582 if (p == null || p.packageName.equals(changingLib.packageName)) { 8583 p = changingLib; 8584 } 8585 } 8586 if (p != null) { 8587 usesLibraryFiles.addAll(p.getAllCodePaths()); 8588 } 8589 } 8590 8591 private void updateSharedLibrariesLPr(PackageParser.Package pkg, 8592 PackageParser.Package changingLib) throws PackageManagerException { 8593 if (pkg == null) { 8594 return; 8595 } 8596 ArraySet<String> usesLibraryFiles = null; 8597 if (pkg.usesLibraries != null) { 8598 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries, 8599 null, null, pkg.packageName, changingLib, true, null); 8600 } 8601 if (pkg.usesStaticLibraries != null) { 8602 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries, 8603 pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests, 8604 pkg.packageName, changingLib, true, usesLibraryFiles); 8605 } 8606 if (pkg.usesOptionalLibraries != null) { 8607 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries, 8608 null, null, pkg.packageName, changingLib, false, usesLibraryFiles); 8609 } 8610 if (!ArrayUtils.isEmpty(usesLibraryFiles)) { 8611 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]); 8612 } else { 8613 pkg.usesLibraryFiles = null; 8614 } 8615 } 8616 8617 private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries, 8618 @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests, 8619 @NonNull String packageName, @Nullable PackageParser.Package changingLib, 8620 boolean required, @Nullable ArraySet<String> outUsedLibraries) 8621 throws PackageManagerException { 8622 final int libCount = requestedLibraries.size(); 8623 for (int i = 0; i < libCount; i++) { 8624 final String libName = requestedLibraries.get(i); 8625 final int libVersion = requiredVersions != null ? requiredVersions[i] 8626 : SharedLibraryInfo.VERSION_UNDEFINED; 8627 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion); 8628 if (libEntry == null) { 8629 if (required) { 8630 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8631 "Package " + packageName + " requires unavailable shared library " 8632 + libName + "; failing!"); 8633 } else { 8634 Slog.w(TAG, "Package " + packageName 8635 + " desires unavailable shared library " 8636 + libName + "; ignoring!"); 8637 } 8638 } else { 8639 if (requiredVersions != null && requiredCertDigests != null) { 8640 if (libEntry.info.getVersion() != requiredVersions[i]) { 8641 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8642 "Package " + packageName + " requires unavailable static shared" 8643 + " library " + libName + " version " 8644 + libEntry.info.getVersion() + "; failing!"); 8645 } 8646 8647 PackageParser.Package libPkg = mPackages.get(libEntry.apk); 8648 if (libPkg == null) { 8649 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8650 "Package " + packageName + " requires unavailable static shared" 8651 + " library; failing!"); 8652 } 8653 8654 String expectedCertDigest = requiredCertDigests[i]; 8655 String libCertDigest = PackageUtils.computeCertSha256Digest( 8656 libPkg.mSignatures[0]); 8657 if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) { 8658 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8659 "Package " + packageName + " requires differently signed" + 8660 " static shared library; failing!"); 8661 } 8662 } 8663 8664 if (outUsedLibraries == null) { 8665 outUsedLibraries = new ArraySet<>(); 8666 } 8667 addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib); 8668 } 8669 } 8670 return outUsedLibraries; 8671 } 8672 8673 private static boolean hasString(List<String> list, List<String> which) { 8674 if (list == null) { 8675 return false; 8676 } 8677 for (int i=list.size()-1; i>=0; i--) { 8678 for (int j=which.size()-1; j>=0; j--) { 8679 if (which.get(j).equals(list.get(i))) { 8680 return true; 8681 } 8682 } 8683 } 8684 return false; 8685 } 8686 8687 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 8688 PackageParser.Package changingPkg) { 8689 ArrayList<PackageParser.Package> res = null; 8690 for (PackageParser.Package pkg : mPackages.values()) { 8691 if (changingPkg != null 8692 && !hasString(pkg.usesLibraries, changingPkg.libraryNames) 8693 && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames) 8694 && !ArrayUtils.contains(pkg.usesStaticLibraries, 8695 changingPkg.staticSharedLibName)) { 8696 return null; 8697 } 8698 if (res == null) { 8699 res = new ArrayList<>(); 8700 } 8701 res.add(pkg); 8702 try { 8703 updateSharedLibrariesLPr(pkg, changingPkg); 8704 } catch (PackageManagerException e) { 8705 // If a system app update or an app and a required lib missing we 8706 // delete the package and for updated system apps keep the data as 8707 // it is better for the user to reinstall than to be in an limbo 8708 // state. Also libs disappearing under an app should never happen 8709 // - just in case. 8710 if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) { 8711 final int flags = pkg.isUpdatedSystemApp() 8712 ? PackageManager.DELETE_KEEP_DATA : 0; 8713 deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(), 8714 flags , null, true, null); 8715 } 8716 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 8717 } 8718 } 8719 return res; 8720 } 8721 8722 /** 8723 * Derive the value of the {@code cpuAbiOverride} based on the provided 8724 * value and an optional stored value from the package settings. 8725 */ 8726 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 8727 String cpuAbiOverride = null; 8728 8729 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 8730 cpuAbiOverride = null; 8731 } else if (abiOverride != null) { 8732 cpuAbiOverride = abiOverride; 8733 } else if (settings != null) { 8734 cpuAbiOverride = settings.cpuAbiOverrideString; 8735 } 8736 8737 return cpuAbiOverride; 8738 } 8739 8740 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 8741 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 8742 throws PackageManagerException { 8743 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 8744 // If the package has children and this is the first dive in the function 8745 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 8746 // whether all packages (parent and children) would be successfully scanned 8747 // before the actual scan since scanning mutates internal state and we want 8748 // to atomically install the package and its children. 8749 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8750 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 8751 scanFlags |= SCAN_CHECK_ONLY; 8752 } 8753 } else { 8754 scanFlags &= ~SCAN_CHECK_ONLY; 8755 } 8756 8757 final PackageParser.Package scannedPkg; 8758 try { 8759 // Scan the parent 8760 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 8761 // Scan the children 8762 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8763 for (int i = 0; i < childCount; i++) { 8764 PackageParser.Package childPkg = pkg.childPackages.get(i); 8765 scanPackageLI(childPkg, policyFlags, 8766 scanFlags, currentTime, user); 8767 } 8768 } finally { 8769 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8770 } 8771 8772 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8773 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 8774 } 8775 8776 return scannedPkg; 8777 } 8778 8779 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 8780 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 8781 boolean success = false; 8782 try { 8783 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 8784 currentTime, user); 8785 success = true; 8786 return res; 8787 } finally { 8788 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 8789 // DELETE_DATA_ON_FAILURES is only used by frozen paths 8790 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 8791 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 8792 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 8793 } 8794 } 8795 } 8796 8797 /** 8798 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 8799 */ 8800 private static boolean apkHasCode(String fileName) { 8801 StrictJarFile jarFile = null; 8802 try { 8803 jarFile = new StrictJarFile(fileName, 8804 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 8805 return jarFile.findEntry("classes.dex") != null; 8806 } catch (IOException ignore) { 8807 } finally { 8808 try { 8809 if (jarFile != null) { 8810 jarFile.close(); 8811 } 8812 } catch (IOException ignore) {} 8813 } 8814 return false; 8815 } 8816 8817 /** 8818 * Enforces code policy for the package. This ensures that if an APK has 8819 * declared hasCode="true" in its manifest that the APK actually contains 8820 * code. 8821 * 8822 * @throws PackageManagerException If bytecode could not be found when it should exist 8823 */ 8824 private static void assertCodePolicy(PackageParser.Package pkg) 8825 throws PackageManagerException { 8826 final boolean shouldHaveCode = 8827 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 8828 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 8829 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8830 "Package " + pkg.baseCodePath + " code is missing"); 8831 } 8832 8833 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 8834 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 8835 final boolean splitShouldHaveCode = 8836 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 8837 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 8838 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8839 "Package " + pkg.splitCodePaths[i] + " code is missing"); 8840 } 8841 } 8842 } 8843 } 8844 8845 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 8846 final int policyFlags, final int scanFlags, long currentTime, UserHandle user) 8847 throws PackageManagerException { 8848 if (DEBUG_PACKAGE_SCANNING) { 8849 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8850 Log.d(TAG, "Scanning package " + pkg.packageName); 8851 } 8852 8853 applyPolicy(pkg, policyFlags); 8854 8855 assertPackageIsValid(pkg, policyFlags, scanFlags); 8856 8857 // Initialize package source and resource directories 8858 final File scanFile = new File(pkg.codePath); 8859 final File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 8860 final File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 8861 8862 SharedUserSetting suid = null; 8863 PackageSetting pkgSetting = null; 8864 8865 // Getting the package setting may have a side-effect, so if we 8866 // are only checking if scan would succeed, stash a copy of the 8867 // old setting to restore at the end. 8868 PackageSetting nonMutatedPs = null; 8869 8870 // We keep references to the derived CPU Abis from settings in oder to reuse 8871 // them in the case where we're not upgrading or booting for the first time. 8872 String primaryCpuAbiFromSettings = null; 8873 String secondaryCpuAbiFromSettings = null; 8874 8875 // writer 8876 synchronized (mPackages) { 8877 if (pkg.mSharedUserId != null) { 8878 // SIDE EFFECTS; may potentially allocate a new shared user 8879 suid = mSettings.getSharedUserLPw( 8880 pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/); 8881 if (DEBUG_PACKAGE_SCANNING) { 8882 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8883 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 8884 + "): packages=" + suid.packages); 8885 } 8886 } 8887 8888 // Check if we are renaming from an original package name. 8889 PackageSetting origPackage = null; 8890 String realName = null; 8891 if (pkg.mOriginalPackages != null) { 8892 // This package may need to be renamed to a previously 8893 // installed name. Let's check on that... 8894 final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage); 8895 if (pkg.mOriginalPackages.contains(renamed)) { 8896 // This package had originally been installed as the 8897 // original name, and we have already taken care of 8898 // transitioning to the new one. Just update the new 8899 // one to continue using the old name. 8900 realName = pkg.mRealPackage; 8901 if (!pkg.packageName.equals(renamed)) { 8902 // Callers into this function may have already taken 8903 // care of renaming the package; only do it here if 8904 // it is not already done. 8905 pkg.setPackageName(renamed); 8906 } 8907 } else { 8908 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 8909 if ((origPackage = mSettings.getPackageLPr( 8910 pkg.mOriginalPackages.get(i))) != null) { 8911 // We do have the package already installed under its 8912 // original name... should we use it? 8913 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 8914 // New package is not compatible with original. 8915 origPackage = null; 8916 continue; 8917 } else if (origPackage.sharedUser != null) { 8918 // Make sure uid is compatible between packages. 8919 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 8920 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 8921 + " to " + pkg.packageName + ": old uid " 8922 + origPackage.sharedUser.name 8923 + " differs from " + pkg.mSharedUserId); 8924 origPackage = null; 8925 continue; 8926 } 8927 // TODO: Add case when shared user id is added [b/28144775] 8928 } else { 8929 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 8930 + pkg.packageName + " to old name " + origPackage.name); 8931 } 8932 break; 8933 } 8934 } 8935 } 8936 } 8937 8938 if (mTransferedPackages.contains(pkg.packageName)) { 8939 Slog.w(TAG, "Package " + pkg.packageName 8940 + " was transferred to another, but its .apk remains"); 8941 } 8942 8943 // See comments in nonMutatedPs declaration 8944 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8945 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName); 8946 if (foundPs != null) { 8947 nonMutatedPs = new PackageSetting(foundPs); 8948 } 8949 } 8950 8951 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) { 8952 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName); 8953 if (foundPs != null) { 8954 primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString; 8955 secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString; 8956 } 8957 } 8958 8959 pkgSetting = mSettings.getPackageLPr(pkg.packageName); 8960 if (pkgSetting != null && pkgSetting.sharedUser != suid) { 8961 PackageManagerService.reportSettingsProblem(Log.WARN, 8962 "Package " + pkg.packageName + " shared user changed from " 8963 + (pkgSetting.sharedUser != null 8964 ? pkgSetting.sharedUser.name : "<nothing>") 8965 + " to " 8966 + (suid != null ? suid.name : "<nothing>") 8967 + "; replacing with new"); 8968 pkgSetting = null; 8969 } 8970 final PackageSetting oldPkgSetting = 8971 pkgSetting == null ? null : new PackageSetting(pkgSetting); 8972 final PackageSetting disabledPkgSetting = 8973 mSettings.getDisabledSystemPkgLPr(pkg.packageName); 8974 8975 String[] usesStaticLibraries = null; 8976 if (pkg.usesStaticLibraries != null) { 8977 usesStaticLibraries = new String[pkg.usesStaticLibraries.size()]; 8978 pkg.usesStaticLibraries.toArray(usesStaticLibraries); 8979 } 8980 8981 if (pkgSetting == null) { 8982 final String parentPackageName = (pkg.parentPackage != null) 8983 ? pkg.parentPackage.packageName : null; 8984 8985 // REMOVE SharedUserSetting from method; update in a separate call 8986 pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage, 8987 disabledPkgSetting, realName, suid, destCodeFile, destResourceFile, 8988 pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi, 8989 pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode, 8990 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user, 8991 true /*allowInstall*/, parentPackageName, pkg.getChildPackageNames(), 8992 UserManagerService.getInstance(), usesStaticLibraries, 8993 pkg.usesStaticLibrariesVersions); 8994 // SIDE EFFECTS; updates system state; move elsewhere 8995 if (origPackage != null) { 8996 mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name); 8997 } 8998 mSettings.addUserToSettingLPw(pkgSetting); 8999 } else { 9000 // REMOVE SharedUserSetting from method; update in a separate call. 9001 // 9002 // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi, 9003 // secondaryCpuAbi are not known at this point so we always update them 9004 // to null here, only to reset them at a later point. 9005 Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile, 9006 pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi, 9007 pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags, 9008 pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(), 9009 UserManagerService.getInstance(), usesStaticLibraries, 9010 pkg.usesStaticLibrariesVersions); 9011 } 9012 // SIDE EFFECTS; persists system state to files on disk; move elsewhere 9013 mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting); 9014 9015 // SIDE EFFECTS; modifies system state; move elsewhere 9016 if (pkgSetting.origPackage != null) { 9017 // If we are first transitioning from an original package, 9018 // fix up the new package's name now. We need to do this after 9019 // looking up the package under its new name, so getPackageLP 9020 // can take care of fiddling things correctly. 9021 pkg.setPackageName(origPackage.name); 9022 9023 // File a report about this. 9024 String msg = "New package " + pkgSetting.realName 9025 + " renamed to replace old package " + pkgSetting.name; 9026 reportSettingsProblem(Log.WARN, msg); 9027 9028 // Make a note of it. 9029 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 9030 mTransferedPackages.add(origPackage.name); 9031 } 9032 9033 // No longer need to retain this. 9034 pkgSetting.origPackage = null; 9035 } 9036 9037 // SIDE EFFECTS; modifies system state; move elsewhere 9038 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 9039 // Make a note of it. 9040 mTransferedPackages.add(pkg.packageName); 9041 } 9042 9043 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 9044 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 9045 } 9046 9047 if ((scanFlags & SCAN_BOOTING) == 0 9048 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 9049 // Check all shared libraries and map to their actual file path. 9050 // We only do this here for apps not on a system dir, because those 9051 // are the only ones that can fail an install due to this. We 9052 // will take care of the system apps by updating all of their 9053 // library paths after the scan is done. Also during the initial 9054 // scan don't update any libs as we do this wholesale after all 9055 // apps are scanned to avoid dependency based scanning. 9056 updateSharedLibrariesLPr(pkg, null); 9057 } 9058 9059 if (mFoundPolicyFile) { 9060 SELinuxMMAC.assignSeinfoValue(pkg); 9061 } 9062 9063 pkg.applicationInfo.uid = pkgSetting.appId; 9064 pkg.mExtras = pkgSetting; 9065 9066 9067 // Static shared libs have same package with different versions where 9068 // we internally use a synthetic package name to allow multiple versions 9069 // of the same package, therefore we need to compare signatures against 9070 // the package setting for the latest library version. 9071 PackageSetting signatureCheckPs = pkgSetting; 9072 if (pkg.applicationInfo.isStaticSharedLibrary()) { 9073 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg); 9074 if (libraryEntry != null) { 9075 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk); 9076 } 9077 } 9078 9079 if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) { 9080 if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) { 9081 // We just determined the app is signed correctly, so bring 9082 // over the latest parsed certs. 9083 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9084 } else { 9085 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 9086 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 9087 "Package " + pkg.packageName + " upgrade keys do not match the " 9088 + "previously installed version"); 9089 } else { 9090 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9091 String msg = "System package " + pkg.packageName 9092 + " signature changed; retaining data."; 9093 reportSettingsProblem(Log.WARN, msg); 9094 } 9095 } 9096 } else { 9097 try { 9098 // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService 9099 verifySignaturesLP(signatureCheckPs, pkg); 9100 // We just determined the app is signed correctly, so bring 9101 // over the latest parsed certs. 9102 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9103 } catch (PackageManagerException e) { 9104 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 9105 throw e; 9106 } 9107 // The signature has changed, but this package is in the system 9108 // image... let's recover! 9109 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9110 // However... if this package is part of a shared user, but it 9111 // doesn't match the signature of the shared user, let's fail. 9112 // What this means is that you can't change the signatures 9113 // associated with an overall shared user, which doesn't seem all 9114 // that unreasonable. 9115 if (signatureCheckPs.sharedUser != null) { 9116 if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures, 9117 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 9118 throw new PackageManagerException( 9119 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 9120 "Signature mismatch for shared user: " 9121 + pkgSetting.sharedUser); 9122 } 9123 } 9124 // File a report about this. 9125 String msg = "System package " + pkg.packageName 9126 + " signature changed; retaining data."; 9127 reportSettingsProblem(Log.WARN, msg); 9128 } 9129 } 9130 9131 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 9132 // This package wants to adopt ownership of permissions from 9133 // another package. 9134 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 9135 final String origName = pkg.mAdoptPermissions.get(i); 9136 final PackageSetting orig = mSettings.getPackageLPr(origName); 9137 if (orig != null) { 9138 if (verifyPackageUpdateLPr(orig, pkg)) { 9139 Slog.i(TAG, "Adopting permissions from " + origName + " to " 9140 + pkg.packageName); 9141 // SIDE EFFECTS; updates permissions system state; move elsewhere 9142 mSettings.transferPermissionsLPw(origName, pkg.packageName); 9143 } 9144 } 9145 } 9146 } 9147 } 9148 9149 pkg.applicationInfo.processName = fixProcessName( 9150 pkg.applicationInfo.packageName, 9151 pkg.applicationInfo.processName); 9152 9153 if (pkg != mPlatformPackage) { 9154 // Get all of our default paths setup 9155 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 9156 } 9157 9158 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 9159 9160 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 9161 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) { 9162 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi"); 9163 derivePackageAbi( 9164 pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir); 9165 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9166 9167 // Some system apps still use directory structure for native libraries 9168 // in which case we might end up not detecting abi solely based on apk 9169 // structure. Try to detect abi based on directory structure. 9170 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 9171 pkg.applicationInfo.primaryCpuAbi == null) { 9172 setBundledAppAbisAndRoots(pkg, pkgSetting); 9173 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 9174 } 9175 } else { 9176 // This is not a first boot or an upgrade, don't bother deriving the 9177 // ABI during the scan. Instead, trust the value that was stored in the 9178 // package setting. 9179 pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings; 9180 pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings; 9181 9182 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 9183 9184 if (DEBUG_ABI_SELECTION) { 9185 Slog.i(TAG, "Using ABIS and native lib paths from settings : " + 9186 pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " + 9187 pkg.applicationInfo.secondaryCpuAbi); 9188 } 9189 } 9190 } else { 9191 if ((scanFlags & SCAN_MOVE) != 0) { 9192 // We haven't run dex-opt for this move (since we've moved the compiled output too) 9193 // but we already have this packages package info in the PackageSetting. We just 9194 // use that and derive the native library path based on the new codepath. 9195 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 9196 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 9197 } 9198 9199 // Set native library paths again. For moves, the path will be updated based on the 9200 // ABIs we've determined above. For non-moves, the path will be updated based on the 9201 // ABIs we determined during compilation, but the path will depend on the final 9202 // package path (after the rename away from the stage path). 9203 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 9204 } 9205 9206 // This is a special case for the "system" package, where the ABI is 9207 // dictated by the zygote configuration (and init.rc). We should keep track 9208 // of this ABI so that we can deal with "normal" applications that run under 9209 // the same UID correctly. 9210 if (mPlatformPackage == pkg) { 9211 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 9212 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 9213 } 9214 9215 // If there's a mismatch between the abi-override in the package setting 9216 // and the abiOverride specified for the install. Warn about this because we 9217 // would've already compiled the app without taking the package setting into 9218 // account. 9219 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 9220 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 9221 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 9222 " for package " + pkg.packageName); 9223 } 9224 } 9225 9226 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9227 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9228 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 9229 9230 // Copy the derived override back to the parsed package, so that we can 9231 // update the package settings accordingly. 9232 pkg.cpuAbiOverride = cpuAbiOverride; 9233 9234 if (DEBUG_ABI_SELECTION) { 9235 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 9236 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 9237 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 9238 } 9239 9240 // Push the derived path down into PackageSettings so we know what to 9241 // clean up at uninstall time. 9242 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 9243 9244 if (DEBUG_ABI_SELECTION) { 9245 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 9246 " primary=" + pkg.applicationInfo.primaryCpuAbi + 9247 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 9248 } 9249 9250 // SIDE EFFECTS; removes DEX files from disk; move elsewhere 9251 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 9252 // We don't do this here during boot because we can do it all 9253 // at once after scanning all existing packages. 9254 // 9255 // We also do this *before* we perform dexopt on this package, so that 9256 // we can avoid redundant dexopts, and also to make sure we've got the 9257 // code and package path correct. 9258 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg); 9259 } 9260 9261 if (mFactoryTest && pkg.requestedPermissions.contains( 9262 android.Manifest.permission.FACTORY_TEST)) { 9263 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 9264 } 9265 9266 if (isSystemApp(pkg)) { 9267 pkgSetting.isOrphaned = true; 9268 } 9269 9270 // Take care of first install / last update times. 9271 final long scanFileTime = getLastModifiedTime(pkg, scanFile); 9272 if (currentTime != 0) { 9273 if (pkgSetting.firstInstallTime == 0) { 9274 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 9275 } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) { 9276 pkgSetting.lastUpdateTime = currentTime; 9277 } 9278 } else if (pkgSetting.firstInstallTime == 0) { 9279 // We need *something*. Take time time stamp of the file. 9280 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 9281 } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 9282 if (scanFileTime != pkgSetting.timeStamp) { 9283 // A package on the system image has changed; consider this 9284 // to be an update. 9285 pkgSetting.lastUpdateTime = scanFileTime; 9286 } 9287 } 9288 pkgSetting.setTimeStamp(scanFileTime); 9289 9290 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 9291 if (nonMutatedPs != null) { 9292 synchronized (mPackages) { 9293 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 9294 } 9295 } 9296 } else { 9297 // Modify state for the given package setting 9298 commitPackageSettings(pkg, pkgSetting, user, scanFlags, 9299 (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/); 9300 if (isEphemeral(pkg)) { 9301 final int userId = user == null ? 0 : user.getIdentifier(); 9302 mEphemeralApplicationRegistry.addEphemeralAppLPw(userId, pkgSetting.appId); 9303 } 9304 } 9305 return pkg; 9306 } 9307 9308 /** 9309 * Applies policy to the parsed package based upon the given policy flags. 9310 * Ensures the package is in a good state. 9311 * <p> 9312 * Implementation detail: This method must NOT have any side effect. It would 9313 * ideally be static, but, it requires locks to read system state. 9314 */ 9315 private void applyPolicy(PackageParser.Package pkg, int policyFlags) { 9316 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 9317 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 9318 if (pkg.applicationInfo.isDirectBootAware()) { 9319 // we're direct boot aware; set for all components 9320 for (PackageParser.Service s : pkg.services) { 9321 s.info.encryptionAware = s.info.directBootAware = true; 9322 } 9323 for (PackageParser.Provider p : pkg.providers) { 9324 p.info.encryptionAware = p.info.directBootAware = true; 9325 } 9326 for (PackageParser.Activity a : pkg.activities) { 9327 a.info.encryptionAware = a.info.directBootAware = true; 9328 } 9329 for (PackageParser.Activity r : pkg.receivers) { 9330 r.info.encryptionAware = r.info.directBootAware = true; 9331 } 9332 } 9333 } else { 9334 // Only allow system apps to be flagged as core apps. 9335 pkg.coreApp = false; 9336 // clear flags not applicable to regular apps 9337 pkg.applicationInfo.privateFlags &= 9338 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 9339 pkg.applicationInfo.privateFlags &= 9340 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 9341 } 9342 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 9343 9344 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 9345 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 9346 } 9347 9348 if (!isSystemApp(pkg)) { 9349 // Only system apps can use these features. 9350 pkg.mOriginalPackages = null; 9351 pkg.mRealPackage = null; 9352 pkg.mAdoptPermissions = null; 9353 } 9354 } 9355 9356 /** 9357 * Asserts the parsed package is valid according to the given policy. If the 9358 * package is invalid, for whatever reason, throws {@link PackgeManagerException}. 9359 * <p> 9360 * Implementation detail: This method must NOT have any side effects. It would 9361 * ideally be static, but, it requires locks to read system state. 9362 * 9363 * @throws PackageManagerException If the package fails any of the validation checks 9364 */ 9365 private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags) 9366 throws PackageManagerException { 9367 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 9368 assertCodePolicy(pkg); 9369 } 9370 9371 if (pkg.applicationInfo.getCodePath() == null || 9372 pkg.applicationInfo.getResourcePath() == null) { 9373 // Bail out. The resource and code paths haven't been set. 9374 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 9375 "Code and resource paths haven't been set correctly"); 9376 } 9377 9378 // Make sure we're not adding any bogus keyset info 9379 KeySetManagerService ksms = mSettings.mKeySetManagerService; 9380 ksms.assertScannedPackageValid(pkg); 9381 9382 synchronized (mPackages) { 9383 // The special "android" package can only be defined once 9384 if (pkg.packageName.equals("android")) { 9385 if (mAndroidApplication != null) { 9386 Slog.w(TAG, "*************************************************"); 9387 Slog.w(TAG, "Core android package being redefined. Skipping."); 9388 Slog.w(TAG, " codePath=" + pkg.codePath); 9389 Slog.w(TAG, "*************************************************"); 9390 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 9391 "Core android package being redefined. Skipping."); 9392 } 9393 } 9394 9395 // A package name must be unique; don't allow duplicates 9396 if (mPackages.containsKey(pkg.packageName)) { 9397 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 9398 "Application package " + pkg.packageName 9399 + " already installed. Skipping duplicate."); 9400 } 9401 9402 if (pkg.applicationInfo.isStaticSharedLibrary()) { 9403 // Static libs have a synthetic package name containing the version 9404 // but we still want the base name to be unique. 9405 if (mPackages.containsKey(pkg.manifestPackageName)) { 9406 throw new PackageManagerException( 9407 "Duplicate static shared lib provider package"); 9408 } 9409 9410 // Static shared libraries should have at least O target SDK 9411 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) { 9412 throw new PackageManagerException( 9413 "Packages declaring static-shared libs must target O SDK or higher"); 9414 } 9415 9416 // Package declaring static a shared lib cannot be ephemeral 9417 if (pkg.applicationInfo.isEphemeralApp()) { 9418 throw new PackageManagerException( 9419 "Packages declaring static-shared libs cannot be ephemeral"); 9420 } 9421 9422 // Package declaring static a shared lib cannot be renamed since the package 9423 // name is synthetic and apps can't code around package manager internals. 9424 if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) { 9425 throw new PackageManagerException( 9426 "Packages declaring static-shared libs cannot be renamed"); 9427 } 9428 9429 // Package declaring static a shared lib cannot declare child packages 9430 if (!ArrayUtils.isEmpty(pkg.childPackages)) { 9431 throw new PackageManagerException( 9432 "Packages declaring static-shared libs cannot have child packages"); 9433 } 9434 9435 // Package declaring static a shared lib cannot declare dynamic libs 9436 if (!ArrayUtils.isEmpty(pkg.libraryNames)) { 9437 throw new PackageManagerException( 9438 "Packages declaring static-shared libs cannot declare dynamic libs"); 9439 } 9440 9441 // Package declaring static a shared lib cannot declare shared users 9442 if (pkg.mSharedUserId != null) { 9443 throw new PackageManagerException( 9444 "Packages declaring static-shared libs cannot declare shared users"); 9445 } 9446 9447 // Static shared libs cannot declare activities 9448 if (!pkg.activities.isEmpty()) { 9449 throw new PackageManagerException( 9450 "Static shared libs cannot declare activities"); 9451 } 9452 9453 // Static shared libs cannot declare services 9454 if (!pkg.services.isEmpty()) { 9455 throw new PackageManagerException( 9456 "Static shared libs cannot declare services"); 9457 } 9458 9459 // Static shared libs cannot declare providers 9460 if (!pkg.providers.isEmpty()) { 9461 throw new PackageManagerException( 9462 "Static shared libs cannot declare content providers"); 9463 } 9464 9465 // Static shared libs cannot declare receivers 9466 if (!pkg.receivers.isEmpty()) { 9467 throw new PackageManagerException( 9468 "Static shared libs cannot declare broadcast receivers"); 9469 } 9470 9471 // Static shared libs cannot declare permission groups 9472 if (!pkg.permissionGroups.isEmpty()) { 9473 throw new PackageManagerException( 9474 "Static shared libs cannot declare permission groups"); 9475 } 9476 9477 // Static shared libs cannot declare permissions 9478 if (!pkg.permissions.isEmpty()) { 9479 throw new PackageManagerException( 9480 "Static shared libs cannot declare permissions"); 9481 } 9482 9483 // Static shared libs cannot declare protected broadcasts 9484 if (pkg.protectedBroadcasts != null) { 9485 throw new PackageManagerException( 9486 "Static shared libs cannot declare protected broadcasts"); 9487 } 9488 9489 // Static shared libs cannot be overlay targets 9490 if (pkg.mOverlayTarget != null) { 9491 throw new PackageManagerException( 9492 "Static shared libs cannot be overlay targets"); 9493 } 9494 9495 // The version codes must be ordered as lib versions 9496 int minVersionCode = Integer.MIN_VALUE; 9497 int maxVersionCode = Integer.MAX_VALUE; 9498 9499 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get( 9500 pkg.staticSharedLibName); 9501 if (versionedLib != null) { 9502 final int versionCount = versionedLib.size(); 9503 for (int i = 0; i < versionCount; i++) { 9504 SharedLibraryInfo libInfo = versionedLib.valueAt(i).info; 9505 // TODO: We will change version code to long, so in the new API it is long 9506 final int libVersionCode = (int) libInfo.getDeclaringPackage() 9507 .getVersionCode(); 9508 if (libInfo.getVersion() < pkg.staticSharedLibVersion) { 9509 minVersionCode = Math.max(minVersionCode, libVersionCode + 1); 9510 } else if (libInfo.getVersion() > pkg.staticSharedLibVersion) { 9511 maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1); 9512 } else { 9513 minVersionCode = maxVersionCode = libVersionCode; 9514 break; 9515 } 9516 } 9517 } 9518 if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) { 9519 throw new PackageManagerException("Static shared" 9520 + " lib version codes must be ordered as lib versions"); 9521 } 9522 } 9523 9524 // Only privileged apps and updated privileged apps can add child packages. 9525 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 9526 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 9527 throw new PackageManagerException("Only privileged apps can add child " 9528 + "packages. Ignoring package " + pkg.packageName); 9529 } 9530 final int childCount = pkg.childPackages.size(); 9531 for (int i = 0; i < childCount; i++) { 9532 PackageParser.Package childPkg = pkg.childPackages.get(i); 9533 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 9534 childPkg.packageName)) { 9535 throw new PackageManagerException("Can't override child of " 9536 + "another disabled app. Ignoring package " + pkg.packageName); 9537 } 9538 } 9539 } 9540 9541 // If we're only installing presumed-existing packages, require that the 9542 // scanned APK is both already known and at the path previously established 9543 // for it. Previously unknown packages we pick up normally, but if we have an 9544 // a priori expectation about this package's install presence, enforce it. 9545 // With a singular exception for new system packages. When an OTA contains 9546 // a new system package, we allow the codepath to change from a system location 9547 // to the user-installed location. If we don't allow this change, any newer, 9548 // user-installed version of the application will be ignored. 9549 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 9550 if (mExpectingBetter.containsKey(pkg.packageName)) { 9551 logCriticalInfo(Log.WARN, 9552 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 9553 } else { 9554 PackageSetting known = mSettings.getPackageLPr(pkg.packageName); 9555 if (known != null) { 9556 if (DEBUG_PACKAGE_SCANNING) { 9557 Log.d(TAG, "Examining " + pkg.codePath 9558 + " and requiring known paths " + known.codePathString 9559 + " & " + known.resourcePathString); 9560 } 9561 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 9562 || !pkg.applicationInfo.getResourcePath().equals( 9563 known.resourcePathString)) { 9564 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 9565 "Application package " + pkg.packageName 9566 + " found at " + pkg.applicationInfo.getCodePath() 9567 + " but expected at " + known.codePathString 9568 + "; ignoring."); 9569 } 9570 } 9571 } 9572 } 9573 9574 // Verify that this new package doesn't have any content providers 9575 // that conflict with existing packages. Only do this if the 9576 // package isn't already installed, since we don't want to break 9577 // things that are installed. 9578 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 9579 final int N = pkg.providers.size(); 9580 int i; 9581 for (i=0; i<N; i++) { 9582 PackageParser.Provider p = pkg.providers.get(i); 9583 if (p.info.authority != null) { 9584 String names[] = p.info.authority.split(";"); 9585 for (int j = 0; j < names.length; j++) { 9586 if (mProvidersByAuthority.containsKey(names[j])) { 9587 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 9588 final String otherPackageName = 9589 ((other != null && other.getComponentName() != null) ? 9590 other.getComponentName().getPackageName() : "?"); 9591 throw new PackageManagerException( 9592 INSTALL_FAILED_CONFLICTING_PROVIDER, 9593 "Can't install because provider name " + names[j] 9594 + " (in package " + pkg.applicationInfo.packageName 9595 + ") is already used by " + otherPackageName); 9596 } 9597 } 9598 } 9599 } 9600 } 9601 } 9602 } 9603 9604 private boolean addSharedLibraryLPw(String path, String apk, String name, int version, 9605 int type, String declaringPackageName, int declaringVersionCode) { 9606 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 9607 if (versionedLib == null) { 9608 versionedLib = new SparseArray<>(); 9609 mSharedLibraries.put(name, versionedLib); 9610 if (type == SharedLibraryInfo.TYPE_STATIC) { 9611 mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib); 9612 } 9613 } else if (versionedLib.indexOfKey(version) >= 0) { 9614 return false; 9615 } 9616 SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name, 9617 version, type, declaringPackageName, declaringVersionCode); 9618 versionedLib.put(version, libEntry); 9619 return true; 9620 } 9621 9622 private boolean removeSharedLibraryLPw(String name, int version) { 9623 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 9624 if (versionedLib == null) { 9625 return false; 9626 } 9627 final int libIdx = versionedLib.indexOfKey(version); 9628 if (libIdx < 0) { 9629 return false; 9630 } 9631 SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx); 9632 versionedLib.remove(version); 9633 if (versionedLib.size() <= 0) { 9634 mSharedLibraries.remove(name); 9635 if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) { 9636 mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage() 9637 .getPackageName()); 9638 } 9639 } 9640 return true; 9641 } 9642 9643 /** 9644 * Adds a scanned package to the system. When this method is finished, the package will 9645 * be available for query, resolution, etc... 9646 */ 9647 private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting, 9648 UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException { 9649 final String pkgName = pkg.packageName; 9650 if (mCustomResolverComponentName != null && 9651 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 9652 setUpCustomResolverActivity(pkg); 9653 } 9654 9655 if (pkg.packageName.equals("android")) { 9656 synchronized (mPackages) { 9657 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 9658 // Set up information for our fall-back user intent resolution activity. 9659 mPlatformPackage = pkg; 9660 pkg.mVersionCode = mSdkVersion; 9661 mAndroidApplication = pkg.applicationInfo; 9662 9663 if (!mResolverReplaced) { 9664 mResolveActivity.applicationInfo = mAndroidApplication; 9665 mResolveActivity.name = ResolverActivity.class.getName(); 9666 mResolveActivity.packageName = mAndroidApplication.packageName; 9667 mResolveActivity.processName = "system:ui"; 9668 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9669 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 9670 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 9671 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 9672 mResolveActivity.exported = true; 9673 mResolveActivity.enabled = true; 9674 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 9675 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 9676 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 9677 | ActivityInfo.CONFIG_SCREEN_LAYOUT 9678 | ActivityInfo.CONFIG_ORIENTATION 9679 | ActivityInfo.CONFIG_KEYBOARD 9680 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 9681 mResolveInfo.activityInfo = mResolveActivity; 9682 mResolveInfo.priority = 0; 9683 mResolveInfo.preferredOrder = 0; 9684 mResolveInfo.match = 0; 9685 mResolveComponentName = new ComponentName( 9686 mAndroidApplication.packageName, mResolveActivity.name); 9687 } 9688 } 9689 } 9690 } 9691 9692 ArrayList<PackageParser.Package> clientLibPkgs = null; 9693 // writer 9694 synchronized (mPackages) { 9695 boolean hasStaticSharedLibs = false; 9696 9697 // Any app can add new static shared libraries 9698 if (pkg.staticSharedLibName != null) { 9699 // Static shared libs don't allow renaming as they have synthetic package 9700 // names to allow install of multiple versions, so use name from manifest. 9701 if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName, 9702 pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC, 9703 pkg.manifestPackageName, pkg.mVersionCode)) { 9704 hasStaticSharedLibs = true; 9705 } else { 9706 Slog.w(TAG, "Package " + pkg.packageName + " library " 9707 + pkg.staticSharedLibName + " already exists; skipping"); 9708 } 9709 // Static shared libs cannot be updated once installed since they 9710 // use synthetic package name which includes the version code, so 9711 // not need to update other packages's shared lib dependencies. 9712 } 9713 9714 if (!hasStaticSharedLibs 9715 && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 9716 // Only system apps can add new dynamic shared libraries. 9717 if (pkg.libraryNames != null) { 9718 for (int i = 0; i < pkg.libraryNames.size(); i++) { 9719 String name = pkg.libraryNames.get(i); 9720 boolean allowed = false; 9721 if (pkg.isUpdatedSystemApp()) { 9722 // New library entries can only be added through the 9723 // system image. This is important to get rid of a lot 9724 // of nasty edge cases: for example if we allowed a non- 9725 // system update of the app to add a library, then uninstalling 9726 // the update would make the library go away, and assumptions 9727 // we made such as through app install filtering would now 9728 // have allowed apps on the device which aren't compatible 9729 // with it. Better to just have the restriction here, be 9730 // conservative, and create many fewer cases that can negatively 9731 // impact the user experience. 9732 final PackageSetting sysPs = mSettings 9733 .getDisabledSystemPkgLPr(pkg.packageName); 9734 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 9735 for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) { 9736 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 9737 allowed = true; 9738 break; 9739 } 9740 } 9741 } 9742 } else { 9743 allowed = true; 9744 } 9745 if (allowed) { 9746 if (!addSharedLibraryLPw(null, pkg.packageName, name, 9747 SharedLibraryInfo.VERSION_UNDEFINED, 9748 SharedLibraryInfo.TYPE_DYNAMIC, 9749 pkg.packageName, pkg.mVersionCode)) { 9750 Slog.w(TAG, "Package " + pkg.packageName + " library " 9751 + name + " already exists; skipping"); 9752 } 9753 } else { 9754 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 9755 + name + " that is not declared on system image; skipping"); 9756 } 9757 } 9758 9759 if ((scanFlags & SCAN_BOOTING) == 0) { 9760 // If we are not booting, we need to update any applications 9761 // that are clients of our shared library. If we are booting, 9762 // this will all be done once the scan is complete. 9763 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 9764 } 9765 } 9766 } 9767 } 9768 9769 if ((scanFlags & SCAN_BOOTING) != 0) { 9770 // No apps can run during boot scan, so they don't need to be frozen 9771 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 9772 // Caller asked to not kill app, so it's probably not frozen 9773 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 9774 // Caller asked us to ignore frozen check for some reason; they 9775 // probably didn't know the package name 9776 } else { 9777 // We're doing major surgery on this package, so it better be frozen 9778 // right now to keep it from launching 9779 checkPackageFrozen(pkgName); 9780 } 9781 9782 // Also need to kill any apps that are dependent on the library. 9783 if (clientLibPkgs != null) { 9784 for (int i=0; i<clientLibPkgs.size(); i++) { 9785 PackageParser.Package clientPkg = clientLibPkgs.get(i); 9786 killApplication(clientPkg.applicationInfo.packageName, 9787 clientPkg.applicationInfo.uid, "update lib"); 9788 } 9789 } 9790 9791 // writer 9792 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 9793 9794 boolean createIdmapFailed = false; 9795 synchronized (mPackages) { 9796 // We don't expect installation to fail beyond this point 9797 9798 if (pkgSetting.pkg != null) { 9799 // Note that |user| might be null during the initial boot scan. If a codePath 9800 // for an app has changed during a boot scan, it's due to an app update that's 9801 // part of the system partition and marker changes must be applied to all users. 9802 final int userId = ((user != null) ? user : UserHandle.ALL).getIdentifier(); 9803 final int[] userIds = resolveUserIds(userId); 9804 maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg, userIds); 9805 } 9806 9807 // Add the new setting to mSettings 9808 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 9809 // Add the new setting to mPackages 9810 mPackages.put(pkg.applicationInfo.packageName, pkg); 9811 // Make sure we don't accidentally delete its data. 9812 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 9813 while (iter.hasNext()) { 9814 PackageCleanItem item = iter.next(); 9815 if (pkgName.equals(item.packageName)) { 9816 iter.remove(); 9817 } 9818 } 9819 9820 // Add the package's KeySets to the global KeySetManagerService 9821 KeySetManagerService ksms = mSettings.mKeySetManagerService; 9822 ksms.addScannedPackageLPw(pkg); 9823 9824 int N = pkg.providers.size(); 9825 StringBuilder r = null; 9826 int i; 9827 for (i=0; i<N; i++) { 9828 PackageParser.Provider p = pkg.providers.get(i); 9829 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 9830 p.info.processName); 9831 mProviders.addProvider(p); 9832 p.syncable = p.info.isSyncable; 9833 if (p.info.authority != null) { 9834 String names[] = p.info.authority.split(";"); 9835 p.info.authority = null; 9836 for (int j = 0; j < names.length; j++) { 9837 if (j == 1 && p.syncable) { 9838 // We only want the first authority for a provider to possibly be 9839 // syncable, so if we already added this provider using a different 9840 // authority clear the syncable flag. We copy the provider before 9841 // changing it because the mProviders object contains a reference 9842 // to a provider that we don't want to change. 9843 // Only do this for the second authority since the resulting provider 9844 // object can be the same for all future authorities for this provider. 9845 p = new PackageParser.Provider(p); 9846 p.syncable = false; 9847 } 9848 if (!mProvidersByAuthority.containsKey(names[j])) { 9849 mProvidersByAuthority.put(names[j], p); 9850 if (p.info.authority == null) { 9851 p.info.authority = names[j]; 9852 } else { 9853 p.info.authority = p.info.authority + ";" + names[j]; 9854 } 9855 if (DEBUG_PACKAGE_SCANNING) { 9856 if (chatty) 9857 Log.d(TAG, "Registered content provider: " + names[j] 9858 + ", className = " + p.info.name + ", isSyncable = " 9859 + p.info.isSyncable); 9860 } 9861 } else { 9862 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 9863 Slog.w(TAG, "Skipping provider name " + names[j] + 9864 " (in package " + pkg.applicationInfo.packageName + 9865 "): name already used by " 9866 + ((other != null && other.getComponentName() != null) 9867 ? other.getComponentName().getPackageName() : "?")); 9868 } 9869 } 9870 } 9871 if (chatty) { 9872 if (r == null) { 9873 r = new StringBuilder(256); 9874 } else { 9875 r.append(' '); 9876 } 9877 r.append(p.info.name); 9878 } 9879 } 9880 if (r != null) { 9881 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 9882 } 9883 9884 N = pkg.services.size(); 9885 r = null; 9886 for (i=0; i<N; i++) { 9887 PackageParser.Service s = pkg.services.get(i); 9888 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 9889 s.info.processName); 9890 mServices.addService(s); 9891 if (chatty) { 9892 if (r == null) { 9893 r = new StringBuilder(256); 9894 } else { 9895 r.append(' '); 9896 } 9897 r.append(s.info.name); 9898 } 9899 } 9900 if (r != null) { 9901 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 9902 } 9903 9904 N = pkg.receivers.size(); 9905 r = null; 9906 for (i=0; i<N; i++) { 9907 PackageParser.Activity a = pkg.receivers.get(i); 9908 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 9909 a.info.processName); 9910 mReceivers.addActivity(a, "receiver"); 9911 if (chatty) { 9912 if (r == null) { 9913 r = new StringBuilder(256); 9914 } else { 9915 r.append(' '); 9916 } 9917 r.append(a.info.name); 9918 } 9919 } 9920 if (r != null) { 9921 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 9922 } 9923 9924 N = pkg.activities.size(); 9925 r = null; 9926 for (i=0; i<N; i++) { 9927 PackageParser.Activity a = pkg.activities.get(i); 9928 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 9929 a.info.processName); 9930 mActivities.addActivity(a, "activity"); 9931 if (chatty) { 9932 if (r == null) { 9933 r = new StringBuilder(256); 9934 } else { 9935 r.append(' '); 9936 } 9937 r.append(a.info.name); 9938 } 9939 } 9940 if (r != null) { 9941 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 9942 } 9943 9944 N = pkg.permissionGroups.size(); 9945 r = null; 9946 for (i=0; i<N; i++) { 9947 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 9948 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 9949 final String curPackageName = cur == null ? null : cur.info.packageName; 9950 // Dont allow ephemeral apps to define new permission groups. 9951 if (pkg.applicationInfo.isEphemeralApp()) { 9952 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 9953 + pg.info.packageName 9954 + " ignored: ephemeral apps cannot define new permission groups."); 9955 continue; 9956 } 9957 final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName); 9958 if (cur == null || isPackageUpdate) { 9959 mPermissionGroups.put(pg.info.name, pg); 9960 if (chatty) { 9961 if (r == null) { 9962 r = new StringBuilder(256); 9963 } else { 9964 r.append(' '); 9965 } 9966 if (isPackageUpdate) { 9967 r.append("UPD:"); 9968 } 9969 r.append(pg.info.name); 9970 } 9971 } else { 9972 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 9973 + pg.info.packageName + " ignored: original from " 9974 + cur.info.packageName); 9975 if (chatty) { 9976 if (r == null) { 9977 r = new StringBuilder(256); 9978 } else { 9979 r.append(' '); 9980 } 9981 r.append("DUP:"); 9982 r.append(pg.info.name); 9983 } 9984 } 9985 } 9986 if (r != null) { 9987 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 9988 } 9989 9990 N = pkg.permissions.size(); 9991 r = null; 9992 for (i=0; i<N; i++) { 9993 PackageParser.Permission p = pkg.permissions.get(i); 9994 9995 // Dont allow ephemeral apps to define new permissions. 9996 if (pkg.applicationInfo.isEphemeralApp()) { 9997 Slog.w(TAG, "Permission " + p.info.name + " from package " 9998 + p.info.packageName 9999 + " ignored: ephemeral apps cannot define new permissions."); 10000 continue; 10001 } 10002 10003 // Assume by default that we did not install this permission into the system. 10004 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 10005 10006 // Now that permission groups have a special meaning, we ignore permission 10007 // groups for legacy apps to prevent unexpected behavior. In particular, 10008 // permissions for one app being granted to someone just becase they happen 10009 // to be in a group defined by another app (before this had no implications). 10010 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 10011 p.group = mPermissionGroups.get(p.info.group); 10012 // Warn for a permission in an unknown group. 10013 if (p.info.group != null && p.group == null) { 10014 Slog.w(TAG, "Permission " + p.info.name + " from package " 10015 + p.info.packageName + " in an unknown group " + p.info.group); 10016 } 10017 } 10018 10019 ArrayMap<String, BasePermission> permissionMap = 10020 p.tree ? mSettings.mPermissionTrees 10021 : mSettings.mPermissions; 10022 BasePermission bp = permissionMap.get(p.info.name); 10023 10024 // Allow system apps to redefine non-system permissions 10025 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 10026 final boolean currentOwnerIsSystem = (bp.perm != null 10027 && isSystemApp(bp.perm.owner)); 10028 if (isSystemApp(p.owner)) { 10029 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 10030 // It's a built-in permission and no owner, take ownership now 10031 bp.packageSetting = pkgSetting; 10032 bp.perm = p; 10033 bp.uid = pkg.applicationInfo.uid; 10034 bp.sourcePackage = p.info.packageName; 10035 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 10036 } else if (!currentOwnerIsSystem) { 10037 String msg = "New decl " + p.owner + " of permission " 10038 + p.info.name + " is system; overriding " + bp.sourcePackage; 10039 reportSettingsProblem(Log.WARN, msg); 10040 bp = null; 10041 } 10042 } 10043 } 10044 10045 if (bp == null) { 10046 bp = new BasePermission(p.info.name, p.info.packageName, 10047 BasePermission.TYPE_NORMAL); 10048 permissionMap.put(p.info.name, bp); 10049 } 10050 10051 if (bp.perm == null) { 10052 if (bp.sourcePackage == null 10053 || bp.sourcePackage.equals(p.info.packageName)) { 10054 BasePermission tree = findPermissionTreeLP(p.info.name); 10055 if (tree == null 10056 || tree.sourcePackage.equals(p.info.packageName)) { 10057 bp.packageSetting = pkgSetting; 10058 bp.perm = p; 10059 bp.uid = pkg.applicationInfo.uid; 10060 bp.sourcePackage = p.info.packageName; 10061 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 10062 if (chatty) { 10063 if (r == null) { 10064 r = new StringBuilder(256); 10065 } else { 10066 r.append(' '); 10067 } 10068 r.append(p.info.name); 10069 } 10070 } else { 10071 Slog.w(TAG, "Permission " + p.info.name + " from package " 10072 + p.info.packageName + " ignored: base tree " 10073 + tree.name + " is from package " 10074 + tree.sourcePackage); 10075 } 10076 } else { 10077 Slog.w(TAG, "Permission " + p.info.name + " from package " 10078 + p.info.packageName + " ignored: original from " 10079 + bp.sourcePackage); 10080 } 10081 } else if (chatty) { 10082 if (r == null) { 10083 r = new StringBuilder(256); 10084 } else { 10085 r.append(' '); 10086 } 10087 r.append("DUP:"); 10088 r.append(p.info.name); 10089 } 10090 if (bp.perm == p) { 10091 bp.protectionLevel = p.info.protectionLevel; 10092 } 10093 } 10094 10095 if (r != null) { 10096 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 10097 } 10098 10099 N = pkg.instrumentation.size(); 10100 r = null; 10101 for (i=0; i<N; i++) { 10102 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 10103 a.info.packageName = pkg.applicationInfo.packageName; 10104 a.info.sourceDir = pkg.applicationInfo.sourceDir; 10105 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 10106 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 10107 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 10108 a.info.dataDir = pkg.applicationInfo.dataDir; 10109 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 10110 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 10111 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 10112 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 10113 mInstrumentation.put(a.getComponentName(), a); 10114 if (chatty) { 10115 if (r == null) { 10116 r = new StringBuilder(256); 10117 } else { 10118 r.append(' '); 10119 } 10120 r.append(a.info.name); 10121 } 10122 } 10123 if (r != null) { 10124 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 10125 } 10126 10127 if (pkg.protectedBroadcasts != null) { 10128 N = pkg.protectedBroadcasts.size(); 10129 for (i=0; i<N; i++) { 10130 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 10131 } 10132 } 10133 10134 // Create idmap files for pairs of (packages, overlay packages). 10135 // Note: "android", ie framework-res.apk, is handled by native layers. 10136 if (pkg.mOverlayTarget != null) { 10137 // This is an overlay package. 10138 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 10139 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 10140 mOverlays.put(pkg.mOverlayTarget, 10141 new ArrayMap<String, PackageParser.Package>()); 10142 } 10143 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 10144 map.put(pkg.packageName, pkg); 10145 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 10146 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 10147 createIdmapFailed = true; 10148 } 10149 } 10150 } else if (mOverlays.containsKey(pkg.packageName) && 10151 !pkg.packageName.equals("android")) { 10152 // This is a regular package, with one or more known overlay packages. 10153 createIdmapsForPackageLI(pkg); 10154 } 10155 } 10156 10157 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10158 10159 if (createIdmapFailed) { 10160 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 10161 "scanPackageLI failed to createIdmap"); 10162 } 10163 } 10164 10165 private static void maybeRenameForeignDexMarkers(PackageParser.Package existing, 10166 PackageParser.Package update, int[] userIds) { 10167 if (existing.applicationInfo == null || update.applicationInfo == null) { 10168 // This isn't due to an app installation. 10169 return; 10170 } 10171 10172 final File oldCodePath = new File(existing.applicationInfo.getCodePath()); 10173 final File newCodePath = new File(update.applicationInfo.getCodePath()); 10174 10175 // The codePath hasn't changed, so there's nothing for us to do. 10176 if (Objects.equals(oldCodePath, newCodePath)) { 10177 return; 10178 } 10179 10180 File canonicalNewCodePath; 10181 try { 10182 canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath)); 10183 } catch (IOException e) { 10184 Slog.w(TAG, "Failed to get canonical path.", e); 10185 return; 10186 } 10187 10188 // This is a bit of a hack. The oldCodePath doesn't exist at this point (because 10189 // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume 10190 // that the last component of the path (i.e, the name) doesn't need canonicalization 10191 // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now 10192 // but may change in the future. Hopefully this function won't exist at that point. 10193 final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(), 10194 oldCodePath.getName()); 10195 10196 // Calculate the prefixes of the markers. These are just the paths with "/" replaced 10197 // with "@". 10198 String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@'); 10199 if (!oldMarkerPrefix.endsWith("@")) { 10200 oldMarkerPrefix += "@"; 10201 } 10202 String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@'); 10203 if (!newMarkerPrefix.endsWith("@")) { 10204 newMarkerPrefix += "@"; 10205 } 10206 10207 List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly(); 10208 List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size()); 10209 for (String updatedPath : updatedPaths) { 10210 String updatedPathName = new File(updatedPath).getName(); 10211 markerSuffixes.add(updatedPathName.replace('/', '@')); 10212 } 10213 10214 for (int userId : userIds) { 10215 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId); 10216 10217 for (String markerSuffix : markerSuffixes) { 10218 File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix); 10219 File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix); 10220 if (oldForeignUseMark.exists()) { 10221 try { 10222 Os.rename(oldForeignUseMark.getAbsolutePath(), 10223 newForeignUseMark.getAbsolutePath()); 10224 } catch (ErrnoException e) { 10225 Slog.w(TAG, "Failed to rename foreign use marker", e); 10226 oldForeignUseMark.delete(); 10227 } 10228 } 10229 } 10230 } 10231 } 10232 10233 /** 10234 * Derive the ABI of a non-system package located at {@code scanFile}. This information 10235 * is derived purely on the basis of the contents of {@code scanFile} and 10236 * {@code cpuAbiOverride}. 10237 * 10238 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 10239 */ 10240 private static void derivePackageAbi(PackageParser.Package pkg, File scanFile, 10241 String cpuAbiOverride, boolean extractLibs, 10242 File appLib32InstallDir) 10243 throws PackageManagerException { 10244 // Give ourselves some initial paths; we'll come back for another 10245 // pass once we've determined ABI below. 10246 setNativeLibraryPaths(pkg, appLib32InstallDir); 10247 10248 // We would never need to extract libs for forward-locked and external packages, 10249 // since the container service will do it for us. We shouldn't attempt to 10250 // extract libs from system app when it was not updated. 10251 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 10252 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 10253 extractLibs = false; 10254 } 10255 10256 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 10257 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 10258 10259 NativeLibraryHelper.Handle handle = null; 10260 try { 10261 handle = NativeLibraryHelper.Handle.create(pkg); 10262 // TODO(multiArch): This can be null for apps that didn't go through the 10263 // usual installation process. We can calculate it again, like we 10264 // do during install time. 10265 // 10266 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 10267 // unnecessary. 10268 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 10269 10270 // Null out the abis so that they can be recalculated. 10271 pkg.applicationInfo.primaryCpuAbi = null; 10272 pkg.applicationInfo.secondaryCpuAbi = null; 10273 if (isMultiArch(pkg.applicationInfo)) { 10274 // Warn if we've set an abiOverride for multi-lib packages.. 10275 // By definition, we need to copy both 32 and 64 bit libraries for 10276 // such packages. 10277 if (pkg.cpuAbiOverride != null 10278 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 10279 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 10280 } 10281 10282 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 10283 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 10284 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 10285 if (extractLibs) { 10286 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 10287 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 10288 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 10289 useIsaSpecificSubdirs); 10290 } else { 10291 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 10292 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 10293 } 10294 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10295 } 10296 10297 maybeThrowExceptionForMultiArchCopy( 10298 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 10299 10300 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 10301 if (extractLibs) { 10302 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 10303 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 10304 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 10305 useIsaSpecificSubdirs); 10306 } else { 10307 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 10308 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 10309 } 10310 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10311 } 10312 10313 maybeThrowExceptionForMultiArchCopy( 10314 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 10315 10316 if (abi64 >= 0) { 10317 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 10318 } 10319 10320 if (abi32 >= 0) { 10321 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 10322 if (abi64 >= 0) { 10323 if (pkg.use32bitAbi) { 10324 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 10325 pkg.applicationInfo.primaryCpuAbi = abi; 10326 } else { 10327 pkg.applicationInfo.secondaryCpuAbi = abi; 10328 } 10329 } else { 10330 pkg.applicationInfo.primaryCpuAbi = abi; 10331 } 10332 } 10333 10334 } else { 10335 String[] abiList = (cpuAbiOverride != null) ? 10336 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 10337 10338 // Enable gross and lame hacks for apps that are built with old 10339 // SDK tools. We must scan their APKs for renderscript bitcode and 10340 // not launch them if it's present. Don't bother checking on devices 10341 // that don't have 64 bit support. 10342 boolean needsRenderScriptOverride = false; 10343 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 10344 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 10345 abiList = Build.SUPPORTED_32_BIT_ABIS; 10346 needsRenderScriptOverride = true; 10347 } 10348 10349 final int copyRet; 10350 if (extractLibs) { 10351 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 10352 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 10353 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 10354 } else { 10355 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 10356 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 10357 } 10358 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10359 10360 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 10361 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 10362 "Error unpackaging native libs for app, errorCode=" + copyRet); 10363 } 10364 10365 if (copyRet >= 0) { 10366 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 10367 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 10368 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 10369 } else if (needsRenderScriptOverride) { 10370 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 10371 } 10372 } 10373 } catch (IOException ioe) { 10374 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 10375 } finally { 10376 IoUtils.closeQuietly(handle); 10377 } 10378 10379 // Now that we've calculated the ABIs and determined if it's an internal app, 10380 // we will go ahead and populate the nativeLibraryPath. 10381 setNativeLibraryPaths(pkg, appLib32InstallDir); 10382 } 10383 10384 /** 10385 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 10386 * i.e, so that all packages can be run inside a single process if required. 10387 * 10388 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 10389 * this function will either try and make the ABI for all packages in {@code packagesForUser} 10390 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 10391 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 10392 * updating a package that belongs to a shared user. 10393 * 10394 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 10395 * adds unnecessary complexity. 10396 */ 10397 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 10398 PackageParser.Package scannedPackage) { 10399 String requiredInstructionSet = null; 10400 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 10401 requiredInstructionSet = VMRuntime.getInstructionSet( 10402 scannedPackage.applicationInfo.primaryCpuAbi); 10403 } 10404 10405 PackageSetting requirer = null; 10406 for (PackageSetting ps : packagesForUser) { 10407 // If packagesForUser contains scannedPackage, we skip it. This will happen 10408 // when scannedPackage is an update of an existing package. Without this check, 10409 // we will never be able to change the ABI of any package belonging to a shared 10410 // user, even if it's compatible with other packages. 10411 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 10412 if (ps.primaryCpuAbiString == null) { 10413 continue; 10414 } 10415 10416 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 10417 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 10418 // We have a mismatch between instruction sets (say arm vs arm64) warn about 10419 // this but there's not much we can do. 10420 String errorMessage = "Instruction set mismatch, " 10421 + ((requirer == null) ? "[caller]" : requirer) 10422 + " requires " + requiredInstructionSet + " whereas " + ps 10423 + " requires " + instructionSet; 10424 Slog.w(TAG, errorMessage); 10425 } 10426 10427 if (requiredInstructionSet == null) { 10428 requiredInstructionSet = instructionSet; 10429 requirer = ps; 10430 } 10431 } 10432 } 10433 10434 if (requiredInstructionSet != null) { 10435 String adjustedAbi; 10436 if (requirer != null) { 10437 // requirer != null implies that either scannedPackage was null or that scannedPackage 10438 // did not require an ABI, in which case we have to adjust scannedPackage to match 10439 // the ABI of the set (which is the same as requirer's ABI) 10440 adjustedAbi = requirer.primaryCpuAbiString; 10441 if (scannedPackage != null) { 10442 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 10443 } 10444 } else { 10445 // requirer == null implies that we're updating all ABIs in the set to 10446 // match scannedPackage. 10447 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 10448 } 10449 10450 for (PackageSetting ps : packagesForUser) { 10451 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 10452 if (ps.primaryCpuAbiString != null) { 10453 continue; 10454 } 10455 10456 ps.primaryCpuAbiString = adjustedAbi; 10457 if (ps.pkg != null && ps.pkg.applicationInfo != null && 10458 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 10459 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 10460 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 10461 + " (requirer=" 10462 + (requirer == null ? "null" : requirer.pkg.packageName) 10463 + ", scannedPackage=" 10464 + (scannedPackage != null ? scannedPackage.packageName : "null") 10465 + ")"); 10466 try { 10467 mInstaller.rmdex(ps.codePathString, 10468 getDexCodeInstructionSet(getPreferredInstructionSet())); 10469 } catch (InstallerException ignored) { 10470 } 10471 } 10472 } 10473 } 10474 } 10475 } 10476 10477 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 10478 synchronized (mPackages) { 10479 mResolverReplaced = true; 10480 // Set up information for custom user intent resolution activity. 10481 mResolveActivity.applicationInfo = pkg.applicationInfo; 10482 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 10483 mResolveActivity.packageName = pkg.applicationInfo.packageName; 10484 mResolveActivity.processName = pkg.applicationInfo.packageName; 10485 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 10486 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 10487 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 10488 mResolveActivity.theme = 0; 10489 mResolveActivity.exported = true; 10490 mResolveActivity.enabled = true; 10491 mResolveInfo.activityInfo = mResolveActivity; 10492 mResolveInfo.priority = 0; 10493 mResolveInfo.preferredOrder = 0; 10494 mResolveInfo.match = 0; 10495 mResolveComponentName = mCustomResolverComponentName; 10496 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 10497 mResolveComponentName); 10498 } 10499 } 10500 10501 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 10502 if (installerComponent == null) { 10503 if (DEBUG_EPHEMERAL) { 10504 Slog.d(TAG, "Clear ephemeral installer activity"); 10505 } 10506 mEphemeralInstallerActivity.applicationInfo = null; 10507 return; 10508 } 10509 10510 if (DEBUG_EPHEMERAL) { 10511 Slog.d(TAG, "Set ephemeral installer activity: " + installerComponent); 10512 } 10513 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 10514 // Set up information for ephemeral installer activity 10515 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 10516 mEphemeralInstallerActivity.name = installerComponent.getClassName(); 10517 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 10518 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 10519 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 10520 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS 10521 | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 10522 mEphemeralInstallerActivity.theme = 0; 10523 mEphemeralInstallerActivity.exported = true; 10524 mEphemeralInstallerActivity.enabled = true; 10525 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 10526 mEphemeralInstallerInfo.priority = 0; 10527 mEphemeralInstallerInfo.preferredOrder = 1; 10528 mEphemeralInstallerInfo.isDefault = true; 10529 mEphemeralInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 10530 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 10531 } 10532 10533 private static String calculateBundledApkRoot(final String codePathString) { 10534 final File codePath = new File(codePathString); 10535 final File codeRoot; 10536 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 10537 codeRoot = Environment.getRootDirectory(); 10538 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 10539 codeRoot = Environment.getOemDirectory(); 10540 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 10541 codeRoot = Environment.getVendorDirectory(); 10542 } else { 10543 // Unrecognized code path; take its top real segment as the apk root: 10544 // e.g. /something/app/blah.apk => /something 10545 try { 10546 File f = codePath.getCanonicalFile(); 10547 File parent = f.getParentFile(); // non-null because codePath is a file 10548 File tmp; 10549 while ((tmp = parent.getParentFile()) != null) { 10550 f = parent; 10551 parent = tmp; 10552 } 10553 codeRoot = f; 10554 Slog.w(TAG, "Unrecognized code path " 10555 + codePath + " - using " + codeRoot); 10556 } catch (IOException e) { 10557 // Can't canonicalize the code path -- shenanigans? 10558 Slog.w(TAG, "Can't canonicalize code path " + codePath); 10559 return Environment.getRootDirectory().getPath(); 10560 } 10561 } 10562 return codeRoot.getPath(); 10563 } 10564 10565 /** 10566 * Derive and set the location of native libraries for the given package, 10567 * which varies depending on where and how the package was installed. 10568 */ 10569 private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) { 10570 final ApplicationInfo info = pkg.applicationInfo; 10571 final String codePath = pkg.codePath; 10572 final File codeFile = new File(codePath); 10573 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 10574 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 10575 10576 info.nativeLibraryRootDir = null; 10577 info.nativeLibraryRootRequiresIsa = false; 10578 info.nativeLibraryDir = null; 10579 info.secondaryNativeLibraryDir = null; 10580 10581 if (isApkFile(codeFile)) { 10582 // Monolithic install 10583 if (bundledApp) { 10584 // If "/system/lib64/apkname" exists, assume that is the per-package 10585 // native library directory to use; otherwise use "/system/lib/apkname". 10586 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 10587 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 10588 getPrimaryInstructionSet(info)); 10589 10590 // This is a bundled system app so choose the path based on the ABI. 10591 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 10592 // is just the default path. 10593 final String apkName = deriveCodePathName(codePath); 10594 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 10595 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 10596 apkName).getAbsolutePath(); 10597 10598 if (info.secondaryCpuAbi != null) { 10599 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 10600 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 10601 secondaryLibDir, apkName).getAbsolutePath(); 10602 } 10603 } else if (asecApp) { 10604 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 10605 .getAbsolutePath(); 10606 } else { 10607 final String apkName = deriveCodePathName(codePath); 10608 info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName) 10609 .getAbsolutePath(); 10610 } 10611 10612 info.nativeLibraryRootRequiresIsa = false; 10613 info.nativeLibraryDir = info.nativeLibraryRootDir; 10614 } else { 10615 // Cluster install 10616 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 10617 info.nativeLibraryRootRequiresIsa = true; 10618 10619 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 10620 getPrimaryInstructionSet(info)).getAbsolutePath(); 10621 10622 if (info.secondaryCpuAbi != null) { 10623 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 10624 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 10625 } 10626 } 10627 } 10628 10629 /** 10630 * Calculate the abis and roots for a bundled app. These can uniquely 10631 * be determined from the contents of the system partition, i.e whether 10632 * it contains 64 or 32 bit shared libraries etc. We do not validate any 10633 * of this information, and instead assume that the system was built 10634 * sensibly. 10635 */ 10636 private static void setBundledAppAbisAndRoots(PackageParser.Package pkg, 10637 PackageSetting pkgSetting) { 10638 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 10639 10640 // If "/system/lib64/apkname" exists, assume that is the per-package 10641 // native library directory to use; otherwise use "/system/lib/apkname". 10642 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 10643 setBundledAppAbi(pkg, apkRoot, apkName); 10644 // pkgSetting might be null during rescan following uninstall of updates 10645 // to a bundled app, so accommodate that possibility. The settings in 10646 // that case will be established later from the parsed package. 10647 // 10648 // If the settings aren't null, sync them up with what we've just derived. 10649 // note that apkRoot isn't stored in the package settings. 10650 if (pkgSetting != null) { 10651 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 10652 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 10653 } 10654 } 10655 10656 /** 10657 * Deduces the ABI of a bundled app and sets the relevant fields on the 10658 * parsed pkg object. 10659 * 10660 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 10661 * under which system libraries are installed. 10662 * @param apkName the name of the installed package. 10663 */ 10664 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 10665 final File codeFile = new File(pkg.codePath); 10666 10667 final boolean has64BitLibs; 10668 final boolean has32BitLibs; 10669 if (isApkFile(codeFile)) { 10670 // Monolithic install 10671 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 10672 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 10673 } else { 10674 // Cluster install 10675 final File rootDir = new File(codeFile, LIB_DIR_NAME); 10676 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 10677 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 10678 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 10679 has64BitLibs = (new File(rootDir, isa)).exists(); 10680 } else { 10681 has64BitLibs = false; 10682 } 10683 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 10684 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 10685 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 10686 has32BitLibs = (new File(rootDir, isa)).exists(); 10687 } else { 10688 has32BitLibs = false; 10689 } 10690 } 10691 10692 if (has64BitLibs && !has32BitLibs) { 10693 // The package has 64 bit libs, but not 32 bit libs. Its primary 10694 // ABI should be 64 bit. We can safely assume here that the bundled 10695 // native libraries correspond to the most preferred ABI in the list. 10696 10697 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 10698 pkg.applicationInfo.secondaryCpuAbi = null; 10699 } else if (has32BitLibs && !has64BitLibs) { 10700 // The package has 32 bit libs but not 64 bit libs. Its primary 10701 // ABI should be 32 bit. 10702 10703 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 10704 pkg.applicationInfo.secondaryCpuAbi = null; 10705 } else if (has32BitLibs && has64BitLibs) { 10706 // The application has both 64 and 32 bit bundled libraries. We check 10707 // here that the app declares multiArch support, and warn if it doesn't. 10708 // 10709 // We will be lenient here and record both ABIs. The primary will be the 10710 // ABI that's higher on the list, i.e, a device that's configured to prefer 10711 // 64 bit apps will see a 64 bit primary ABI, 10712 10713 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 10714 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 10715 } 10716 10717 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 10718 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 10719 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 10720 } else { 10721 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 10722 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 10723 } 10724 } else { 10725 pkg.applicationInfo.primaryCpuAbi = null; 10726 pkg.applicationInfo.secondaryCpuAbi = null; 10727 } 10728 } 10729 10730 private void killApplication(String pkgName, int appId, String reason) { 10731 killApplication(pkgName, appId, UserHandle.USER_ALL, reason); 10732 } 10733 10734 private void killApplication(String pkgName, int appId, int userId, String reason) { 10735 // Request the ActivityManager to kill the process(only for existing packages) 10736 // so that we do not end up in a confused state while the user is still using the older 10737 // version of the application while the new one gets installed. 10738 final long token = Binder.clearCallingIdentity(); 10739 try { 10740 IActivityManager am = ActivityManager.getService(); 10741 if (am != null) { 10742 try { 10743 am.killApplication(pkgName, appId, userId, reason); 10744 } catch (RemoteException e) { 10745 } 10746 } 10747 } finally { 10748 Binder.restoreCallingIdentity(token); 10749 } 10750 } 10751 10752 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 10753 // Remove the parent package setting 10754 PackageSetting ps = (PackageSetting) pkg.mExtras; 10755 if (ps != null) { 10756 removePackageLI(ps, chatty); 10757 } 10758 // Remove the child package setting 10759 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 10760 for (int i = 0; i < childCount; i++) { 10761 PackageParser.Package childPkg = pkg.childPackages.get(i); 10762 ps = (PackageSetting) childPkg.mExtras; 10763 if (ps != null) { 10764 removePackageLI(ps, chatty); 10765 } 10766 } 10767 } 10768 10769 void removePackageLI(PackageSetting ps, boolean chatty) { 10770 if (DEBUG_INSTALL) { 10771 if (chatty) 10772 Log.d(TAG, "Removing package " + ps.name); 10773 } 10774 10775 // writer 10776 synchronized (mPackages) { 10777 mPackages.remove(ps.name); 10778 final PackageParser.Package pkg = ps.pkg; 10779 if (pkg != null) { 10780 cleanPackageDataStructuresLILPw(pkg, chatty); 10781 } 10782 } 10783 } 10784 10785 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 10786 if (DEBUG_INSTALL) { 10787 if (chatty) 10788 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 10789 } 10790 10791 // writer 10792 synchronized (mPackages) { 10793 // Remove the parent package 10794 mPackages.remove(pkg.applicationInfo.packageName); 10795 cleanPackageDataStructuresLILPw(pkg, chatty); 10796 10797 // Remove the child packages 10798 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 10799 for (int i = 0; i < childCount; i++) { 10800 PackageParser.Package childPkg = pkg.childPackages.get(i); 10801 mPackages.remove(childPkg.applicationInfo.packageName); 10802 cleanPackageDataStructuresLILPw(childPkg, chatty); 10803 } 10804 } 10805 } 10806 10807 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 10808 int N = pkg.providers.size(); 10809 StringBuilder r = null; 10810 int i; 10811 for (i=0; i<N; i++) { 10812 PackageParser.Provider p = pkg.providers.get(i); 10813 mProviders.removeProvider(p); 10814 if (p.info.authority == null) { 10815 10816 /* There was another ContentProvider with this authority when 10817 * this app was installed so this authority is null, 10818 * Ignore it as we don't have to unregister the provider. 10819 */ 10820 continue; 10821 } 10822 String names[] = p.info.authority.split(";"); 10823 for (int j = 0; j < names.length; j++) { 10824 if (mProvidersByAuthority.get(names[j]) == p) { 10825 mProvidersByAuthority.remove(names[j]); 10826 if (DEBUG_REMOVE) { 10827 if (chatty) 10828 Log.d(TAG, "Unregistered content provider: " + names[j] 10829 + ", className = " + p.info.name + ", isSyncable = " 10830 + p.info.isSyncable); 10831 } 10832 } 10833 } 10834 if (DEBUG_REMOVE && chatty) { 10835 if (r == null) { 10836 r = new StringBuilder(256); 10837 } else { 10838 r.append(' '); 10839 } 10840 r.append(p.info.name); 10841 } 10842 } 10843 if (r != null) { 10844 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 10845 } 10846 10847 N = pkg.services.size(); 10848 r = null; 10849 for (i=0; i<N; i++) { 10850 PackageParser.Service s = pkg.services.get(i); 10851 mServices.removeService(s); 10852 if (chatty) { 10853 if (r == null) { 10854 r = new StringBuilder(256); 10855 } else { 10856 r.append(' '); 10857 } 10858 r.append(s.info.name); 10859 } 10860 } 10861 if (r != null) { 10862 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 10863 } 10864 10865 N = pkg.receivers.size(); 10866 r = null; 10867 for (i=0; i<N; i++) { 10868 PackageParser.Activity a = pkg.receivers.get(i); 10869 mReceivers.removeActivity(a, "receiver"); 10870 if (DEBUG_REMOVE && chatty) { 10871 if (r == null) { 10872 r = new StringBuilder(256); 10873 } else { 10874 r.append(' '); 10875 } 10876 r.append(a.info.name); 10877 } 10878 } 10879 if (r != null) { 10880 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 10881 } 10882 10883 N = pkg.activities.size(); 10884 r = null; 10885 for (i=0; i<N; i++) { 10886 PackageParser.Activity a = pkg.activities.get(i); 10887 mActivities.removeActivity(a, "activity"); 10888 if (DEBUG_REMOVE && chatty) { 10889 if (r == null) { 10890 r = new StringBuilder(256); 10891 } else { 10892 r.append(' '); 10893 } 10894 r.append(a.info.name); 10895 } 10896 } 10897 if (r != null) { 10898 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 10899 } 10900 10901 N = pkg.permissions.size(); 10902 r = null; 10903 for (i=0; i<N; i++) { 10904 PackageParser.Permission p = pkg.permissions.get(i); 10905 BasePermission bp = mSettings.mPermissions.get(p.info.name); 10906 if (bp == null) { 10907 bp = mSettings.mPermissionTrees.get(p.info.name); 10908 } 10909 if (bp != null && bp.perm == p) { 10910 bp.perm = null; 10911 if (DEBUG_REMOVE && chatty) { 10912 if (r == null) { 10913 r = new StringBuilder(256); 10914 } else { 10915 r.append(' '); 10916 } 10917 r.append(p.info.name); 10918 } 10919 } 10920 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 10921 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 10922 if (appOpPkgs != null) { 10923 appOpPkgs.remove(pkg.packageName); 10924 } 10925 } 10926 } 10927 if (r != null) { 10928 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 10929 } 10930 10931 N = pkg.requestedPermissions.size(); 10932 r = null; 10933 for (i=0; i<N; i++) { 10934 String perm = pkg.requestedPermissions.get(i); 10935 BasePermission bp = mSettings.mPermissions.get(perm); 10936 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 10937 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 10938 if (appOpPkgs != null) { 10939 appOpPkgs.remove(pkg.packageName); 10940 if (appOpPkgs.isEmpty()) { 10941 mAppOpPermissionPackages.remove(perm); 10942 } 10943 } 10944 } 10945 } 10946 if (r != null) { 10947 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 10948 } 10949 10950 N = pkg.instrumentation.size(); 10951 r = null; 10952 for (i=0; i<N; i++) { 10953 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 10954 mInstrumentation.remove(a.getComponentName()); 10955 if (DEBUG_REMOVE && chatty) { 10956 if (r == null) { 10957 r = new StringBuilder(256); 10958 } else { 10959 r.append(' '); 10960 } 10961 r.append(a.info.name); 10962 } 10963 } 10964 if (r != null) { 10965 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 10966 } 10967 10968 r = null; 10969 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 10970 // Only system apps can hold shared libraries. 10971 if (pkg.libraryNames != null) { 10972 for (i = 0; i < pkg.libraryNames.size(); i++) { 10973 String name = pkg.libraryNames.get(i); 10974 if (removeSharedLibraryLPw(name, 0)) { 10975 if (DEBUG_REMOVE && chatty) { 10976 if (r == null) { 10977 r = new StringBuilder(256); 10978 } else { 10979 r.append(' '); 10980 } 10981 r.append(name); 10982 } 10983 } 10984 } 10985 } 10986 } 10987 10988 r = null; 10989 10990 // Any package can hold static shared libraries. 10991 if (pkg.staticSharedLibName != null) { 10992 if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) { 10993 if (DEBUG_REMOVE && chatty) { 10994 if (r == null) { 10995 r = new StringBuilder(256); 10996 } else { 10997 r.append(' '); 10998 } 10999 r.append(pkg.staticSharedLibName); 11000 } 11001 } 11002 } 11003 11004 if (r != null) { 11005 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 11006 } 11007 } 11008 11009 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 11010 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 11011 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 11012 return true; 11013 } 11014 } 11015 return false; 11016 } 11017 11018 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 11019 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 11020 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 11021 11022 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 11023 // Update the parent permissions 11024 updatePermissionsLPw(pkg.packageName, pkg, flags); 11025 // Update the child permissions 11026 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 11027 for (int i = 0; i < childCount; i++) { 11028 PackageParser.Package childPkg = pkg.childPackages.get(i); 11029 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 11030 } 11031 } 11032 11033 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 11034 int flags) { 11035 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 11036 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 11037 } 11038 11039 private void updatePermissionsLPw(String changingPkg, 11040 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 11041 // Make sure there are no dangling permission trees. 11042 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 11043 while (it.hasNext()) { 11044 final BasePermission bp = it.next(); 11045 if (bp.packageSetting == null) { 11046 // We may not yet have parsed the package, so just see if 11047 // we still know about its settings. 11048 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 11049 } 11050 if (bp.packageSetting == null) { 11051 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 11052 + " from package " + bp.sourcePackage); 11053 it.remove(); 11054 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 11055 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 11056 Slog.i(TAG, "Removing old permission tree: " + bp.name 11057 + " from package " + bp.sourcePackage); 11058 flags |= UPDATE_PERMISSIONS_ALL; 11059 it.remove(); 11060 } 11061 } 11062 } 11063 11064 // Make sure all dynamic permissions have been assigned to a package, 11065 // and make sure there are no dangling permissions. 11066 it = mSettings.mPermissions.values().iterator(); 11067 while (it.hasNext()) { 11068 final BasePermission bp = it.next(); 11069 if (bp.type == BasePermission.TYPE_DYNAMIC) { 11070 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 11071 + bp.name + " pkg=" + bp.sourcePackage 11072 + " info=" + bp.pendingInfo); 11073 if (bp.packageSetting == null && bp.pendingInfo != null) { 11074 final BasePermission tree = findPermissionTreeLP(bp.name); 11075 if (tree != null && tree.perm != null) { 11076 bp.packageSetting = tree.packageSetting; 11077 bp.perm = new PackageParser.Permission(tree.perm.owner, 11078 new PermissionInfo(bp.pendingInfo)); 11079 bp.perm.info.packageName = tree.perm.info.packageName; 11080 bp.perm.info.name = bp.name; 11081 bp.uid = tree.uid; 11082 } 11083 } 11084 } 11085 if (bp.packageSetting == null) { 11086 // We may not yet have parsed the package, so just see if 11087 // we still know about its settings. 11088 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 11089 } 11090 if (bp.packageSetting == null) { 11091 Slog.w(TAG, "Removing dangling permission: " + bp.name 11092 + " from package " + bp.sourcePackage); 11093 it.remove(); 11094 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 11095 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 11096 Slog.i(TAG, "Removing old permission: " + bp.name 11097 + " from package " + bp.sourcePackage); 11098 flags |= UPDATE_PERMISSIONS_ALL; 11099 it.remove(); 11100 } 11101 } 11102 } 11103 11104 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 11105 // Now update the permissions for all packages, in particular 11106 // replace the granted permissions of the system packages. 11107 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 11108 for (PackageParser.Package pkg : mPackages.values()) { 11109 if (pkg != pkgInfo) { 11110 // Only replace for packages on requested volume 11111 final String volumeUuid = getVolumeUuidForPackage(pkg); 11112 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 11113 && Objects.equals(replaceVolumeUuid, volumeUuid); 11114 grantPermissionsLPw(pkg, replace, changingPkg); 11115 } 11116 } 11117 } 11118 11119 if (pkgInfo != null) { 11120 // Only replace for packages on requested volume 11121 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 11122 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 11123 && Objects.equals(replaceVolumeUuid, volumeUuid); 11124 grantPermissionsLPw(pkgInfo, replace, changingPkg); 11125 } 11126 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11127 } 11128 11129 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 11130 String packageOfInterest) { 11131 // IMPORTANT: There are two types of permissions: install and runtime. 11132 // Install time permissions are granted when the app is installed to 11133 // all device users and users added in the future. Runtime permissions 11134 // are granted at runtime explicitly to specific users. Normal and signature 11135 // protected permissions are install time permissions. Dangerous permissions 11136 // are install permissions if the app's target SDK is Lollipop MR1 or older, 11137 // otherwise they are runtime permissions. This function does not manage 11138 // runtime permissions except for the case an app targeting Lollipop MR1 11139 // being upgraded to target a newer SDK, in which case dangerous permissions 11140 // are transformed from install time to runtime ones. 11141 11142 final PackageSetting ps = (PackageSetting) pkg.mExtras; 11143 if (ps == null) { 11144 return; 11145 } 11146 11147 PermissionsState permissionsState = ps.getPermissionsState(); 11148 PermissionsState origPermissions = permissionsState; 11149 11150 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 11151 11152 boolean runtimePermissionsRevoked = false; 11153 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 11154 11155 boolean changedInstallPermission = false; 11156 11157 if (replace) { 11158 ps.installPermissionsFixed = false; 11159 if (!ps.isSharedUser()) { 11160 origPermissions = new PermissionsState(permissionsState); 11161 permissionsState.reset(); 11162 } else { 11163 // We need to know only about runtime permission changes since the 11164 // calling code always writes the install permissions state but 11165 // the runtime ones are written only if changed. The only cases of 11166 // changed runtime permissions here are promotion of an install to 11167 // runtime and revocation of a runtime from a shared user. 11168 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 11169 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 11170 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 11171 runtimePermissionsRevoked = true; 11172 } 11173 } 11174 } 11175 11176 permissionsState.setGlobalGids(mGlobalGids); 11177 11178 final int N = pkg.requestedPermissions.size(); 11179 for (int i=0; i<N; i++) { 11180 final String name = pkg.requestedPermissions.get(i); 11181 final BasePermission bp = mSettings.mPermissions.get(name); 11182 11183 if (DEBUG_INSTALL) { 11184 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 11185 } 11186 11187 if (bp == null || bp.packageSetting == null) { 11188 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 11189 Slog.w(TAG, "Unknown permission " + name 11190 + " in package " + pkg.packageName); 11191 } 11192 continue; 11193 } 11194 11195 11196 // Limit ephemeral apps to ephemeral allowed permissions. 11197 if (pkg.applicationInfo.isEphemeralApp() && !bp.isEphemeral()) { 11198 Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package " 11199 + pkg.packageName); 11200 continue; 11201 } 11202 11203 final String perm = bp.name; 11204 boolean allowedSig = false; 11205 int grant = GRANT_DENIED; 11206 11207 // Keep track of app op permissions. 11208 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 11209 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 11210 if (pkgs == null) { 11211 pkgs = new ArraySet<>(); 11212 mAppOpPermissionPackages.put(bp.name, pkgs); 11213 } 11214 pkgs.add(pkg.packageName); 11215 } 11216 11217 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 11218 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 11219 >= Build.VERSION_CODES.M; 11220 switch (level) { 11221 case PermissionInfo.PROTECTION_NORMAL: { 11222 // For all apps normal permissions are install time ones. 11223 grant = GRANT_INSTALL; 11224 } break; 11225 11226 case PermissionInfo.PROTECTION_DANGEROUS: { 11227 // If a permission review is required for legacy apps we represent 11228 // their permissions as always granted runtime ones since we need 11229 // to keep the review required permission flag per user while an 11230 // install permission's state is shared across all users. 11231 if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) { 11232 // For legacy apps dangerous permissions are install time ones. 11233 grant = GRANT_INSTALL; 11234 } else if (origPermissions.hasInstallPermission(bp.name)) { 11235 // For legacy apps that became modern, install becomes runtime. 11236 grant = GRANT_UPGRADE; 11237 } else if (mPromoteSystemApps 11238 && isSystemApp(ps) 11239 && mExistingSystemPackages.contains(ps.name)) { 11240 // For legacy system apps, install becomes runtime. 11241 // We cannot check hasInstallPermission() for system apps since those 11242 // permissions were granted implicitly and not persisted pre-M. 11243 grant = GRANT_UPGRADE; 11244 } else { 11245 // For modern apps keep runtime permissions unchanged. 11246 grant = GRANT_RUNTIME; 11247 } 11248 } break; 11249 11250 case PermissionInfo.PROTECTION_SIGNATURE: { 11251 // For all apps signature permissions are install time ones. 11252 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 11253 if (allowedSig) { 11254 grant = GRANT_INSTALL; 11255 } 11256 } break; 11257 } 11258 11259 if (DEBUG_INSTALL) { 11260 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 11261 } 11262 11263 if (grant != GRANT_DENIED) { 11264 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 11265 // If this is an existing, non-system package, then 11266 // we can't add any new permissions to it. 11267 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 11268 // Except... if this is a permission that was added 11269 // to the platform (note: need to only do this when 11270 // updating the platform). 11271 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 11272 grant = GRANT_DENIED; 11273 } 11274 } 11275 } 11276 11277 switch (grant) { 11278 case GRANT_INSTALL: { 11279 // Revoke this as runtime permission to handle the case of 11280 // a runtime permission being downgraded to an install one. 11281 // Also in permission review mode we keep dangerous permissions 11282 // for legacy apps 11283 for (int userId : UserManagerService.getInstance().getUserIds()) { 11284 if (origPermissions.getRuntimePermissionState( 11285 bp.name, userId) != null) { 11286 // Revoke the runtime permission and clear the flags. 11287 origPermissions.revokeRuntimePermission(bp, userId); 11288 origPermissions.updatePermissionFlags(bp, userId, 11289 PackageManager.MASK_PERMISSION_FLAGS, 0); 11290 // If we revoked a permission permission, we have to write. 11291 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11292 changedRuntimePermissionUserIds, userId); 11293 } 11294 } 11295 // Grant an install permission. 11296 if (permissionsState.grantInstallPermission(bp) != 11297 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11298 changedInstallPermission = true; 11299 } 11300 } break; 11301 11302 case GRANT_RUNTIME: { 11303 // Grant previously granted runtime permissions. 11304 for (int userId : UserManagerService.getInstance().getUserIds()) { 11305 PermissionState permissionState = origPermissions 11306 .getRuntimePermissionState(bp.name, userId); 11307 int flags = permissionState != null 11308 ? permissionState.getFlags() : 0; 11309 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 11310 // Don't propagate the permission in a permission review mode if 11311 // the former was revoked, i.e. marked to not propagate on upgrade. 11312 // Note that in a permission review mode install permissions are 11313 // represented as constantly granted runtime ones since we need to 11314 // keep a per user state associated with the permission. Also the 11315 // revoke on upgrade flag is no longer applicable and is reset. 11316 final boolean revokeOnUpgrade = (flags & PackageManager 11317 .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 11318 if (revokeOnUpgrade) { 11319 flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 11320 // Since we changed the flags, we have to write. 11321 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11322 changedRuntimePermissionUserIds, userId); 11323 } 11324 if (!mPermissionReviewRequired || !revokeOnUpgrade) { 11325 if (permissionsState.grantRuntimePermission(bp, userId) == 11326 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11327 // If we cannot put the permission as it was, 11328 // we have to write. 11329 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11330 changedRuntimePermissionUserIds, userId); 11331 } 11332 } 11333 11334 // If the app supports runtime permissions no need for a review. 11335 if (mPermissionReviewRequired 11336 && appSupportsRuntimePermissions 11337 && (flags & PackageManager 11338 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 11339 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 11340 // Since we changed the flags, we have to write. 11341 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11342 changedRuntimePermissionUserIds, userId); 11343 } 11344 } else if (mPermissionReviewRequired 11345 && !appSupportsRuntimePermissions) { 11346 // For legacy apps that need a permission review, every new 11347 // runtime permission is granted but it is pending a review. 11348 // We also need to review only platform defined runtime 11349 // permissions as these are the only ones the platform knows 11350 // how to disable the API to simulate revocation as legacy 11351 // apps don't expect to run with revoked permissions. 11352 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 11353 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 11354 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 11355 // We changed the flags, hence have to write. 11356 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11357 changedRuntimePermissionUserIds, userId); 11358 } 11359 } 11360 if (permissionsState.grantRuntimePermission(bp, userId) 11361 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 11362 // We changed the permission, hence have to write. 11363 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11364 changedRuntimePermissionUserIds, userId); 11365 } 11366 } 11367 // Propagate the permission flags. 11368 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 11369 } 11370 } break; 11371 11372 case GRANT_UPGRADE: { 11373 // Grant runtime permissions for a previously held install permission. 11374 PermissionState permissionState = origPermissions 11375 .getInstallPermissionState(bp.name); 11376 final int flags = permissionState != null ? permissionState.getFlags() : 0; 11377 11378 if (origPermissions.revokeInstallPermission(bp) 11379 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 11380 // We will be transferring the permission flags, so clear them. 11381 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 11382 PackageManager.MASK_PERMISSION_FLAGS, 0); 11383 changedInstallPermission = true; 11384 } 11385 11386 // If the permission is not to be promoted to runtime we ignore it and 11387 // also its other flags as they are not applicable to install permissions. 11388 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 11389 for (int userId : currentUserIds) { 11390 if (permissionsState.grantRuntimePermission(bp, userId) != 11391 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11392 // Transfer the permission flags. 11393 permissionsState.updatePermissionFlags(bp, userId, 11394 flags, flags); 11395 // If we granted the permission, we have to write. 11396 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11397 changedRuntimePermissionUserIds, userId); 11398 } 11399 } 11400 } 11401 } break; 11402 11403 default: { 11404 if (packageOfInterest == null 11405 || packageOfInterest.equals(pkg.packageName)) { 11406 Slog.w(TAG, "Not granting permission " + perm 11407 + " to package " + pkg.packageName 11408 + " because it was previously installed without"); 11409 } 11410 } break; 11411 } 11412 } else { 11413 if (permissionsState.revokeInstallPermission(bp) != 11414 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11415 // Also drop the permission flags. 11416 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 11417 PackageManager.MASK_PERMISSION_FLAGS, 0); 11418 changedInstallPermission = true; 11419 Slog.i(TAG, "Un-granting permission " + perm 11420 + " from package " + pkg.packageName 11421 + " (protectionLevel=" + bp.protectionLevel 11422 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 11423 + ")"); 11424 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 11425 // Don't print warning for app op permissions, since it is fine for them 11426 // not to be granted, there is a UI for the user to decide. 11427 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 11428 Slog.w(TAG, "Not granting permission " + perm 11429 + " to package " + pkg.packageName 11430 + " (protectionLevel=" + bp.protectionLevel 11431 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 11432 + ")"); 11433 } 11434 } 11435 } 11436 } 11437 11438 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 11439 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 11440 // This is the first that we have heard about this package, so the 11441 // permissions we have now selected are fixed until explicitly 11442 // changed. 11443 ps.installPermissionsFixed = true; 11444 } 11445 11446 // Persist the runtime permissions state for users with changes. If permissions 11447 // were revoked because no app in the shared user declares them we have to 11448 // write synchronously to avoid losing runtime permissions state. 11449 for (int userId : changedRuntimePermissionUserIds) { 11450 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 11451 } 11452 } 11453 11454 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 11455 boolean allowed = false; 11456 final int NP = PackageParser.NEW_PERMISSIONS.length; 11457 for (int ip=0; ip<NP; ip++) { 11458 final PackageParser.NewPermissionInfo npi 11459 = PackageParser.NEW_PERMISSIONS[ip]; 11460 if (npi.name.equals(perm) 11461 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 11462 allowed = true; 11463 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 11464 + pkg.packageName); 11465 break; 11466 } 11467 } 11468 return allowed; 11469 } 11470 11471 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 11472 BasePermission bp, PermissionsState origPermissions) { 11473 boolean privilegedPermission = (bp.protectionLevel 11474 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0; 11475 boolean privappPermissionsDisable = 11476 RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE; 11477 boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage); 11478 boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName); 11479 if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp() 11480 && !platformPackage && platformPermission) { 11481 ArraySet<String> wlPermissions = SystemConfig.getInstance() 11482 .getPrivAppPermissions(pkg.packageName); 11483 boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm); 11484 if (!whitelisted) { 11485 Slog.w(TAG, "Privileged permission " + perm + " for package " 11486 + pkg.packageName + " - not in privapp-permissions whitelist"); 11487 if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) { 11488 return false; 11489 } 11490 } 11491 } 11492 boolean allowed = (compareSignatures( 11493 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 11494 == PackageManager.SIGNATURE_MATCH) 11495 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 11496 == PackageManager.SIGNATURE_MATCH); 11497 if (!allowed && privilegedPermission) { 11498 if (isSystemApp(pkg)) { 11499 // For updated system applications, a system permission 11500 // is granted only if it had been defined by the original application. 11501 if (pkg.isUpdatedSystemApp()) { 11502 final PackageSetting sysPs = mSettings 11503 .getDisabledSystemPkgLPr(pkg.packageName); 11504 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 11505 // If the original was granted this permission, we take 11506 // that grant decision as read and propagate it to the 11507 // update. 11508 if (sysPs.isPrivileged()) { 11509 allowed = true; 11510 } 11511 } else { 11512 // The system apk may have been updated with an older 11513 // version of the one on the data partition, but which 11514 // granted a new system permission that it didn't have 11515 // before. In this case we do want to allow the app to 11516 // now get the new permission if the ancestral apk is 11517 // privileged to get it. 11518 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 11519 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 11520 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 11521 allowed = true; 11522 break; 11523 } 11524 } 11525 } 11526 // Also if a privileged parent package on the system image or any of 11527 // its children requested a privileged permission, the updated child 11528 // packages can also get the permission. 11529 if (pkg.parentPackage != null) { 11530 final PackageSetting disabledSysParentPs = mSettings 11531 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 11532 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 11533 && disabledSysParentPs.isPrivileged()) { 11534 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 11535 allowed = true; 11536 } else if (disabledSysParentPs.pkg.childPackages != null) { 11537 final int count = disabledSysParentPs.pkg.childPackages.size(); 11538 for (int i = 0; i < count; i++) { 11539 PackageParser.Package disabledSysChildPkg = 11540 disabledSysParentPs.pkg.childPackages.get(i); 11541 if (isPackageRequestingPermission(disabledSysChildPkg, 11542 perm)) { 11543 allowed = true; 11544 break; 11545 } 11546 } 11547 } 11548 } 11549 } 11550 } 11551 } else { 11552 allowed = isPrivilegedApp(pkg); 11553 } 11554 } 11555 } 11556 if (!allowed) { 11557 if (!allowed && (bp.protectionLevel 11558 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 11559 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 11560 // If this was a previously normal/dangerous permission that got moved 11561 // to a system permission as part of the runtime permission redesign, then 11562 // we still want to blindly grant it to old apps. 11563 allowed = true; 11564 } 11565 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 11566 && pkg.packageName.equals(mRequiredInstallerPackage)) { 11567 // If this permission is to be granted to the system installer and 11568 // this app is an installer, then it gets the permission. 11569 allowed = true; 11570 } 11571 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 11572 && pkg.packageName.equals(mRequiredVerifierPackage)) { 11573 // If this permission is to be granted to the system verifier and 11574 // this app is a verifier, then it gets the permission. 11575 allowed = true; 11576 } 11577 if (!allowed && (bp.protectionLevel 11578 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 11579 && isSystemApp(pkg)) { 11580 // Any pre-installed system app is allowed to get this permission. 11581 allowed = true; 11582 } 11583 if (!allowed && (bp.protectionLevel 11584 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 11585 // For development permissions, a development permission 11586 // is granted only if it was already granted. 11587 allowed = origPermissions.hasInstallPermission(perm); 11588 } 11589 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 11590 && pkg.packageName.equals(mSetupWizardPackage)) { 11591 // If this permission is to be granted to the system setup wizard and 11592 // this app is a setup wizard, then it gets the permission. 11593 allowed = true; 11594 } 11595 } 11596 return allowed; 11597 } 11598 11599 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 11600 final int permCount = pkg.requestedPermissions.size(); 11601 for (int j = 0; j < permCount; j++) { 11602 String requestedPermission = pkg.requestedPermissions.get(j); 11603 if (permission.equals(requestedPermission)) { 11604 return true; 11605 } 11606 } 11607 return false; 11608 } 11609 11610 final class ActivityIntentResolver 11611 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 11612 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 11613 boolean defaultOnly, boolean visibleToEphemeral, boolean isEphemeral, int userId) { 11614 if (!sUserManager.exists(userId)) return null; 11615 mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0) 11616 | (visibleToEphemeral ? PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY : 0) 11617 | (isEphemeral ? PackageManager.MATCH_EPHEMERAL : 0); 11618 return super.queryIntent(intent, resolvedType, defaultOnly, visibleToEphemeral, 11619 isEphemeral, userId); 11620 } 11621 11622 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 11623 int userId) { 11624 if (!sUserManager.exists(userId)) return null; 11625 mFlags = flags; 11626 return super.queryIntent(intent, resolvedType, 11627 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 11628 (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0, 11629 (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId); 11630 } 11631 11632 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 11633 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 11634 if (!sUserManager.exists(userId)) return null; 11635 if (packageActivities == null) { 11636 return null; 11637 } 11638 mFlags = flags; 11639 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 11640 final boolean vislbleToEphemeral = 11641 (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0; 11642 final boolean isEphemeral = (flags & PackageManager.MATCH_EPHEMERAL) != 0; 11643 final int N = packageActivities.size(); 11644 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 11645 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 11646 11647 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 11648 for (int i = 0; i < N; ++i) { 11649 intentFilters = packageActivities.get(i).intents; 11650 if (intentFilters != null && intentFilters.size() > 0) { 11651 PackageParser.ActivityIntentInfo[] array = 11652 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 11653 intentFilters.toArray(array); 11654 listCut.add(array); 11655 } 11656 } 11657 return super.queryIntentFromList(intent, resolvedType, defaultOnly, 11658 vislbleToEphemeral, isEphemeral, listCut, userId); 11659 } 11660 11661 /** 11662 * Finds a privileged activity that matches the specified activity names. 11663 */ 11664 private PackageParser.Activity findMatchingActivity( 11665 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 11666 for (PackageParser.Activity sysActivity : activityList) { 11667 if (sysActivity.info.name.equals(activityInfo.name)) { 11668 return sysActivity; 11669 } 11670 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 11671 return sysActivity; 11672 } 11673 if (sysActivity.info.targetActivity != null) { 11674 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 11675 return sysActivity; 11676 } 11677 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 11678 return sysActivity; 11679 } 11680 } 11681 } 11682 return null; 11683 } 11684 11685 public class IterGenerator<E> { 11686 public Iterator<E> generate(ActivityIntentInfo info) { 11687 return null; 11688 } 11689 } 11690 11691 public class ActionIterGenerator extends IterGenerator<String> { 11692 @Override 11693 public Iterator<String> generate(ActivityIntentInfo info) { 11694 return info.actionsIterator(); 11695 } 11696 } 11697 11698 public class CategoriesIterGenerator extends IterGenerator<String> { 11699 @Override 11700 public Iterator<String> generate(ActivityIntentInfo info) { 11701 return info.categoriesIterator(); 11702 } 11703 } 11704 11705 public class SchemesIterGenerator extends IterGenerator<String> { 11706 @Override 11707 public Iterator<String> generate(ActivityIntentInfo info) { 11708 return info.schemesIterator(); 11709 } 11710 } 11711 11712 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 11713 @Override 11714 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 11715 return info.authoritiesIterator(); 11716 } 11717 } 11718 11719 /** 11720 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 11721 * MODIFIED. Do not pass in a list that should not be changed. 11722 */ 11723 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 11724 IterGenerator<T> generator, Iterator<T> searchIterator) { 11725 // loop through the set of actions; every one must be found in the intent filter 11726 while (searchIterator.hasNext()) { 11727 // we must have at least one filter in the list to consider a match 11728 if (intentList.size() == 0) { 11729 break; 11730 } 11731 11732 final T searchAction = searchIterator.next(); 11733 11734 // loop through the set of intent filters 11735 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 11736 while (intentIter.hasNext()) { 11737 final ActivityIntentInfo intentInfo = intentIter.next(); 11738 boolean selectionFound = false; 11739 11740 // loop through the intent filter's selection criteria; at least one 11741 // of them must match the searched criteria 11742 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 11743 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 11744 final T intentSelection = intentSelectionIter.next(); 11745 if (intentSelection != null && intentSelection.equals(searchAction)) { 11746 selectionFound = true; 11747 break; 11748 } 11749 } 11750 11751 // the selection criteria wasn't found in this filter's set; this filter 11752 // is not a potential match 11753 if (!selectionFound) { 11754 intentIter.remove(); 11755 } 11756 } 11757 } 11758 } 11759 11760 private boolean isProtectedAction(ActivityIntentInfo filter) { 11761 final Iterator<String> actionsIter = filter.actionsIterator(); 11762 while (actionsIter != null && actionsIter.hasNext()) { 11763 final String filterAction = actionsIter.next(); 11764 if (PROTECTED_ACTIONS.contains(filterAction)) { 11765 return true; 11766 } 11767 } 11768 return false; 11769 } 11770 11771 /** 11772 * Adjusts the priority of the given intent filter according to policy. 11773 * <p> 11774 * <ul> 11775 * <li>The priority for non privileged applications is capped to '0'</li> 11776 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 11777 * <li>The priority for unbundled updates to privileged applications is capped to the 11778 * priority defined on the system partition</li> 11779 * </ul> 11780 * <p> 11781 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 11782 * allowed to obtain any priority on any action. 11783 */ 11784 private void adjustPriority( 11785 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 11786 // nothing to do; priority is fine as-is 11787 if (intent.getPriority() <= 0) { 11788 return; 11789 } 11790 11791 final ActivityInfo activityInfo = intent.activity.info; 11792 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 11793 11794 final boolean privilegedApp = 11795 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 11796 if (!privilegedApp) { 11797 // non-privileged applications can never define a priority >0 11798 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 11799 + " package: " + applicationInfo.packageName 11800 + " activity: " + intent.activity.className 11801 + " origPrio: " + intent.getPriority()); 11802 intent.setPriority(0); 11803 return; 11804 } 11805 11806 if (systemActivities == null) { 11807 // the system package is not disabled; we're parsing the system partition 11808 if (isProtectedAction(intent)) { 11809 if (mDeferProtectedFilters) { 11810 // We can't deal with these just yet. No component should ever obtain a 11811 // >0 priority for a protected actions, with ONE exception -- the setup 11812 // wizard. The setup wizard, however, cannot be known until we're able to 11813 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 11814 // until all intent filters have been processed. Chicken, meet egg. 11815 // Let the filter temporarily have a high priority and rectify the 11816 // priorities after all system packages have been scanned. 11817 mProtectedFilters.add(intent); 11818 if (DEBUG_FILTERS) { 11819 Slog.i(TAG, "Protected action; save for later;" 11820 + " package: " + applicationInfo.packageName 11821 + " activity: " + intent.activity.className 11822 + " origPrio: " + intent.getPriority()); 11823 } 11824 return; 11825 } else { 11826 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 11827 Slog.i(TAG, "No setup wizard;" 11828 + " All protected intents capped to priority 0"); 11829 } 11830 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 11831 if (DEBUG_FILTERS) { 11832 Slog.i(TAG, "Found setup wizard;" 11833 + " allow priority " + intent.getPriority() + ";" 11834 + " package: " + intent.activity.info.packageName 11835 + " activity: " + intent.activity.className 11836 + " priority: " + intent.getPriority()); 11837 } 11838 // setup wizard gets whatever it wants 11839 return; 11840 } 11841 Slog.w(TAG, "Protected action; cap priority to 0;" 11842 + " package: " + intent.activity.info.packageName 11843 + " activity: " + intent.activity.className 11844 + " origPrio: " + intent.getPriority()); 11845 intent.setPriority(0); 11846 return; 11847 } 11848 } 11849 // privileged apps on the system image get whatever priority they request 11850 return; 11851 } 11852 11853 // privileged app unbundled update ... try to find the same activity 11854 final PackageParser.Activity foundActivity = 11855 findMatchingActivity(systemActivities, activityInfo); 11856 if (foundActivity == null) { 11857 // this is a new activity; it cannot obtain >0 priority 11858 if (DEBUG_FILTERS) { 11859 Slog.i(TAG, "New activity; cap priority to 0;" 11860 + " package: " + applicationInfo.packageName 11861 + " activity: " + intent.activity.className 11862 + " origPrio: " + intent.getPriority()); 11863 } 11864 intent.setPriority(0); 11865 return; 11866 } 11867 11868 // found activity, now check for filter equivalence 11869 11870 // a shallow copy is enough; we modify the list, not its contents 11871 final List<ActivityIntentInfo> intentListCopy = 11872 new ArrayList<>(foundActivity.intents); 11873 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 11874 11875 // find matching action subsets 11876 final Iterator<String> actionsIterator = intent.actionsIterator(); 11877 if (actionsIterator != null) { 11878 getIntentListSubset( 11879 intentListCopy, new ActionIterGenerator(), actionsIterator); 11880 if (intentListCopy.size() == 0) { 11881 // no more intents to match; we're not equivalent 11882 if (DEBUG_FILTERS) { 11883 Slog.i(TAG, "Mismatched action; cap priority to 0;" 11884 + " package: " + applicationInfo.packageName 11885 + " activity: " + intent.activity.className 11886 + " origPrio: " + intent.getPriority()); 11887 } 11888 intent.setPriority(0); 11889 return; 11890 } 11891 } 11892 11893 // find matching category subsets 11894 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 11895 if (categoriesIterator != null) { 11896 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 11897 categoriesIterator); 11898 if (intentListCopy.size() == 0) { 11899 // no more intents to match; we're not equivalent 11900 if (DEBUG_FILTERS) { 11901 Slog.i(TAG, "Mismatched category; cap priority to 0;" 11902 + " package: " + applicationInfo.packageName 11903 + " activity: " + intent.activity.className 11904 + " origPrio: " + intent.getPriority()); 11905 } 11906 intent.setPriority(0); 11907 return; 11908 } 11909 } 11910 11911 // find matching schemes subsets 11912 final Iterator<String> schemesIterator = intent.schemesIterator(); 11913 if (schemesIterator != null) { 11914 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 11915 schemesIterator); 11916 if (intentListCopy.size() == 0) { 11917 // no more intents to match; we're not equivalent 11918 if (DEBUG_FILTERS) { 11919 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 11920 + " package: " + applicationInfo.packageName 11921 + " activity: " + intent.activity.className 11922 + " origPrio: " + intent.getPriority()); 11923 } 11924 intent.setPriority(0); 11925 return; 11926 } 11927 } 11928 11929 // find matching authorities subsets 11930 final Iterator<IntentFilter.AuthorityEntry> 11931 authoritiesIterator = intent.authoritiesIterator(); 11932 if (authoritiesIterator != null) { 11933 getIntentListSubset(intentListCopy, 11934 new AuthoritiesIterGenerator(), 11935 authoritiesIterator); 11936 if (intentListCopy.size() == 0) { 11937 // no more intents to match; we're not equivalent 11938 if (DEBUG_FILTERS) { 11939 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 11940 + " package: " + applicationInfo.packageName 11941 + " activity: " + intent.activity.className 11942 + " origPrio: " + intent.getPriority()); 11943 } 11944 intent.setPriority(0); 11945 return; 11946 } 11947 } 11948 11949 // we found matching filter(s); app gets the max priority of all intents 11950 int cappedPriority = 0; 11951 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 11952 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 11953 } 11954 if (intent.getPriority() > cappedPriority) { 11955 if (DEBUG_FILTERS) { 11956 Slog.i(TAG, "Found matching filter(s);" 11957 + " cap priority to " + cappedPriority + ";" 11958 + " package: " + applicationInfo.packageName 11959 + " activity: " + intent.activity.className 11960 + " origPrio: " + intent.getPriority()); 11961 } 11962 intent.setPriority(cappedPriority); 11963 return; 11964 } 11965 // all this for nothing; the requested priority was <= what was on the system 11966 } 11967 11968 public final void addActivity(PackageParser.Activity a, String type) { 11969 mActivities.put(a.getComponentName(), a); 11970 if (DEBUG_SHOW_INFO) 11971 Log.v( 11972 TAG, " " + type + " " + 11973 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 11974 if (DEBUG_SHOW_INFO) 11975 Log.v(TAG, " Class=" + a.info.name); 11976 final int NI = a.intents.size(); 11977 for (int j=0; j<NI; j++) { 11978 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 11979 if ("activity".equals(type)) { 11980 final PackageSetting ps = 11981 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 11982 final List<PackageParser.Activity> systemActivities = 11983 ps != null && ps.pkg != null ? ps.pkg.activities : null; 11984 adjustPriority(systemActivities, intent); 11985 } 11986 if (DEBUG_SHOW_INFO) { 11987 Log.v(TAG, " IntentFilter:"); 11988 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11989 } 11990 if (!intent.debugCheck()) { 11991 Log.w(TAG, "==> For Activity " + a.info.name); 11992 } 11993 addFilter(intent); 11994 } 11995 } 11996 11997 public final void removeActivity(PackageParser.Activity a, String type) { 11998 mActivities.remove(a.getComponentName()); 11999 if (DEBUG_SHOW_INFO) { 12000 Log.v(TAG, " " + type + " " 12001 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 12002 : a.info.name) + ":"); 12003 Log.v(TAG, " Class=" + a.info.name); 12004 } 12005 final int NI = a.intents.size(); 12006 for (int j=0; j<NI; j++) { 12007 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 12008 if (DEBUG_SHOW_INFO) { 12009 Log.v(TAG, " IntentFilter:"); 12010 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12011 } 12012 removeFilter(intent); 12013 } 12014 } 12015 12016 @Override 12017 protected boolean allowFilterResult( 12018 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 12019 ActivityInfo filterAi = filter.activity.info; 12020 for (int i=dest.size()-1; i>=0; i--) { 12021 ActivityInfo destAi = dest.get(i).activityInfo; 12022 if (destAi.name == filterAi.name 12023 && destAi.packageName == filterAi.packageName) { 12024 return false; 12025 } 12026 } 12027 return true; 12028 } 12029 12030 @Override 12031 protected ActivityIntentInfo[] newArray(int size) { 12032 return new ActivityIntentInfo[size]; 12033 } 12034 12035 @Override 12036 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 12037 if (!sUserManager.exists(userId)) return true; 12038 PackageParser.Package p = filter.activity.owner; 12039 if (p != null) { 12040 PackageSetting ps = (PackageSetting)p.mExtras; 12041 if (ps != null) { 12042 // System apps are never considered stopped for purposes of 12043 // filtering, because there may be no way for the user to 12044 // actually re-launch them. 12045 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 12046 && ps.getStopped(userId); 12047 } 12048 } 12049 return false; 12050 } 12051 12052 @Override 12053 protected boolean isPackageForFilter(String packageName, 12054 PackageParser.ActivityIntentInfo info) { 12055 return packageName.equals(info.activity.owner.packageName); 12056 } 12057 12058 @Override 12059 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 12060 int match, int userId) { 12061 if (!sUserManager.exists(userId)) return null; 12062 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 12063 return null; 12064 } 12065 final PackageParser.Activity activity = info.activity; 12066 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 12067 if (ps == null) { 12068 return null; 12069 } 12070 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 12071 ps.readUserState(userId), userId); 12072 if (ai == null) { 12073 return null; 12074 } 12075 final ResolveInfo res = new ResolveInfo(); 12076 res.activityInfo = ai; 12077 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 12078 res.filter = info; 12079 } 12080 if (info != null) { 12081 res.handleAllWebDataURI = info.handleAllWebDataURI(); 12082 } 12083 res.priority = info.getPriority(); 12084 res.preferredOrder = activity.owner.mPreferredOrder; 12085 //System.out.println("Result: " + res.activityInfo.className + 12086 // " = " + res.priority); 12087 res.match = match; 12088 res.isDefault = info.hasDefault; 12089 res.labelRes = info.labelRes; 12090 res.nonLocalizedLabel = info.nonLocalizedLabel; 12091 if (userNeedsBadging(userId)) { 12092 res.noResourceId = true; 12093 } else { 12094 res.icon = info.icon; 12095 } 12096 res.iconResourceId = info.icon; 12097 res.system = res.activityInfo.applicationInfo.isSystemApp(); 12098 return res; 12099 } 12100 12101 @Override 12102 protected void sortResults(List<ResolveInfo> results) { 12103 Collections.sort(results, mResolvePrioritySorter); 12104 } 12105 12106 @Override 12107 protected void dumpFilter(PrintWriter out, String prefix, 12108 PackageParser.ActivityIntentInfo filter) { 12109 out.print(prefix); out.print( 12110 Integer.toHexString(System.identityHashCode(filter.activity))); 12111 out.print(' '); 12112 filter.activity.printComponentShortName(out); 12113 out.print(" filter "); 12114 out.println(Integer.toHexString(System.identityHashCode(filter))); 12115 } 12116 12117 @Override 12118 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 12119 return filter.activity; 12120 } 12121 12122 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12123 PackageParser.Activity activity = (PackageParser.Activity)label; 12124 out.print(prefix); out.print( 12125 Integer.toHexString(System.identityHashCode(activity))); 12126 out.print(' '); 12127 activity.printComponentShortName(out); 12128 if (count > 1) { 12129 out.print(" ("); out.print(count); out.print(" filters)"); 12130 } 12131 out.println(); 12132 } 12133 12134 // Keys are String (activity class name), values are Activity. 12135 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 12136 = new ArrayMap<ComponentName, PackageParser.Activity>(); 12137 private int mFlags; 12138 } 12139 12140 private final class ServiceIntentResolver 12141 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 12142 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12143 boolean defaultOnly, boolean visibleToEphemeral, boolean isEphemeral, int userId) { 12144 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 12145 return super.queryIntent(intent, resolvedType, defaultOnly, visibleToEphemeral, 12146 isEphemeral, userId); 12147 } 12148 12149 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12150 int userId) { 12151 if (!sUserManager.exists(userId)) return null; 12152 mFlags = flags; 12153 return super.queryIntent(intent, resolvedType, 12154 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12155 (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0, 12156 (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId); 12157 } 12158 12159 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12160 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 12161 if (!sUserManager.exists(userId)) return null; 12162 if (packageServices == null) { 12163 return null; 12164 } 12165 mFlags = flags; 12166 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 12167 final boolean vislbleToEphemeral = 12168 (flags&PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0; 12169 final boolean isEphemeral = (flags&PackageManager.MATCH_EPHEMERAL) != 0; 12170 final int N = packageServices.size(); 12171 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 12172 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 12173 12174 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 12175 for (int i = 0; i < N; ++i) { 12176 intentFilters = packageServices.get(i).intents; 12177 if (intentFilters != null && intentFilters.size() > 0) { 12178 PackageParser.ServiceIntentInfo[] array = 12179 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 12180 intentFilters.toArray(array); 12181 listCut.add(array); 12182 } 12183 } 12184 return super.queryIntentFromList(intent, resolvedType, defaultOnly, 12185 vislbleToEphemeral, isEphemeral, listCut, userId); 12186 } 12187 12188 public final void addService(PackageParser.Service s) { 12189 mServices.put(s.getComponentName(), s); 12190 if (DEBUG_SHOW_INFO) { 12191 Log.v(TAG, " " 12192 + (s.info.nonLocalizedLabel != null 12193 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 12194 Log.v(TAG, " Class=" + s.info.name); 12195 } 12196 final int NI = s.intents.size(); 12197 int j; 12198 for (j=0; j<NI; j++) { 12199 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 12200 if (DEBUG_SHOW_INFO) { 12201 Log.v(TAG, " IntentFilter:"); 12202 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12203 } 12204 if (!intent.debugCheck()) { 12205 Log.w(TAG, "==> For Service " + s.info.name); 12206 } 12207 addFilter(intent); 12208 } 12209 } 12210 12211 public final void removeService(PackageParser.Service s) { 12212 mServices.remove(s.getComponentName()); 12213 if (DEBUG_SHOW_INFO) { 12214 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 12215 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 12216 Log.v(TAG, " Class=" + s.info.name); 12217 } 12218 final int NI = s.intents.size(); 12219 int j; 12220 for (j=0; j<NI; j++) { 12221 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 12222 if (DEBUG_SHOW_INFO) { 12223 Log.v(TAG, " IntentFilter:"); 12224 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12225 } 12226 removeFilter(intent); 12227 } 12228 } 12229 12230 @Override 12231 protected boolean allowFilterResult( 12232 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 12233 ServiceInfo filterSi = filter.service.info; 12234 for (int i=dest.size()-1; i>=0; i--) { 12235 ServiceInfo destAi = dest.get(i).serviceInfo; 12236 if (destAi.name == filterSi.name 12237 && destAi.packageName == filterSi.packageName) { 12238 return false; 12239 } 12240 } 12241 return true; 12242 } 12243 12244 @Override 12245 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 12246 return new PackageParser.ServiceIntentInfo[size]; 12247 } 12248 12249 @Override 12250 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 12251 if (!sUserManager.exists(userId)) return true; 12252 PackageParser.Package p = filter.service.owner; 12253 if (p != null) { 12254 PackageSetting ps = (PackageSetting)p.mExtras; 12255 if (ps != null) { 12256 // System apps are never considered stopped for purposes of 12257 // filtering, because there may be no way for the user to 12258 // actually re-launch them. 12259 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 12260 && ps.getStopped(userId); 12261 } 12262 } 12263 return false; 12264 } 12265 12266 @Override 12267 protected boolean isPackageForFilter(String packageName, 12268 PackageParser.ServiceIntentInfo info) { 12269 return packageName.equals(info.service.owner.packageName); 12270 } 12271 12272 @Override 12273 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 12274 int match, int userId) { 12275 if (!sUserManager.exists(userId)) return null; 12276 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 12277 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 12278 return null; 12279 } 12280 final PackageParser.Service service = info.service; 12281 PackageSetting ps = (PackageSetting) service.owner.mExtras; 12282 if (ps == null) { 12283 return null; 12284 } 12285 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 12286 ps.readUserState(userId), userId); 12287 if (si == null) { 12288 return null; 12289 } 12290 final ResolveInfo res = new ResolveInfo(); 12291 res.serviceInfo = si; 12292 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 12293 res.filter = filter; 12294 } 12295 res.priority = info.getPriority(); 12296 res.preferredOrder = service.owner.mPreferredOrder; 12297 res.match = match; 12298 res.isDefault = info.hasDefault; 12299 res.labelRes = info.labelRes; 12300 res.nonLocalizedLabel = info.nonLocalizedLabel; 12301 res.icon = info.icon; 12302 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 12303 return res; 12304 } 12305 12306 @Override 12307 protected void sortResults(List<ResolveInfo> results) { 12308 Collections.sort(results, mResolvePrioritySorter); 12309 } 12310 12311 @Override 12312 protected void dumpFilter(PrintWriter out, String prefix, 12313 PackageParser.ServiceIntentInfo filter) { 12314 out.print(prefix); out.print( 12315 Integer.toHexString(System.identityHashCode(filter.service))); 12316 out.print(' '); 12317 filter.service.printComponentShortName(out); 12318 out.print(" filter "); 12319 out.println(Integer.toHexString(System.identityHashCode(filter))); 12320 } 12321 12322 @Override 12323 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 12324 return filter.service; 12325 } 12326 12327 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12328 PackageParser.Service service = (PackageParser.Service)label; 12329 out.print(prefix); out.print( 12330 Integer.toHexString(System.identityHashCode(service))); 12331 out.print(' '); 12332 service.printComponentShortName(out); 12333 if (count > 1) { 12334 out.print(" ("); out.print(count); out.print(" filters)"); 12335 } 12336 out.println(); 12337 } 12338 12339// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 12340// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 12341// final List<ResolveInfo> retList = Lists.newArrayList(); 12342// while (i.hasNext()) { 12343// final ResolveInfo resolveInfo = (ResolveInfo) i; 12344// if (isEnabledLP(resolveInfo.serviceInfo)) { 12345// retList.add(resolveInfo); 12346// } 12347// } 12348// return retList; 12349// } 12350 12351 // Keys are String (activity class name), values are Activity. 12352 private final ArrayMap<ComponentName, PackageParser.Service> mServices 12353 = new ArrayMap<ComponentName, PackageParser.Service>(); 12354 private int mFlags; 12355 } 12356 12357 private final class ProviderIntentResolver 12358 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 12359 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12360 boolean defaultOnly, boolean visibleToEphemeral, boolean isEphemeral, int userId) { 12361 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 12362 return super.queryIntent(intent, resolvedType, defaultOnly, visibleToEphemeral, 12363 isEphemeral, userId); 12364 } 12365 12366 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12367 int userId) { 12368 if (!sUserManager.exists(userId)) 12369 return null; 12370 mFlags = flags; 12371 return super.queryIntent(intent, resolvedType, 12372 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12373 (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0, 12374 (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId); 12375 } 12376 12377 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12378 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 12379 if (!sUserManager.exists(userId)) 12380 return null; 12381 if (packageProviders == null) { 12382 return null; 12383 } 12384 mFlags = flags; 12385 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 12386 final boolean isEphemeral = (flags&PackageManager.MATCH_EPHEMERAL) != 0; 12387 final boolean vislbleToEphemeral = 12388 (flags&PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0; 12389 final int N = packageProviders.size(); 12390 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 12391 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 12392 12393 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 12394 for (int i = 0; i < N; ++i) { 12395 intentFilters = packageProviders.get(i).intents; 12396 if (intentFilters != null && intentFilters.size() > 0) { 12397 PackageParser.ProviderIntentInfo[] array = 12398 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 12399 intentFilters.toArray(array); 12400 listCut.add(array); 12401 } 12402 } 12403 return super.queryIntentFromList(intent, resolvedType, defaultOnly, 12404 vislbleToEphemeral, isEphemeral, listCut, userId); 12405 } 12406 12407 public final void addProvider(PackageParser.Provider p) { 12408 if (mProviders.containsKey(p.getComponentName())) { 12409 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 12410 return; 12411 } 12412 12413 mProviders.put(p.getComponentName(), p); 12414 if (DEBUG_SHOW_INFO) { 12415 Log.v(TAG, " " 12416 + (p.info.nonLocalizedLabel != null 12417 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 12418 Log.v(TAG, " Class=" + p.info.name); 12419 } 12420 final int NI = p.intents.size(); 12421 int j; 12422 for (j = 0; j < NI; j++) { 12423 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 12424 if (DEBUG_SHOW_INFO) { 12425 Log.v(TAG, " IntentFilter:"); 12426 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12427 } 12428 if (!intent.debugCheck()) { 12429 Log.w(TAG, "==> For Provider " + p.info.name); 12430 } 12431 addFilter(intent); 12432 } 12433 } 12434 12435 public final void removeProvider(PackageParser.Provider p) { 12436 mProviders.remove(p.getComponentName()); 12437 if (DEBUG_SHOW_INFO) { 12438 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 12439 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 12440 Log.v(TAG, " Class=" + p.info.name); 12441 } 12442 final int NI = p.intents.size(); 12443 int j; 12444 for (j = 0; j < NI; j++) { 12445 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 12446 if (DEBUG_SHOW_INFO) { 12447 Log.v(TAG, " IntentFilter:"); 12448 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12449 } 12450 removeFilter(intent); 12451 } 12452 } 12453 12454 @Override 12455 protected boolean allowFilterResult( 12456 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 12457 ProviderInfo filterPi = filter.provider.info; 12458 for (int i = dest.size() - 1; i >= 0; i--) { 12459 ProviderInfo destPi = dest.get(i).providerInfo; 12460 if (destPi.name == filterPi.name 12461 && destPi.packageName == filterPi.packageName) { 12462 return false; 12463 } 12464 } 12465 return true; 12466 } 12467 12468 @Override 12469 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 12470 return new PackageParser.ProviderIntentInfo[size]; 12471 } 12472 12473 @Override 12474 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 12475 if (!sUserManager.exists(userId)) 12476 return true; 12477 PackageParser.Package p = filter.provider.owner; 12478 if (p != null) { 12479 PackageSetting ps = (PackageSetting) p.mExtras; 12480 if (ps != null) { 12481 // System apps are never considered stopped for purposes of 12482 // filtering, because there may be no way for the user to 12483 // actually re-launch them. 12484 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 12485 && ps.getStopped(userId); 12486 } 12487 } 12488 return false; 12489 } 12490 12491 @Override 12492 protected boolean isPackageForFilter(String packageName, 12493 PackageParser.ProviderIntentInfo info) { 12494 return packageName.equals(info.provider.owner.packageName); 12495 } 12496 12497 @Override 12498 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 12499 int match, int userId) { 12500 if (!sUserManager.exists(userId)) 12501 return null; 12502 final PackageParser.ProviderIntentInfo info = filter; 12503 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 12504 return null; 12505 } 12506 final PackageParser.Provider provider = info.provider; 12507 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 12508 if (ps == null) { 12509 return null; 12510 } 12511 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 12512 ps.readUserState(userId), userId); 12513 if (pi == null) { 12514 return null; 12515 } 12516 final ResolveInfo res = new ResolveInfo(); 12517 res.providerInfo = pi; 12518 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 12519 res.filter = filter; 12520 } 12521 res.priority = info.getPriority(); 12522 res.preferredOrder = provider.owner.mPreferredOrder; 12523 res.match = match; 12524 res.isDefault = info.hasDefault; 12525 res.labelRes = info.labelRes; 12526 res.nonLocalizedLabel = info.nonLocalizedLabel; 12527 res.icon = info.icon; 12528 res.system = res.providerInfo.applicationInfo.isSystemApp(); 12529 return res; 12530 } 12531 12532 @Override 12533 protected void sortResults(List<ResolveInfo> results) { 12534 Collections.sort(results, mResolvePrioritySorter); 12535 } 12536 12537 @Override 12538 protected void dumpFilter(PrintWriter out, String prefix, 12539 PackageParser.ProviderIntentInfo filter) { 12540 out.print(prefix); 12541 out.print( 12542 Integer.toHexString(System.identityHashCode(filter.provider))); 12543 out.print(' '); 12544 filter.provider.printComponentShortName(out); 12545 out.print(" filter "); 12546 out.println(Integer.toHexString(System.identityHashCode(filter))); 12547 } 12548 12549 @Override 12550 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 12551 return filter.provider; 12552 } 12553 12554 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12555 PackageParser.Provider provider = (PackageParser.Provider)label; 12556 out.print(prefix); out.print( 12557 Integer.toHexString(System.identityHashCode(provider))); 12558 out.print(' '); 12559 provider.printComponentShortName(out); 12560 if (count > 1) { 12561 out.print(" ("); out.print(count); out.print(" filters)"); 12562 } 12563 out.println(); 12564 } 12565 12566 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 12567 = new ArrayMap<ComponentName, PackageParser.Provider>(); 12568 private int mFlags; 12569 } 12570 12571 static final class EphemeralIntentResolver 12572 extends IntentResolver<EphemeralResponse, EphemeralResponse> { 12573 /** 12574 * The result that has the highest defined order. Ordering applies on a 12575 * per-package basis. Mapping is from package name to Pair of order and 12576 * EphemeralResolveInfo. 12577 * <p> 12578 * NOTE: This is implemented as a field variable for convenience and efficiency. 12579 * By having a field variable, we're able to track filter ordering as soon as 12580 * a non-zero order is defined. Otherwise, multiple loops across the result set 12581 * would be needed to apply ordering. If the intent resolver becomes re-entrant, 12582 * this needs to be contained entirely within {@link #filterResults()}. 12583 */ 12584 final ArrayMap<String, Pair<Integer, EphemeralResolveInfo>> mOrderResult = new ArrayMap<>(); 12585 12586 @Override 12587 protected EphemeralResponse[] newArray(int size) { 12588 return new EphemeralResponse[size]; 12589 } 12590 12591 @Override 12592 protected boolean isPackageForFilter(String packageName, EphemeralResponse responseObj) { 12593 return true; 12594 } 12595 12596 @Override 12597 protected EphemeralResponse newResult(EphemeralResponse responseObj, int match, 12598 int userId) { 12599 if (!sUserManager.exists(userId)) { 12600 return null; 12601 } 12602 final String packageName = responseObj.resolveInfo.getPackageName(); 12603 final Integer order = responseObj.getOrder(); 12604 final Pair<Integer, EphemeralResolveInfo> lastOrderResult = 12605 mOrderResult.get(packageName); 12606 // ordering is enabled and this item's order isn't high enough 12607 if (lastOrderResult != null && lastOrderResult.first >= order) { 12608 return null; 12609 } 12610 final EphemeralResolveInfo res = responseObj.resolveInfo; 12611 if (order > 0) { 12612 // non-zero order, enable ordering 12613 mOrderResult.put(packageName, new Pair<>(order, res)); 12614 } 12615 return responseObj; 12616 } 12617 12618 @Override 12619 protected void filterResults(List<EphemeralResponse> results) { 12620 // only do work if ordering is enabled [most of the time it won't be] 12621 if (mOrderResult.size() == 0) { 12622 return; 12623 } 12624 int resultSize = results.size(); 12625 for (int i = 0; i < resultSize; i++) { 12626 final EphemeralResolveInfo info = results.get(i).resolveInfo; 12627 final String packageName = info.getPackageName(); 12628 final Pair<Integer, EphemeralResolveInfo> savedInfo = mOrderResult.get(packageName); 12629 if (savedInfo == null) { 12630 // package doesn't having ordering 12631 continue; 12632 } 12633 if (savedInfo.second == info) { 12634 // circled back to the highest ordered item; remove from order list 12635 mOrderResult.remove(savedInfo); 12636 if (mOrderResult.size() == 0) { 12637 // no more ordered items 12638 break; 12639 } 12640 continue; 12641 } 12642 // item has a worse order, remove it from the result list 12643 results.remove(i); 12644 resultSize--; 12645 i--; 12646 } 12647 } 12648 } 12649 12650 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 12651 new Comparator<ResolveInfo>() { 12652 public int compare(ResolveInfo r1, ResolveInfo r2) { 12653 int v1 = r1.priority; 12654 int v2 = r2.priority; 12655 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 12656 if (v1 != v2) { 12657 return (v1 > v2) ? -1 : 1; 12658 } 12659 v1 = r1.preferredOrder; 12660 v2 = r2.preferredOrder; 12661 if (v1 != v2) { 12662 return (v1 > v2) ? -1 : 1; 12663 } 12664 if (r1.isDefault != r2.isDefault) { 12665 return r1.isDefault ? -1 : 1; 12666 } 12667 v1 = r1.match; 12668 v2 = r2.match; 12669 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 12670 if (v1 != v2) { 12671 return (v1 > v2) ? -1 : 1; 12672 } 12673 if (r1.system != r2.system) { 12674 return r1.system ? -1 : 1; 12675 } 12676 if (r1.activityInfo != null) { 12677 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 12678 } 12679 if (r1.serviceInfo != null) { 12680 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 12681 } 12682 if (r1.providerInfo != null) { 12683 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 12684 } 12685 return 0; 12686 } 12687 }; 12688 12689 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 12690 new Comparator<ProviderInfo>() { 12691 public int compare(ProviderInfo p1, ProviderInfo p2) { 12692 final int v1 = p1.initOrder; 12693 final int v2 = p2.initOrder; 12694 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 12695 } 12696 }; 12697 12698 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 12699 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 12700 final int[] userIds) { 12701 mHandler.post(new Runnable() { 12702 @Override 12703 public void run() { 12704 try { 12705 final IActivityManager am = ActivityManager.getService(); 12706 if (am == null) return; 12707 final int[] resolvedUserIds; 12708 if (userIds == null) { 12709 resolvedUserIds = am.getRunningUserIds(); 12710 } else { 12711 resolvedUserIds = userIds; 12712 } 12713 for (int id : resolvedUserIds) { 12714 final Intent intent = new Intent(action, 12715 pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null); 12716 if (extras != null) { 12717 intent.putExtras(extras); 12718 } 12719 if (targetPkg != null) { 12720 intent.setPackage(targetPkg); 12721 } 12722 // Modify the UID when posting to other users 12723 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 12724 if (uid > 0 && UserHandle.getUserId(uid) != id) { 12725 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 12726 intent.putExtra(Intent.EXTRA_UID, uid); 12727 } 12728 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 12729 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 12730 if (DEBUG_BROADCASTS) { 12731 RuntimeException here = new RuntimeException("here"); 12732 here.fillInStackTrace(); 12733 Slog.d(TAG, "Sending to user " + id + ": " 12734 + intent.toShortString(false, true, false, false) 12735 + " " + intent.getExtras(), here); 12736 } 12737 am.broadcastIntent(null, intent, null, finishedReceiver, 12738 0, null, null, null, android.app.AppOpsManager.OP_NONE, 12739 null, finishedReceiver != null, false, id); 12740 } 12741 } catch (RemoteException ex) { 12742 } 12743 } 12744 }); 12745 } 12746 12747 /** 12748 * Check if the external storage media is available. This is true if there 12749 * is a mounted external storage medium or if the external storage is 12750 * emulated. 12751 */ 12752 private boolean isExternalMediaAvailable() { 12753 return mMediaMounted || Environment.isExternalStorageEmulated(); 12754 } 12755 12756 @Override 12757 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 12758 // writer 12759 synchronized (mPackages) { 12760 if (!isExternalMediaAvailable()) { 12761 // If the external storage is no longer mounted at this point, 12762 // the caller may not have been able to delete all of this 12763 // packages files and can not delete any more. Bail. 12764 return null; 12765 } 12766 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 12767 if (lastPackage != null) { 12768 pkgs.remove(lastPackage); 12769 } 12770 if (pkgs.size() > 0) { 12771 return pkgs.get(0); 12772 } 12773 } 12774 return null; 12775 } 12776 12777 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 12778 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 12779 userId, andCode ? 1 : 0, packageName); 12780 if (mSystemReady) { 12781 msg.sendToTarget(); 12782 } else { 12783 if (mPostSystemReadyMessages == null) { 12784 mPostSystemReadyMessages = new ArrayList<>(); 12785 } 12786 mPostSystemReadyMessages.add(msg); 12787 } 12788 } 12789 12790 void startCleaningPackages() { 12791 // reader 12792 if (!isExternalMediaAvailable()) { 12793 return; 12794 } 12795 synchronized (mPackages) { 12796 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 12797 return; 12798 } 12799 } 12800 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 12801 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 12802 IActivityManager am = ActivityManager.getService(); 12803 if (am != null) { 12804 try { 12805 am.startService(null, intent, null, -1, null, mContext.getOpPackageName(), 12806 UserHandle.USER_SYSTEM); 12807 } catch (RemoteException e) { 12808 } 12809 } 12810 } 12811 12812 @Override 12813 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 12814 int installFlags, String installerPackageName, int userId) { 12815 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 12816 12817 final int callingUid = Binder.getCallingUid(); 12818 enforceCrossUserPermission(callingUid, userId, 12819 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 12820 12821 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 12822 try { 12823 if (observer != null) { 12824 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 12825 } 12826 } catch (RemoteException re) { 12827 } 12828 return; 12829 } 12830 12831 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 12832 installFlags |= PackageManager.INSTALL_FROM_ADB; 12833 12834 } else { 12835 // Caller holds INSTALL_PACKAGES permission, so we're less strict 12836 // about installerPackageName. 12837 12838 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 12839 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 12840 } 12841 12842 UserHandle user; 12843 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 12844 user = UserHandle.ALL; 12845 } else { 12846 user = new UserHandle(userId); 12847 } 12848 12849 // Only system components can circumvent runtime permissions when installing. 12850 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 12851 && mContext.checkCallingOrSelfPermission(Manifest.permission 12852 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 12853 throw new SecurityException("You need the " 12854 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 12855 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 12856 } 12857 12858 final File originFile = new File(originPath); 12859 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 12860 12861 final Message msg = mHandler.obtainMessage(INIT_COPY); 12862 final VerificationInfo verificationInfo = new VerificationInfo( 12863 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 12864 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 12865 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 12866 null /*packageAbiOverride*/, null /*grantedPermissions*/, 12867 null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN); 12868 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 12869 msg.obj = params; 12870 12871 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 12872 System.identityHashCode(msg.obj)); 12873 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 12874 System.identityHashCode(msg.obj)); 12875 12876 mHandler.sendMessage(msg); 12877 } 12878 12879 12880 /** 12881 * Ensure that the install reason matches what we know about the package installer (e.g. whether 12882 * it is acting on behalf on an enterprise or the user). 12883 * 12884 * Note that the ordering of the conditionals in this method is important. The checks we perform 12885 * are as follows, in this order: 12886 * 12887 * 1) If the install is being performed by a system app, we can trust the app to have set the 12888 * install reason correctly. Thus, we pass through the install reason unchanged, no matter 12889 * what it is. 12890 * 2) If the install is being performed by a device or profile owner app, the install reason 12891 * should be enterprise policy. However, we cannot be sure that the device or profile owner 12892 * set the install reason correctly. If the app targets an older SDK version where install 12893 * reasons did not exist yet, or if the app author simply forgot, the install reason may be 12894 * unset or wrong. Thus, we force the install reason to be enterprise policy. 12895 * 3) In all other cases, the install is being performed by a regular app that is neither part 12896 * of the system nor a device or profile owner. We have no reason to believe that this app is 12897 * acting on behalf of the enterprise admin. Thus, we check whether the install reason was 12898 * set to enterprise policy and if so, change it to unknown instead. 12899 */ 12900 private int fixUpInstallReason(String installerPackageName, int installerUid, 12901 int installReason) { 12902 if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid) 12903 == PERMISSION_GRANTED) { 12904 // If the install is being performed by a system app, we trust that app to have set the 12905 // install reason correctly. 12906 return installReason; 12907 } 12908 12909 final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 12910 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 12911 if (dpm != null) { 12912 ComponentName owner = null; 12913 try { 12914 owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */); 12915 if (owner == null) { 12916 owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid)); 12917 } 12918 } catch (RemoteException e) { 12919 } 12920 if (owner != null && owner.getPackageName().equals(installerPackageName)) { 12921 // If the install is being performed by a device or profile owner, the install 12922 // reason should be enterprise policy. 12923 return PackageManager.INSTALL_REASON_POLICY; 12924 } 12925 } 12926 12927 if (installReason == PackageManager.INSTALL_REASON_POLICY) { 12928 // If the install is being performed by a regular app (i.e. neither system app nor 12929 // device or profile owner), we have no reason to believe that the app is acting on 12930 // behalf of an enterprise. If the app set the install reason to enterprise policy, 12931 // change it to unknown instead. 12932 return PackageManager.INSTALL_REASON_UNKNOWN; 12933 } 12934 12935 // If the install is being performed by a regular app and the install reason was set to any 12936 // value but enterprise policy, leave the install reason unchanged. 12937 return installReason; 12938 } 12939 12940 void installStage(String packageName, File stagedDir, String stagedCid, 12941 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 12942 String installerPackageName, int installerUid, UserHandle user, 12943 Certificate[][] certificates) { 12944 if (DEBUG_EPHEMERAL) { 12945 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 12946 Slog.d(TAG, "Ephemeral install of " + packageName); 12947 } 12948 } 12949 final VerificationInfo verificationInfo = new VerificationInfo( 12950 sessionParams.originatingUri, sessionParams.referrerUri, 12951 sessionParams.originatingUid, installerUid); 12952 12953 final OriginInfo origin; 12954 if (stagedDir != null) { 12955 origin = OriginInfo.fromStagedFile(stagedDir); 12956 } else { 12957 origin = OriginInfo.fromStagedContainer(stagedCid); 12958 } 12959 12960 final Message msg = mHandler.obtainMessage(INIT_COPY); 12961 final int installReason = fixUpInstallReason(installerPackageName, installerUid, 12962 sessionParams.installReason); 12963 final InstallParams params = new InstallParams(origin, null, observer, 12964 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 12965 verificationInfo, user, sessionParams.abiOverride, 12966 sessionParams.grantedRuntimePermissions, certificates, installReason); 12967 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 12968 msg.obj = params; 12969 12970 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 12971 System.identityHashCode(msg.obj)); 12972 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 12973 System.identityHashCode(msg.obj)); 12974 12975 mHandler.sendMessage(msg); 12976 } 12977 12978 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 12979 int userId) { 12980 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 12981 sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId); 12982 } 12983 12984 private void sendPackageAddedForNewUsers(String packageName, boolean isSystem, 12985 int appId, int... userIds) { 12986 if (ArrayUtils.isEmpty(userIds)) { 12987 return; 12988 } 12989 Bundle extras = new Bundle(1); 12990 // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast 12991 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId)); 12992 12993 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 12994 packageName, extras, 0, null, null, userIds); 12995 if (isSystem) { 12996 mHandler.post(() -> { 12997 for (int userId : userIds) { 12998 sendBootCompletedBroadcastToSystemApp(packageName, userId); 12999 } 13000 } 13001 ); 13002 } 13003 } 13004 13005 /** 13006 * The just-installed/enabled app is bundled on the system, so presumed to be able to run 13007 * automatically without needing an explicit launch. 13008 * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones. 13009 */ 13010 private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) { 13011 // If user is not running, the app didn't miss any broadcast 13012 if (!mUserManagerInternal.isUserRunning(userId)) { 13013 return; 13014 } 13015 final IActivityManager am = ActivityManager.getService(); 13016 try { 13017 // Deliver LOCKED_BOOT_COMPLETED first 13018 Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED) 13019 .setPackage(packageName); 13020 final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED}; 13021 am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions, 13022 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 13023 13024 // Deliver BOOT_COMPLETED only if user is unlocked 13025 if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) { 13026 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName); 13027 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions, 13028 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 13029 } 13030 } catch (RemoteException e) { 13031 throw e.rethrowFromSystemServer(); 13032 } 13033 } 13034 13035 @Override 13036 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 13037 int userId) { 13038 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13039 PackageSetting pkgSetting; 13040 final int uid = Binder.getCallingUid(); 13041 enforceCrossUserPermission(uid, userId, 13042 true /* requireFullPermission */, true /* checkShell */, 13043 "setApplicationHiddenSetting for user " + userId); 13044 13045 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 13046 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 13047 return false; 13048 } 13049 13050 long callingId = Binder.clearCallingIdentity(); 13051 try { 13052 boolean sendAdded = false; 13053 boolean sendRemoved = false; 13054 // writer 13055 synchronized (mPackages) { 13056 pkgSetting = mSettings.mPackages.get(packageName); 13057 if (pkgSetting == null) { 13058 return false; 13059 } 13060 // Do not allow "android" is being disabled 13061 if ("android".equals(packageName)) { 13062 Slog.w(TAG, "Cannot hide package: android"); 13063 return false; 13064 } 13065 // Cannot hide static shared libs as they are considered 13066 // a part of the using app (emulating static linking). Also 13067 // static libs are installed always on internal storage. 13068 PackageParser.Package pkg = mPackages.get(packageName); 13069 if (pkg != null && pkg.staticSharedLibName != null) { 13070 Slog.w(TAG, "Cannot hide package: " + packageName 13071 + " providing static shared library: " 13072 + pkg.staticSharedLibName); 13073 return false; 13074 } 13075 // Only allow protected packages to hide themselves. 13076 if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId) 13077 && mProtectedPackages.isPackageStateProtected(userId, packageName)) { 13078 Slog.w(TAG, "Not hiding protected package: " + packageName); 13079 return false; 13080 } 13081 13082 if (pkgSetting.getHidden(userId) != hidden) { 13083 pkgSetting.setHidden(hidden, userId); 13084 mSettings.writePackageRestrictionsLPr(userId); 13085 if (hidden) { 13086 sendRemoved = true; 13087 } else { 13088 sendAdded = true; 13089 } 13090 } 13091 } 13092 if (sendAdded) { 13093 sendPackageAddedForUser(packageName, pkgSetting, userId); 13094 return true; 13095 } 13096 if (sendRemoved) { 13097 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 13098 "hiding pkg"); 13099 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 13100 return true; 13101 } 13102 } finally { 13103 Binder.restoreCallingIdentity(callingId); 13104 } 13105 return false; 13106 } 13107 13108 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 13109 int userId) { 13110 final PackageRemovedInfo info = new PackageRemovedInfo(); 13111 info.removedPackage = packageName; 13112 info.removedUsers = new int[] {userId}; 13113 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 13114 info.sendPackageRemovedBroadcasts(true /*killApp*/); 13115 } 13116 13117 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 13118 if (pkgList.length > 0) { 13119 Bundle extras = new Bundle(1); 13120 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 13121 13122 sendPackageBroadcast( 13123 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 13124 : Intent.ACTION_PACKAGES_UNSUSPENDED, 13125 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 13126 new int[] {userId}); 13127 } 13128 } 13129 13130 /** 13131 * Returns true if application is not found or there was an error. Otherwise it returns 13132 * the hidden state of the package for the given user. 13133 */ 13134 @Override 13135 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 13136 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13137 enforceCrossUserPermission(Binder.getCallingUid(), userId, 13138 true /* requireFullPermission */, false /* checkShell */, 13139 "getApplicationHidden for user " + userId); 13140 PackageSetting pkgSetting; 13141 long callingId = Binder.clearCallingIdentity(); 13142 try { 13143 // writer 13144 synchronized (mPackages) { 13145 pkgSetting = mSettings.mPackages.get(packageName); 13146 if (pkgSetting == null) { 13147 return true; 13148 } 13149 return pkgSetting.getHidden(userId); 13150 } 13151 } finally { 13152 Binder.restoreCallingIdentity(callingId); 13153 } 13154 } 13155 13156 /** 13157 * @hide 13158 */ 13159 @Override 13160 public int installExistingPackageAsUser(String packageName, int userId, int installReason) { 13161 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 13162 null); 13163 PackageSetting pkgSetting; 13164 final int uid = Binder.getCallingUid(); 13165 enforceCrossUserPermission(uid, userId, 13166 true /* requireFullPermission */, true /* checkShell */, 13167 "installExistingPackage for user " + userId); 13168 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 13169 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 13170 } 13171 13172 long callingId = Binder.clearCallingIdentity(); 13173 try { 13174 boolean installed = false; 13175 13176 // writer 13177 synchronized (mPackages) { 13178 pkgSetting = mSettings.mPackages.get(packageName); 13179 if (pkgSetting == null) { 13180 return PackageManager.INSTALL_FAILED_INVALID_URI; 13181 } 13182 if (!pkgSetting.getInstalled(userId)) { 13183 pkgSetting.setInstalled(true, userId); 13184 pkgSetting.setHidden(false, userId); 13185 pkgSetting.setInstallReason(installReason, userId); 13186 mSettings.writePackageRestrictionsLPr(userId); 13187 installed = true; 13188 } 13189 } 13190 13191 if (installed) { 13192 if (pkgSetting.pkg != null) { 13193 synchronized (mInstallLock) { 13194 // We don't need to freeze for a brand new install 13195 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 13196 } 13197 } 13198 sendPackageAddedForUser(packageName, pkgSetting, userId); 13199 } 13200 } finally { 13201 Binder.restoreCallingIdentity(callingId); 13202 } 13203 13204 return PackageManager.INSTALL_SUCCEEDED; 13205 } 13206 13207 boolean isUserRestricted(int userId, String restrictionKey) { 13208 Bundle restrictions = sUserManager.getUserRestrictions(userId); 13209 if (restrictions.getBoolean(restrictionKey, false)) { 13210 Log.w(TAG, "User is restricted: " + restrictionKey); 13211 return true; 13212 } 13213 return false; 13214 } 13215 13216 @Override 13217 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 13218 int userId) { 13219 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13220 enforceCrossUserPermission(Binder.getCallingUid(), userId, 13221 true /* requireFullPermission */, true /* checkShell */, 13222 "setPackagesSuspended for user " + userId); 13223 13224 if (ArrayUtils.isEmpty(packageNames)) { 13225 return packageNames; 13226 } 13227 13228 // List of package names for whom the suspended state has changed. 13229 List<String> changedPackages = new ArrayList<>(packageNames.length); 13230 // List of package names for whom the suspended state is not set as requested in this 13231 // method. 13232 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 13233 long callingId = Binder.clearCallingIdentity(); 13234 try { 13235 for (int i = 0; i < packageNames.length; i++) { 13236 String packageName = packageNames[i]; 13237 boolean changed = false; 13238 final int appId; 13239 synchronized (mPackages) { 13240 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 13241 if (pkgSetting == null) { 13242 Slog.w(TAG, "Could not find package setting for package \"" + packageName 13243 + "\". Skipping suspending/un-suspending."); 13244 unactionedPackages.add(packageName); 13245 continue; 13246 } 13247 appId = pkgSetting.appId; 13248 if (pkgSetting.getSuspended(userId) != suspended) { 13249 if (!canSuspendPackageForUserLocked(packageName, userId)) { 13250 unactionedPackages.add(packageName); 13251 continue; 13252 } 13253 pkgSetting.setSuspended(suspended, userId); 13254 mSettings.writePackageRestrictionsLPr(userId); 13255 changed = true; 13256 changedPackages.add(packageName); 13257 } 13258 } 13259 13260 if (changed && suspended) { 13261 killApplication(packageName, UserHandle.getUid(userId, appId), 13262 "suspending package"); 13263 } 13264 } 13265 } finally { 13266 Binder.restoreCallingIdentity(callingId); 13267 } 13268 13269 if (!changedPackages.isEmpty()) { 13270 sendPackagesSuspendedForUser(changedPackages.toArray( 13271 new String[changedPackages.size()]), userId, suspended); 13272 } 13273 13274 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 13275 } 13276 13277 @Override 13278 public boolean isPackageSuspendedForUser(String packageName, int userId) { 13279 enforceCrossUserPermission(Binder.getCallingUid(), userId, 13280 true /* requireFullPermission */, false /* checkShell */, 13281 "isPackageSuspendedForUser for user " + userId); 13282 synchronized (mPackages) { 13283 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 13284 if (pkgSetting == null) { 13285 throw new IllegalArgumentException("Unknown target package: " + packageName); 13286 } 13287 return pkgSetting.getSuspended(userId); 13288 } 13289 } 13290 13291 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 13292 if (isPackageDeviceAdmin(packageName, userId)) { 13293 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13294 + "\": has an active device admin"); 13295 return false; 13296 } 13297 13298 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 13299 if (packageName.equals(activeLauncherPackageName)) { 13300 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13301 + "\": contains the active launcher"); 13302 return false; 13303 } 13304 13305 if (packageName.equals(mRequiredInstallerPackage)) { 13306 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13307 + "\": required for package installation"); 13308 return false; 13309 } 13310 13311 if (packageName.equals(mRequiredUninstallerPackage)) { 13312 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13313 + "\": required for package uninstallation"); 13314 return false; 13315 } 13316 13317 if (packageName.equals(mRequiredVerifierPackage)) { 13318 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13319 + "\": required for package verification"); 13320 return false; 13321 } 13322 13323 if (packageName.equals(getDefaultDialerPackageName(userId))) { 13324 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13325 + "\": is the default dialer"); 13326 return false; 13327 } 13328 13329 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 13330 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13331 + "\": protected package"); 13332 return false; 13333 } 13334 13335 // Cannot suspend static shared libs as they are considered 13336 // a part of the using app (emulating static linking). Also 13337 // static libs are installed always on internal storage. 13338 PackageParser.Package pkg = mPackages.get(packageName); 13339 if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) { 13340 Slog.w(TAG, "Cannot suspend package: " + packageName 13341 + " providing static shared library: " 13342 + pkg.staticSharedLibName); 13343 return false; 13344 } 13345 13346 return true; 13347 } 13348 13349 private String getActiveLauncherPackageName(int userId) { 13350 Intent intent = new Intent(Intent.ACTION_MAIN); 13351 intent.addCategory(Intent.CATEGORY_HOME); 13352 ResolveInfo resolveInfo = resolveIntent( 13353 intent, 13354 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 13355 PackageManager.MATCH_DEFAULT_ONLY, 13356 userId); 13357 13358 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 13359 } 13360 13361 private String getDefaultDialerPackageName(int userId) { 13362 synchronized (mPackages) { 13363 return mSettings.getDefaultDialerPackageNameLPw(userId); 13364 } 13365 } 13366 13367 @Override 13368 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 13369 mContext.enforceCallingOrSelfPermission( 13370 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13371 "Only package verification agents can verify applications"); 13372 13373 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 13374 final PackageVerificationResponse response = new PackageVerificationResponse( 13375 verificationCode, Binder.getCallingUid()); 13376 msg.arg1 = id; 13377 msg.obj = response; 13378 mHandler.sendMessage(msg); 13379 } 13380 13381 @Override 13382 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 13383 long millisecondsToDelay) { 13384 mContext.enforceCallingOrSelfPermission( 13385 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13386 "Only package verification agents can extend verification timeouts"); 13387 13388 final PackageVerificationState state = mPendingVerification.get(id); 13389 final PackageVerificationResponse response = new PackageVerificationResponse( 13390 verificationCodeAtTimeout, Binder.getCallingUid()); 13391 13392 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 13393 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 13394 } 13395 if (millisecondsToDelay < 0) { 13396 millisecondsToDelay = 0; 13397 } 13398 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 13399 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 13400 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 13401 } 13402 13403 if ((state != null) && !state.timeoutExtended()) { 13404 state.extendTimeout(); 13405 13406 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 13407 msg.arg1 = id; 13408 msg.obj = response; 13409 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 13410 } 13411 } 13412 13413 private void broadcastPackageVerified(int verificationId, Uri packageUri, 13414 int verificationCode, UserHandle user) { 13415 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 13416 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 13417 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 13418 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 13419 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 13420 13421 mContext.sendBroadcastAsUser(intent, user, 13422 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 13423 } 13424 13425 private ComponentName matchComponentForVerifier(String packageName, 13426 List<ResolveInfo> receivers) { 13427 ActivityInfo targetReceiver = null; 13428 13429 final int NR = receivers.size(); 13430 for (int i = 0; i < NR; i++) { 13431 final ResolveInfo info = receivers.get(i); 13432 if (info.activityInfo == null) { 13433 continue; 13434 } 13435 13436 if (packageName.equals(info.activityInfo.packageName)) { 13437 targetReceiver = info.activityInfo; 13438 break; 13439 } 13440 } 13441 13442 if (targetReceiver == null) { 13443 return null; 13444 } 13445 13446 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 13447 } 13448 13449 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 13450 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 13451 if (pkgInfo.verifiers.length == 0) { 13452 return null; 13453 } 13454 13455 final int N = pkgInfo.verifiers.length; 13456 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 13457 for (int i = 0; i < N; i++) { 13458 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 13459 13460 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 13461 receivers); 13462 if (comp == null) { 13463 continue; 13464 } 13465 13466 final int verifierUid = getUidForVerifier(verifierInfo); 13467 if (verifierUid == -1) { 13468 continue; 13469 } 13470 13471 if (DEBUG_VERIFY) { 13472 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 13473 + " with the correct signature"); 13474 } 13475 sufficientVerifiers.add(comp); 13476 verificationState.addSufficientVerifier(verifierUid); 13477 } 13478 13479 return sufficientVerifiers; 13480 } 13481 13482 private int getUidForVerifier(VerifierInfo verifierInfo) { 13483 synchronized (mPackages) { 13484 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 13485 if (pkg == null) { 13486 return -1; 13487 } else if (pkg.mSignatures.length != 1) { 13488 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 13489 + " has more than one signature; ignoring"); 13490 return -1; 13491 } 13492 13493 /* 13494 * If the public key of the package's signature does not match 13495 * our expected public key, then this is a different package and 13496 * we should skip. 13497 */ 13498 13499 final byte[] expectedPublicKey; 13500 try { 13501 final Signature verifierSig = pkg.mSignatures[0]; 13502 final PublicKey publicKey = verifierSig.getPublicKey(); 13503 expectedPublicKey = publicKey.getEncoded(); 13504 } catch (CertificateException e) { 13505 return -1; 13506 } 13507 13508 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 13509 13510 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 13511 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 13512 + " does not have the expected public key; ignoring"); 13513 return -1; 13514 } 13515 13516 return pkg.applicationInfo.uid; 13517 } 13518 } 13519 13520 @Override 13521 public void finishPackageInstall(int token, boolean didLaunch) { 13522 enforceSystemOrRoot("Only the system is allowed to finish installs"); 13523 13524 if (DEBUG_INSTALL) { 13525 Slog.v(TAG, "BM finishing package install for " + token); 13526 } 13527 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 13528 13529 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 13530 mHandler.sendMessage(msg); 13531 } 13532 13533 /** 13534 * Get the verification agent timeout. 13535 * 13536 * @return verification timeout in milliseconds 13537 */ 13538 private long getVerificationTimeout() { 13539 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 13540 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 13541 DEFAULT_VERIFICATION_TIMEOUT); 13542 } 13543 13544 /** 13545 * Get the default verification agent response code. 13546 * 13547 * @return default verification response code 13548 */ 13549 private int getDefaultVerificationResponse() { 13550 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13551 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 13552 DEFAULT_VERIFICATION_RESPONSE); 13553 } 13554 13555 /** 13556 * Check whether or not package verification has been enabled. 13557 * 13558 * @return true if verification should be performed 13559 */ 13560 private boolean isVerificationEnabled(int userId, int installFlags) { 13561 if (!DEFAULT_VERIFY_ENABLE) { 13562 return false; 13563 } 13564 // Ephemeral apps don't get the full verification treatment 13565 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 13566 if (DEBUG_EPHEMERAL) { 13567 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 13568 } 13569 return false; 13570 } 13571 13572 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 13573 13574 // Check if installing from ADB 13575 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 13576 // Do not run verification in a test harness environment 13577 if (ActivityManager.isRunningInTestHarness()) { 13578 return false; 13579 } 13580 if (ensureVerifyAppsEnabled) { 13581 return true; 13582 } 13583 // Check if the developer does not want package verification for ADB installs 13584 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13585 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 13586 return false; 13587 } 13588 } 13589 13590 if (ensureVerifyAppsEnabled) { 13591 return true; 13592 } 13593 13594 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13595 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 13596 } 13597 13598 @Override 13599 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 13600 throws RemoteException { 13601 mContext.enforceCallingOrSelfPermission( 13602 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 13603 "Only intentfilter verification agents can verify applications"); 13604 13605 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 13606 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 13607 Binder.getCallingUid(), verificationCode, failedDomains); 13608 msg.arg1 = id; 13609 msg.obj = response; 13610 mHandler.sendMessage(msg); 13611 } 13612 13613 @Override 13614 public int getIntentVerificationStatus(String packageName, int userId) { 13615 synchronized (mPackages) { 13616 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 13617 } 13618 } 13619 13620 @Override 13621 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 13622 mContext.enforceCallingOrSelfPermission( 13623 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13624 13625 boolean result = false; 13626 synchronized (mPackages) { 13627 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 13628 } 13629 if (result) { 13630 scheduleWritePackageRestrictionsLocked(userId); 13631 } 13632 return result; 13633 } 13634 13635 @Override 13636 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 13637 String packageName) { 13638 synchronized (mPackages) { 13639 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 13640 } 13641 } 13642 13643 @Override 13644 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 13645 if (TextUtils.isEmpty(packageName)) { 13646 return ParceledListSlice.emptyList(); 13647 } 13648 synchronized (mPackages) { 13649 PackageParser.Package pkg = mPackages.get(packageName); 13650 if (pkg == null || pkg.activities == null) { 13651 return ParceledListSlice.emptyList(); 13652 } 13653 final int count = pkg.activities.size(); 13654 ArrayList<IntentFilter> result = new ArrayList<>(); 13655 for (int n=0; n<count; n++) { 13656 PackageParser.Activity activity = pkg.activities.get(n); 13657 if (activity.intents != null && activity.intents.size() > 0) { 13658 result.addAll(activity.intents); 13659 } 13660 } 13661 return new ParceledListSlice<>(result); 13662 } 13663 } 13664 13665 @Override 13666 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 13667 mContext.enforceCallingOrSelfPermission( 13668 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13669 13670 synchronized (mPackages) { 13671 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 13672 if (packageName != null) { 13673 result |= updateIntentVerificationStatus(packageName, 13674 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 13675 userId); 13676 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 13677 packageName, userId); 13678 } 13679 return result; 13680 } 13681 } 13682 13683 @Override 13684 public String getDefaultBrowserPackageName(int userId) { 13685 synchronized (mPackages) { 13686 return mSettings.getDefaultBrowserPackageNameLPw(userId); 13687 } 13688 } 13689 13690 /** 13691 * Get the "allow unknown sources" setting. 13692 * 13693 * @return the current "allow unknown sources" setting 13694 */ 13695 private int getUnknownSourcesSettings() { 13696 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 13697 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 13698 -1); 13699 } 13700 13701 @Override 13702 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 13703 final int uid = Binder.getCallingUid(); 13704 // writer 13705 synchronized (mPackages) { 13706 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 13707 if (targetPackageSetting == null) { 13708 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 13709 } 13710 13711 PackageSetting installerPackageSetting; 13712 if (installerPackageName != null) { 13713 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 13714 if (installerPackageSetting == null) { 13715 throw new IllegalArgumentException("Unknown installer package: " 13716 + installerPackageName); 13717 } 13718 } else { 13719 installerPackageSetting = null; 13720 } 13721 13722 Signature[] callerSignature; 13723 Object obj = mSettings.getUserIdLPr(uid); 13724 if (obj != null) { 13725 if (obj instanceof SharedUserSetting) { 13726 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 13727 } else if (obj instanceof PackageSetting) { 13728 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 13729 } else { 13730 throw new SecurityException("Bad object " + obj + " for uid " + uid); 13731 } 13732 } else { 13733 throw new SecurityException("Unknown calling UID: " + uid); 13734 } 13735 13736 // Verify: can't set installerPackageName to a package that is 13737 // not signed with the same cert as the caller. 13738 if (installerPackageSetting != null) { 13739 if (compareSignatures(callerSignature, 13740 installerPackageSetting.signatures.mSignatures) 13741 != PackageManager.SIGNATURE_MATCH) { 13742 throw new SecurityException( 13743 "Caller does not have same cert as new installer package " 13744 + installerPackageName); 13745 } 13746 } 13747 13748 // Verify: if target already has an installer package, it must 13749 // be signed with the same cert as the caller. 13750 if (targetPackageSetting.installerPackageName != null) { 13751 PackageSetting setting = mSettings.mPackages.get( 13752 targetPackageSetting.installerPackageName); 13753 // If the currently set package isn't valid, then it's always 13754 // okay to change it. 13755 if (setting != null) { 13756 if (compareSignatures(callerSignature, 13757 setting.signatures.mSignatures) 13758 != PackageManager.SIGNATURE_MATCH) { 13759 throw new SecurityException( 13760 "Caller does not have same cert as old installer package " 13761 + targetPackageSetting.installerPackageName); 13762 } 13763 } 13764 } 13765 13766 // Okay! 13767 targetPackageSetting.installerPackageName = installerPackageName; 13768 if (installerPackageName != null) { 13769 mSettings.mInstallerPackages.add(installerPackageName); 13770 } 13771 scheduleWriteSettingsLocked(); 13772 } 13773 } 13774 13775 @Override 13776 public void setApplicationCategoryHint(String packageName, int categoryHint, 13777 String callerPackageName) { 13778 mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(), 13779 callerPackageName); 13780 synchronized (mPackages) { 13781 PackageSetting ps = mSettings.mPackages.get(packageName); 13782 if (ps == null) { 13783 throw new IllegalArgumentException("Unknown target package " + packageName); 13784 } 13785 13786 if (!Objects.equals(callerPackageName, ps.installerPackageName)) { 13787 throw new IllegalArgumentException("Calling package " + callerPackageName 13788 + " is not installer for " + packageName); 13789 } 13790 13791 if (ps.categoryHint != categoryHint) { 13792 ps.categoryHint = categoryHint; 13793 scheduleWriteSettingsLocked(); 13794 } 13795 } 13796 } 13797 13798 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 13799 // Queue up an async operation since the package installation may take a little while. 13800 mHandler.post(new Runnable() { 13801 public void run() { 13802 mHandler.removeCallbacks(this); 13803 // Result object to be returned 13804 PackageInstalledInfo res = new PackageInstalledInfo(); 13805 res.setReturnCode(currentStatus); 13806 res.uid = -1; 13807 res.pkg = null; 13808 res.removedInfo = null; 13809 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13810 args.doPreInstall(res.returnCode); 13811 synchronized (mInstallLock) { 13812 installPackageTracedLI(args, res); 13813 } 13814 args.doPostInstall(res.returnCode, res.uid); 13815 } 13816 13817 // A restore should be performed at this point if (a) the install 13818 // succeeded, (b) the operation is not an update, and (c) the new 13819 // package has not opted out of backup participation. 13820 final boolean update = res.removedInfo != null 13821 && res.removedInfo.removedPackage != null; 13822 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 13823 boolean doRestore = !update 13824 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 13825 13826 // Set up the post-install work request bookkeeping. This will be used 13827 // and cleaned up by the post-install event handling regardless of whether 13828 // there's a restore pass performed. Token values are >= 1. 13829 int token; 13830 if (mNextInstallToken < 0) mNextInstallToken = 1; 13831 token = mNextInstallToken++; 13832 13833 PostInstallData data = new PostInstallData(args, res); 13834 mRunningInstalls.put(token, data); 13835 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 13836 13837 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 13838 // Pass responsibility to the Backup Manager. It will perform a 13839 // restore if appropriate, then pass responsibility back to the 13840 // Package Manager to run the post-install observer callbacks 13841 // and broadcasts. 13842 IBackupManager bm = IBackupManager.Stub.asInterface( 13843 ServiceManager.getService(Context.BACKUP_SERVICE)); 13844 if (bm != null) { 13845 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 13846 + " to BM for possible restore"); 13847 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 13848 try { 13849 // TODO: http://b/22388012 13850 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 13851 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 13852 } else { 13853 doRestore = false; 13854 } 13855 } catch (RemoteException e) { 13856 // can't happen; the backup manager is local 13857 } catch (Exception e) { 13858 Slog.e(TAG, "Exception trying to enqueue restore", e); 13859 doRestore = false; 13860 } 13861 } else { 13862 Slog.e(TAG, "Backup Manager not found!"); 13863 doRestore = false; 13864 } 13865 } 13866 13867 if (!doRestore) { 13868 // No restore possible, or the Backup Manager was mysteriously not 13869 // available -- just fire the post-install work request directly. 13870 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 13871 13872 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 13873 13874 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 13875 mHandler.sendMessage(msg); 13876 } 13877 } 13878 }); 13879 } 13880 13881 /** 13882 * Callback from PackageSettings whenever an app is first transitioned out of the 13883 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 13884 * the app was "launched" for a restoreAtInstall operation. Therefore we check 13885 * here whether the app is the target of an ongoing install, and only send the 13886 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 13887 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 13888 * handling. 13889 */ 13890 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 13891 // Serialize this with the rest of the install-process message chain. In the 13892 // restore-at-install case, this Runnable will necessarily run before the 13893 // POST_INSTALL message is processed, so the contents of mRunningInstalls 13894 // are coherent. In the non-restore case, the app has already completed install 13895 // and been launched through some other means, so it is not in a problematic 13896 // state for observers to see the FIRST_LAUNCH signal. 13897 mHandler.post(new Runnable() { 13898 @Override 13899 public void run() { 13900 for (int i = 0; i < mRunningInstalls.size(); i++) { 13901 final PostInstallData data = mRunningInstalls.valueAt(i); 13902 if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 13903 continue; 13904 } 13905 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 13906 // right package; but is it for the right user? 13907 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 13908 if (userId == data.res.newUsers[uIndex]) { 13909 if (DEBUG_BACKUP) { 13910 Slog.i(TAG, "Package " + pkgName 13911 + " being restored so deferring FIRST_LAUNCH"); 13912 } 13913 return; 13914 } 13915 } 13916 } 13917 } 13918 // didn't find it, so not being restored 13919 if (DEBUG_BACKUP) { 13920 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 13921 } 13922 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 13923 } 13924 }); 13925 } 13926 13927 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 13928 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 13929 installerPkg, null, userIds); 13930 } 13931 13932 private abstract class HandlerParams { 13933 private static final int MAX_RETRIES = 4; 13934 13935 /** 13936 * Number of times startCopy() has been attempted and had a non-fatal 13937 * error. 13938 */ 13939 private int mRetries = 0; 13940 13941 /** User handle for the user requesting the information or installation. */ 13942 private final UserHandle mUser; 13943 String traceMethod; 13944 int traceCookie; 13945 13946 HandlerParams(UserHandle user) { 13947 mUser = user; 13948 } 13949 13950 UserHandle getUser() { 13951 return mUser; 13952 } 13953 13954 HandlerParams setTraceMethod(String traceMethod) { 13955 this.traceMethod = traceMethod; 13956 return this; 13957 } 13958 13959 HandlerParams setTraceCookie(int traceCookie) { 13960 this.traceCookie = traceCookie; 13961 return this; 13962 } 13963 13964 final boolean startCopy() { 13965 boolean res; 13966 try { 13967 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 13968 13969 if (++mRetries > MAX_RETRIES) { 13970 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 13971 mHandler.sendEmptyMessage(MCS_GIVE_UP); 13972 handleServiceError(); 13973 return false; 13974 } else { 13975 handleStartCopy(); 13976 res = true; 13977 } 13978 } catch (RemoteException e) { 13979 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 13980 mHandler.sendEmptyMessage(MCS_RECONNECT); 13981 res = false; 13982 } 13983 handleReturnCode(); 13984 return res; 13985 } 13986 13987 final void serviceError() { 13988 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 13989 handleServiceError(); 13990 handleReturnCode(); 13991 } 13992 13993 abstract void handleStartCopy() throws RemoteException; 13994 abstract void handleServiceError(); 13995 abstract void handleReturnCode(); 13996 } 13997 13998 class MeasureParams extends HandlerParams { 13999 private final PackageStats mStats; 14000 private boolean mSuccess; 14001 14002 private final IPackageStatsObserver mObserver; 14003 14004 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 14005 super(new UserHandle(stats.userHandle)); 14006 mObserver = observer; 14007 mStats = stats; 14008 } 14009 14010 @Override 14011 public String toString() { 14012 return "MeasureParams{" 14013 + Integer.toHexString(System.identityHashCode(this)) 14014 + " " + mStats.packageName + "}"; 14015 } 14016 14017 @Override 14018 void handleStartCopy() throws RemoteException { 14019 synchronized (mInstallLock) { 14020 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 14021 } 14022 14023 if (mSuccess) { 14024 boolean mounted = false; 14025 try { 14026 final String status = Environment.getExternalStorageState(); 14027 mounted = (Environment.MEDIA_MOUNTED.equals(status) 14028 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 14029 } catch (Exception e) { 14030 } 14031 14032 if (mounted) { 14033 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 14034 14035 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 14036 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 14037 14038 mStats.externalDataSize = calculateDirectorySize(mContainerService, 14039 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 14040 14041 // Always subtract cache size, since it's a subdirectory 14042 mStats.externalDataSize -= mStats.externalCacheSize; 14043 14044 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 14045 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 14046 14047 mStats.externalObbSize = calculateDirectorySize(mContainerService, 14048 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 14049 } 14050 } 14051 } 14052 14053 @Override 14054 void handleReturnCode() { 14055 if (mObserver != null) { 14056 try { 14057 mObserver.onGetStatsCompleted(mStats, mSuccess); 14058 } catch (RemoteException e) { 14059 Slog.i(TAG, "Observer no longer exists."); 14060 } 14061 } 14062 } 14063 14064 @Override 14065 void handleServiceError() { 14066 Slog.e(TAG, "Could not measure application " + mStats.packageName 14067 + " external storage"); 14068 } 14069 } 14070 14071 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 14072 throws RemoteException { 14073 long result = 0; 14074 for (File path : paths) { 14075 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 14076 } 14077 return result; 14078 } 14079 14080 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 14081 for (File path : paths) { 14082 try { 14083 mcs.clearDirectory(path.getAbsolutePath()); 14084 } catch (RemoteException e) { 14085 } 14086 } 14087 } 14088 14089 static class OriginInfo { 14090 /** 14091 * Location where install is coming from, before it has been 14092 * copied/renamed into place. This could be a single monolithic APK 14093 * file, or a cluster directory. This location may be untrusted. 14094 */ 14095 final File file; 14096 final String cid; 14097 14098 /** 14099 * Flag indicating that {@link #file} or {@link #cid} has already been 14100 * staged, meaning downstream users don't need to defensively copy the 14101 * contents. 14102 */ 14103 final boolean staged; 14104 14105 /** 14106 * Flag indicating that {@link #file} or {@link #cid} is an already 14107 * installed app that is being moved. 14108 */ 14109 final boolean existing; 14110 14111 final String resolvedPath; 14112 final File resolvedFile; 14113 14114 static OriginInfo fromNothing() { 14115 return new OriginInfo(null, null, false, false); 14116 } 14117 14118 static OriginInfo fromUntrustedFile(File file) { 14119 return new OriginInfo(file, null, false, false); 14120 } 14121 14122 static OriginInfo fromExistingFile(File file) { 14123 return new OriginInfo(file, null, false, true); 14124 } 14125 14126 static OriginInfo fromStagedFile(File file) { 14127 return new OriginInfo(file, null, true, false); 14128 } 14129 14130 static OriginInfo fromStagedContainer(String cid) { 14131 return new OriginInfo(null, cid, true, false); 14132 } 14133 14134 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 14135 this.file = file; 14136 this.cid = cid; 14137 this.staged = staged; 14138 this.existing = existing; 14139 14140 if (cid != null) { 14141 resolvedPath = PackageHelper.getSdDir(cid); 14142 resolvedFile = new File(resolvedPath); 14143 } else if (file != null) { 14144 resolvedPath = file.getAbsolutePath(); 14145 resolvedFile = file; 14146 } else { 14147 resolvedPath = null; 14148 resolvedFile = null; 14149 } 14150 } 14151 } 14152 14153 static class MoveInfo { 14154 final int moveId; 14155 final String fromUuid; 14156 final String toUuid; 14157 final String packageName; 14158 final String dataAppName; 14159 final int appId; 14160 final String seinfo; 14161 final int targetSdkVersion; 14162 14163 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 14164 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 14165 this.moveId = moveId; 14166 this.fromUuid = fromUuid; 14167 this.toUuid = toUuid; 14168 this.packageName = packageName; 14169 this.dataAppName = dataAppName; 14170 this.appId = appId; 14171 this.seinfo = seinfo; 14172 this.targetSdkVersion = targetSdkVersion; 14173 } 14174 } 14175 14176 static class VerificationInfo { 14177 /** A constant used to indicate that a uid value is not present. */ 14178 public static final int NO_UID = -1; 14179 14180 /** URI referencing where the package was downloaded from. */ 14181 final Uri originatingUri; 14182 14183 /** HTTP referrer URI associated with the originatingURI. */ 14184 final Uri referrer; 14185 14186 /** UID of the application that the install request originated from. */ 14187 final int originatingUid; 14188 14189 /** UID of application requesting the install */ 14190 final int installerUid; 14191 14192 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 14193 this.originatingUri = originatingUri; 14194 this.referrer = referrer; 14195 this.originatingUid = originatingUid; 14196 this.installerUid = installerUid; 14197 } 14198 } 14199 14200 class InstallParams extends HandlerParams { 14201 final OriginInfo origin; 14202 final MoveInfo move; 14203 final IPackageInstallObserver2 observer; 14204 int installFlags; 14205 final String installerPackageName; 14206 final String volumeUuid; 14207 private InstallArgs mArgs; 14208 private int mRet; 14209 final String packageAbiOverride; 14210 final String[] grantedRuntimePermissions; 14211 final VerificationInfo verificationInfo; 14212 final Certificate[][] certificates; 14213 final int installReason; 14214 14215 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 14216 int installFlags, String installerPackageName, String volumeUuid, 14217 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 14218 String[] grantedPermissions, Certificate[][] certificates, int installReason) { 14219 super(user); 14220 this.origin = origin; 14221 this.move = move; 14222 this.observer = observer; 14223 this.installFlags = installFlags; 14224 this.installerPackageName = installerPackageName; 14225 this.volumeUuid = volumeUuid; 14226 this.verificationInfo = verificationInfo; 14227 this.packageAbiOverride = packageAbiOverride; 14228 this.grantedRuntimePermissions = grantedPermissions; 14229 this.certificates = certificates; 14230 this.installReason = installReason; 14231 } 14232 14233 @Override 14234 public String toString() { 14235 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 14236 + " file=" + origin.file + " cid=" + origin.cid + "}"; 14237 } 14238 14239 private int installLocationPolicy(PackageInfoLite pkgLite) { 14240 String packageName = pkgLite.packageName; 14241 int installLocation = pkgLite.installLocation; 14242 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14243 // reader 14244 synchronized (mPackages) { 14245 // Currently installed package which the new package is attempting to replace or 14246 // null if no such package is installed. 14247 PackageParser.Package installedPkg = mPackages.get(packageName); 14248 // Package which currently owns the data which the new package will own if installed. 14249 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 14250 // will be null whereas dataOwnerPkg will contain information about the package 14251 // which was uninstalled while keeping its data. 14252 PackageParser.Package dataOwnerPkg = installedPkg; 14253 if (dataOwnerPkg == null) { 14254 PackageSetting ps = mSettings.mPackages.get(packageName); 14255 if (ps != null) { 14256 dataOwnerPkg = ps.pkg; 14257 } 14258 } 14259 14260 if (dataOwnerPkg != null) { 14261 // If installed, the package will get access to data left on the device by its 14262 // predecessor. As a security measure, this is permited only if this is not a 14263 // version downgrade or if the predecessor package is marked as debuggable and 14264 // a downgrade is explicitly requested. 14265 // 14266 // On debuggable platform builds, downgrades are permitted even for 14267 // non-debuggable packages to make testing easier. Debuggable platform builds do 14268 // not offer security guarantees and thus it's OK to disable some security 14269 // mechanisms to make debugging/testing easier on those builds. However, even on 14270 // debuggable builds downgrades of packages are permitted only if requested via 14271 // installFlags. This is because we aim to keep the behavior of debuggable 14272 // platform builds as close as possible to the behavior of non-debuggable 14273 // platform builds. 14274 final boolean downgradeRequested = 14275 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 14276 final boolean packageDebuggable = 14277 (dataOwnerPkg.applicationInfo.flags 14278 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 14279 final boolean downgradePermitted = 14280 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 14281 if (!downgradePermitted) { 14282 try { 14283 checkDowngrade(dataOwnerPkg, pkgLite); 14284 } catch (PackageManagerException e) { 14285 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 14286 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 14287 } 14288 } 14289 } 14290 14291 if (installedPkg != null) { 14292 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14293 // Check for updated system application. 14294 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 14295 if (onSd) { 14296 Slog.w(TAG, "Cannot install update to system app on sdcard"); 14297 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 14298 } 14299 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14300 } else { 14301 if (onSd) { 14302 // Install flag overrides everything. 14303 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14304 } 14305 // If current upgrade specifies particular preference 14306 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 14307 // Application explicitly specified internal. 14308 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14309 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 14310 // App explictly prefers external. Let policy decide 14311 } else { 14312 // Prefer previous location 14313 if (isExternal(installedPkg)) { 14314 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14315 } 14316 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14317 } 14318 } 14319 } else { 14320 // Invalid install. Return error code 14321 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 14322 } 14323 } 14324 } 14325 // All the special cases have been taken care of. 14326 // Return result based on recommended install location. 14327 if (onSd) { 14328 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14329 } 14330 return pkgLite.recommendedInstallLocation; 14331 } 14332 14333 /* 14334 * Invoke remote method to get package information and install 14335 * location values. Override install location based on default 14336 * policy if needed and then create install arguments based 14337 * on the install location. 14338 */ 14339 public void handleStartCopy() throws RemoteException { 14340 int ret = PackageManager.INSTALL_SUCCEEDED; 14341 14342 // If we're already staged, we've firmly committed to an install location 14343 if (origin.staged) { 14344 if (origin.file != null) { 14345 installFlags |= PackageManager.INSTALL_INTERNAL; 14346 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 14347 } else if (origin.cid != null) { 14348 installFlags |= PackageManager.INSTALL_EXTERNAL; 14349 installFlags &= ~PackageManager.INSTALL_INTERNAL; 14350 } else { 14351 throw new IllegalStateException("Invalid stage location"); 14352 } 14353 } 14354 14355 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14356 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 14357 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 14358 PackageInfoLite pkgLite = null; 14359 14360 if (onInt && onSd) { 14361 // Check if both bits are set. 14362 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 14363 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14364 } else if (onSd && ephemeral) { 14365 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 14366 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14367 } else { 14368 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 14369 packageAbiOverride); 14370 14371 if (DEBUG_EPHEMERAL && ephemeral) { 14372 Slog.v(TAG, "pkgLite for install: " + pkgLite); 14373 } 14374 14375 /* 14376 * If we have too little free space, try to free cache 14377 * before giving up. 14378 */ 14379 if (!origin.staged && pkgLite.recommendedInstallLocation 14380 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 14381 // TODO: focus freeing disk space on the target device 14382 final StorageManager storage = StorageManager.from(mContext); 14383 final long lowThreshold = storage.getStorageLowBytes( 14384 Environment.getDataDirectory()); 14385 14386 final long sizeBytes = mContainerService.calculateInstalledSize( 14387 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 14388 14389 try { 14390 mInstaller.freeCache(null, sizeBytes + lowThreshold, 0); 14391 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 14392 installFlags, packageAbiOverride); 14393 } catch (InstallerException e) { 14394 Slog.w(TAG, "Failed to free cache", e); 14395 } 14396 14397 /* 14398 * The cache free must have deleted the file we 14399 * downloaded to install. 14400 * 14401 * TODO: fix the "freeCache" call to not delete 14402 * the file we care about. 14403 */ 14404 if (pkgLite.recommendedInstallLocation 14405 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 14406 pkgLite.recommendedInstallLocation 14407 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 14408 } 14409 } 14410 } 14411 14412 if (ret == PackageManager.INSTALL_SUCCEEDED) { 14413 int loc = pkgLite.recommendedInstallLocation; 14414 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 14415 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14416 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 14417 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 14418 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 14419 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 14420 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 14421 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 14422 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 14423 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 14424 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 14425 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 14426 } else { 14427 // Override with defaults if needed. 14428 loc = installLocationPolicy(pkgLite); 14429 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 14430 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 14431 } else if (!onSd && !onInt) { 14432 // Override install location with flags 14433 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 14434 // Set the flag to install on external media. 14435 installFlags |= PackageManager.INSTALL_EXTERNAL; 14436 installFlags &= ~PackageManager.INSTALL_INTERNAL; 14437 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 14438 if (DEBUG_EPHEMERAL) { 14439 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 14440 } 14441 installFlags |= PackageManager.INSTALL_EPHEMERAL; 14442 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 14443 |PackageManager.INSTALL_INTERNAL); 14444 } else { 14445 // Make sure the flag for installing on external 14446 // media is unset 14447 installFlags |= PackageManager.INSTALL_INTERNAL; 14448 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 14449 } 14450 } 14451 } 14452 } 14453 14454 final InstallArgs args = createInstallArgs(this); 14455 mArgs = args; 14456 14457 if (ret == PackageManager.INSTALL_SUCCEEDED) { 14458 // TODO: http://b/22976637 14459 // Apps installed for "all" users use the device owner to verify the app 14460 UserHandle verifierUser = getUser(); 14461 if (verifierUser == UserHandle.ALL) { 14462 verifierUser = UserHandle.SYSTEM; 14463 } 14464 14465 /* 14466 * Determine if we have any installed package verifiers. If we 14467 * do, then we'll defer to them to verify the packages. 14468 */ 14469 final int requiredUid = mRequiredVerifierPackage == null ? -1 14470 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 14471 verifierUser.getIdentifier()); 14472 if (!origin.existing && requiredUid != -1 14473 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 14474 final Intent verification = new Intent( 14475 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 14476 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 14477 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 14478 PACKAGE_MIME_TYPE); 14479 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 14480 14481 // Query all live verifiers based on current user state 14482 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 14483 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 14484 14485 if (DEBUG_VERIFY) { 14486 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 14487 + verification.toString() + " with " + pkgLite.verifiers.length 14488 + " optional verifiers"); 14489 } 14490 14491 final int verificationId = mPendingVerificationToken++; 14492 14493 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 14494 14495 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 14496 installerPackageName); 14497 14498 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 14499 installFlags); 14500 14501 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 14502 pkgLite.packageName); 14503 14504 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 14505 pkgLite.versionCode); 14506 14507 if (verificationInfo != null) { 14508 if (verificationInfo.originatingUri != null) { 14509 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 14510 verificationInfo.originatingUri); 14511 } 14512 if (verificationInfo.referrer != null) { 14513 verification.putExtra(Intent.EXTRA_REFERRER, 14514 verificationInfo.referrer); 14515 } 14516 if (verificationInfo.originatingUid >= 0) { 14517 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 14518 verificationInfo.originatingUid); 14519 } 14520 if (verificationInfo.installerUid >= 0) { 14521 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 14522 verificationInfo.installerUid); 14523 } 14524 } 14525 14526 final PackageVerificationState verificationState = new PackageVerificationState( 14527 requiredUid, args); 14528 14529 mPendingVerification.append(verificationId, verificationState); 14530 14531 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 14532 receivers, verificationState); 14533 14534 /* 14535 * If any sufficient verifiers were listed in the package 14536 * manifest, attempt to ask them. 14537 */ 14538 if (sufficientVerifiers != null) { 14539 final int N = sufficientVerifiers.size(); 14540 if (N == 0) { 14541 Slog.i(TAG, "Additional verifiers required, but none installed."); 14542 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 14543 } else { 14544 for (int i = 0; i < N; i++) { 14545 final ComponentName verifierComponent = sufficientVerifiers.get(i); 14546 14547 final Intent sufficientIntent = new Intent(verification); 14548 sufficientIntent.setComponent(verifierComponent); 14549 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 14550 } 14551 } 14552 } 14553 14554 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 14555 mRequiredVerifierPackage, receivers); 14556 if (ret == PackageManager.INSTALL_SUCCEEDED 14557 && mRequiredVerifierPackage != null) { 14558 Trace.asyncTraceBegin( 14559 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 14560 /* 14561 * Send the intent to the required verification agent, 14562 * but only start the verification timeout after the 14563 * target BroadcastReceivers have run. 14564 */ 14565 verification.setComponent(requiredVerifierComponent); 14566 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 14567 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 14568 new BroadcastReceiver() { 14569 @Override 14570 public void onReceive(Context context, Intent intent) { 14571 final Message msg = mHandler 14572 .obtainMessage(CHECK_PENDING_VERIFICATION); 14573 msg.arg1 = verificationId; 14574 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 14575 } 14576 }, null, 0, null, null); 14577 14578 /* 14579 * We don't want the copy to proceed until verification 14580 * succeeds, so null out this field. 14581 */ 14582 mArgs = null; 14583 } 14584 } else { 14585 /* 14586 * No package verification is enabled, so immediately start 14587 * the remote call to initiate copy using temporary file. 14588 */ 14589 ret = args.copyApk(mContainerService, true); 14590 } 14591 } 14592 14593 mRet = ret; 14594 } 14595 14596 @Override 14597 void handleReturnCode() { 14598 // If mArgs is null, then MCS couldn't be reached. When it 14599 // reconnects, it will try again to install. At that point, this 14600 // will succeed. 14601 if (mArgs != null) { 14602 processPendingInstall(mArgs, mRet); 14603 } 14604 } 14605 14606 @Override 14607 void handleServiceError() { 14608 mArgs = createInstallArgs(this); 14609 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 14610 } 14611 14612 public boolean isForwardLocked() { 14613 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 14614 } 14615 } 14616 14617 /** 14618 * Used during creation of InstallArgs 14619 * 14620 * @param installFlags package installation flags 14621 * @return true if should be installed on external storage 14622 */ 14623 private static boolean installOnExternalAsec(int installFlags) { 14624 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 14625 return false; 14626 } 14627 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 14628 return true; 14629 } 14630 return false; 14631 } 14632 14633 /** 14634 * Used during creation of InstallArgs 14635 * 14636 * @param installFlags package installation flags 14637 * @return true if should be installed as forward locked 14638 */ 14639 private static boolean installForwardLocked(int installFlags) { 14640 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 14641 } 14642 14643 private InstallArgs createInstallArgs(InstallParams params) { 14644 if (params.move != null) { 14645 return new MoveInstallArgs(params); 14646 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 14647 return new AsecInstallArgs(params); 14648 } else { 14649 return new FileInstallArgs(params); 14650 } 14651 } 14652 14653 /** 14654 * Create args that describe an existing installed package. Typically used 14655 * when cleaning up old installs, or used as a move source. 14656 */ 14657 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 14658 String resourcePath, String[] instructionSets) { 14659 final boolean isInAsec; 14660 if (installOnExternalAsec(installFlags)) { 14661 /* Apps on SD card are always in ASEC containers. */ 14662 isInAsec = true; 14663 } else if (installForwardLocked(installFlags) 14664 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 14665 /* 14666 * Forward-locked apps are only in ASEC containers if they're the 14667 * new style 14668 */ 14669 isInAsec = true; 14670 } else { 14671 isInAsec = false; 14672 } 14673 14674 if (isInAsec) { 14675 return new AsecInstallArgs(codePath, instructionSets, 14676 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 14677 } else { 14678 return new FileInstallArgs(codePath, resourcePath, instructionSets); 14679 } 14680 } 14681 14682 static abstract class InstallArgs { 14683 /** @see InstallParams#origin */ 14684 final OriginInfo origin; 14685 /** @see InstallParams#move */ 14686 final MoveInfo move; 14687 14688 final IPackageInstallObserver2 observer; 14689 // Always refers to PackageManager flags only 14690 final int installFlags; 14691 final String installerPackageName; 14692 final String volumeUuid; 14693 final UserHandle user; 14694 final String abiOverride; 14695 final String[] installGrantPermissions; 14696 /** If non-null, drop an async trace when the install completes */ 14697 final String traceMethod; 14698 final int traceCookie; 14699 final Certificate[][] certificates; 14700 final int installReason; 14701 14702 // The list of instruction sets supported by this app. This is currently 14703 // only used during the rmdex() phase to clean up resources. We can get rid of this 14704 // if we move dex files under the common app path. 14705 /* nullable */ String[] instructionSets; 14706 14707 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 14708 int installFlags, String installerPackageName, String volumeUuid, 14709 UserHandle user, String[] instructionSets, 14710 String abiOverride, String[] installGrantPermissions, 14711 String traceMethod, int traceCookie, Certificate[][] certificates, 14712 int installReason) { 14713 this.origin = origin; 14714 this.move = move; 14715 this.installFlags = installFlags; 14716 this.observer = observer; 14717 this.installerPackageName = installerPackageName; 14718 this.volumeUuid = volumeUuid; 14719 this.user = user; 14720 this.instructionSets = instructionSets; 14721 this.abiOverride = abiOverride; 14722 this.installGrantPermissions = installGrantPermissions; 14723 this.traceMethod = traceMethod; 14724 this.traceCookie = traceCookie; 14725 this.certificates = certificates; 14726 this.installReason = installReason; 14727 } 14728 14729 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 14730 abstract int doPreInstall(int status); 14731 14732 /** 14733 * Rename package into final resting place. All paths on the given 14734 * scanned package should be updated to reflect the rename. 14735 */ 14736 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 14737 abstract int doPostInstall(int status, int uid); 14738 14739 /** @see PackageSettingBase#codePathString */ 14740 abstract String getCodePath(); 14741 /** @see PackageSettingBase#resourcePathString */ 14742 abstract String getResourcePath(); 14743 14744 // Need installer lock especially for dex file removal. 14745 abstract void cleanUpResourcesLI(); 14746 abstract boolean doPostDeleteLI(boolean delete); 14747 14748 /** 14749 * Called before the source arguments are copied. This is used mostly 14750 * for MoveParams when it needs to read the source file to put it in the 14751 * destination. 14752 */ 14753 int doPreCopy() { 14754 return PackageManager.INSTALL_SUCCEEDED; 14755 } 14756 14757 /** 14758 * Called after the source arguments are copied. This is used mostly for 14759 * MoveParams when it needs to read the source file to put it in the 14760 * destination. 14761 */ 14762 int doPostCopy(int uid) { 14763 return PackageManager.INSTALL_SUCCEEDED; 14764 } 14765 14766 protected boolean isFwdLocked() { 14767 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 14768 } 14769 14770 protected boolean isExternalAsec() { 14771 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14772 } 14773 14774 protected boolean isEphemeral() { 14775 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 14776 } 14777 14778 UserHandle getUser() { 14779 return user; 14780 } 14781 } 14782 14783 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 14784 if (!allCodePaths.isEmpty()) { 14785 if (instructionSets == null) { 14786 throw new IllegalStateException("instructionSet == null"); 14787 } 14788 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 14789 for (String codePath : allCodePaths) { 14790 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 14791 try { 14792 mInstaller.rmdex(codePath, dexCodeInstructionSet); 14793 } catch (InstallerException ignored) { 14794 } 14795 } 14796 } 14797 } 14798 } 14799 14800 /** 14801 * Logic to handle installation of non-ASEC applications, including copying 14802 * and renaming logic. 14803 */ 14804 class FileInstallArgs extends InstallArgs { 14805 private File codeFile; 14806 private File resourceFile; 14807 14808 // Example topology: 14809 // /data/app/com.example/base.apk 14810 // /data/app/com.example/split_foo.apk 14811 // /data/app/com.example/lib/arm/libfoo.so 14812 // /data/app/com.example/lib/arm64/libfoo.so 14813 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 14814 14815 /** New install */ 14816 FileInstallArgs(InstallParams params) { 14817 super(params.origin, params.move, params.observer, params.installFlags, 14818 params.installerPackageName, params.volumeUuid, 14819 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 14820 params.grantedRuntimePermissions, 14821 params.traceMethod, params.traceCookie, params.certificates, 14822 params.installReason); 14823 if (isFwdLocked()) { 14824 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 14825 } 14826 } 14827 14828 /** Existing install */ 14829 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 14830 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 14831 null, null, null, 0, null /*certificates*/, 14832 PackageManager.INSTALL_REASON_UNKNOWN); 14833 this.codeFile = (codePath != null) ? new File(codePath) : null; 14834 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 14835 } 14836 14837 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 14838 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 14839 try { 14840 return doCopyApk(imcs, temp); 14841 } finally { 14842 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14843 } 14844 } 14845 14846 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 14847 if (origin.staged) { 14848 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 14849 codeFile = origin.file; 14850 resourceFile = origin.file; 14851 return PackageManager.INSTALL_SUCCEEDED; 14852 } 14853 14854 try { 14855 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 14856 final File tempDir = 14857 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 14858 codeFile = tempDir; 14859 resourceFile = tempDir; 14860 } catch (IOException e) { 14861 Slog.w(TAG, "Failed to create copy file: " + e); 14862 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 14863 } 14864 14865 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 14866 @Override 14867 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 14868 if (!FileUtils.isValidExtFilename(name)) { 14869 throw new IllegalArgumentException("Invalid filename: " + name); 14870 } 14871 try { 14872 final File file = new File(codeFile, name); 14873 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 14874 O_RDWR | O_CREAT, 0644); 14875 Os.chmod(file.getAbsolutePath(), 0644); 14876 return new ParcelFileDescriptor(fd); 14877 } catch (ErrnoException e) { 14878 throw new RemoteException("Failed to open: " + e.getMessage()); 14879 } 14880 } 14881 }; 14882 14883 int ret = PackageManager.INSTALL_SUCCEEDED; 14884 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 14885 if (ret != PackageManager.INSTALL_SUCCEEDED) { 14886 Slog.e(TAG, "Failed to copy package"); 14887 return ret; 14888 } 14889 14890 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 14891 NativeLibraryHelper.Handle handle = null; 14892 try { 14893 handle = NativeLibraryHelper.Handle.create(codeFile); 14894 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 14895 abiOverride); 14896 } catch (IOException e) { 14897 Slog.e(TAG, "Copying native libraries failed", e); 14898 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 14899 } finally { 14900 IoUtils.closeQuietly(handle); 14901 } 14902 14903 return ret; 14904 } 14905 14906 int doPreInstall(int status) { 14907 if (status != PackageManager.INSTALL_SUCCEEDED) { 14908 cleanUp(); 14909 } 14910 return status; 14911 } 14912 14913 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 14914 if (status != PackageManager.INSTALL_SUCCEEDED) { 14915 cleanUp(); 14916 return false; 14917 } 14918 14919 final File targetDir = codeFile.getParentFile(); 14920 final File beforeCodeFile = codeFile; 14921 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 14922 14923 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 14924 try { 14925 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 14926 } catch (ErrnoException e) { 14927 Slog.w(TAG, "Failed to rename", e); 14928 return false; 14929 } 14930 14931 if (!SELinux.restoreconRecursive(afterCodeFile)) { 14932 Slog.w(TAG, "Failed to restorecon"); 14933 return false; 14934 } 14935 14936 // Reflect the rename internally 14937 codeFile = afterCodeFile; 14938 resourceFile = afterCodeFile; 14939 14940 // Reflect the rename in scanned details 14941 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 14942 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 14943 afterCodeFile, pkg.baseCodePath)); 14944 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 14945 afterCodeFile, pkg.splitCodePaths)); 14946 14947 // Reflect the rename in app info 14948 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 14949 pkg.setApplicationInfoCodePath(pkg.codePath); 14950 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 14951 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 14952 pkg.setApplicationInfoResourcePath(pkg.codePath); 14953 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 14954 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 14955 14956 return true; 14957 } 14958 14959 int doPostInstall(int status, int uid) { 14960 if (status != PackageManager.INSTALL_SUCCEEDED) { 14961 cleanUp(); 14962 } 14963 return status; 14964 } 14965 14966 @Override 14967 String getCodePath() { 14968 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 14969 } 14970 14971 @Override 14972 String getResourcePath() { 14973 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 14974 } 14975 14976 private boolean cleanUp() { 14977 if (codeFile == null || !codeFile.exists()) { 14978 return false; 14979 } 14980 14981 removeCodePathLI(codeFile); 14982 14983 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 14984 resourceFile.delete(); 14985 } 14986 14987 return true; 14988 } 14989 14990 void cleanUpResourcesLI() { 14991 // Try enumerating all code paths before deleting 14992 List<String> allCodePaths = Collections.EMPTY_LIST; 14993 if (codeFile != null && codeFile.exists()) { 14994 try { 14995 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 14996 allCodePaths = pkg.getAllCodePaths(); 14997 } catch (PackageParserException e) { 14998 // Ignored; we tried our best 14999 } 15000 } 15001 15002 cleanUp(); 15003 removeDexFiles(allCodePaths, instructionSets); 15004 } 15005 15006 boolean doPostDeleteLI(boolean delete) { 15007 // XXX err, shouldn't we respect the delete flag? 15008 cleanUpResourcesLI(); 15009 return true; 15010 } 15011 } 15012 15013 private boolean isAsecExternal(String cid) { 15014 final String asecPath = PackageHelper.getSdFilesystem(cid); 15015 return !asecPath.startsWith(mAsecInternalPath); 15016 } 15017 15018 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 15019 PackageManagerException { 15020 if (copyRet < 0) { 15021 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 15022 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 15023 throw new PackageManagerException(copyRet, message); 15024 } 15025 } 15026 } 15027 15028 /** 15029 * Extract the StorageManagerService "container ID" from the full code path of an 15030 * .apk. 15031 */ 15032 static String cidFromCodePath(String fullCodePath) { 15033 int eidx = fullCodePath.lastIndexOf("/"); 15034 String subStr1 = fullCodePath.substring(0, eidx); 15035 int sidx = subStr1.lastIndexOf("/"); 15036 return subStr1.substring(sidx+1, eidx); 15037 } 15038 15039 /** 15040 * Logic to handle installation of ASEC applications, including copying and 15041 * renaming logic. 15042 */ 15043 class AsecInstallArgs extends InstallArgs { 15044 static final String RES_FILE_NAME = "pkg.apk"; 15045 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 15046 15047 String cid; 15048 String packagePath; 15049 String resourcePath; 15050 15051 /** New install */ 15052 AsecInstallArgs(InstallParams params) { 15053 super(params.origin, params.move, params.observer, params.installFlags, 15054 params.installerPackageName, params.volumeUuid, 15055 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 15056 params.grantedRuntimePermissions, 15057 params.traceMethod, params.traceCookie, params.certificates, 15058 params.installReason); 15059 } 15060 15061 /** Existing install */ 15062 AsecInstallArgs(String fullCodePath, String[] instructionSets, 15063 boolean isExternal, boolean isForwardLocked) { 15064 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 15065 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 15066 instructionSets, null, null, null, 0, null /*certificates*/, 15067 PackageManager.INSTALL_REASON_UNKNOWN); 15068 // Hackily pretend we're still looking at a full code path 15069 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 15070 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 15071 } 15072 15073 // Extract cid from fullCodePath 15074 int eidx = fullCodePath.lastIndexOf("/"); 15075 String subStr1 = fullCodePath.substring(0, eidx); 15076 int sidx = subStr1.lastIndexOf("/"); 15077 cid = subStr1.substring(sidx+1, eidx); 15078 setMountPath(subStr1); 15079 } 15080 15081 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 15082 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 15083 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 15084 instructionSets, null, null, null, 0, null /*certificates*/, 15085 PackageManager.INSTALL_REASON_UNKNOWN); 15086 this.cid = cid; 15087 setMountPath(PackageHelper.getSdDir(cid)); 15088 } 15089 15090 void createCopyFile() { 15091 cid = mInstallerService.allocateExternalStageCidLegacy(); 15092 } 15093 15094 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 15095 if (origin.staged && origin.cid != null) { 15096 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 15097 cid = origin.cid; 15098 setMountPath(PackageHelper.getSdDir(cid)); 15099 return PackageManager.INSTALL_SUCCEEDED; 15100 } 15101 15102 if (temp) { 15103 createCopyFile(); 15104 } else { 15105 /* 15106 * Pre-emptively destroy the container since it's destroyed if 15107 * copying fails due to it existing anyway. 15108 */ 15109 PackageHelper.destroySdDir(cid); 15110 } 15111 15112 final String newMountPath = imcs.copyPackageToContainer( 15113 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 15114 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 15115 15116 if (newMountPath != null) { 15117 setMountPath(newMountPath); 15118 return PackageManager.INSTALL_SUCCEEDED; 15119 } else { 15120 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15121 } 15122 } 15123 15124 @Override 15125 String getCodePath() { 15126 return packagePath; 15127 } 15128 15129 @Override 15130 String getResourcePath() { 15131 return resourcePath; 15132 } 15133 15134 int doPreInstall(int status) { 15135 if (status != PackageManager.INSTALL_SUCCEEDED) { 15136 // Destroy container 15137 PackageHelper.destroySdDir(cid); 15138 } else { 15139 boolean mounted = PackageHelper.isContainerMounted(cid); 15140 if (!mounted) { 15141 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 15142 Process.SYSTEM_UID); 15143 if (newMountPath != null) { 15144 setMountPath(newMountPath); 15145 } else { 15146 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15147 } 15148 } 15149 } 15150 return status; 15151 } 15152 15153 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15154 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 15155 String newMountPath = null; 15156 if (PackageHelper.isContainerMounted(cid)) { 15157 // Unmount the container 15158 if (!PackageHelper.unMountSdDir(cid)) { 15159 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 15160 return false; 15161 } 15162 } 15163 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 15164 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 15165 " which might be stale. Will try to clean up."); 15166 // Clean up the stale container and proceed to recreate. 15167 if (!PackageHelper.destroySdDir(newCacheId)) { 15168 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 15169 return false; 15170 } 15171 // Successfully cleaned up stale container. Try to rename again. 15172 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 15173 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 15174 + " inspite of cleaning it up."); 15175 return false; 15176 } 15177 } 15178 if (!PackageHelper.isContainerMounted(newCacheId)) { 15179 Slog.w(TAG, "Mounting container " + newCacheId); 15180 newMountPath = PackageHelper.mountSdDir(newCacheId, 15181 getEncryptKey(), Process.SYSTEM_UID); 15182 } else { 15183 newMountPath = PackageHelper.getSdDir(newCacheId); 15184 } 15185 if (newMountPath == null) { 15186 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 15187 return false; 15188 } 15189 Log.i(TAG, "Succesfully renamed " + cid + 15190 " to " + newCacheId + 15191 " at new path: " + newMountPath); 15192 cid = newCacheId; 15193 15194 final File beforeCodeFile = new File(packagePath); 15195 setMountPath(newMountPath); 15196 final File afterCodeFile = new File(packagePath); 15197 15198 // Reflect the rename in scanned details 15199 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 15200 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 15201 afterCodeFile, pkg.baseCodePath)); 15202 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 15203 afterCodeFile, pkg.splitCodePaths)); 15204 15205 // Reflect the rename in app info 15206 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15207 pkg.setApplicationInfoCodePath(pkg.codePath); 15208 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15209 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15210 pkg.setApplicationInfoResourcePath(pkg.codePath); 15211 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15212 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15213 15214 return true; 15215 } 15216 15217 private void setMountPath(String mountPath) { 15218 final File mountFile = new File(mountPath); 15219 15220 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 15221 if (monolithicFile.exists()) { 15222 packagePath = monolithicFile.getAbsolutePath(); 15223 if (isFwdLocked()) { 15224 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 15225 } else { 15226 resourcePath = packagePath; 15227 } 15228 } else { 15229 packagePath = mountFile.getAbsolutePath(); 15230 resourcePath = packagePath; 15231 } 15232 } 15233 15234 int doPostInstall(int status, int uid) { 15235 if (status != PackageManager.INSTALL_SUCCEEDED) { 15236 cleanUp(); 15237 } else { 15238 final int groupOwner; 15239 final String protectedFile; 15240 if (isFwdLocked()) { 15241 groupOwner = UserHandle.getSharedAppGid(uid); 15242 protectedFile = RES_FILE_NAME; 15243 } else { 15244 groupOwner = -1; 15245 protectedFile = null; 15246 } 15247 15248 if (uid < Process.FIRST_APPLICATION_UID 15249 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 15250 Slog.e(TAG, "Failed to finalize " + cid); 15251 PackageHelper.destroySdDir(cid); 15252 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15253 } 15254 15255 boolean mounted = PackageHelper.isContainerMounted(cid); 15256 if (!mounted) { 15257 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 15258 } 15259 } 15260 return status; 15261 } 15262 15263 private void cleanUp() { 15264 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 15265 15266 // Destroy secure container 15267 PackageHelper.destroySdDir(cid); 15268 } 15269 15270 private List<String> getAllCodePaths() { 15271 final File codeFile = new File(getCodePath()); 15272 if (codeFile != null && codeFile.exists()) { 15273 try { 15274 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 15275 return pkg.getAllCodePaths(); 15276 } catch (PackageParserException e) { 15277 // Ignored; we tried our best 15278 } 15279 } 15280 return Collections.EMPTY_LIST; 15281 } 15282 15283 void cleanUpResourcesLI() { 15284 // Enumerate all code paths before deleting 15285 cleanUpResourcesLI(getAllCodePaths()); 15286 } 15287 15288 private void cleanUpResourcesLI(List<String> allCodePaths) { 15289 cleanUp(); 15290 removeDexFiles(allCodePaths, instructionSets); 15291 } 15292 15293 String getPackageName() { 15294 return getAsecPackageName(cid); 15295 } 15296 15297 boolean doPostDeleteLI(boolean delete) { 15298 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 15299 final List<String> allCodePaths = getAllCodePaths(); 15300 boolean mounted = PackageHelper.isContainerMounted(cid); 15301 if (mounted) { 15302 // Unmount first 15303 if (PackageHelper.unMountSdDir(cid)) { 15304 mounted = false; 15305 } 15306 } 15307 if (!mounted && delete) { 15308 cleanUpResourcesLI(allCodePaths); 15309 } 15310 return !mounted; 15311 } 15312 15313 @Override 15314 int doPreCopy() { 15315 if (isFwdLocked()) { 15316 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 15317 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 15318 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15319 } 15320 } 15321 15322 return PackageManager.INSTALL_SUCCEEDED; 15323 } 15324 15325 @Override 15326 int doPostCopy(int uid) { 15327 if (isFwdLocked()) { 15328 if (uid < Process.FIRST_APPLICATION_UID 15329 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 15330 RES_FILE_NAME)) { 15331 Slog.e(TAG, "Failed to finalize " + cid); 15332 PackageHelper.destroySdDir(cid); 15333 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15334 } 15335 } 15336 15337 return PackageManager.INSTALL_SUCCEEDED; 15338 } 15339 } 15340 15341 /** 15342 * Logic to handle movement of existing installed applications. 15343 */ 15344 class MoveInstallArgs extends InstallArgs { 15345 private File codeFile; 15346 private File resourceFile; 15347 15348 /** New install */ 15349 MoveInstallArgs(InstallParams params) { 15350 super(params.origin, params.move, params.observer, params.installFlags, 15351 params.installerPackageName, params.volumeUuid, 15352 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 15353 params.grantedRuntimePermissions, 15354 params.traceMethod, params.traceCookie, params.certificates, 15355 params.installReason); 15356 } 15357 15358 int copyApk(IMediaContainerService imcs, boolean temp) { 15359 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 15360 + move.fromUuid + " to " + move.toUuid); 15361 synchronized (mInstaller) { 15362 try { 15363 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 15364 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 15365 } catch (InstallerException e) { 15366 Slog.w(TAG, "Failed to move app", e); 15367 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15368 } 15369 } 15370 15371 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 15372 resourceFile = codeFile; 15373 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 15374 15375 return PackageManager.INSTALL_SUCCEEDED; 15376 } 15377 15378 int doPreInstall(int status) { 15379 if (status != PackageManager.INSTALL_SUCCEEDED) { 15380 cleanUp(move.toUuid); 15381 } 15382 return status; 15383 } 15384 15385 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15386 if (status != PackageManager.INSTALL_SUCCEEDED) { 15387 cleanUp(move.toUuid); 15388 return false; 15389 } 15390 15391 // Reflect the move in app info 15392 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15393 pkg.setApplicationInfoCodePath(pkg.codePath); 15394 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15395 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15396 pkg.setApplicationInfoResourcePath(pkg.codePath); 15397 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15398 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15399 15400 return true; 15401 } 15402 15403 int doPostInstall(int status, int uid) { 15404 if (status == PackageManager.INSTALL_SUCCEEDED) { 15405 cleanUp(move.fromUuid); 15406 } else { 15407 cleanUp(move.toUuid); 15408 } 15409 return status; 15410 } 15411 15412 @Override 15413 String getCodePath() { 15414 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 15415 } 15416 15417 @Override 15418 String getResourcePath() { 15419 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 15420 } 15421 15422 private boolean cleanUp(String volumeUuid) { 15423 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 15424 move.dataAppName); 15425 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 15426 final int[] userIds = sUserManager.getUserIds(); 15427 synchronized (mInstallLock) { 15428 // Clean up both app data and code 15429 // All package moves are frozen until finished 15430 for (int userId : userIds) { 15431 try { 15432 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 15433 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 15434 } catch (InstallerException e) { 15435 Slog.w(TAG, String.valueOf(e)); 15436 } 15437 } 15438 removeCodePathLI(codeFile); 15439 } 15440 return true; 15441 } 15442 15443 void cleanUpResourcesLI() { 15444 throw new UnsupportedOperationException(); 15445 } 15446 15447 boolean doPostDeleteLI(boolean delete) { 15448 throw new UnsupportedOperationException(); 15449 } 15450 } 15451 15452 static String getAsecPackageName(String packageCid) { 15453 int idx = packageCid.lastIndexOf("-"); 15454 if (idx == -1) { 15455 return packageCid; 15456 } 15457 return packageCid.substring(0, idx); 15458 } 15459 15460 // Utility method used to create code paths based on package name and available index. 15461 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 15462 String idxStr = ""; 15463 int idx = 1; 15464 // Fall back to default value of idx=1 if prefix is not 15465 // part of oldCodePath 15466 if (oldCodePath != null) { 15467 String subStr = oldCodePath; 15468 // Drop the suffix right away 15469 if (suffix != null && subStr.endsWith(suffix)) { 15470 subStr = subStr.substring(0, subStr.length() - suffix.length()); 15471 } 15472 // If oldCodePath already contains prefix find out the 15473 // ending index to either increment or decrement. 15474 int sidx = subStr.lastIndexOf(prefix); 15475 if (sidx != -1) { 15476 subStr = subStr.substring(sidx + prefix.length()); 15477 if (subStr != null) { 15478 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 15479 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 15480 } 15481 try { 15482 idx = Integer.parseInt(subStr); 15483 if (idx <= 1) { 15484 idx++; 15485 } else { 15486 idx--; 15487 } 15488 } catch(NumberFormatException e) { 15489 } 15490 } 15491 } 15492 } 15493 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 15494 return prefix + idxStr; 15495 } 15496 15497 private File getNextCodePath(File targetDir, String packageName) { 15498 File result; 15499 SecureRandom random = new SecureRandom(); 15500 byte[] bytes = new byte[16]; 15501 do { 15502 random.nextBytes(bytes); 15503 String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP); 15504 result = new File(targetDir, packageName + "-" + suffix); 15505 } while (result.exists()); 15506 return result; 15507 } 15508 15509 // Utility method that returns the relative package path with respect 15510 // to the installation directory. Like say for /data/data/com.test-1.apk 15511 // string com.test-1 is returned. 15512 static String deriveCodePathName(String codePath) { 15513 if (codePath == null) { 15514 return null; 15515 } 15516 final File codeFile = new File(codePath); 15517 final String name = codeFile.getName(); 15518 if (codeFile.isDirectory()) { 15519 return name; 15520 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 15521 final int lastDot = name.lastIndexOf('.'); 15522 return name.substring(0, lastDot); 15523 } else { 15524 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 15525 return null; 15526 } 15527 } 15528 15529 static class PackageInstalledInfo { 15530 String name; 15531 int uid; 15532 // The set of users that originally had this package installed. 15533 int[] origUsers; 15534 // The set of users that now have this package installed. 15535 int[] newUsers; 15536 PackageParser.Package pkg; 15537 int returnCode; 15538 String returnMsg; 15539 PackageRemovedInfo removedInfo; 15540 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 15541 15542 public void setError(int code, String msg) { 15543 setReturnCode(code); 15544 setReturnMessage(msg); 15545 Slog.w(TAG, msg); 15546 } 15547 15548 public void setError(String msg, PackageParserException e) { 15549 setReturnCode(e.error); 15550 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 15551 Slog.w(TAG, msg, e); 15552 } 15553 15554 public void setError(String msg, PackageManagerException e) { 15555 returnCode = e.error; 15556 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 15557 Slog.w(TAG, msg, e); 15558 } 15559 15560 public void setReturnCode(int returnCode) { 15561 this.returnCode = returnCode; 15562 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15563 for (int i = 0; i < childCount; i++) { 15564 addedChildPackages.valueAt(i).returnCode = returnCode; 15565 } 15566 } 15567 15568 private void setReturnMessage(String returnMsg) { 15569 this.returnMsg = returnMsg; 15570 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15571 for (int i = 0; i < childCount; i++) { 15572 addedChildPackages.valueAt(i).returnMsg = returnMsg; 15573 } 15574 } 15575 15576 // In some error cases we want to convey more info back to the observer 15577 String origPackage; 15578 String origPermission; 15579 } 15580 15581 /* 15582 * Install a non-existing package. 15583 */ 15584 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 15585 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 15586 PackageInstalledInfo res, int installReason) { 15587 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 15588 15589 // Remember this for later, in case we need to rollback this install 15590 String pkgName = pkg.packageName; 15591 15592 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 15593 15594 synchronized(mPackages) { 15595 final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName); 15596 if (renamedPackage != null) { 15597 // A package with the same name is already installed, though 15598 // it has been renamed to an older name. The package we 15599 // are trying to install should be installed as an update to 15600 // the existing one, but that has not been requested, so bail. 15601 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 15602 + " without first uninstalling package running as " 15603 + renamedPackage); 15604 return; 15605 } 15606 if (mPackages.containsKey(pkgName)) { 15607 // Don't allow installation over an existing package with the same name. 15608 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 15609 + " without first uninstalling."); 15610 return; 15611 } 15612 } 15613 15614 try { 15615 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 15616 System.currentTimeMillis(), user); 15617 15618 updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason); 15619 15620 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 15621 prepareAppDataAfterInstallLIF(newPackage); 15622 15623 } else { 15624 // Remove package from internal structures, but keep around any 15625 // data that might have already existed 15626 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 15627 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 15628 } 15629 } catch (PackageManagerException e) { 15630 res.setError("Package couldn't be installed in " + pkg.codePath, e); 15631 } 15632 15633 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15634 } 15635 15636 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 15637 // Can't rotate keys during boot or if sharedUser. 15638 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 15639 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 15640 return false; 15641 } 15642 // app is using upgradeKeySets; make sure all are valid 15643 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15644 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 15645 for (int i = 0; i < upgradeKeySets.length; i++) { 15646 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 15647 Slog.wtf(TAG, "Package " 15648 + (oldPs.name != null ? oldPs.name : "<null>") 15649 + " contains upgrade-key-set reference to unknown key-set: " 15650 + upgradeKeySets[i] 15651 + " reverting to signatures check."); 15652 return false; 15653 } 15654 } 15655 return true; 15656 } 15657 15658 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 15659 // Upgrade keysets are being used. Determine if new package has a superset of the 15660 // required keys. 15661 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 15662 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15663 for (int i = 0; i < upgradeKeySets.length; i++) { 15664 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 15665 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 15666 return true; 15667 } 15668 } 15669 return false; 15670 } 15671 15672 private static void updateDigest(MessageDigest digest, File file) throws IOException { 15673 try (DigestInputStream digestStream = 15674 new DigestInputStream(new FileInputStream(file), digest)) { 15675 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 15676 } 15677 } 15678 15679 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 15680 UserHandle user, String installerPackageName, PackageInstalledInfo res, 15681 int installReason) { 15682 final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 15683 15684 final PackageParser.Package oldPackage; 15685 final String pkgName = pkg.packageName; 15686 final int[] allUsers; 15687 final int[] installedUsers; 15688 15689 synchronized(mPackages) { 15690 oldPackage = mPackages.get(pkgName); 15691 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 15692 15693 // don't allow upgrade to target a release SDK from a pre-release SDK 15694 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 15695 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 15696 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 15697 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 15698 if (oldTargetsPreRelease 15699 && !newTargetsPreRelease 15700 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 15701 Slog.w(TAG, "Can't install package targeting released sdk"); 15702 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 15703 return; 15704 } 15705 15706 // don't allow an upgrade from full to ephemeral 15707 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 15708 if (isEphemeral && !oldIsEphemeral) { 15709 // can't downgrade from full to ephemeral 15710 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 15711 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 15712 return; 15713 } 15714 15715 // verify signatures are valid 15716 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15717 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 15718 if (!checkUpgradeKeySetLP(ps, pkg)) { 15719 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 15720 "New package not signed by keys specified by upgrade-keysets: " 15721 + pkgName); 15722 return; 15723 } 15724 } else { 15725 // default to original signature matching 15726 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 15727 != PackageManager.SIGNATURE_MATCH) { 15728 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 15729 "New package has a different signature: " + pkgName); 15730 return; 15731 } 15732 } 15733 15734 // don't allow a system upgrade unless the upgrade hash matches 15735 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 15736 byte[] digestBytes = null; 15737 try { 15738 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 15739 updateDigest(digest, new File(pkg.baseCodePath)); 15740 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 15741 for (String path : pkg.splitCodePaths) { 15742 updateDigest(digest, new File(path)); 15743 } 15744 } 15745 digestBytes = digest.digest(); 15746 } catch (NoSuchAlgorithmException | IOException e) { 15747 res.setError(INSTALL_FAILED_INVALID_APK, 15748 "Could not compute hash: " + pkgName); 15749 return; 15750 } 15751 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 15752 res.setError(INSTALL_FAILED_INVALID_APK, 15753 "New package fails restrict-update check: " + pkgName); 15754 return; 15755 } 15756 // retain upgrade restriction 15757 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 15758 } 15759 15760 // Check for shared user id changes 15761 String invalidPackageName = 15762 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 15763 if (invalidPackageName != null) { 15764 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 15765 "Package " + invalidPackageName + " tried to change user " 15766 + oldPackage.mSharedUserId); 15767 return; 15768 } 15769 15770 // In case of rollback, remember per-user/profile install state 15771 allUsers = sUserManager.getUserIds(); 15772 installedUsers = ps.queryInstalledUsers(allUsers, true); 15773 } 15774 15775 // Update what is removed 15776 res.removedInfo = new PackageRemovedInfo(); 15777 res.removedInfo.uid = oldPackage.applicationInfo.uid; 15778 res.removedInfo.removedPackage = oldPackage.packageName; 15779 res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null; 15780 res.removedInfo.isUpdate = true; 15781 res.removedInfo.origUsers = installedUsers; 15782 final PackageSetting ps = mSettings.getPackageLPr(pkgName); 15783 res.removedInfo.installReasons = new SparseArray<>(installedUsers.length); 15784 for (int i = 0; i < installedUsers.length; i++) { 15785 final int userId = installedUsers[i]; 15786 res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId)); 15787 } 15788 15789 final int childCount = (oldPackage.childPackages != null) 15790 ? oldPackage.childPackages.size() : 0; 15791 for (int i = 0; i < childCount; i++) { 15792 boolean childPackageUpdated = false; 15793 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 15794 final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 15795 if (res.addedChildPackages != null) { 15796 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 15797 if (childRes != null) { 15798 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 15799 childRes.removedInfo.removedPackage = childPkg.packageName; 15800 childRes.removedInfo.isUpdate = true; 15801 childRes.removedInfo.installReasons = res.removedInfo.installReasons; 15802 childPackageUpdated = true; 15803 } 15804 } 15805 if (!childPackageUpdated) { 15806 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 15807 childRemovedRes.removedPackage = childPkg.packageName; 15808 childRemovedRes.isUpdate = false; 15809 childRemovedRes.dataRemoved = true; 15810 synchronized (mPackages) { 15811 if (childPs != null) { 15812 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 15813 } 15814 } 15815 if (res.removedInfo.removedChildPackages == null) { 15816 res.removedInfo.removedChildPackages = new ArrayMap<>(); 15817 } 15818 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 15819 } 15820 } 15821 15822 boolean sysPkg = (isSystemApp(oldPackage)); 15823 if (sysPkg) { 15824 // Set the system/privileged flags as needed 15825 final boolean privileged = 15826 (oldPackage.applicationInfo.privateFlags 15827 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 15828 final int systemPolicyFlags = policyFlags 15829 | PackageParser.PARSE_IS_SYSTEM 15830 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 15831 15832 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 15833 user, allUsers, installerPackageName, res, installReason); 15834 } else { 15835 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 15836 user, allUsers, installerPackageName, res, installReason); 15837 } 15838 } 15839 15840 public List<String> getPreviousCodePaths(String packageName) { 15841 final PackageSetting ps = mSettings.mPackages.get(packageName); 15842 final List<String> result = new ArrayList<String>(); 15843 if (ps != null && ps.oldCodePaths != null) { 15844 result.addAll(ps.oldCodePaths); 15845 } 15846 return result; 15847 } 15848 15849 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 15850 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 15851 int[] allUsers, String installerPackageName, PackageInstalledInfo res, 15852 int installReason) { 15853 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 15854 + deletedPackage); 15855 15856 String pkgName = deletedPackage.packageName; 15857 boolean deletedPkg = true; 15858 boolean addedPkg = false; 15859 boolean updatedSettings = false; 15860 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 15861 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 15862 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 15863 15864 final long origUpdateTime = (pkg.mExtras != null) 15865 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 15866 15867 // First delete the existing package while retaining the data directory 15868 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 15869 res.removedInfo, true, pkg)) { 15870 // If the existing package wasn't successfully deleted 15871 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 15872 deletedPkg = false; 15873 } else { 15874 // Successfully deleted the old package; proceed with replace. 15875 15876 // If deleted package lived in a container, give users a chance to 15877 // relinquish resources before killing. 15878 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 15879 if (DEBUG_INSTALL) { 15880 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 15881 } 15882 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 15883 final ArrayList<String> pkgList = new ArrayList<String>(1); 15884 pkgList.add(deletedPackage.applicationInfo.packageName); 15885 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 15886 } 15887 15888 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 15889 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 15890 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 15891 15892 try { 15893 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 15894 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 15895 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 15896 installReason); 15897 15898 // Update the in-memory copy of the previous code paths. 15899 PackageSetting ps = mSettings.mPackages.get(pkgName); 15900 if (!killApp) { 15901 if (ps.oldCodePaths == null) { 15902 ps.oldCodePaths = new ArraySet<>(); 15903 } 15904 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 15905 if (deletedPackage.splitCodePaths != null) { 15906 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 15907 } 15908 } else { 15909 ps.oldCodePaths = null; 15910 } 15911 if (ps.childPackageNames != null) { 15912 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 15913 final String childPkgName = ps.childPackageNames.get(i); 15914 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 15915 childPs.oldCodePaths = ps.oldCodePaths; 15916 } 15917 } 15918 prepareAppDataAfterInstallLIF(newPackage); 15919 addedPkg = true; 15920 } catch (PackageManagerException e) { 15921 res.setError("Package couldn't be installed in " + pkg.codePath, e); 15922 } 15923 } 15924 15925 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 15926 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 15927 15928 // Revert all internal state mutations and added folders for the failed install 15929 if (addedPkg) { 15930 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 15931 res.removedInfo, true, null); 15932 } 15933 15934 // Restore the old package 15935 if (deletedPkg) { 15936 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 15937 File restoreFile = new File(deletedPackage.codePath); 15938 // Parse old package 15939 boolean oldExternal = isExternal(deletedPackage); 15940 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 15941 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 15942 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 15943 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 15944 try { 15945 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 15946 null); 15947 } catch (PackageManagerException e) { 15948 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 15949 + e.getMessage()); 15950 return; 15951 } 15952 15953 synchronized (mPackages) { 15954 // Ensure the installer package name up to date 15955 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 15956 15957 // Update permissions for restored package 15958 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 15959 15960 mSettings.writeLPr(); 15961 } 15962 15963 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 15964 } 15965 } else { 15966 synchronized (mPackages) { 15967 PackageSetting ps = mSettings.getPackageLPr(pkg.packageName); 15968 if (ps != null) { 15969 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 15970 if (res.removedInfo.removedChildPackages != null) { 15971 final int childCount = res.removedInfo.removedChildPackages.size(); 15972 // Iterate in reverse as we may modify the collection 15973 for (int i = childCount - 1; i >= 0; i--) { 15974 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 15975 if (res.addedChildPackages.containsKey(childPackageName)) { 15976 res.removedInfo.removedChildPackages.removeAt(i); 15977 } else { 15978 PackageRemovedInfo childInfo = res.removedInfo 15979 .removedChildPackages.valueAt(i); 15980 childInfo.removedForAllUsers = mPackages.get( 15981 childInfo.removedPackage) == null; 15982 } 15983 } 15984 } 15985 } 15986 } 15987 } 15988 } 15989 15990 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 15991 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 15992 int[] allUsers, String installerPackageName, PackageInstalledInfo res, 15993 int installReason) { 15994 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 15995 + ", old=" + deletedPackage); 15996 15997 final boolean disabledSystem; 15998 15999 // Remove existing system package 16000 removePackageLI(deletedPackage, true); 16001 16002 synchronized (mPackages) { 16003 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 16004 } 16005 if (!disabledSystem) { 16006 // We didn't need to disable the .apk as a current system package, 16007 // which means we are replacing another update that is already 16008 // installed. We need to make sure to delete the older one's .apk. 16009 res.removedInfo.args = createInstallArgsForExisting(0, 16010 deletedPackage.applicationInfo.getCodePath(), 16011 deletedPackage.applicationInfo.getResourcePath(), 16012 getAppDexInstructionSets(deletedPackage.applicationInfo)); 16013 } else { 16014 res.removedInfo.args = null; 16015 } 16016 16017 // Successfully disabled the old package. Now proceed with re-installation 16018 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 16019 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16020 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 16021 16022 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16023 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 16024 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 16025 16026 PackageParser.Package newPackage = null; 16027 try { 16028 // Add the package to the internal data structures 16029 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 16030 16031 // Set the update and install times 16032 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 16033 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 16034 System.currentTimeMillis()); 16035 16036 // Update the package dynamic state if succeeded 16037 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 16038 // Now that the install succeeded make sure we remove data 16039 // directories for any child package the update removed. 16040 final int deletedChildCount = (deletedPackage.childPackages != null) 16041 ? deletedPackage.childPackages.size() : 0; 16042 final int newChildCount = (newPackage.childPackages != null) 16043 ? newPackage.childPackages.size() : 0; 16044 for (int i = 0; i < deletedChildCount; i++) { 16045 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 16046 boolean childPackageDeleted = true; 16047 for (int j = 0; j < newChildCount; j++) { 16048 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 16049 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 16050 childPackageDeleted = false; 16051 break; 16052 } 16053 } 16054 if (childPackageDeleted) { 16055 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 16056 deletedChildPkg.packageName); 16057 if (ps != null && res.removedInfo.removedChildPackages != null) { 16058 PackageRemovedInfo removedChildRes = res.removedInfo 16059 .removedChildPackages.get(deletedChildPkg.packageName); 16060 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 16061 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 16062 } 16063 } 16064 } 16065 16066 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 16067 installReason); 16068 prepareAppDataAfterInstallLIF(newPackage); 16069 } 16070 } catch (PackageManagerException e) { 16071 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 16072 res.setError("Package couldn't be installed in " + pkg.codePath, e); 16073 } 16074 16075 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 16076 // Re installation failed. Restore old information 16077 // Remove new pkg information 16078 if (newPackage != null) { 16079 removeInstalledPackageLI(newPackage, true); 16080 } 16081 // Add back the old system package 16082 try { 16083 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 16084 } catch (PackageManagerException e) { 16085 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 16086 } 16087 16088 synchronized (mPackages) { 16089 if (disabledSystem) { 16090 enableSystemPackageLPw(deletedPackage); 16091 } 16092 16093 // Ensure the installer package name up to date 16094 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 16095 16096 // Update permissions for restored package 16097 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 16098 16099 mSettings.writeLPr(); 16100 } 16101 16102 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 16103 + " after failed upgrade"); 16104 } 16105 } 16106 16107 /** 16108 * Checks whether the parent or any of the child packages have a change shared 16109 * user. For a package to be a valid update the shred users of the parent and 16110 * the children should match. We may later support changing child shared users. 16111 * @param oldPkg The updated package. 16112 * @param newPkg The update package. 16113 * @return The shared user that change between the versions. 16114 */ 16115 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 16116 PackageParser.Package newPkg) { 16117 // Check parent shared user 16118 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 16119 return newPkg.packageName; 16120 } 16121 // Check child shared users 16122 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 16123 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 16124 for (int i = 0; i < newChildCount; i++) { 16125 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 16126 // If this child was present, did it have the same shared user? 16127 for (int j = 0; j < oldChildCount; j++) { 16128 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 16129 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 16130 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 16131 return newChildPkg.packageName; 16132 } 16133 } 16134 } 16135 return null; 16136 } 16137 16138 private void removeNativeBinariesLI(PackageSetting ps) { 16139 // Remove the lib path for the parent package 16140 if (ps != null) { 16141 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 16142 // Remove the lib path for the child packages 16143 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 16144 for (int i = 0; i < childCount; i++) { 16145 PackageSetting childPs = null; 16146 synchronized (mPackages) { 16147 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 16148 } 16149 if (childPs != null) { 16150 NativeLibraryHelper.removeNativeBinariesLI(childPs 16151 .legacyNativeLibraryPathString); 16152 } 16153 } 16154 } 16155 } 16156 16157 private void enableSystemPackageLPw(PackageParser.Package pkg) { 16158 // Enable the parent package 16159 mSettings.enableSystemPackageLPw(pkg.packageName); 16160 // Enable the child packages 16161 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16162 for (int i = 0; i < childCount; i++) { 16163 PackageParser.Package childPkg = pkg.childPackages.get(i); 16164 mSettings.enableSystemPackageLPw(childPkg.packageName); 16165 } 16166 } 16167 16168 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 16169 PackageParser.Package newPkg) { 16170 // Disable the parent package (parent always replaced) 16171 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 16172 // Disable the child packages 16173 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 16174 for (int i = 0; i < childCount; i++) { 16175 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 16176 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 16177 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 16178 } 16179 return disabled; 16180 } 16181 16182 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 16183 String installerPackageName) { 16184 // Enable the parent package 16185 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 16186 // Enable the child packages 16187 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16188 for (int i = 0; i < childCount; i++) { 16189 PackageParser.Package childPkg = pkg.childPackages.get(i); 16190 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 16191 } 16192 } 16193 16194 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 16195 // Collect all used permissions in the UID 16196 ArraySet<String> usedPermissions = new ArraySet<>(); 16197 final int packageCount = su.packages.size(); 16198 for (int i = 0; i < packageCount; i++) { 16199 PackageSetting ps = su.packages.valueAt(i); 16200 if (ps.pkg == null) { 16201 continue; 16202 } 16203 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 16204 for (int j = 0; j < requestedPermCount; j++) { 16205 String permission = ps.pkg.requestedPermissions.get(j); 16206 BasePermission bp = mSettings.mPermissions.get(permission); 16207 if (bp != null) { 16208 usedPermissions.add(permission); 16209 } 16210 } 16211 } 16212 16213 PermissionsState permissionsState = su.getPermissionsState(); 16214 // Prune install permissions 16215 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 16216 final int installPermCount = installPermStates.size(); 16217 for (int i = installPermCount - 1; i >= 0; i--) { 16218 PermissionState permissionState = installPermStates.get(i); 16219 if (!usedPermissions.contains(permissionState.getName())) { 16220 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 16221 if (bp != null) { 16222 permissionsState.revokeInstallPermission(bp); 16223 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 16224 PackageManager.MASK_PERMISSION_FLAGS, 0); 16225 } 16226 } 16227 } 16228 16229 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 16230 16231 // Prune runtime permissions 16232 for (int userId : allUserIds) { 16233 List<PermissionState> runtimePermStates = permissionsState 16234 .getRuntimePermissionStates(userId); 16235 final int runtimePermCount = runtimePermStates.size(); 16236 for (int i = runtimePermCount - 1; i >= 0; i--) { 16237 PermissionState permissionState = runtimePermStates.get(i); 16238 if (!usedPermissions.contains(permissionState.getName())) { 16239 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 16240 if (bp != null) { 16241 permissionsState.revokeRuntimePermission(bp, userId); 16242 permissionsState.updatePermissionFlags(bp, userId, 16243 PackageManager.MASK_PERMISSION_FLAGS, 0); 16244 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 16245 runtimePermissionChangedUserIds, userId); 16246 } 16247 } 16248 } 16249 } 16250 16251 return runtimePermissionChangedUserIds; 16252 } 16253 16254 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 16255 int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) { 16256 // Update the parent package setting 16257 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 16258 res, user, installReason); 16259 // Update the child packages setting 16260 final int childCount = (newPackage.childPackages != null) 16261 ? newPackage.childPackages.size() : 0; 16262 for (int i = 0; i < childCount; i++) { 16263 PackageParser.Package childPackage = newPackage.childPackages.get(i); 16264 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 16265 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 16266 childRes.origUsers, childRes, user, installReason); 16267 } 16268 } 16269 16270 private void updateSettingsInternalLI(PackageParser.Package newPackage, 16271 String installerPackageName, int[] allUsers, int[] installedForUsers, 16272 PackageInstalledInfo res, UserHandle user, int installReason) { 16273 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 16274 16275 String pkgName = newPackage.packageName; 16276 synchronized (mPackages) { 16277 //write settings. the installStatus will be incomplete at this stage. 16278 //note that the new package setting would have already been 16279 //added to mPackages. It hasn't been persisted yet. 16280 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 16281 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 16282 mSettings.writeLPr(); 16283 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16284 } 16285 16286 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 16287 synchronized (mPackages) { 16288 updatePermissionsLPw(newPackage.packageName, newPackage, 16289 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 16290 ? UPDATE_PERMISSIONS_ALL : 0)); 16291 // For system-bundled packages, we assume that installing an upgraded version 16292 // of the package implies that the user actually wants to run that new code, 16293 // so we enable the package. 16294 PackageSetting ps = mSettings.mPackages.get(pkgName); 16295 final int userId = user.getIdentifier(); 16296 if (ps != null) { 16297 if (isSystemApp(newPackage)) { 16298 if (DEBUG_INSTALL) { 16299 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 16300 } 16301 // Enable system package for requested users 16302 if (res.origUsers != null) { 16303 for (int origUserId : res.origUsers) { 16304 if (userId == UserHandle.USER_ALL || userId == origUserId) { 16305 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 16306 origUserId, installerPackageName); 16307 } 16308 } 16309 } 16310 // Also convey the prior install/uninstall state 16311 if (allUsers != null && installedForUsers != null) { 16312 for (int currentUserId : allUsers) { 16313 final boolean installed = ArrayUtils.contains( 16314 installedForUsers, currentUserId); 16315 if (DEBUG_INSTALL) { 16316 Slog.d(TAG, " user " + currentUserId + " => " + installed); 16317 } 16318 ps.setInstalled(installed, currentUserId); 16319 } 16320 // these install state changes will be persisted in the 16321 // upcoming call to mSettings.writeLPr(). 16322 } 16323 } 16324 // It's implied that when a user requests installation, they want the app to be 16325 // installed and enabled. 16326 if (userId != UserHandle.USER_ALL) { 16327 ps.setInstalled(true, userId); 16328 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 16329 } 16330 16331 // When replacing an existing package, preserve the original install reason for all 16332 // users that had the package installed before. 16333 final Set<Integer> previousUserIds = new ArraySet<>(); 16334 if (res.removedInfo != null && res.removedInfo.installReasons != null) { 16335 final int installReasonCount = res.removedInfo.installReasons.size(); 16336 for (int i = 0; i < installReasonCount; i++) { 16337 final int previousUserId = res.removedInfo.installReasons.keyAt(i); 16338 final int previousInstallReason = res.removedInfo.installReasons.valueAt(i); 16339 ps.setInstallReason(previousInstallReason, previousUserId); 16340 previousUserIds.add(previousUserId); 16341 } 16342 } 16343 16344 // Set install reason for users that are having the package newly installed. 16345 if (userId == UserHandle.USER_ALL) { 16346 for (int currentUserId : sUserManager.getUserIds()) { 16347 if (!previousUserIds.contains(currentUserId)) { 16348 ps.setInstallReason(installReason, currentUserId); 16349 } 16350 } 16351 } else if (!previousUserIds.contains(userId)) { 16352 ps.setInstallReason(installReason, userId); 16353 } 16354 } 16355 res.name = pkgName; 16356 res.uid = newPackage.applicationInfo.uid; 16357 res.pkg = newPackage; 16358 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 16359 mSettings.setInstallerPackageName(pkgName, installerPackageName); 16360 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16361 //to update install status 16362 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 16363 mSettings.writeLPr(); 16364 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16365 } 16366 16367 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16368 } 16369 16370 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 16371 try { 16372 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 16373 installPackageLI(args, res); 16374 } finally { 16375 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16376 } 16377 } 16378 16379 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 16380 final int installFlags = args.installFlags; 16381 final String installerPackageName = args.installerPackageName; 16382 final String volumeUuid = args.volumeUuid; 16383 final File tmpPackageFile = new File(args.getCodePath()); 16384 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 16385 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 16386 || (args.volumeUuid != null)); 16387 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 16388 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 16389 boolean replace = false; 16390 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 16391 if (args.move != null) { 16392 // moving a complete application; perform an initial scan on the new install location 16393 scanFlags |= SCAN_INITIAL; 16394 } 16395 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 16396 scanFlags |= SCAN_DONT_KILL_APP; 16397 } 16398 16399 // Result object to be returned 16400 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16401 16402 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 16403 16404 // Sanity check 16405 if (ephemeral && (forwardLocked || onExternal)) { 16406 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 16407 + " external=" + onExternal); 16408 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 16409 return; 16410 } 16411 16412 // Retrieve PackageSettings and parse package 16413 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 16414 | PackageParser.PARSE_ENFORCE_CODE 16415 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 16416 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 16417 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0) 16418 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 16419 PackageParser pp = new PackageParser(); 16420 pp.setSeparateProcesses(mSeparateProcesses); 16421 pp.setDisplayMetrics(mMetrics); 16422 16423 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 16424 final PackageParser.Package pkg; 16425 try { 16426 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 16427 } catch (PackageParserException e) { 16428 res.setError("Failed parse during installPackageLI", e); 16429 return; 16430 } finally { 16431 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16432 } 16433 16434 // Ephemeral apps must have target SDK >= O. 16435 // TODO: Update conditional and error message when O gets locked down 16436 if (ephemeral && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) { 16437 res.setError(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID, 16438 "Ephemeral apps must have target SDK version of at least O"); 16439 return; 16440 } 16441 16442 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16443 // Static shared libraries have synthetic package names 16444 renameStaticSharedLibraryPackage(pkg); 16445 16446 // No static shared libs on external storage 16447 if (onExternal) { 16448 Slog.i(TAG, "Static shared libs can only be installed on internal storage."); 16449 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 16450 "Packages declaring static-shared libs cannot be updated"); 16451 return; 16452 } 16453 } 16454 16455 // If we are installing a clustered package add results for the children 16456 if (pkg.childPackages != null) { 16457 synchronized (mPackages) { 16458 final int childCount = pkg.childPackages.size(); 16459 for (int i = 0; i < childCount; i++) { 16460 PackageParser.Package childPkg = pkg.childPackages.get(i); 16461 PackageInstalledInfo childRes = new PackageInstalledInfo(); 16462 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16463 childRes.pkg = childPkg; 16464 childRes.name = childPkg.packageName; 16465 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 16466 if (childPs != null) { 16467 childRes.origUsers = childPs.queryInstalledUsers( 16468 sUserManager.getUserIds(), true); 16469 } 16470 if ((mPackages.containsKey(childPkg.packageName))) { 16471 childRes.removedInfo = new PackageRemovedInfo(); 16472 childRes.removedInfo.removedPackage = childPkg.packageName; 16473 } 16474 if (res.addedChildPackages == null) { 16475 res.addedChildPackages = new ArrayMap<>(); 16476 } 16477 res.addedChildPackages.put(childPkg.packageName, childRes); 16478 } 16479 } 16480 } 16481 16482 // If package doesn't declare API override, mark that we have an install 16483 // time CPU ABI override. 16484 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 16485 pkg.cpuAbiOverride = args.abiOverride; 16486 } 16487 16488 String pkgName = res.name = pkg.packageName; 16489 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 16490 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 16491 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 16492 return; 16493 } 16494 } 16495 16496 try { 16497 // either use what we've been given or parse directly from the APK 16498 if (args.certificates != null) { 16499 try { 16500 PackageParser.populateCertificates(pkg, args.certificates); 16501 } catch (PackageParserException e) { 16502 // there was something wrong with the certificates we were given; 16503 // try to pull them from the APK 16504 PackageParser.collectCertificates(pkg, parseFlags); 16505 } 16506 } else { 16507 PackageParser.collectCertificates(pkg, parseFlags); 16508 } 16509 } catch (PackageParserException e) { 16510 res.setError("Failed collect during installPackageLI", e); 16511 return; 16512 } 16513 16514 // Get rid of all references to package scan path via parser. 16515 pp = null; 16516 String oldCodePath = null; 16517 boolean systemApp = false; 16518 synchronized (mPackages) { 16519 // Check if installing already existing package 16520 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 16521 String oldName = mSettings.getRenamedPackageLPr(pkgName); 16522 if (pkg.mOriginalPackages != null 16523 && pkg.mOriginalPackages.contains(oldName) 16524 && mPackages.containsKey(oldName)) { 16525 // This package is derived from an original package, 16526 // and this device has been updating from that original 16527 // name. We must continue using the original name, so 16528 // rename the new package here. 16529 pkg.setPackageName(oldName); 16530 pkgName = pkg.packageName; 16531 replace = true; 16532 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 16533 + oldName + " pkgName=" + pkgName); 16534 } else if (mPackages.containsKey(pkgName)) { 16535 // This package, under its official name, already exists 16536 // on the device; we should replace it. 16537 replace = true; 16538 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 16539 } 16540 16541 // Child packages are installed through the parent package 16542 if (pkg.parentPackage != null) { 16543 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 16544 "Package " + pkg.packageName + " is child of package " 16545 + pkg.parentPackage.parentPackage + ". Child packages " 16546 + "can be updated only through the parent package."); 16547 return; 16548 } 16549 16550 if (replace) { 16551 // Prevent apps opting out from runtime permissions 16552 PackageParser.Package oldPackage = mPackages.get(pkgName); 16553 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 16554 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 16555 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 16556 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 16557 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 16558 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 16559 + " doesn't support runtime permissions but the old" 16560 + " target SDK " + oldTargetSdk + " does."); 16561 return; 16562 } 16563 16564 // Prevent installing of child packages 16565 if (oldPackage.parentPackage != null) { 16566 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 16567 "Package " + pkg.packageName + " is child of package " 16568 + oldPackage.parentPackage + ". Child packages " 16569 + "can be updated only through the parent package."); 16570 return; 16571 } 16572 } 16573 } 16574 16575 PackageSetting ps = mSettings.mPackages.get(pkgName); 16576 if (ps != null) { 16577 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 16578 16579 // Static shared libs have same package with different versions where 16580 // we internally use a synthetic package name to allow multiple versions 16581 // of the same package, therefore we need to compare signatures against 16582 // the package setting for the latest library version. 16583 PackageSetting signatureCheckPs = ps; 16584 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16585 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg); 16586 if (libraryEntry != null) { 16587 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk); 16588 } 16589 } 16590 16591 // Quick sanity check that we're signed correctly if updating; 16592 // we'll check this again later when scanning, but we want to 16593 // bail early here before tripping over redefined permissions. 16594 if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) { 16595 if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) { 16596 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 16597 + pkg.packageName + " upgrade keys do not match the " 16598 + "previously installed version"); 16599 return; 16600 } 16601 } else { 16602 try { 16603 verifySignaturesLP(signatureCheckPs, pkg); 16604 } catch (PackageManagerException e) { 16605 res.setError(e.error, e.getMessage()); 16606 return; 16607 } 16608 } 16609 16610 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 16611 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 16612 systemApp = (ps.pkg.applicationInfo.flags & 16613 ApplicationInfo.FLAG_SYSTEM) != 0; 16614 } 16615 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 16616 } 16617 16618 // Check whether the newly-scanned package wants to define an already-defined perm 16619 int N = pkg.permissions.size(); 16620 for (int i = N-1; i >= 0; i--) { 16621 PackageParser.Permission perm = pkg.permissions.get(i); 16622 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 16623 if (bp != null) { 16624 // If the defining package is signed with our cert, it's okay. This 16625 // also includes the "updating the same package" case, of course. 16626 // "updating same package" could also involve key-rotation. 16627 final boolean sigsOk; 16628 if (bp.sourcePackage.equals(pkg.packageName) 16629 && (bp.packageSetting instanceof PackageSetting) 16630 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 16631 scanFlags))) { 16632 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 16633 } else { 16634 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 16635 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 16636 } 16637 if (!sigsOk) { 16638 // If the owning package is the system itself, we log but allow 16639 // install to proceed; we fail the install on all other permission 16640 // redefinitions. 16641 if (!bp.sourcePackage.equals("android")) { 16642 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 16643 + pkg.packageName + " attempting to redeclare permission " 16644 + perm.info.name + " already owned by " + bp.sourcePackage); 16645 res.origPermission = perm.info.name; 16646 res.origPackage = bp.sourcePackage; 16647 return; 16648 } else { 16649 Slog.w(TAG, "Package " + pkg.packageName 16650 + " attempting to redeclare system permission " 16651 + perm.info.name + "; ignoring new declaration"); 16652 pkg.permissions.remove(i); 16653 } 16654 } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) { 16655 // Prevent apps to change protection level to dangerous from any other 16656 // type as this would allow a privilege escalation where an app adds a 16657 // normal/signature permission in other app's group and later redefines 16658 // it as dangerous leading to the group auto-grant. 16659 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE) 16660 == PermissionInfo.PROTECTION_DANGEROUS) { 16661 if (bp != null && !bp.isRuntime()) { 16662 Slog.w(TAG, "Package " + pkg.packageName + " trying to change a " 16663 + "non-runtime permission " + perm.info.name 16664 + " to runtime; keeping old protection level"); 16665 perm.info.protectionLevel = bp.protectionLevel; 16666 } 16667 } 16668 } 16669 } 16670 } 16671 } 16672 16673 if (systemApp) { 16674 if (onExternal) { 16675 // Abort update; system app can't be replaced with app on sdcard 16676 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 16677 "Cannot install updates to system apps on sdcard"); 16678 return; 16679 } else if (ephemeral) { 16680 // Abort update; system app can't be replaced with an ephemeral app 16681 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 16682 "Cannot update a system app with an ephemeral app"); 16683 return; 16684 } 16685 } 16686 16687 if (args.move != null) { 16688 // We did an in-place move, so dex is ready to roll 16689 scanFlags |= SCAN_NO_DEX; 16690 scanFlags |= SCAN_MOVE; 16691 16692 synchronized (mPackages) { 16693 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16694 if (ps == null) { 16695 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 16696 "Missing settings for moved package " + pkgName); 16697 } 16698 16699 // We moved the entire application as-is, so bring over the 16700 // previously derived ABI information. 16701 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 16702 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 16703 } 16704 16705 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 16706 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 16707 scanFlags |= SCAN_NO_DEX; 16708 16709 try { 16710 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 16711 args.abiOverride : pkg.cpuAbiOverride); 16712 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 16713 true /*extractLibs*/, mAppLib32InstallDir); 16714 } catch (PackageManagerException pme) { 16715 Slog.e(TAG, "Error deriving application ABI", pme); 16716 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 16717 return; 16718 } 16719 16720 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 16721 // Do not run PackageDexOptimizer through the local performDexOpt 16722 // method because `pkg` may not be in `mPackages` yet. 16723 // 16724 // Also, don't fail application installs if the dexopt step fails. 16725 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 16726 null /* instructionSets */, false /* checkProfiles */, 16727 getCompilerFilterForReason(REASON_INSTALL), 16728 getOrCreateCompilerPackageStats(pkg)); 16729 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16730 16731 // Notify BackgroundDexOptService that the package has been changed. 16732 // If this is an update of a package which used to fail to compile, 16733 // BDOS will remove it from its blacklist. 16734 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 16735 } 16736 16737 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 16738 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 16739 return; 16740 } 16741 16742 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 16743 16744 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 16745 "installPackageLI")) { 16746 if (replace) { 16747 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16748 // Static libs have a synthetic package name containing the version 16749 // and cannot be updated as an update would get a new package name, 16750 // unless this is the exact same version code which is useful for 16751 // development. 16752 PackageParser.Package existingPkg = mPackages.get(pkg.packageName); 16753 if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) { 16754 res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring " 16755 + "static-shared libs cannot be updated"); 16756 return; 16757 } 16758 } 16759 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 16760 installerPackageName, res, args.installReason); 16761 } else { 16762 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 16763 args.user, installerPackageName, volumeUuid, res, args.installReason); 16764 } 16765 } 16766 synchronized (mPackages) { 16767 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16768 if (ps != null) { 16769 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 16770 } 16771 16772 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16773 for (int i = 0; i < childCount; i++) { 16774 PackageParser.Package childPkg = pkg.childPackages.get(i); 16775 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 16776 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 16777 if (childPs != null) { 16778 childRes.newUsers = childPs.queryInstalledUsers( 16779 sUserManager.getUserIds(), true); 16780 } 16781 } 16782 } 16783 } 16784 16785 private void startIntentFilterVerifications(int userId, boolean replacing, 16786 PackageParser.Package pkg) { 16787 if (mIntentFilterVerifierComponent == null) { 16788 Slog.w(TAG, "No IntentFilter verification will not be done as " 16789 + "there is no IntentFilterVerifier available!"); 16790 return; 16791 } 16792 16793 final int verifierUid = getPackageUid( 16794 mIntentFilterVerifierComponent.getPackageName(), 16795 MATCH_DEBUG_TRIAGED_MISSING, 16796 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 16797 16798 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 16799 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 16800 mHandler.sendMessage(msg); 16801 16802 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16803 for (int i = 0; i < childCount; i++) { 16804 PackageParser.Package childPkg = pkg.childPackages.get(i); 16805 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 16806 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 16807 mHandler.sendMessage(msg); 16808 } 16809 } 16810 16811 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 16812 PackageParser.Package pkg) { 16813 int size = pkg.activities.size(); 16814 if (size == 0) { 16815 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 16816 "No activity, so no need to verify any IntentFilter!"); 16817 return; 16818 } 16819 16820 final boolean hasDomainURLs = hasDomainURLs(pkg); 16821 if (!hasDomainURLs) { 16822 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 16823 "No domain URLs, so no need to verify any IntentFilter!"); 16824 return; 16825 } 16826 16827 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 16828 + " if any IntentFilter from the " + size 16829 + " Activities needs verification ..."); 16830 16831 int count = 0; 16832 final String packageName = pkg.packageName; 16833 16834 synchronized (mPackages) { 16835 // If this is a new install and we see that we've already run verification for this 16836 // package, we have nothing to do: it means the state was restored from backup. 16837 if (!replacing) { 16838 IntentFilterVerificationInfo ivi = 16839 mSettings.getIntentFilterVerificationLPr(packageName); 16840 if (ivi != null) { 16841 if (DEBUG_DOMAIN_VERIFICATION) { 16842 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 16843 + ivi.getStatusString()); 16844 } 16845 return; 16846 } 16847 } 16848 16849 // If any filters need to be verified, then all need to be. 16850 boolean needToVerify = false; 16851 for (PackageParser.Activity a : pkg.activities) { 16852 for (ActivityIntentInfo filter : a.intents) { 16853 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 16854 if (DEBUG_DOMAIN_VERIFICATION) { 16855 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 16856 } 16857 needToVerify = true; 16858 break; 16859 } 16860 } 16861 } 16862 16863 if (needToVerify) { 16864 final int verificationId = mIntentFilterVerificationToken++; 16865 for (PackageParser.Activity a : pkg.activities) { 16866 for (ActivityIntentInfo filter : a.intents) { 16867 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 16868 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 16869 "Verification needed for IntentFilter:" + filter.toString()); 16870 mIntentFilterVerifier.addOneIntentFilterVerification( 16871 verifierUid, userId, verificationId, filter, packageName); 16872 count++; 16873 } 16874 } 16875 } 16876 } 16877 } 16878 16879 if (count > 0) { 16880 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 16881 + " IntentFilter verification" + (count > 1 ? "s" : "") 16882 + " for userId:" + userId); 16883 mIntentFilterVerifier.startVerifications(userId); 16884 } else { 16885 if (DEBUG_DOMAIN_VERIFICATION) { 16886 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 16887 } 16888 } 16889 } 16890 16891 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 16892 final ComponentName cn = filter.activity.getComponentName(); 16893 final String packageName = cn.getPackageName(); 16894 16895 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 16896 packageName); 16897 if (ivi == null) { 16898 return true; 16899 } 16900 int status = ivi.getStatus(); 16901 switch (status) { 16902 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 16903 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 16904 return true; 16905 16906 default: 16907 // Nothing to do 16908 return false; 16909 } 16910 } 16911 16912 private static boolean isMultiArch(ApplicationInfo info) { 16913 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 16914 } 16915 16916 private static boolean isExternal(PackageParser.Package pkg) { 16917 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 16918 } 16919 16920 private static boolean isExternal(PackageSetting ps) { 16921 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 16922 } 16923 16924 private static boolean isEphemeral(PackageParser.Package pkg) { 16925 return pkg.applicationInfo.isEphemeralApp(); 16926 } 16927 16928 private static boolean isEphemeral(PackageSetting ps) { 16929 return ps.pkg != null && isEphemeral(ps.pkg); 16930 } 16931 16932 private static boolean isSystemApp(PackageParser.Package pkg) { 16933 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 16934 } 16935 16936 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 16937 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 16938 } 16939 16940 private static boolean hasDomainURLs(PackageParser.Package pkg) { 16941 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 16942 } 16943 16944 private static boolean isSystemApp(PackageSetting ps) { 16945 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 16946 } 16947 16948 private static boolean isUpdatedSystemApp(PackageSetting ps) { 16949 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 16950 } 16951 16952 private int packageFlagsToInstallFlags(PackageSetting ps) { 16953 int installFlags = 0; 16954 if (isEphemeral(ps)) { 16955 installFlags |= PackageManager.INSTALL_EPHEMERAL; 16956 } 16957 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 16958 // This existing package was an external ASEC install when we have 16959 // the external flag without a UUID 16960 installFlags |= PackageManager.INSTALL_EXTERNAL; 16961 } 16962 if (ps.isForwardLocked()) { 16963 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 16964 } 16965 return installFlags; 16966 } 16967 16968 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 16969 if (isExternal(pkg)) { 16970 if (TextUtils.isEmpty(pkg.volumeUuid)) { 16971 return StorageManager.UUID_PRIMARY_PHYSICAL; 16972 } else { 16973 return pkg.volumeUuid; 16974 } 16975 } else { 16976 return StorageManager.UUID_PRIVATE_INTERNAL; 16977 } 16978 } 16979 16980 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 16981 if (isExternal(pkg)) { 16982 if (TextUtils.isEmpty(pkg.volumeUuid)) { 16983 return mSettings.getExternalVersion(); 16984 } else { 16985 return mSettings.findOrCreateVersion(pkg.volumeUuid); 16986 } 16987 } else { 16988 return mSettings.getInternalVersion(); 16989 } 16990 } 16991 16992 private void deleteTempPackageFiles() { 16993 final FilenameFilter filter = new FilenameFilter() { 16994 public boolean accept(File dir, String name) { 16995 return name.startsWith("vmdl") && name.endsWith(".tmp"); 16996 } 16997 }; 16998 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 16999 file.delete(); 17000 } 17001 } 17002 17003 @Override 17004 public void deletePackageAsUser(String packageName, int versionCode, 17005 IPackageDeleteObserver observer, int userId, int flags) { 17006 deletePackageVersioned(new VersionedPackage(packageName, versionCode), 17007 new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags); 17008 } 17009 17010 @Override 17011 public void deletePackageVersioned(VersionedPackage versionedPackage, 17012 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 17013 mContext.enforceCallingOrSelfPermission( 17014 android.Manifest.permission.DELETE_PACKAGES, null); 17015 Preconditions.checkNotNull(versionedPackage); 17016 Preconditions.checkNotNull(observer); 17017 Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(), 17018 PackageManager.VERSION_CODE_HIGHEST, 17019 Integer.MAX_VALUE, "versionCode must be >= -1"); 17020 17021 final String packageName = versionedPackage.getPackageName(); 17022 // TODO: We will change version code to long, so in the new API it is long 17023 final int versionCode = (int) versionedPackage.getVersionCode(); 17024 final String internalPackageName; 17025 synchronized (mPackages) { 17026 // Normalize package name to handle renamed packages and static libs 17027 internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(), 17028 // TODO: We will change version code to long, so in the new API it is long 17029 (int) versionedPackage.getVersionCode()); 17030 } 17031 17032 final int uid = Binder.getCallingUid(); 17033 if (!isOrphaned(internalPackageName) 17034 && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) { 17035 try { 17036 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 17037 intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null)); 17038 intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder()); 17039 observer.onUserActionRequired(intent); 17040 } catch (RemoteException re) { 17041 } 17042 return; 17043 } 17044 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 17045 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 17046 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 17047 mContext.enforceCallingOrSelfPermission( 17048 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 17049 "deletePackage for user " + userId); 17050 } 17051 17052 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 17053 try { 17054 observer.onPackageDeleted(packageName, 17055 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 17056 } catch (RemoteException re) { 17057 } 17058 return; 17059 } 17060 17061 if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) { 17062 try { 17063 observer.onPackageDeleted(packageName, 17064 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 17065 } catch (RemoteException re) { 17066 } 17067 return; 17068 } 17069 17070 if (DEBUG_REMOVE) { 17071 Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId 17072 + " deleteAllUsers: " + deleteAllUsers + " version=" 17073 + (versionCode == PackageManager.VERSION_CODE_HIGHEST 17074 ? "VERSION_CODE_HIGHEST" : versionCode)); 17075 } 17076 // Queue up an async operation since the package deletion may take a little while. 17077 mHandler.post(new Runnable() { 17078 public void run() { 17079 mHandler.removeCallbacks(this); 17080 int returnCode; 17081 if (!deleteAllUsers) { 17082 returnCode = deletePackageX(internalPackageName, versionCode, 17083 userId, deleteFlags); 17084 } else { 17085 int[] blockUninstallUserIds = getBlockUninstallForUsers( 17086 internalPackageName, users); 17087 // If nobody is blocking uninstall, proceed with delete for all users 17088 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 17089 returnCode = deletePackageX(internalPackageName, versionCode, 17090 userId, deleteFlags); 17091 } else { 17092 // Otherwise uninstall individually for users with blockUninstalls=false 17093 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 17094 for (int userId : users) { 17095 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 17096 returnCode = deletePackageX(internalPackageName, versionCode, 17097 userId, userFlags); 17098 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 17099 Slog.w(TAG, "Package delete failed for user " + userId 17100 + ", returnCode " + returnCode); 17101 } 17102 } 17103 } 17104 // The app has only been marked uninstalled for certain users. 17105 // We still need to report that delete was blocked 17106 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 17107 } 17108 } 17109 try { 17110 observer.onPackageDeleted(packageName, returnCode, null); 17111 } catch (RemoteException e) { 17112 Log.i(TAG, "Observer no longer exists."); 17113 } //end catch 17114 } //end run 17115 }); 17116 } 17117 17118 private String resolveExternalPackageNameLPr(PackageParser.Package pkg) { 17119 if (pkg.staticSharedLibName != null) { 17120 return pkg.manifestPackageName; 17121 } 17122 return pkg.packageName; 17123 } 17124 17125 private String resolveInternalPackageNameLPr(String packageName, int versionCode) { 17126 // Handle renamed packages 17127 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 17128 packageName = normalizedPackageName != null ? normalizedPackageName : packageName; 17129 17130 // Is this a static library? 17131 SparseArray<SharedLibraryEntry> versionedLib = 17132 mStaticLibsByDeclaringPackage.get(packageName); 17133 if (versionedLib == null || versionedLib.size() <= 0) { 17134 return packageName; 17135 } 17136 17137 // Figure out which lib versions the caller can see 17138 SparseIntArray versionsCallerCanSee = null; 17139 final int callingAppId = UserHandle.getAppId(Binder.getCallingUid()); 17140 if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID 17141 && callingAppId != Process.ROOT_UID) { 17142 versionsCallerCanSee = new SparseIntArray(); 17143 String libName = versionedLib.valueAt(0).info.getName(); 17144 String[] uidPackages = getPackagesForUid(Binder.getCallingUid()); 17145 if (uidPackages != null) { 17146 for (String uidPackage : uidPackages) { 17147 PackageSetting ps = mSettings.getPackageLPr(uidPackage); 17148 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 17149 if (libIdx >= 0) { 17150 final int libVersion = ps.usesStaticLibrariesVersions[libIdx]; 17151 versionsCallerCanSee.append(libVersion, libVersion); 17152 } 17153 } 17154 } 17155 } 17156 17157 // Caller can see nothing - done 17158 if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) { 17159 return packageName; 17160 } 17161 17162 // Find the version the caller can see and the app version code 17163 SharedLibraryEntry highestVersion = null; 17164 final int versionCount = versionedLib.size(); 17165 for (int i = 0; i < versionCount; i++) { 17166 SharedLibraryEntry libEntry = versionedLib.valueAt(i); 17167 if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey( 17168 libEntry.info.getVersion()) < 0) { 17169 continue; 17170 } 17171 // TODO: We will change version code to long, so in the new API it is long 17172 final int libVersionCode = (int) libEntry.info.getDeclaringPackage().getVersionCode(); 17173 if (versionCode != PackageManager.VERSION_CODE_HIGHEST) { 17174 if (libVersionCode == versionCode) { 17175 return libEntry.apk; 17176 } 17177 } else if (highestVersion == null) { 17178 highestVersion = libEntry; 17179 } else if (libVersionCode > highestVersion.info 17180 .getDeclaringPackage().getVersionCode()) { 17181 highestVersion = libEntry; 17182 } 17183 } 17184 17185 if (highestVersion != null) { 17186 return highestVersion.apk; 17187 } 17188 17189 return packageName; 17190 } 17191 17192 private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) { 17193 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID 17194 || callingUid == Process.SYSTEM_UID) { 17195 return true; 17196 } 17197 final int callingUserId = UserHandle.getUserId(callingUid); 17198 // If the caller installed the pkgName, then allow it to silently uninstall. 17199 if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) { 17200 return true; 17201 } 17202 17203 // Allow package verifier to silently uninstall. 17204 if (mRequiredVerifierPackage != null && 17205 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) { 17206 return true; 17207 } 17208 17209 // Allow package uninstaller to silently uninstall. 17210 if (mRequiredUninstallerPackage != null && 17211 callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) { 17212 return true; 17213 } 17214 17215 // Allow storage manager to silently uninstall. 17216 if (mStorageManagerPackage != null && 17217 callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) { 17218 return true; 17219 } 17220 return false; 17221 } 17222 17223 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 17224 int[] result = EMPTY_INT_ARRAY; 17225 for (int userId : userIds) { 17226 if (getBlockUninstallForUser(packageName, userId)) { 17227 result = ArrayUtils.appendInt(result, userId); 17228 } 17229 } 17230 return result; 17231 } 17232 17233 @Override 17234 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 17235 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 17236 } 17237 17238 private boolean isPackageDeviceAdmin(String packageName, int userId) { 17239 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 17240 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 17241 try { 17242 if (dpm != null) { 17243 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 17244 /* callingUserOnly =*/ false); 17245 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 17246 : deviceOwnerComponentName.getPackageName(); 17247 // Does the package contains the device owner? 17248 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 17249 // this check is probably not needed, since DO should be registered as a device 17250 // admin on some user too. (Original bug for this: b/17657954) 17251 if (packageName.equals(deviceOwnerPackageName)) { 17252 return true; 17253 } 17254 // Does it contain a device admin for any user? 17255 int[] users; 17256 if (userId == UserHandle.USER_ALL) { 17257 users = sUserManager.getUserIds(); 17258 } else { 17259 users = new int[]{userId}; 17260 } 17261 for (int i = 0; i < users.length; ++i) { 17262 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 17263 return true; 17264 } 17265 } 17266 } 17267 } catch (RemoteException e) { 17268 } 17269 return false; 17270 } 17271 17272 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 17273 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 17274 } 17275 17276 /** 17277 * This method is an internal method that could be get invoked either 17278 * to delete an installed package or to clean up a failed installation. 17279 * After deleting an installed package, a broadcast is sent to notify any 17280 * listeners that the package has been removed. For cleaning up a failed 17281 * installation, the broadcast is not necessary since the package's 17282 * installation wouldn't have sent the initial broadcast either 17283 * The key steps in deleting a package are 17284 * deleting the package information in internal structures like mPackages, 17285 * deleting the packages base directories through installd 17286 * updating mSettings to reflect current status 17287 * persisting settings for later use 17288 * sending a broadcast if necessary 17289 */ 17290 private int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) { 17291 final PackageRemovedInfo info = new PackageRemovedInfo(); 17292 final boolean res; 17293 17294 final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 17295 ? UserHandle.USER_ALL : userId; 17296 17297 if (isPackageDeviceAdmin(packageName, removeUser)) { 17298 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 17299 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 17300 } 17301 17302 PackageSetting uninstalledPs = null; 17303 17304 // for the uninstall-updates case and restricted profiles, remember the per- 17305 // user handle installed state 17306 int[] allUsers; 17307 synchronized (mPackages) { 17308 uninstalledPs = mSettings.mPackages.get(packageName); 17309 if (uninstalledPs == null) { 17310 Slog.w(TAG, "Not removing non-existent package " + packageName); 17311 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17312 } 17313 17314 if (versionCode != PackageManager.VERSION_CODE_HIGHEST 17315 && uninstalledPs.versionCode != versionCode) { 17316 Slog.w(TAG, "Not removing package " + packageName + " with versionCode " 17317 + uninstalledPs.versionCode + " != " + versionCode); 17318 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17319 } 17320 17321 // Static shared libs can be declared by any package, so let us not 17322 // allow removing a package if it provides a lib others depend on. 17323 PackageParser.Package pkg = mPackages.get(packageName); 17324 if (pkg != null && pkg.staticSharedLibName != null) { 17325 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName, 17326 pkg.staticSharedLibVersion); 17327 if (libEntry != null) { 17328 List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr( 17329 libEntry.info, 0, userId); 17330 if (!ArrayUtils.isEmpty(libClientPackages)) { 17331 Slog.w(TAG, "Not removing package " + pkg.manifestPackageName 17332 + " hosting lib " + libEntry.info.getName() + " version " 17333 + libEntry.info.getVersion() + " used by " + libClientPackages); 17334 return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY; 17335 } 17336 } 17337 } 17338 17339 allUsers = sUserManager.getUserIds(); 17340 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 17341 } 17342 17343 final int freezeUser; 17344 if (isUpdatedSystemApp(uninstalledPs) 17345 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) { 17346 // We're downgrading a system app, which will apply to all users, so 17347 // freeze them all during the downgrade 17348 freezeUser = UserHandle.USER_ALL; 17349 } else { 17350 freezeUser = removeUser; 17351 } 17352 17353 synchronized (mInstallLock) { 17354 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 17355 try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser, 17356 deleteFlags, "deletePackageX")) { 17357 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers, 17358 deleteFlags | REMOVE_CHATTY, info, true, null); 17359 } 17360 synchronized (mPackages) { 17361 if (res) { 17362 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 17363 } 17364 } 17365 } 17366 17367 if (res) { 17368 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 17369 info.sendPackageRemovedBroadcasts(killApp); 17370 info.sendSystemPackageUpdatedBroadcasts(); 17371 info.sendSystemPackageAppearedBroadcasts(); 17372 } 17373 // Force a gc here. 17374 Runtime.getRuntime().gc(); 17375 // Delete the resources here after sending the broadcast to let 17376 // other processes clean up before deleting resources. 17377 if (info.args != null) { 17378 synchronized (mInstallLock) { 17379 info.args.doPostDeleteLI(true); 17380 } 17381 } 17382 17383 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17384 } 17385 17386 class PackageRemovedInfo { 17387 String removedPackage; 17388 int uid = -1; 17389 int removedAppId = -1; 17390 int[] origUsers; 17391 int[] removedUsers = null; 17392 SparseArray<Integer> installReasons; 17393 boolean isRemovedPackageSystemUpdate = false; 17394 boolean isUpdate; 17395 boolean dataRemoved; 17396 boolean removedForAllUsers; 17397 boolean isStaticSharedLib; 17398 // Clean up resources deleted packages. 17399 InstallArgs args = null; 17400 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 17401 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 17402 17403 void sendPackageRemovedBroadcasts(boolean killApp) { 17404 sendPackageRemovedBroadcastInternal(killApp); 17405 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 17406 for (int i = 0; i < childCount; i++) { 17407 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 17408 childInfo.sendPackageRemovedBroadcastInternal(killApp); 17409 } 17410 } 17411 17412 void sendSystemPackageUpdatedBroadcasts() { 17413 if (isRemovedPackageSystemUpdate) { 17414 sendSystemPackageUpdatedBroadcastsInternal(); 17415 final int childCount = (removedChildPackages != null) 17416 ? removedChildPackages.size() : 0; 17417 for (int i = 0; i < childCount; i++) { 17418 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 17419 if (childInfo.isRemovedPackageSystemUpdate) { 17420 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 17421 } 17422 } 17423 } 17424 } 17425 17426 void sendSystemPackageAppearedBroadcasts() { 17427 final int packageCount = (appearedChildPackages != null) 17428 ? appearedChildPackages.size() : 0; 17429 for (int i = 0; i < packageCount; i++) { 17430 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 17431 sendPackageAddedForNewUsers(installedInfo.name, true, 17432 UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers); 17433 } 17434 } 17435 17436 private void sendSystemPackageUpdatedBroadcastsInternal() { 17437 Bundle extras = new Bundle(2); 17438 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 17439 extras.putBoolean(Intent.EXTRA_REPLACING, true); 17440 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 17441 extras, 0, null, null, null); 17442 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 17443 extras, 0, null, null, null); 17444 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 17445 null, 0, removedPackage, null, null); 17446 } 17447 17448 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 17449 // Don't send static shared library removal broadcasts as these 17450 // libs are visible only the the apps that depend on them an one 17451 // cannot remove the library if it has a dependency. 17452 if (isStaticSharedLib) { 17453 return; 17454 } 17455 Bundle extras = new Bundle(2); 17456 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 17457 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 17458 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 17459 if (isUpdate || isRemovedPackageSystemUpdate) { 17460 extras.putBoolean(Intent.EXTRA_REPLACING, true); 17461 } 17462 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 17463 if (removedPackage != null) { 17464 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 17465 extras, 0, null, null, removedUsers); 17466 if (dataRemoved && !isRemovedPackageSystemUpdate) { 17467 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 17468 removedPackage, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, 17469 null, null, removedUsers); 17470 } 17471 } 17472 if (removedAppId >= 0) { 17473 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 17474 removedUsers); 17475 } 17476 } 17477 } 17478 17479 /* 17480 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 17481 * flag is not set, the data directory is removed as well. 17482 * make sure this flag is set for partially installed apps. If not its meaningless to 17483 * delete a partially installed application. 17484 */ 17485 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 17486 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 17487 String packageName = ps.name; 17488 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 17489 // Retrieve object to delete permissions for shared user later on 17490 final PackageParser.Package deletedPkg; 17491 final PackageSetting deletedPs; 17492 // reader 17493 synchronized (mPackages) { 17494 deletedPkg = mPackages.get(packageName); 17495 deletedPs = mSettings.mPackages.get(packageName); 17496 if (outInfo != null) { 17497 outInfo.removedPackage = packageName; 17498 outInfo.isStaticSharedLib = deletedPkg != null 17499 && deletedPkg.staticSharedLibName != null; 17500 outInfo.removedUsers = deletedPs != null 17501 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 17502 : null; 17503 } 17504 } 17505 17506 removePackageLI(ps, (flags & REMOVE_CHATTY) != 0); 17507 17508 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 17509 final PackageParser.Package resolvedPkg; 17510 if (deletedPkg != null) { 17511 resolvedPkg = deletedPkg; 17512 } else { 17513 // We don't have a parsed package when it lives on an ejected 17514 // adopted storage device, so fake something together 17515 resolvedPkg = new PackageParser.Package(ps.name); 17516 resolvedPkg.setVolumeUuid(ps.volumeUuid); 17517 } 17518 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 17519 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 17520 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 17521 if (outInfo != null) { 17522 outInfo.dataRemoved = true; 17523 } 17524 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 17525 } 17526 17527 int removedAppId = -1; 17528 17529 // writer 17530 synchronized (mPackages) { 17531 if (deletedPs != null) { 17532 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 17533 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 17534 clearDefaultBrowserIfNeeded(packageName); 17535 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 17536 removedAppId = mSettings.removePackageLPw(packageName); 17537 if (outInfo != null) { 17538 outInfo.removedAppId = removedAppId; 17539 } 17540 updatePermissionsLPw(deletedPs.name, null, 0); 17541 if (deletedPs.sharedUser != null) { 17542 // Remove permissions associated with package. Since runtime 17543 // permissions are per user we have to kill the removed package 17544 // or packages running under the shared user of the removed 17545 // package if revoking the permissions requested only by the removed 17546 // package is successful and this causes a change in gids. 17547 for (int userId : UserManagerService.getInstance().getUserIds()) { 17548 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 17549 userId); 17550 if (userIdToKill == UserHandle.USER_ALL 17551 || userIdToKill >= UserHandle.USER_SYSTEM) { 17552 // If gids changed for this user, kill all affected packages. 17553 mHandler.post(new Runnable() { 17554 @Override 17555 public void run() { 17556 // This has to happen with no lock held. 17557 killApplication(deletedPs.name, deletedPs.appId, 17558 KILL_APP_REASON_GIDS_CHANGED); 17559 } 17560 }); 17561 break; 17562 } 17563 } 17564 } 17565 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 17566 } 17567 // make sure to preserve per-user disabled state if this removal was just 17568 // a downgrade of a system app to the factory package 17569 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 17570 if (DEBUG_REMOVE) { 17571 Slog.d(TAG, "Propagating install state across downgrade"); 17572 } 17573 for (int userId : allUserHandles) { 17574 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 17575 if (DEBUG_REMOVE) { 17576 Slog.d(TAG, " user " + userId + " => " + installed); 17577 } 17578 ps.setInstalled(installed, userId); 17579 } 17580 } 17581 } 17582 // can downgrade to reader 17583 if (writeSettings) { 17584 // Save settings now 17585 mSettings.writeLPr(); 17586 } 17587 } 17588 if (removedAppId != -1) { 17589 // A user ID was deleted here. Go through all users and remove it 17590 // from KeyStore. 17591 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId); 17592 } 17593 } 17594 17595 static boolean locationIsPrivileged(File path) { 17596 try { 17597 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 17598 .getCanonicalPath(); 17599 return path.getCanonicalPath().startsWith(privilegedAppDir); 17600 } catch (IOException e) { 17601 Slog.e(TAG, "Unable to access code path " + path); 17602 } 17603 return false; 17604 } 17605 17606 /* 17607 * Tries to delete system package. 17608 */ 17609 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 17610 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 17611 boolean writeSettings) { 17612 if (deletedPs.parentPackageName != null) { 17613 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 17614 return false; 17615 } 17616 17617 final boolean applyUserRestrictions 17618 = (allUserHandles != null) && (outInfo.origUsers != null); 17619 final PackageSetting disabledPs; 17620 // Confirm if the system package has been updated 17621 // An updated system app can be deleted. This will also have to restore 17622 // the system pkg from system partition 17623 // reader 17624 synchronized (mPackages) { 17625 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 17626 } 17627 17628 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 17629 + " disabledPs=" + disabledPs); 17630 17631 if (disabledPs == null) { 17632 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 17633 return false; 17634 } else if (DEBUG_REMOVE) { 17635 Slog.d(TAG, "Deleting system pkg from data partition"); 17636 } 17637 17638 if (DEBUG_REMOVE) { 17639 if (applyUserRestrictions) { 17640 Slog.d(TAG, "Remembering install states:"); 17641 for (int userId : allUserHandles) { 17642 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 17643 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 17644 } 17645 } 17646 } 17647 17648 // Delete the updated package 17649 outInfo.isRemovedPackageSystemUpdate = true; 17650 if (outInfo.removedChildPackages != null) { 17651 final int childCount = (deletedPs.childPackageNames != null) 17652 ? deletedPs.childPackageNames.size() : 0; 17653 for (int i = 0; i < childCount; i++) { 17654 String childPackageName = deletedPs.childPackageNames.get(i); 17655 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 17656 .contains(childPackageName)) { 17657 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 17658 childPackageName); 17659 if (childInfo != null) { 17660 childInfo.isRemovedPackageSystemUpdate = true; 17661 } 17662 } 17663 } 17664 } 17665 17666 if (disabledPs.versionCode < deletedPs.versionCode) { 17667 // Delete data for downgrades 17668 flags &= ~PackageManager.DELETE_KEEP_DATA; 17669 } else { 17670 // Preserve data by setting flag 17671 flags |= PackageManager.DELETE_KEEP_DATA; 17672 } 17673 17674 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 17675 outInfo, writeSettings, disabledPs.pkg); 17676 if (!ret) { 17677 return false; 17678 } 17679 17680 // writer 17681 synchronized (mPackages) { 17682 // Reinstate the old system package 17683 enableSystemPackageLPw(disabledPs.pkg); 17684 // Remove any native libraries from the upgraded package. 17685 removeNativeBinariesLI(deletedPs); 17686 } 17687 17688 // Install the system package 17689 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 17690 int parseFlags = mDefParseFlags 17691 | PackageParser.PARSE_MUST_BE_APK 17692 | PackageParser.PARSE_IS_SYSTEM 17693 | PackageParser.PARSE_IS_SYSTEM_DIR; 17694 if (locationIsPrivileged(disabledPs.codePath)) { 17695 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 17696 } 17697 17698 final PackageParser.Package newPkg; 17699 try { 17700 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */, 17701 0 /* currentTime */, null); 17702 } catch (PackageManagerException e) { 17703 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 17704 + e.getMessage()); 17705 return false; 17706 } 17707 17708 prepareAppDataAfterInstallLIF(newPkg); 17709 17710 // writer 17711 synchronized (mPackages) { 17712 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 17713 17714 // Propagate the permissions state as we do not want to drop on the floor 17715 // runtime permissions. The update permissions method below will take 17716 // care of removing obsolete permissions and grant install permissions. 17717 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 17718 updatePermissionsLPw(newPkg.packageName, newPkg, 17719 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 17720 17721 if (applyUserRestrictions) { 17722 if (DEBUG_REMOVE) { 17723 Slog.d(TAG, "Propagating install state across reinstall"); 17724 } 17725 for (int userId : allUserHandles) { 17726 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 17727 if (DEBUG_REMOVE) { 17728 Slog.d(TAG, " user " + userId + " => " + installed); 17729 } 17730 ps.setInstalled(installed, userId); 17731 17732 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 17733 } 17734 // Regardless of writeSettings we need to ensure that this restriction 17735 // state propagation is persisted 17736 mSettings.writeAllUsersPackageRestrictionsLPr(); 17737 } 17738 // can downgrade to reader here 17739 if (writeSettings) { 17740 mSettings.writeLPr(); 17741 } 17742 } 17743 return true; 17744 } 17745 17746 private boolean deleteInstalledPackageLIF(PackageSetting ps, 17747 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 17748 PackageRemovedInfo outInfo, boolean writeSettings, 17749 PackageParser.Package replacingPackage) { 17750 synchronized (mPackages) { 17751 if (outInfo != null) { 17752 outInfo.uid = ps.appId; 17753 } 17754 17755 if (outInfo != null && outInfo.removedChildPackages != null) { 17756 final int childCount = (ps.childPackageNames != null) 17757 ? ps.childPackageNames.size() : 0; 17758 for (int i = 0; i < childCount; i++) { 17759 String childPackageName = ps.childPackageNames.get(i); 17760 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 17761 if (childPs == null) { 17762 return false; 17763 } 17764 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 17765 childPackageName); 17766 if (childInfo != null) { 17767 childInfo.uid = childPs.appId; 17768 } 17769 } 17770 } 17771 } 17772 17773 // Delete package data from internal structures and also remove data if flag is set 17774 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 17775 17776 // Delete the child packages data 17777 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 17778 for (int i = 0; i < childCount; i++) { 17779 PackageSetting childPs; 17780 synchronized (mPackages) { 17781 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 17782 } 17783 if (childPs != null) { 17784 PackageRemovedInfo childOutInfo = (outInfo != null 17785 && outInfo.removedChildPackages != null) 17786 ? outInfo.removedChildPackages.get(childPs.name) : null; 17787 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 17788 && (replacingPackage != null 17789 && !replacingPackage.hasChildPackage(childPs.name)) 17790 ? flags & ~DELETE_KEEP_DATA : flags; 17791 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 17792 deleteFlags, writeSettings); 17793 } 17794 } 17795 17796 // Delete application code and resources only for parent packages 17797 if (ps.parentPackageName == null) { 17798 if (deleteCodeAndResources && (outInfo != null)) { 17799 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 17800 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 17801 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 17802 } 17803 } 17804 17805 return true; 17806 } 17807 17808 @Override 17809 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 17810 int userId) { 17811 mContext.enforceCallingOrSelfPermission( 17812 android.Manifest.permission.DELETE_PACKAGES, null); 17813 synchronized (mPackages) { 17814 PackageSetting ps = mSettings.mPackages.get(packageName); 17815 if (ps == null) { 17816 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 17817 return false; 17818 } 17819 // Cannot block uninstall of static shared libs as they are 17820 // considered a part of the using app (emulating static linking). 17821 // Also static libs are installed always on internal storage. 17822 PackageParser.Package pkg = mPackages.get(packageName); 17823 if (pkg != null && pkg.staticSharedLibName != null) { 17824 Slog.w(TAG, "Cannot block uninstall of package: " + packageName 17825 + " providing static shared library: " + pkg.staticSharedLibName); 17826 return false; 17827 } 17828 if (!ps.getInstalled(userId)) { 17829 // Can't block uninstall for an app that is not installed or enabled. 17830 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 17831 return false; 17832 } 17833 ps.setBlockUninstall(blockUninstall, userId); 17834 mSettings.writePackageRestrictionsLPr(userId); 17835 } 17836 return true; 17837 } 17838 17839 @Override 17840 public boolean getBlockUninstallForUser(String packageName, int userId) { 17841 synchronized (mPackages) { 17842 PackageSetting ps = mSettings.mPackages.get(packageName); 17843 if (ps == null) { 17844 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 17845 return false; 17846 } 17847 return ps.getBlockUninstall(userId); 17848 } 17849 } 17850 17851 @Override 17852 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 17853 int callingUid = Binder.getCallingUid(); 17854 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 17855 throw new SecurityException( 17856 "setRequiredForSystemUser can only be run by the system or root"); 17857 } 17858 synchronized (mPackages) { 17859 PackageSetting ps = mSettings.mPackages.get(packageName); 17860 if (ps == null) { 17861 Log.w(TAG, "Package doesn't exist: " + packageName); 17862 return false; 17863 } 17864 if (systemUserApp) { 17865 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 17866 } else { 17867 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 17868 } 17869 mSettings.writeLPr(); 17870 } 17871 return true; 17872 } 17873 17874 /* 17875 * This method handles package deletion in general 17876 */ 17877 private boolean deletePackageLIF(String packageName, UserHandle user, 17878 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 17879 PackageRemovedInfo outInfo, boolean writeSettings, 17880 PackageParser.Package replacingPackage) { 17881 if (packageName == null) { 17882 Slog.w(TAG, "Attempt to delete null packageName."); 17883 return false; 17884 } 17885 17886 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 17887 17888 PackageSetting ps; 17889 synchronized (mPackages) { 17890 ps = mSettings.mPackages.get(packageName); 17891 if (ps == null) { 17892 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 17893 return false; 17894 } 17895 17896 if (ps.parentPackageName != null && (!isSystemApp(ps) 17897 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 17898 if (DEBUG_REMOVE) { 17899 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 17900 + ((user == null) ? UserHandle.USER_ALL : user)); 17901 } 17902 final int removedUserId = (user != null) ? user.getIdentifier() 17903 : UserHandle.USER_ALL; 17904 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 17905 return false; 17906 } 17907 markPackageUninstalledForUserLPw(ps, user); 17908 scheduleWritePackageRestrictionsLocked(user); 17909 return true; 17910 } 17911 } 17912 17913 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 17914 && user.getIdentifier() != UserHandle.USER_ALL)) { 17915 // The caller is asking that the package only be deleted for a single 17916 // user. To do this, we just mark its uninstalled state and delete 17917 // its data. If this is a system app, we only allow this to happen if 17918 // they have set the special DELETE_SYSTEM_APP which requests different 17919 // semantics than normal for uninstalling system apps. 17920 markPackageUninstalledForUserLPw(ps, user); 17921 17922 if (!isSystemApp(ps)) { 17923 // Do not uninstall the APK if an app should be cached 17924 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 17925 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 17926 // Other user still have this package installed, so all 17927 // we need to do is clear this user's data and save that 17928 // it is uninstalled. 17929 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 17930 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 17931 return false; 17932 } 17933 scheduleWritePackageRestrictionsLocked(user); 17934 return true; 17935 } else { 17936 // We need to set it back to 'installed' so the uninstall 17937 // broadcasts will be sent correctly. 17938 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 17939 ps.setInstalled(true, user.getIdentifier()); 17940 } 17941 } else { 17942 // This is a system app, so we assume that the 17943 // other users still have this package installed, so all 17944 // we need to do is clear this user's data and save that 17945 // it is uninstalled. 17946 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 17947 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 17948 return false; 17949 } 17950 scheduleWritePackageRestrictionsLocked(user); 17951 return true; 17952 } 17953 } 17954 17955 // If we are deleting a composite package for all users, keep track 17956 // of result for each child. 17957 if (ps.childPackageNames != null && outInfo != null) { 17958 synchronized (mPackages) { 17959 final int childCount = ps.childPackageNames.size(); 17960 outInfo.removedChildPackages = new ArrayMap<>(childCount); 17961 for (int i = 0; i < childCount; i++) { 17962 String childPackageName = ps.childPackageNames.get(i); 17963 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 17964 childInfo.removedPackage = childPackageName; 17965 outInfo.removedChildPackages.put(childPackageName, childInfo); 17966 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 17967 if (childPs != null) { 17968 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 17969 } 17970 } 17971 } 17972 } 17973 17974 boolean ret = false; 17975 if (isSystemApp(ps)) { 17976 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 17977 // When an updated system application is deleted we delete the existing resources 17978 // as well and fall back to existing code in system partition 17979 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 17980 } else { 17981 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 17982 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 17983 outInfo, writeSettings, replacingPackage); 17984 } 17985 17986 // Take a note whether we deleted the package for all users 17987 if (outInfo != null) { 17988 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 17989 if (outInfo.removedChildPackages != null) { 17990 synchronized (mPackages) { 17991 final int childCount = outInfo.removedChildPackages.size(); 17992 for (int i = 0; i < childCount; i++) { 17993 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 17994 if (childInfo != null) { 17995 childInfo.removedForAllUsers = mPackages.get( 17996 childInfo.removedPackage) == null; 17997 } 17998 } 17999 } 18000 } 18001 // If we uninstalled an update to a system app there may be some 18002 // child packages that appeared as they are declared in the system 18003 // app but were not declared in the update. 18004 if (isSystemApp(ps)) { 18005 synchronized (mPackages) { 18006 PackageSetting updatedPs = mSettings.getPackageLPr(ps.name); 18007 final int childCount = (updatedPs.childPackageNames != null) 18008 ? updatedPs.childPackageNames.size() : 0; 18009 for (int i = 0; i < childCount; i++) { 18010 String childPackageName = updatedPs.childPackageNames.get(i); 18011 if (outInfo.removedChildPackages == null 18012 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 18013 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 18014 if (childPs == null) { 18015 continue; 18016 } 18017 PackageInstalledInfo installRes = new PackageInstalledInfo(); 18018 installRes.name = childPackageName; 18019 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 18020 installRes.pkg = mPackages.get(childPackageName); 18021 installRes.uid = childPs.pkg.applicationInfo.uid; 18022 if (outInfo.appearedChildPackages == null) { 18023 outInfo.appearedChildPackages = new ArrayMap<>(); 18024 } 18025 outInfo.appearedChildPackages.put(childPackageName, installRes); 18026 } 18027 } 18028 } 18029 } 18030 } 18031 18032 return ret; 18033 } 18034 18035 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 18036 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 18037 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 18038 for (int nextUserId : userIds) { 18039 if (DEBUG_REMOVE) { 18040 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 18041 } 18042 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 18043 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 18044 false /*hidden*/, false /*suspended*/, null, null, null, 18045 false /*blockUninstall*/, 18046 ps.readUserState(nextUserId).domainVerificationStatus, 0, 18047 PackageManager.INSTALL_REASON_UNKNOWN); 18048 } 18049 } 18050 18051 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 18052 PackageRemovedInfo outInfo) { 18053 final PackageParser.Package pkg; 18054 synchronized (mPackages) { 18055 pkg = mPackages.get(ps.name); 18056 } 18057 18058 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 18059 : new int[] {userId}; 18060 for (int nextUserId : userIds) { 18061 if (DEBUG_REMOVE) { 18062 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 18063 + nextUserId); 18064 } 18065 18066 destroyAppDataLIF(pkg, userId, 18067 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18068 destroyAppProfilesLIF(pkg, userId); 18069 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 18070 schedulePackageCleaning(ps.name, nextUserId, false); 18071 synchronized (mPackages) { 18072 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 18073 scheduleWritePackageRestrictionsLocked(nextUserId); 18074 } 18075 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 18076 } 18077 } 18078 18079 if (outInfo != null) { 18080 outInfo.removedPackage = ps.name; 18081 outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null; 18082 outInfo.removedAppId = ps.appId; 18083 outInfo.removedUsers = userIds; 18084 } 18085 18086 return true; 18087 } 18088 18089 private final class ClearStorageConnection implements ServiceConnection { 18090 IMediaContainerService mContainerService; 18091 18092 @Override 18093 public void onServiceConnected(ComponentName name, IBinder service) { 18094 synchronized (this) { 18095 mContainerService = IMediaContainerService.Stub 18096 .asInterface(Binder.allowBlocking(service)); 18097 notifyAll(); 18098 } 18099 } 18100 18101 @Override 18102 public void onServiceDisconnected(ComponentName name) { 18103 } 18104 } 18105 18106 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 18107 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 18108 18109 final boolean mounted; 18110 if (Environment.isExternalStorageEmulated()) { 18111 mounted = true; 18112 } else { 18113 final String status = Environment.getExternalStorageState(); 18114 18115 mounted = status.equals(Environment.MEDIA_MOUNTED) 18116 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 18117 } 18118 18119 if (!mounted) { 18120 return; 18121 } 18122 18123 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 18124 int[] users; 18125 if (userId == UserHandle.USER_ALL) { 18126 users = sUserManager.getUserIds(); 18127 } else { 18128 users = new int[] { userId }; 18129 } 18130 final ClearStorageConnection conn = new ClearStorageConnection(); 18131 if (mContext.bindServiceAsUser( 18132 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 18133 try { 18134 for (int curUser : users) { 18135 long timeout = SystemClock.uptimeMillis() + 5000; 18136 synchronized (conn) { 18137 long now; 18138 while (conn.mContainerService == null && 18139 (now = SystemClock.uptimeMillis()) < timeout) { 18140 try { 18141 conn.wait(timeout - now); 18142 } catch (InterruptedException e) { 18143 } 18144 } 18145 } 18146 if (conn.mContainerService == null) { 18147 return; 18148 } 18149 18150 final UserEnvironment userEnv = new UserEnvironment(curUser); 18151 clearDirectory(conn.mContainerService, 18152 userEnv.buildExternalStorageAppCacheDirs(packageName)); 18153 if (allData) { 18154 clearDirectory(conn.mContainerService, 18155 userEnv.buildExternalStorageAppDataDirs(packageName)); 18156 clearDirectory(conn.mContainerService, 18157 userEnv.buildExternalStorageAppMediaDirs(packageName)); 18158 } 18159 } 18160 } finally { 18161 mContext.unbindService(conn); 18162 } 18163 } 18164 } 18165 18166 @Override 18167 public void clearApplicationProfileData(String packageName) { 18168 enforceSystemOrRoot("Only the system can clear all profile data"); 18169 18170 final PackageParser.Package pkg; 18171 synchronized (mPackages) { 18172 pkg = mPackages.get(packageName); 18173 } 18174 18175 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 18176 synchronized (mInstallLock) { 18177 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 18178 destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL, 18179 true /* removeBaseMarker */); 18180 } 18181 } 18182 } 18183 18184 @Override 18185 public void clearApplicationUserData(final String packageName, 18186 final IPackageDataObserver observer, final int userId) { 18187 mContext.enforceCallingOrSelfPermission( 18188 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 18189 18190 enforceCrossUserPermission(Binder.getCallingUid(), userId, 18191 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 18192 18193 if (mProtectedPackages.isPackageDataProtected(userId, packageName)) { 18194 throw new SecurityException("Cannot clear data for a protected package: " 18195 + packageName); 18196 } 18197 // Queue up an async operation since the package deletion may take a little while. 18198 mHandler.post(new Runnable() { 18199 public void run() { 18200 mHandler.removeCallbacks(this); 18201 final boolean succeeded; 18202 try (PackageFreezer freezer = freezePackage(packageName, 18203 "clearApplicationUserData")) { 18204 synchronized (mInstallLock) { 18205 succeeded = clearApplicationUserDataLIF(packageName, userId); 18206 } 18207 clearExternalStorageDataSync(packageName, userId, true); 18208 } 18209 if (succeeded) { 18210 // invoke DeviceStorageMonitor's update method to clear any notifications 18211 DeviceStorageMonitorInternal dsm = LocalServices 18212 .getService(DeviceStorageMonitorInternal.class); 18213 if (dsm != null) { 18214 dsm.checkMemory(); 18215 } 18216 } 18217 if(observer != null) { 18218 try { 18219 observer.onRemoveCompleted(packageName, succeeded); 18220 } catch (RemoteException e) { 18221 Log.i(TAG, "Observer no longer exists."); 18222 } 18223 } //end if observer 18224 } //end run 18225 }); 18226 } 18227 18228 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 18229 if (packageName == null) { 18230 Slog.w(TAG, "Attempt to delete null packageName."); 18231 return false; 18232 } 18233 18234 // Try finding details about the requested package 18235 PackageParser.Package pkg; 18236 synchronized (mPackages) { 18237 pkg = mPackages.get(packageName); 18238 if (pkg == null) { 18239 final PackageSetting ps = mSettings.mPackages.get(packageName); 18240 if (ps != null) { 18241 pkg = ps.pkg; 18242 } 18243 } 18244 18245 if (pkg == null) { 18246 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 18247 return false; 18248 } 18249 18250 PackageSetting ps = (PackageSetting) pkg.mExtras; 18251 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 18252 } 18253 18254 clearAppDataLIF(pkg, userId, 18255 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18256 18257 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 18258 removeKeystoreDataIfNeeded(userId, appId); 18259 18260 UserManagerInternal umInternal = getUserManagerInternal(); 18261 final int flags; 18262 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 18263 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18264 } else if (umInternal.isUserRunning(userId)) { 18265 flags = StorageManager.FLAG_STORAGE_DE; 18266 } else { 18267 flags = 0; 18268 } 18269 prepareAppDataContentsLIF(pkg, userId, flags); 18270 18271 return true; 18272 } 18273 18274 /** 18275 * Reverts user permission state changes (permissions and flags) in 18276 * all packages for a given user. 18277 * 18278 * @param userId The device user for which to do a reset. 18279 */ 18280 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 18281 final int packageCount = mPackages.size(); 18282 for (int i = 0; i < packageCount; i++) { 18283 PackageParser.Package pkg = mPackages.valueAt(i); 18284 PackageSetting ps = (PackageSetting) pkg.mExtras; 18285 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 18286 } 18287 } 18288 18289 private void resetNetworkPolicies(int userId) { 18290 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 18291 } 18292 18293 /** 18294 * Reverts user permission state changes (permissions and flags). 18295 * 18296 * @param ps The package for which to reset. 18297 * @param userId The device user for which to do a reset. 18298 */ 18299 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 18300 final PackageSetting ps, final int userId) { 18301 if (ps.pkg == null) { 18302 return; 18303 } 18304 18305 // These are flags that can change base on user actions. 18306 final int userSettableMask = FLAG_PERMISSION_USER_SET 18307 | FLAG_PERMISSION_USER_FIXED 18308 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 18309 | FLAG_PERMISSION_REVIEW_REQUIRED; 18310 18311 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 18312 | FLAG_PERMISSION_POLICY_FIXED; 18313 18314 boolean writeInstallPermissions = false; 18315 boolean writeRuntimePermissions = false; 18316 18317 final int permissionCount = ps.pkg.requestedPermissions.size(); 18318 for (int i = 0; i < permissionCount; i++) { 18319 String permission = ps.pkg.requestedPermissions.get(i); 18320 18321 BasePermission bp = mSettings.mPermissions.get(permission); 18322 if (bp == null) { 18323 continue; 18324 } 18325 18326 // If shared user we just reset the state to which only this app contributed. 18327 if (ps.sharedUser != null) { 18328 boolean used = false; 18329 final int packageCount = ps.sharedUser.packages.size(); 18330 for (int j = 0; j < packageCount; j++) { 18331 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 18332 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 18333 && pkg.pkg.requestedPermissions.contains(permission)) { 18334 used = true; 18335 break; 18336 } 18337 } 18338 if (used) { 18339 continue; 18340 } 18341 } 18342 18343 PermissionsState permissionsState = ps.getPermissionsState(); 18344 18345 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 18346 18347 // Always clear the user settable flags. 18348 final boolean hasInstallState = permissionsState.getInstallPermissionState( 18349 bp.name) != null; 18350 // If permission review is enabled and this is a legacy app, mark the 18351 // permission as requiring a review as this is the initial state. 18352 int flags = 0; 18353 if (mPermissionReviewRequired 18354 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 18355 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 18356 } 18357 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 18358 if (hasInstallState) { 18359 writeInstallPermissions = true; 18360 } else { 18361 writeRuntimePermissions = true; 18362 } 18363 } 18364 18365 // Below is only runtime permission handling. 18366 if (!bp.isRuntime()) { 18367 continue; 18368 } 18369 18370 // Never clobber system or policy. 18371 if ((oldFlags & policyOrSystemFlags) != 0) { 18372 continue; 18373 } 18374 18375 // If this permission was granted by default, make sure it is. 18376 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 18377 if (permissionsState.grantRuntimePermission(bp, userId) 18378 != PERMISSION_OPERATION_FAILURE) { 18379 writeRuntimePermissions = true; 18380 } 18381 // If permission review is enabled the permissions for a legacy apps 18382 // are represented as constantly granted runtime ones, so don't revoke. 18383 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 18384 // Otherwise, reset the permission. 18385 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 18386 switch (revokeResult) { 18387 case PERMISSION_OPERATION_SUCCESS: 18388 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 18389 writeRuntimePermissions = true; 18390 final int appId = ps.appId; 18391 mHandler.post(new Runnable() { 18392 @Override 18393 public void run() { 18394 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 18395 } 18396 }); 18397 } break; 18398 } 18399 } 18400 } 18401 18402 // Synchronously write as we are taking permissions away. 18403 if (writeRuntimePermissions) { 18404 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 18405 } 18406 18407 // Synchronously write as we are taking permissions away. 18408 if (writeInstallPermissions) { 18409 mSettings.writeLPr(); 18410 } 18411 } 18412 18413 /** 18414 * Remove entries from the keystore daemon. Will only remove it if the 18415 * {@code appId} is valid. 18416 */ 18417 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 18418 if (appId < 0) { 18419 return; 18420 } 18421 18422 final KeyStore keyStore = KeyStore.getInstance(); 18423 if (keyStore != null) { 18424 if (userId == UserHandle.USER_ALL) { 18425 for (final int individual : sUserManager.getUserIds()) { 18426 keyStore.clearUid(UserHandle.getUid(individual, appId)); 18427 } 18428 } else { 18429 keyStore.clearUid(UserHandle.getUid(userId, appId)); 18430 } 18431 } else { 18432 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 18433 } 18434 } 18435 18436 @Override 18437 public void deleteApplicationCacheFiles(final String packageName, 18438 final IPackageDataObserver observer) { 18439 final int userId = UserHandle.getCallingUserId(); 18440 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 18441 } 18442 18443 @Override 18444 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 18445 final IPackageDataObserver observer) { 18446 mContext.enforceCallingOrSelfPermission( 18447 android.Manifest.permission.DELETE_CACHE_FILES, null); 18448 enforceCrossUserPermission(Binder.getCallingUid(), userId, 18449 /* requireFullPermission= */ true, /* checkShell= */ false, 18450 "delete application cache files"); 18451 18452 final PackageParser.Package pkg; 18453 synchronized (mPackages) { 18454 pkg = mPackages.get(packageName); 18455 } 18456 18457 // Queue up an async operation since the package deletion may take a little while. 18458 mHandler.post(new Runnable() { 18459 public void run() { 18460 synchronized (mInstallLock) { 18461 final int flags = StorageManager.FLAG_STORAGE_DE 18462 | StorageManager.FLAG_STORAGE_CE; 18463 // We're only clearing cache files, so we don't care if the 18464 // app is unfrozen and still able to run 18465 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 18466 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 18467 } 18468 clearExternalStorageDataSync(packageName, userId, false); 18469 if (observer != null) { 18470 try { 18471 observer.onRemoveCompleted(packageName, true); 18472 } catch (RemoteException e) { 18473 Log.i(TAG, "Observer no longer exists."); 18474 } 18475 } 18476 } 18477 }); 18478 } 18479 18480 @Override 18481 public void getPackageSizeInfo(final String packageName, int userHandle, 18482 final IPackageStatsObserver observer) { 18483 mContext.enforceCallingOrSelfPermission( 18484 android.Manifest.permission.GET_PACKAGE_SIZE, null); 18485 if (packageName == null) { 18486 throw new IllegalArgumentException("Attempt to get size of null packageName"); 18487 } 18488 18489 PackageStats stats = new PackageStats(packageName, userHandle); 18490 18491 /* 18492 * Queue up an async operation since the package measurement may take a 18493 * little while. 18494 */ 18495 Message msg = mHandler.obtainMessage(INIT_COPY); 18496 msg.obj = new MeasureParams(stats, observer); 18497 mHandler.sendMessage(msg); 18498 } 18499 18500 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 18501 final PackageSetting ps; 18502 synchronized (mPackages) { 18503 ps = mSettings.mPackages.get(packageName); 18504 if (ps == null) { 18505 Slog.w(TAG, "Failed to find settings for " + packageName); 18506 return false; 18507 } 18508 } 18509 18510 final String[] packageNames = { packageName }; 18511 final long[] ceDataInodes = { ps.getCeDataInode(userId) }; 18512 final String[] codePaths = { ps.codePathString }; 18513 18514 try { 18515 mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0, 18516 ps.appId, ceDataInodes, codePaths, stats); 18517 18518 // For now, ignore code size of packages on system partition 18519 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 18520 stats.codeSize = 0; 18521 } 18522 18523 // External clients expect these to be tracked separately 18524 stats.dataSize -= stats.cacheSize; 18525 18526 } catch (InstallerException e) { 18527 Slog.w(TAG, String.valueOf(e)); 18528 return false; 18529 } 18530 18531 return true; 18532 } 18533 18534 private int getUidTargetSdkVersionLockedLPr(int uid) { 18535 Object obj = mSettings.getUserIdLPr(uid); 18536 if (obj instanceof SharedUserSetting) { 18537 final SharedUserSetting sus = (SharedUserSetting) obj; 18538 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 18539 final Iterator<PackageSetting> it = sus.packages.iterator(); 18540 while (it.hasNext()) { 18541 final PackageSetting ps = it.next(); 18542 if (ps.pkg != null) { 18543 int v = ps.pkg.applicationInfo.targetSdkVersion; 18544 if (v < vers) vers = v; 18545 } 18546 } 18547 return vers; 18548 } else if (obj instanceof PackageSetting) { 18549 final PackageSetting ps = (PackageSetting) obj; 18550 if (ps.pkg != null) { 18551 return ps.pkg.applicationInfo.targetSdkVersion; 18552 } 18553 } 18554 return Build.VERSION_CODES.CUR_DEVELOPMENT; 18555 } 18556 18557 @Override 18558 public void addPreferredActivity(IntentFilter filter, int match, 18559 ComponentName[] set, ComponentName activity, int userId) { 18560 addPreferredActivityInternal(filter, match, set, activity, true, userId, 18561 "Adding preferred"); 18562 } 18563 18564 private void addPreferredActivityInternal(IntentFilter filter, int match, 18565 ComponentName[] set, ComponentName activity, boolean always, int userId, 18566 String opname) { 18567 // writer 18568 int callingUid = Binder.getCallingUid(); 18569 enforceCrossUserPermission(callingUid, userId, 18570 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 18571 if (filter.countActions() == 0) { 18572 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 18573 return; 18574 } 18575 synchronized (mPackages) { 18576 if (mContext.checkCallingOrSelfPermission( 18577 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 18578 != PackageManager.PERMISSION_GRANTED) { 18579 if (getUidTargetSdkVersionLockedLPr(callingUid) 18580 < Build.VERSION_CODES.FROYO) { 18581 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 18582 + callingUid); 18583 return; 18584 } 18585 mContext.enforceCallingOrSelfPermission( 18586 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 18587 } 18588 18589 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 18590 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 18591 + userId + ":"); 18592 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18593 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 18594 scheduleWritePackageRestrictionsLocked(userId); 18595 postPreferredActivityChangedBroadcast(userId); 18596 } 18597 } 18598 18599 private void postPreferredActivityChangedBroadcast(int userId) { 18600 mHandler.post(() -> { 18601 final IActivityManager am = ActivityManager.getService(); 18602 if (am == null) { 18603 return; 18604 } 18605 18606 final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED); 18607 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 18608 try { 18609 am.broadcastIntent(null, intent, null, null, 18610 0, null, null, null, android.app.AppOpsManager.OP_NONE, 18611 null, false, false, userId); 18612 } catch (RemoteException e) { 18613 } 18614 }); 18615 } 18616 18617 @Override 18618 public void replacePreferredActivity(IntentFilter filter, int match, 18619 ComponentName[] set, ComponentName activity, int userId) { 18620 if (filter.countActions() != 1) { 18621 throw new IllegalArgumentException( 18622 "replacePreferredActivity expects filter to have only 1 action."); 18623 } 18624 if (filter.countDataAuthorities() != 0 18625 || filter.countDataPaths() != 0 18626 || filter.countDataSchemes() > 1 18627 || filter.countDataTypes() != 0) { 18628 throw new IllegalArgumentException( 18629 "replacePreferredActivity expects filter to have no data authorities, " + 18630 "paths, or types; and at most one scheme."); 18631 } 18632 18633 final int callingUid = Binder.getCallingUid(); 18634 enforceCrossUserPermission(callingUid, userId, 18635 true /* requireFullPermission */, false /* checkShell */, 18636 "replace preferred activity"); 18637 synchronized (mPackages) { 18638 if (mContext.checkCallingOrSelfPermission( 18639 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 18640 != PackageManager.PERMISSION_GRANTED) { 18641 if (getUidTargetSdkVersionLockedLPr(callingUid) 18642 < Build.VERSION_CODES.FROYO) { 18643 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 18644 + Binder.getCallingUid()); 18645 return; 18646 } 18647 mContext.enforceCallingOrSelfPermission( 18648 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 18649 } 18650 18651 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 18652 if (pir != null) { 18653 // Get all of the existing entries that exactly match this filter. 18654 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 18655 if (existing != null && existing.size() == 1) { 18656 PreferredActivity cur = existing.get(0); 18657 if (DEBUG_PREFERRED) { 18658 Slog.i(TAG, "Checking replace of preferred:"); 18659 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18660 if (!cur.mPref.mAlways) { 18661 Slog.i(TAG, " -- CUR; not mAlways!"); 18662 } else { 18663 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 18664 Slog.i(TAG, " -- CUR: mSet=" 18665 + Arrays.toString(cur.mPref.mSetComponents)); 18666 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 18667 Slog.i(TAG, " -- NEW: mMatch=" 18668 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 18669 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 18670 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 18671 } 18672 } 18673 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 18674 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 18675 && cur.mPref.sameSet(set)) { 18676 // Setting the preferred activity to what it happens to be already 18677 if (DEBUG_PREFERRED) { 18678 Slog.i(TAG, "Replacing with same preferred activity " 18679 + cur.mPref.mShortComponent + " for user " 18680 + userId + ":"); 18681 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18682 } 18683 return; 18684 } 18685 } 18686 18687 if (existing != null) { 18688 if (DEBUG_PREFERRED) { 18689 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 18690 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18691 } 18692 for (int i = 0; i < existing.size(); i++) { 18693 PreferredActivity pa = existing.get(i); 18694 if (DEBUG_PREFERRED) { 18695 Slog.i(TAG, "Removing existing preferred activity " 18696 + pa.mPref.mComponent + ":"); 18697 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 18698 } 18699 pir.removeFilter(pa); 18700 } 18701 } 18702 } 18703 addPreferredActivityInternal(filter, match, set, activity, true, userId, 18704 "Replacing preferred"); 18705 } 18706 } 18707 18708 @Override 18709 public void clearPackagePreferredActivities(String packageName) { 18710 final int uid = Binder.getCallingUid(); 18711 // writer 18712 synchronized (mPackages) { 18713 PackageParser.Package pkg = mPackages.get(packageName); 18714 if (pkg == null || pkg.applicationInfo.uid != uid) { 18715 if (mContext.checkCallingOrSelfPermission( 18716 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 18717 != PackageManager.PERMISSION_GRANTED) { 18718 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 18719 < Build.VERSION_CODES.FROYO) { 18720 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 18721 + Binder.getCallingUid()); 18722 return; 18723 } 18724 mContext.enforceCallingOrSelfPermission( 18725 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 18726 } 18727 } 18728 18729 int user = UserHandle.getCallingUserId(); 18730 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 18731 scheduleWritePackageRestrictionsLocked(user); 18732 } 18733 } 18734 } 18735 18736 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 18737 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 18738 ArrayList<PreferredActivity> removed = null; 18739 boolean changed = false; 18740 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18741 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 18742 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18743 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 18744 continue; 18745 } 18746 Iterator<PreferredActivity> it = pir.filterIterator(); 18747 while (it.hasNext()) { 18748 PreferredActivity pa = it.next(); 18749 // Mark entry for removal only if it matches the package name 18750 // and the entry is of type "always". 18751 if (packageName == null || 18752 (pa.mPref.mComponent.getPackageName().equals(packageName) 18753 && pa.mPref.mAlways)) { 18754 if (removed == null) { 18755 removed = new ArrayList<PreferredActivity>(); 18756 } 18757 removed.add(pa); 18758 } 18759 } 18760 if (removed != null) { 18761 for (int j=0; j<removed.size(); j++) { 18762 PreferredActivity pa = removed.get(j); 18763 pir.removeFilter(pa); 18764 } 18765 changed = true; 18766 } 18767 } 18768 if (changed) { 18769 postPreferredActivityChangedBroadcast(userId); 18770 } 18771 return changed; 18772 } 18773 18774 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 18775 private void clearIntentFilterVerificationsLPw(int userId) { 18776 final int packageCount = mPackages.size(); 18777 for (int i = 0; i < packageCount; i++) { 18778 PackageParser.Package pkg = mPackages.valueAt(i); 18779 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 18780 } 18781 } 18782 18783 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 18784 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 18785 if (userId == UserHandle.USER_ALL) { 18786 if (mSettings.removeIntentFilterVerificationLPw(packageName, 18787 sUserManager.getUserIds())) { 18788 for (int oneUserId : sUserManager.getUserIds()) { 18789 scheduleWritePackageRestrictionsLocked(oneUserId); 18790 } 18791 } 18792 } else { 18793 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 18794 scheduleWritePackageRestrictionsLocked(userId); 18795 } 18796 } 18797 } 18798 18799 void clearDefaultBrowserIfNeeded(String packageName) { 18800 for (int oneUserId : sUserManager.getUserIds()) { 18801 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 18802 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 18803 if (packageName.equals(defaultBrowserPackageName)) { 18804 setDefaultBrowserPackageName(null, oneUserId); 18805 } 18806 } 18807 } 18808 18809 @Override 18810 public void resetApplicationPreferences(int userId) { 18811 mContext.enforceCallingOrSelfPermission( 18812 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 18813 final long identity = Binder.clearCallingIdentity(); 18814 // writer 18815 try { 18816 synchronized (mPackages) { 18817 clearPackagePreferredActivitiesLPw(null, userId); 18818 mSettings.applyDefaultPreferredAppsLPw(this, userId); 18819 // TODO: We have to reset the default SMS and Phone. This requires 18820 // significant refactoring to keep all default apps in the package 18821 // manager (cleaner but more work) or have the services provide 18822 // callbacks to the package manager to request a default app reset. 18823 applyFactoryDefaultBrowserLPw(userId); 18824 clearIntentFilterVerificationsLPw(userId); 18825 primeDomainVerificationsLPw(userId); 18826 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 18827 scheduleWritePackageRestrictionsLocked(userId); 18828 } 18829 resetNetworkPolicies(userId); 18830 } finally { 18831 Binder.restoreCallingIdentity(identity); 18832 } 18833 } 18834 18835 @Override 18836 public int getPreferredActivities(List<IntentFilter> outFilters, 18837 List<ComponentName> outActivities, String packageName) { 18838 18839 int num = 0; 18840 final int userId = UserHandle.getCallingUserId(); 18841 // reader 18842 synchronized (mPackages) { 18843 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 18844 if (pir != null) { 18845 final Iterator<PreferredActivity> it = pir.filterIterator(); 18846 while (it.hasNext()) { 18847 final PreferredActivity pa = it.next(); 18848 if (packageName == null 18849 || (pa.mPref.mComponent.getPackageName().equals(packageName) 18850 && pa.mPref.mAlways)) { 18851 if (outFilters != null) { 18852 outFilters.add(new IntentFilter(pa)); 18853 } 18854 if (outActivities != null) { 18855 outActivities.add(pa.mPref.mComponent); 18856 } 18857 } 18858 } 18859 } 18860 } 18861 18862 return num; 18863 } 18864 18865 @Override 18866 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 18867 int userId) { 18868 int callingUid = Binder.getCallingUid(); 18869 if (callingUid != Process.SYSTEM_UID) { 18870 throw new SecurityException( 18871 "addPersistentPreferredActivity can only be run by the system"); 18872 } 18873 if (filter.countActions() == 0) { 18874 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 18875 return; 18876 } 18877 synchronized (mPackages) { 18878 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 18879 ":"); 18880 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18881 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 18882 new PersistentPreferredActivity(filter, activity)); 18883 scheduleWritePackageRestrictionsLocked(userId); 18884 postPreferredActivityChangedBroadcast(userId); 18885 } 18886 } 18887 18888 @Override 18889 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 18890 int callingUid = Binder.getCallingUid(); 18891 if (callingUid != Process.SYSTEM_UID) { 18892 throw new SecurityException( 18893 "clearPackagePersistentPreferredActivities can only be run by the system"); 18894 } 18895 ArrayList<PersistentPreferredActivity> removed = null; 18896 boolean changed = false; 18897 synchronized (mPackages) { 18898 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 18899 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 18900 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 18901 .valueAt(i); 18902 if (userId != thisUserId) { 18903 continue; 18904 } 18905 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 18906 while (it.hasNext()) { 18907 PersistentPreferredActivity ppa = it.next(); 18908 // Mark entry for removal only if it matches the package name. 18909 if (ppa.mComponent.getPackageName().equals(packageName)) { 18910 if (removed == null) { 18911 removed = new ArrayList<PersistentPreferredActivity>(); 18912 } 18913 removed.add(ppa); 18914 } 18915 } 18916 if (removed != null) { 18917 for (int j=0; j<removed.size(); j++) { 18918 PersistentPreferredActivity ppa = removed.get(j); 18919 ppir.removeFilter(ppa); 18920 } 18921 changed = true; 18922 } 18923 } 18924 18925 if (changed) { 18926 scheduleWritePackageRestrictionsLocked(userId); 18927 postPreferredActivityChangedBroadcast(userId); 18928 } 18929 } 18930 } 18931 18932 /** 18933 * Common machinery for picking apart a restored XML blob and passing 18934 * it to a caller-supplied functor to be applied to the running system. 18935 */ 18936 private void restoreFromXml(XmlPullParser parser, int userId, 18937 String expectedStartTag, BlobXmlRestorer functor) 18938 throws IOException, XmlPullParserException { 18939 int type; 18940 while ((type = parser.next()) != XmlPullParser.START_TAG 18941 && type != XmlPullParser.END_DOCUMENT) { 18942 } 18943 if (type != XmlPullParser.START_TAG) { 18944 // oops didn't find a start tag?! 18945 if (DEBUG_BACKUP) { 18946 Slog.e(TAG, "Didn't find start tag during restore"); 18947 } 18948 return; 18949 } 18950Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 18951 // this is supposed to be TAG_PREFERRED_BACKUP 18952 if (!expectedStartTag.equals(parser.getName())) { 18953 if (DEBUG_BACKUP) { 18954 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 18955 } 18956 return; 18957 } 18958 18959 // skip interfering stuff, then we're aligned with the backing implementation 18960 while ((type = parser.next()) == XmlPullParser.TEXT) { } 18961Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 18962 functor.apply(parser, userId); 18963 } 18964 18965 private interface BlobXmlRestorer { 18966 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 18967 } 18968 18969 /** 18970 * Non-Binder method, support for the backup/restore mechanism: write the 18971 * full set of preferred activities in its canonical XML format. Returns the 18972 * XML output as a byte array, or null if there is none. 18973 */ 18974 @Override 18975 public byte[] getPreferredActivityBackup(int userId) { 18976 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 18977 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 18978 } 18979 18980 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 18981 try { 18982 final XmlSerializer serializer = new FastXmlSerializer(); 18983 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 18984 serializer.startDocument(null, true); 18985 serializer.startTag(null, TAG_PREFERRED_BACKUP); 18986 18987 synchronized (mPackages) { 18988 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 18989 } 18990 18991 serializer.endTag(null, TAG_PREFERRED_BACKUP); 18992 serializer.endDocument(); 18993 serializer.flush(); 18994 } catch (Exception e) { 18995 if (DEBUG_BACKUP) { 18996 Slog.e(TAG, "Unable to write preferred activities for backup", e); 18997 } 18998 return null; 18999 } 19000 19001 return dataStream.toByteArray(); 19002 } 19003 19004 @Override 19005 public void restorePreferredActivities(byte[] backup, int userId) { 19006 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19007 throw new SecurityException("Only the system may call restorePreferredActivities()"); 19008 } 19009 19010 try { 19011 final XmlPullParser parser = Xml.newPullParser(); 19012 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19013 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 19014 new BlobXmlRestorer() { 19015 @Override 19016 public void apply(XmlPullParser parser, int userId) 19017 throws XmlPullParserException, IOException { 19018 synchronized (mPackages) { 19019 mSettings.readPreferredActivitiesLPw(parser, userId); 19020 } 19021 } 19022 } ); 19023 } catch (Exception e) { 19024 if (DEBUG_BACKUP) { 19025 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19026 } 19027 } 19028 } 19029 19030 /** 19031 * Non-Binder method, support for the backup/restore mechanism: write the 19032 * default browser (etc) settings in its canonical XML format. Returns the default 19033 * browser XML representation as a byte array, or null if there is none. 19034 */ 19035 @Override 19036 public byte[] getDefaultAppsBackup(int userId) { 19037 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19038 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 19039 } 19040 19041 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19042 try { 19043 final XmlSerializer serializer = new FastXmlSerializer(); 19044 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19045 serializer.startDocument(null, true); 19046 serializer.startTag(null, TAG_DEFAULT_APPS); 19047 19048 synchronized (mPackages) { 19049 mSettings.writeDefaultAppsLPr(serializer, userId); 19050 } 19051 19052 serializer.endTag(null, TAG_DEFAULT_APPS); 19053 serializer.endDocument(); 19054 serializer.flush(); 19055 } catch (Exception e) { 19056 if (DEBUG_BACKUP) { 19057 Slog.e(TAG, "Unable to write default apps for backup", e); 19058 } 19059 return null; 19060 } 19061 19062 return dataStream.toByteArray(); 19063 } 19064 19065 @Override 19066 public void restoreDefaultApps(byte[] backup, int userId) { 19067 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19068 throw new SecurityException("Only the system may call restoreDefaultApps()"); 19069 } 19070 19071 try { 19072 final XmlPullParser parser = Xml.newPullParser(); 19073 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19074 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 19075 new BlobXmlRestorer() { 19076 @Override 19077 public void apply(XmlPullParser parser, int userId) 19078 throws XmlPullParserException, IOException { 19079 synchronized (mPackages) { 19080 mSettings.readDefaultAppsLPw(parser, userId); 19081 } 19082 } 19083 } ); 19084 } catch (Exception e) { 19085 if (DEBUG_BACKUP) { 19086 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 19087 } 19088 } 19089 } 19090 19091 @Override 19092 public byte[] getIntentFilterVerificationBackup(int userId) { 19093 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19094 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 19095 } 19096 19097 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19098 try { 19099 final XmlSerializer serializer = new FastXmlSerializer(); 19100 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19101 serializer.startDocument(null, true); 19102 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 19103 19104 synchronized (mPackages) { 19105 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 19106 } 19107 19108 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 19109 serializer.endDocument(); 19110 serializer.flush(); 19111 } catch (Exception e) { 19112 if (DEBUG_BACKUP) { 19113 Slog.e(TAG, "Unable to write default apps for backup", e); 19114 } 19115 return null; 19116 } 19117 19118 return dataStream.toByteArray(); 19119 } 19120 19121 @Override 19122 public void restoreIntentFilterVerification(byte[] backup, int userId) { 19123 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19124 throw new SecurityException("Only the system may call restorePreferredActivities()"); 19125 } 19126 19127 try { 19128 final XmlPullParser parser = Xml.newPullParser(); 19129 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19130 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 19131 new BlobXmlRestorer() { 19132 @Override 19133 public void apply(XmlPullParser parser, int userId) 19134 throws XmlPullParserException, IOException { 19135 synchronized (mPackages) { 19136 mSettings.readAllDomainVerificationsLPr(parser, userId); 19137 mSettings.writeLPr(); 19138 } 19139 } 19140 } ); 19141 } catch (Exception e) { 19142 if (DEBUG_BACKUP) { 19143 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19144 } 19145 } 19146 } 19147 19148 @Override 19149 public byte[] getPermissionGrantBackup(int userId) { 19150 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19151 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 19152 } 19153 19154 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19155 try { 19156 final XmlSerializer serializer = new FastXmlSerializer(); 19157 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19158 serializer.startDocument(null, true); 19159 serializer.startTag(null, TAG_PERMISSION_BACKUP); 19160 19161 synchronized (mPackages) { 19162 serializeRuntimePermissionGrantsLPr(serializer, userId); 19163 } 19164 19165 serializer.endTag(null, TAG_PERMISSION_BACKUP); 19166 serializer.endDocument(); 19167 serializer.flush(); 19168 } catch (Exception e) { 19169 if (DEBUG_BACKUP) { 19170 Slog.e(TAG, "Unable to write default apps for backup", e); 19171 } 19172 return null; 19173 } 19174 19175 return dataStream.toByteArray(); 19176 } 19177 19178 @Override 19179 public void restorePermissionGrants(byte[] backup, int userId) { 19180 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19181 throw new SecurityException("Only the system may call restorePermissionGrants()"); 19182 } 19183 19184 try { 19185 final XmlPullParser parser = Xml.newPullParser(); 19186 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19187 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 19188 new BlobXmlRestorer() { 19189 @Override 19190 public void apply(XmlPullParser parser, int userId) 19191 throws XmlPullParserException, IOException { 19192 synchronized (mPackages) { 19193 processRestoredPermissionGrantsLPr(parser, userId); 19194 } 19195 } 19196 } ); 19197 } catch (Exception e) { 19198 if (DEBUG_BACKUP) { 19199 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19200 } 19201 } 19202 } 19203 19204 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 19205 throws IOException { 19206 serializer.startTag(null, TAG_ALL_GRANTS); 19207 19208 final int N = mSettings.mPackages.size(); 19209 for (int i = 0; i < N; i++) { 19210 final PackageSetting ps = mSettings.mPackages.valueAt(i); 19211 boolean pkgGrantsKnown = false; 19212 19213 PermissionsState packagePerms = ps.getPermissionsState(); 19214 19215 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 19216 final int grantFlags = state.getFlags(); 19217 // only look at grants that are not system/policy fixed 19218 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 19219 final boolean isGranted = state.isGranted(); 19220 // And only back up the user-twiddled state bits 19221 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 19222 final String packageName = mSettings.mPackages.keyAt(i); 19223 if (!pkgGrantsKnown) { 19224 serializer.startTag(null, TAG_GRANT); 19225 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 19226 pkgGrantsKnown = true; 19227 } 19228 19229 final boolean userSet = 19230 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 19231 final boolean userFixed = 19232 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 19233 final boolean revoke = 19234 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 19235 19236 serializer.startTag(null, TAG_PERMISSION); 19237 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 19238 if (isGranted) { 19239 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 19240 } 19241 if (userSet) { 19242 serializer.attribute(null, ATTR_USER_SET, "true"); 19243 } 19244 if (userFixed) { 19245 serializer.attribute(null, ATTR_USER_FIXED, "true"); 19246 } 19247 if (revoke) { 19248 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 19249 } 19250 serializer.endTag(null, TAG_PERMISSION); 19251 } 19252 } 19253 } 19254 19255 if (pkgGrantsKnown) { 19256 serializer.endTag(null, TAG_GRANT); 19257 } 19258 } 19259 19260 serializer.endTag(null, TAG_ALL_GRANTS); 19261 } 19262 19263 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 19264 throws XmlPullParserException, IOException { 19265 String pkgName = null; 19266 int outerDepth = parser.getDepth(); 19267 int type; 19268 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 19269 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 19270 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 19271 continue; 19272 } 19273 19274 final String tagName = parser.getName(); 19275 if (tagName.equals(TAG_GRANT)) { 19276 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 19277 if (DEBUG_BACKUP) { 19278 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 19279 } 19280 } else if (tagName.equals(TAG_PERMISSION)) { 19281 19282 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 19283 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 19284 19285 int newFlagSet = 0; 19286 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 19287 newFlagSet |= FLAG_PERMISSION_USER_SET; 19288 } 19289 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 19290 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 19291 } 19292 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 19293 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 19294 } 19295 if (DEBUG_BACKUP) { 19296 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 19297 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 19298 } 19299 final PackageSetting ps = mSettings.mPackages.get(pkgName); 19300 if (ps != null) { 19301 // Already installed so we apply the grant immediately 19302 if (DEBUG_BACKUP) { 19303 Slog.v(TAG, " + already installed; applying"); 19304 } 19305 PermissionsState perms = ps.getPermissionsState(); 19306 BasePermission bp = mSettings.mPermissions.get(permName); 19307 if (bp != null) { 19308 if (isGranted) { 19309 perms.grantRuntimePermission(bp, userId); 19310 } 19311 if (newFlagSet != 0) { 19312 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 19313 } 19314 } 19315 } else { 19316 // Need to wait for post-restore install to apply the grant 19317 if (DEBUG_BACKUP) { 19318 Slog.v(TAG, " - not yet installed; saving for later"); 19319 } 19320 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 19321 isGranted, newFlagSet, userId); 19322 } 19323 } else { 19324 PackageManagerService.reportSettingsProblem(Log.WARN, 19325 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 19326 XmlUtils.skipCurrentTag(parser); 19327 } 19328 } 19329 19330 scheduleWriteSettingsLocked(); 19331 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 19332 } 19333 19334 @Override 19335 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 19336 int sourceUserId, int targetUserId, int flags) { 19337 mContext.enforceCallingOrSelfPermission( 19338 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 19339 int callingUid = Binder.getCallingUid(); 19340 enforceOwnerRights(ownerPackage, callingUid); 19341 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 19342 if (intentFilter.countActions() == 0) { 19343 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 19344 return; 19345 } 19346 synchronized (mPackages) { 19347 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 19348 ownerPackage, targetUserId, flags); 19349 CrossProfileIntentResolver resolver = 19350 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 19351 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 19352 // We have all those whose filter is equal. Now checking if the rest is equal as well. 19353 if (existing != null) { 19354 int size = existing.size(); 19355 for (int i = 0; i < size; i++) { 19356 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 19357 return; 19358 } 19359 } 19360 } 19361 resolver.addFilter(newFilter); 19362 scheduleWritePackageRestrictionsLocked(sourceUserId); 19363 } 19364 } 19365 19366 @Override 19367 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 19368 mContext.enforceCallingOrSelfPermission( 19369 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 19370 int callingUid = Binder.getCallingUid(); 19371 enforceOwnerRights(ownerPackage, callingUid); 19372 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 19373 synchronized (mPackages) { 19374 CrossProfileIntentResolver resolver = 19375 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 19376 ArraySet<CrossProfileIntentFilter> set = 19377 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 19378 for (CrossProfileIntentFilter filter : set) { 19379 if (filter.getOwnerPackage().equals(ownerPackage)) { 19380 resolver.removeFilter(filter); 19381 } 19382 } 19383 scheduleWritePackageRestrictionsLocked(sourceUserId); 19384 } 19385 } 19386 19387 // Enforcing that callingUid is owning pkg on userId 19388 private void enforceOwnerRights(String pkg, int callingUid) { 19389 // The system owns everything. 19390 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 19391 return; 19392 } 19393 int callingUserId = UserHandle.getUserId(callingUid); 19394 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 19395 if (pi == null) { 19396 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 19397 + callingUserId); 19398 } 19399 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 19400 throw new SecurityException("Calling uid " + callingUid 19401 + " does not own package " + pkg); 19402 } 19403 } 19404 19405 @Override 19406 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 19407 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 19408 } 19409 19410 private Intent getHomeIntent() { 19411 Intent intent = new Intent(Intent.ACTION_MAIN); 19412 intent.addCategory(Intent.CATEGORY_HOME); 19413 intent.addCategory(Intent.CATEGORY_DEFAULT); 19414 return intent; 19415 } 19416 19417 private IntentFilter getHomeFilter() { 19418 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 19419 filter.addCategory(Intent.CATEGORY_HOME); 19420 filter.addCategory(Intent.CATEGORY_DEFAULT); 19421 return filter; 19422 } 19423 19424 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 19425 int userId) { 19426 Intent intent = getHomeIntent(); 19427 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 19428 PackageManager.GET_META_DATA, userId); 19429 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 19430 true, false, false, userId); 19431 19432 allHomeCandidates.clear(); 19433 if (list != null) { 19434 for (ResolveInfo ri : list) { 19435 allHomeCandidates.add(ri); 19436 } 19437 } 19438 return (preferred == null || preferred.activityInfo == null) 19439 ? null 19440 : new ComponentName(preferred.activityInfo.packageName, 19441 preferred.activityInfo.name); 19442 } 19443 19444 @Override 19445 public void setHomeActivity(ComponentName comp, int userId) { 19446 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 19447 getHomeActivitiesAsUser(homeActivities, userId); 19448 19449 boolean found = false; 19450 19451 final int size = homeActivities.size(); 19452 final ComponentName[] set = new ComponentName[size]; 19453 for (int i = 0; i < size; i++) { 19454 final ResolveInfo candidate = homeActivities.get(i); 19455 final ActivityInfo info = candidate.activityInfo; 19456 final ComponentName activityName = new ComponentName(info.packageName, info.name); 19457 set[i] = activityName; 19458 if (!found && activityName.equals(comp)) { 19459 found = true; 19460 } 19461 } 19462 if (!found) { 19463 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 19464 + userId); 19465 } 19466 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 19467 set, comp, userId); 19468 } 19469 19470 private @Nullable String getSetupWizardPackageName() { 19471 final Intent intent = new Intent(Intent.ACTION_MAIN); 19472 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 19473 19474 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 19475 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 19476 | MATCH_DISABLED_COMPONENTS, 19477 UserHandle.myUserId()); 19478 if (matches.size() == 1) { 19479 return matches.get(0).getComponentInfo().packageName; 19480 } else { 19481 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 19482 + ": matches=" + matches); 19483 return null; 19484 } 19485 } 19486 19487 private @Nullable String getStorageManagerPackageName() { 19488 final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE); 19489 19490 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 19491 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 19492 | MATCH_DISABLED_COMPONENTS, 19493 UserHandle.myUserId()); 19494 if (matches.size() == 1) { 19495 return matches.get(0).getComponentInfo().packageName; 19496 } else { 19497 Slog.e(TAG, "There should probably be exactly one storage manager; found " 19498 + matches.size() + ": matches=" + matches); 19499 return null; 19500 } 19501 } 19502 19503 @Override 19504 public void setApplicationEnabledSetting(String appPackageName, 19505 int newState, int flags, int userId, String callingPackage) { 19506 if (!sUserManager.exists(userId)) return; 19507 if (callingPackage == null) { 19508 callingPackage = Integer.toString(Binder.getCallingUid()); 19509 } 19510 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 19511 } 19512 19513 @Override 19514 public void setComponentEnabledSetting(ComponentName componentName, 19515 int newState, int flags, int userId) { 19516 if (!sUserManager.exists(userId)) return; 19517 setEnabledSetting(componentName.getPackageName(), 19518 componentName.getClassName(), newState, flags, userId, null); 19519 } 19520 19521 private void setEnabledSetting(final String packageName, String className, int newState, 19522 final int flags, int userId, String callingPackage) { 19523 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 19524 || newState == COMPONENT_ENABLED_STATE_ENABLED 19525 || newState == COMPONENT_ENABLED_STATE_DISABLED 19526 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 19527 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 19528 throw new IllegalArgumentException("Invalid new component state: " 19529 + newState); 19530 } 19531 PackageSetting pkgSetting; 19532 final int uid = Binder.getCallingUid(); 19533 final int permission; 19534 if (uid == Process.SYSTEM_UID) { 19535 permission = PackageManager.PERMISSION_GRANTED; 19536 } else { 19537 permission = mContext.checkCallingOrSelfPermission( 19538 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 19539 } 19540 enforceCrossUserPermission(uid, userId, 19541 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 19542 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 19543 boolean sendNow = false; 19544 boolean isApp = (className == null); 19545 String componentName = isApp ? packageName : className; 19546 int packageUid = -1; 19547 ArrayList<String> components; 19548 19549 // writer 19550 synchronized (mPackages) { 19551 pkgSetting = mSettings.mPackages.get(packageName); 19552 if (pkgSetting == null) { 19553 if (className == null) { 19554 throw new IllegalArgumentException("Unknown package: " + packageName); 19555 } 19556 throw new IllegalArgumentException( 19557 "Unknown component: " + packageName + "/" + className); 19558 } 19559 } 19560 19561 // Limit who can change which apps 19562 if (!UserHandle.isSameApp(uid, pkgSetting.appId)) { 19563 // Don't allow apps that don't have permission to modify other apps 19564 if (!allowedByPermission) { 19565 throw new SecurityException( 19566 "Permission Denial: attempt to change component state from pid=" 19567 + Binder.getCallingPid() 19568 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 19569 } 19570 // Don't allow changing protected packages. 19571 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 19572 throw new SecurityException("Cannot disable a protected package: " + packageName); 19573 } 19574 } 19575 19576 synchronized (mPackages) { 19577 if (uid == Process.SHELL_UID 19578 && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) { 19579 // Shell can only change whole packages between ENABLED and DISABLED_USER states 19580 // unless it is a test package. 19581 int oldState = pkgSetting.getEnabled(userId); 19582 if (className == null 19583 && 19584 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 19585 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 19586 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 19587 && 19588 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 19589 || newState == COMPONENT_ENABLED_STATE_DEFAULT 19590 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 19591 // ok 19592 } else { 19593 throw new SecurityException( 19594 "Shell cannot change component state for " + packageName + "/" 19595 + className + " to " + newState); 19596 } 19597 } 19598 if (className == null) { 19599 // We're dealing with an application/package level state change 19600 if (pkgSetting.getEnabled(userId) == newState) { 19601 // Nothing to do 19602 return; 19603 } 19604 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 19605 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 19606 // Don't care about who enables an app. 19607 callingPackage = null; 19608 } 19609 pkgSetting.setEnabled(newState, userId, callingPackage); 19610 // pkgSetting.pkg.mSetEnabled = newState; 19611 } else { 19612 // We're dealing with a component level state change 19613 // First, verify that this is a valid class name. 19614 PackageParser.Package pkg = pkgSetting.pkg; 19615 if (pkg == null || !pkg.hasComponentClassName(className)) { 19616 if (pkg != null && 19617 pkg.applicationInfo.targetSdkVersion >= 19618 Build.VERSION_CODES.JELLY_BEAN) { 19619 throw new IllegalArgumentException("Component class " + className 19620 + " does not exist in " + packageName); 19621 } else { 19622 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 19623 + className + " does not exist in " + packageName); 19624 } 19625 } 19626 switch (newState) { 19627 case COMPONENT_ENABLED_STATE_ENABLED: 19628 if (!pkgSetting.enableComponentLPw(className, userId)) { 19629 return; 19630 } 19631 break; 19632 case COMPONENT_ENABLED_STATE_DISABLED: 19633 if (!pkgSetting.disableComponentLPw(className, userId)) { 19634 return; 19635 } 19636 break; 19637 case COMPONENT_ENABLED_STATE_DEFAULT: 19638 if (!pkgSetting.restoreComponentLPw(className, userId)) { 19639 return; 19640 } 19641 break; 19642 default: 19643 Slog.e(TAG, "Invalid new component state: " + newState); 19644 return; 19645 } 19646 } 19647 scheduleWritePackageRestrictionsLocked(userId); 19648 components = mPendingBroadcasts.get(userId, packageName); 19649 final boolean newPackage = components == null; 19650 if (newPackage) { 19651 components = new ArrayList<String>(); 19652 } 19653 if (!components.contains(componentName)) { 19654 components.add(componentName); 19655 } 19656 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 19657 sendNow = true; 19658 // Purge entry from pending broadcast list if another one exists already 19659 // since we are sending one right away. 19660 mPendingBroadcasts.remove(userId, packageName); 19661 } else { 19662 if (newPackage) { 19663 mPendingBroadcasts.put(userId, packageName, components); 19664 } 19665 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 19666 // Schedule a message 19667 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 19668 } 19669 } 19670 } 19671 19672 long callingId = Binder.clearCallingIdentity(); 19673 try { 19674 if (sendNow) { 19675 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 19676 sendPackageChangedBroadcast(packageName, 19677 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 19678 } 19679 } finally { 19680 Binder.restoreCallingIdentity(callingId); 19681 } 19682 } 19683 19684 @Override 19685 public void flushPackageRestrictionsAsUser(int userId) { 19686 if (!sUserManager.exists(userId)) { 19687 return; 19688 } 19689 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 19690 false /* checkShell */, "flushPackageRestrictions"); 19691 synchronized (mPackages) { 19692 mSettings.writePackageRestrictionsLPr(userId); 19693 mDirtyUsers.remove(userId); 19694 if (mDirtyUsers.isEmpty()) { 19695 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 19696 } 19697 } 19698 } 19699 19700 private void sendPackageChangedBroadcast(String packageName, 19701 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 19702 if (DEBUG_INSTALL) 19703 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 19704 + componentNames); 19705 Bundle extras = new Bundle(4); 19706 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 19707 String nameList[] = new String[componentNames.size()]; 19708 componentNames.toArray(nameList); 19709 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 19710 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 19711 extras.putInt(Intent.EXTRA_UID, packageUid); 19712 // If this is not reporting a change of the overall package, then only send it 19713 // to registered receivers. We don't want to launch a swath of apps for every 19714 // little component state change. 19715 final int flags = !componentNames.contains(packageName) 19716 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 19717 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 19718 new int[] {UserHandle.getUserId(packageUid)}); 19719 } 19720 19721 @Override 19722 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 19723 if (!sUserManager.exists(userId)) return; 19724 final int uid = Binder.getCallingUid(); 19725 final int permission = mContext.checkCallingOrSelfPermission( 19726 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 19727 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 19728 enforceCrossUserPermission(uid, userId, 19729 true /* requireFullPermission */, true /* checkShell */, "stop package"); 19730 // writer 19731 synchronized (mPackages) { 19732 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 19733 allowedByPermission, uid, userId)) { 19734 scheduleWritePackageRestrictionsLocked(userId); 19735 } 19736 } 19737 } 19738 19739 @Override 19740 public String getInstallerPackageName(String packageName) { 19741 // reader 19742 synchronized (mPackages) { 19743 return mSettings.getInstallerPackageNameLPr(packageName); 19744 } 19745 } 19746 19747 public boolean isOrphaned(String packageName) { 19748 // reader 19749 synchronized (mPackages) { 19750 return mSettings.isOrphaned(packageName); 19751 } 19752 } 19753 19754 @Override 19755 public int getApplicationEnabledSetting(String packageName, int userId) { 19756 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 19757 int uid = Binder.getCallingUid(); 19758 enforceCrossUserPermission(uid, userId, 19759 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 19760 // reader 19761 synchronized (mPackages) { 19762 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 19763 } 19764 } 19765 19766 @Override 19767 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 19768 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 19769 int uid = Binder.getCallingUid(); 19770 enforceCrossUserPermission(uid, userId, 19771 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 19772 // reader 19773 synchronized (mPackages) { 19774 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 19775 } 19776 } 19777 19778 @Override 19779 public void enterSafeMode() { 19780 enforceSystemOrRoot("Only the system can request entering safe mode"); 19781 19782 if (!mSystemReady) { 19783 mSafeMode = true; 19784 } 19785 } 19786 19787 @Override 19788 public void systemReady() { 19789 mSystemReady = true; 19790 19791 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 19792 // disabled after already being started. 19793 CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this, 19794 mContext.getContentResolver(), UserHandle.USER_SYSTEM); 19795 19796 // Read the compatibilty setting when the system is ready. 19797 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 19798 mContext.getContentResolver(), 19799 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 19800 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 19801 if (DEBUG_SETTINGS) { 19802 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 19803 } 19804 19805 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 19806 19807 synchronized (mPackages) { 19808 // Verify that all of the preferred activity components actually 19809 // exist. It is possible for applications to be updated and at 19810 // that point remove a previously declared activity component that 19811 // had been set as a preferred activity. We try to clean this up 19812 // the next time we encounter that preferred activity, but it is 19813 // possible for the user flow to never be able to return to that 19814 // situation so here we do a sanity check to make sure we haven't 19815 // left any junk around. 19816 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 19817 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 19818 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 19819 removed.clear(); 19820 for (PreferredActivity pa : pir.filterSet()) { 19821 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 19822 removed.add(pa); 19823 } 19824 } 19825 if (removed.size() > 0) { 19826 for (int r=0; r<removed.size(); r++) { 19827 PreferredActivity pa = removed.get(r); 19828 Slog.w(TAG, "Removing dangling preferred activity: " 19829 + pa.mPref.mComponent); 19830 pir.removeFilter(pa); 19831 } 19832 mSettings.writePackageRestrictionsLPr( 19833 mSettings.mPreferredActivities.keyAt(i)); 19834 } 19835 } 19836 19837 for (int userId : UserManagerService.getInstance().getUserIds()) { 19838 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 19839 grantPermissionsUserIds = ArrayUtils.appendInt( 19840 grantPermissionsUserIds, userId); 19841 } 19842 } 19843 } 19844 sUserManager.systemReady(); 19845 19846 // If we upgraded grant all default permissions before kicking off. 19847 for (int userId : grantPermissionsUserIds) { 19848 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 19849 } 19850 19851 // If we did not grant default permissions, we preload from this the 19852 // default permission exceptions lazily to ensure we don't hit the 19853 // disk on a new user creation. 19854 if (grantPermissionsUserIds == EMPTY_INT_ARRAY) { 19855 mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions(); 19856 } 19857 19858 // Kick off any messages waiting for system ready 19859 if (mPostSystemReadyMessages != null) { 19860 for (Message msg : mPostSystemReadyMessages) { 19861 msg.sendToTarget(); 19862 } 19863 mPostSystemReadyMessages = null; 19864 } 19865 19866 // Watch for external volumes that come and go over time 19867 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19868 storage.registerListener(mStorageListener); 19869 19870 mInstallerService.systemReady(); 19871 mPackageDexOptimizer.systemReady(); 19872 19873 StorageManagerInternal StorageManagerInternal = LocalServices.getService( 19874 StorageManagerInternal.class); 19875 StorageManagerInternal.addExternalStoragePolicy( 19876 new StorageManagerInternal.ExternalStorageMountPolicy() { 19877 @Override 19878 public int getMountMode(int uid, String packageName) { 19879 if (Process.isIsolated(uid)) { 19880 return Zygote.MOUNT_EXTERNAL_NONE; 19881 } 19882 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 19883 return Zygote.MOUNT_EXTERNAL_DEFAULT; 19884 } 19885 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 19886 return Zygote.MOUNT_EXTERNAL_DEFAULT; 19887 } 19888 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 19889 return Zygote.MOUNT_EXTERNAL_READ; 19890 } 19891 return Zygote.MOUNT_EXTERNAL_WRITE; 19892 } 19893 19894 @Override 19895 public boolean hasExternalStorage(int uid, String packageName) { 19896 return true; 19897 } 19898 }); 19899 19900 // Now that we're mostly running, clean up stale users and apps 19901 reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 19902 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 19903 } 19904 19905 @Override 19906 public boolean isSafeMode() { 19907 return mSafeMode; 19908 } 19909 19910 @Override 19911 public boolean hasSystemUidErrors() { 19912 return mHasSystemUidErrors; 19913 } 19914 19915 static String arrayToString(int[] array) { 19916 StringBuffer buf = new StringBuffer(128); 19917 buf.append('['); 19918 if (array != null) { 19919 for (int i=0; i<array.length; i++) { 19920 if (i > 0) buf.append(", "); 19921 buf.append(array[i]); 19922 } 19923 } 19924 buf.append(']'); 19925 return buf.toString(); 19926 } 19927 19928 static class DumpState { 19929 public static final int DUMP_LIBS = 1 << 0; 19930 public static final int DUMP_FEATURES = 1 << 1; 19931 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 19932 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 19933 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 19934 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 19935 public static final int DUMP_PERMISSIONS = 1 << 6; 19936 public static final int DUMP_PACKAGES = 1 << 7; 19937 public static final int DUMP_SHARED_USERS = 1 << 8; 19938 public static final int DUMP_MESSAGES = 1 << 9; 19939 public static final int DUMP_PROVIDERS = 1 << 10; 19940 public static final int DUMP_VERIFIERS = 1 << 11; 19941 public static final int DUMP_PREFERRED = 1 << 12; 19942 public static final int DUMP_PREFERRED_XML = 1 << 13; 19943 public static final int DUMP_KEYSETS = 1 << 14; 19944 public static final int DUMP_VERSION = 1 << 15; 19945 public static final int DUMP_INSTALLS = 1 << 16; 19946 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 19947 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 19948 public static final int DUMP_FROZEN = 1 << 19; 19949 public static final int DUMP_DEXOPT = 1 << 20; 19950 public static final int DUMP_COMPILER_STATS = 1 << 21; 19951 19952 public static final int OPTION_SHOW_FILTERS = 1 << 0; 19953 19954 private int mTypes; 19955 19956 private int mOptions; 19957 19958 private boolean mTitlePrinted; 19959 19960 private SharedUserSetting mSharedUser; 19961 19962 public boolean isDumping(int type) { 19963 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 19964 return true; 19965 } 19966 19967 return (mTypes & type) != 0; 19968 } 19969 19970 public void setDump(int type) { 19971 mTypes |= type; 19972 } 19973 19974 public boolean isOptionEnabled(int option) { 19975 return (mOptions & option) != 0; 19976 } 19977 19978 public void setOptionEnabled(int option) { 19979 mOptions |= option; 19980 } 19981 19982 public boolean onTitlePrinted() { 19983 final boolean printed = mTitlePrinted; 19984 mTitlePrinted = true; 19985 return printed; 19986 } 19987 19988 public boolean getTitlePrinted() { 19989 return mTitlePrinted; 19990 } 19991 19992 public void setTitlePrinted(boolean enabled) { 19993 mTitlePrinted = enabled; 19994 } 19995 19996 public SharedUserSetting getSharedUser() { 19997 return mSharedUser; 19998 } 19999 20000 public void setSharedUser(SharedUserSetting user) { 20001 mSharedUser = user; 20002 } 20003 } 20004 20005 @Override 20006 public void onShellCommand(FileDescriptor in, FileDescriptor out, 20007 FileDescriptor err, String[] args, ShellCallback callback, 20008 ResultReceiver resultReceiver) { 20009 (new PackageManagerShellCommand(this)).exec( 20010 this, in, out, err, args, callback, resultReceiver); 20011 } 20012 20013 @Override 20014 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 20015 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 20016 != PackageManager.PERMISSION_GRANTED) { 20017 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 20018 + Binder.getCallingPid() 20019 + ", uid=" + Binder.getCallingUid() 20020 + " without permission " 20021 + android.Manifest.permission.DUMP); 20022 return; 20023 } 20024 20025 DumpState dumpState = new DumpState(); 20026 boolean fullPreferred = false; 20027 boolean checkin = false; 20028 20029 String packageName = null; 20030 ArraySet<String> permissionNames = null; 20031 20032 int opti = 0; 20033 while (opti < args.length) { 20034 String opt = args[opti]; 20035 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 20036 break; 20037 } 20038 opti++; 20039 20040 if ("-a".equals(opt)) { 20041 // Right now we only know how to print all. 20042 } else if ("-h".equals(opt)) { 20043 pw.println("Package manager dump options:"); 20044 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 20045 pw.println(" --checkin: dump for a checkin"); 20046 pw.println(" -f: print details of intent filters"); 20047 pw.println(" -h: print this help"); 20048 pw.println(" cmd may be one of:"); 20049 pw.println(" l[ibraries]: list known shared libraries"); 20050 pw.println(" f[eatures]: list device features"); 20051 pw.println(" k[eysets]: print known keysets"); 20052 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 20053 pw.println(" perm[issions]: dump permissions"); 20054 pw.println(" permission [name ...]: dump declaration and use of given permission"); 20055 pw.println(" pref[erred]: print preferred package settings"); 20056 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 20057 pw.println(" prov[iders]: dump content providers"); 20058 pw.println(" p[ackages]: dump installed packages"); 20059 pw.println(" s[hared-users]: dump shared user IDs"); 20060 pw.println(" m[essages]: print collected runtime messages"); 20061 pw.println(" v[erifiers]: print package verifier info"); 20062 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 20063 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 20064 pw.println(" version: print database version info"); 20065 pw.println(" write: write current settings now"); 20066 pw.println(" installs: details about install sessions"); 20067 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 20068 pw.println(" dexopt: dump dexopt state"); 20069 pw.println(" compiler-stats: dump compiler statistics"); 20070 pw.println(" <package.name>: info about given package"); 20071 return; 20072 } else if ("--checkin".equals(opt)) { 20073 checkin = true; 20074 } else if ("-f".equals(opt)) { 20075 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 20076 } else { 20077 pw.println("Unknown argument: " + opt + "; use -h for help"); 20078 } 20079 } 20080 20081 // Is the caller requesting to dump a particular piece of data? 20082 if (opti < args.length) { 20083 String cmd = args[opti]; 20084 opti++; 20085 // Is this a package name? 20086 if ("android".equals(cmd) || cmd.contains(".")) { 20087 packageName = cmd; 20088 // When dumping a single package, we always dump all of its 20089 // filter information since the amount of data will be reasonable. 20090 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 20091 } else if ("check-permission".equals(cmd)) { 20092 if (opti >= args.length) { 20093 pw.println("Error: check-permission missing permission argument"); 20094 return; 20095 } 20096 String perm = args[opti]; 20097 opti++; 20098 if (opti >= args.length) { 20099 pw.println("Error: check-permission missing package argument"); 20100 return; 20101 } 20102 20103 String pkg = args[opti]; 20104 opti++; 20105 int user = UserHandle.getUserId(Binder.getCallingUid()); 20106 if (opti < args.length) { 20107 try { 20108 user = Integer.parseInt(args[opti]); 20109 } catch (NumberFormatException e) { 20110 pw.println("Error: check-permission user argument is not a number: " 20111 + args[opti]); 20112 return; 20113 } 20114 } 20115 20116 // Normalize package name to handle renamed packages and static libs 20117 pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST); 20118 20119 pw.println(checkPermission(perm, pkg, user)); 20120 return; 20121 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 20122 dumpState.setDump(DumpState.DUMP_LIBS); 20123 } else if ("f".equals(cmd) || "features".equals(cmd)) { 20124 dumpState.setDump(DumpState.DUMP_FEATURES); 20125 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 20126 if (opti >= args.length) { 20127 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 20128 | DumpState.DUMP_SERVICE_RESOLVERS 20129 | DumpState.DUMP_RECEIVER_RESOLVERS 20130 | DumpState.DUMP_CONTENT_RESOLVERS); 20131 } else { 20132 while (opti < args.length) { 20133 String name = args[opti]; 20134 if ("a".equals(name) || "activity".equals(name)) { 20135 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 20136 } else if ("s".equals(name) || "service".equals(name)) { 20137 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 20138 } else if ("r".equals(name) || "receiver".equals(name)) { 20139 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 20140 } else if ("c".equals(name) || "content".equals(name)) { 20141 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 20142 } else { 20143 pw.println("Error: unknown resolver table type: " + name); 20144 return; 20145 } 20146 opti++; 20147 } 20148 } 20149 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 20150 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 20151 } else if ("permission".equals(cmd)) { 20152 if (opti >= args.length) { 20153 pw.println("Error: permission requires permission name"); 20154 return; 20155 } 20156 permissionNames = new ArraySet<>(); 20157 while (opti < args.length) { 20158 permissionNames.add(args[opti]); 20159 opti++; 20160 } 20161 dumpState.setDump(DumpState.DUMP_PERMISSIONS 20162 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 20163 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 20164 dumpState.setDump(DumpState.DUMP_PREFERRED); 20165 } else if ("preferred-xml".equals(cmd)) { 20166 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 20167 if (opti < args.length && "--full".equals(args[opti])) { 20168 fullPreferred = true; 20169 opti++; 20170 } 20171 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 20172 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 20173 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 20174 dumpState.setDump(DumpState.DUMP_PACKAGES); 20175 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 20176 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 20177 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 20178 dumpState.setDump(DumpState.DUMP_PROVIDERS); 20179 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 20180 dumpState.setDump(DumpState.DUMP_MESSAGES); 20181 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 20182 dumpState.setDump(DumpState.DUMP_VERIFIERS); 20183 } else if ("i".equals(cmd) || "ifv".equals(cmd) 20184 || "intent-filter-verifiers".equals(cmd)) { 20185 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 20186 } else if ("version".equals(cmd)) { 20187 dumpState.setDump(DumpState.DUMP_VERSION); 20188 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 20189 dumpState.setDump(DumpState.DUMP_KEYSETS); 20190 } else if ("installs".equals(cmd)) { 20191 dumpState.setDump(DumpState.DUMP_INSTALLS); 20192 } else if ("frozen".equals(cmd)) { 20193 dumpState.setDump(DumpState.DUMP_FROZEN); 20194 } else if ("dexopt".equals(cmd)) { 20195 dumpState.setDump(DumpState.DUMP_DEXOPT); 20196 } else if ("compiler-stats".equals(cmd)) { 20197 dumpState.setDump(DumpState.DUMP_COMPILER_STATS); 20198 } else if ("write".equals(cmd)) { 20199 synchronized (mPackages) { 20200 mSettings.writeLPr(); 20201 pw.println("Settings written."); 20202 return; 20203 } 20204 } 20205 } 20206 20207 if (checkin) { 20208 pw.println("vers,1"); 20209 } 20210 20211 // reader 20212 synchronized (mPackages) { 20213 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 20214 if (!checkin) { 20215 if (dumpState.onTitlePrinted()) 20216 pw.println(); 20217 pw.println("Database versions:"); 20218 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 20219 } 20220 } 20221 20222 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 20223 if (!checkin) { 20224 if (dumpState.onTitlePrinted()) 20225 pw.println(); 20226 pw.println("Verifiers:"); 20227 pw.print(" Required: "); 20228 pw.print(mRequiredVerifierPackage); 20229 pw.print(" (uid="); 20230 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 20231 UserHandle.USER_SYSTEM)); 20232 pw.println(")"); 20233 } else if (mRequiredVerifierPackage != null) { 20234 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 20235 pw.print(","); 20236 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 20237 UserHandle.USER_SYSTEM)); 20238 } 20239 } 20240 20241 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 20242 packageName == null) { 20243 if (mIntentFilterVerifierComponent != null) { 20244 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 20245 if (!checkin) { 20246 if (dumpState.onTitlePrinted()) 20247 pw.println(); 20248 pw.println("Intent Filter Verifier:"); 20249 pw.print(" Using: "); 20250 pw.print(verifierPackageName); 20251 pw.print(" (uid="); 20252 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 20253 UserHandle.USER_SYSTEM)); 20254 pw.println(")"); 20255 } else if (verifierPackageName != null) { 20256 pw.print("ifv,"); pw.print(verifierPackageName); 20257 pw.print(","); 20258 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 20259 UserHandle.USER_SYSTEM)); 20260 } 20261 } else { 20262 pw.println(); 20263 pw.println("No Intent Filter Verifier available!"); 20264 } 20265 } 20266 20267 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 20268 boolean printedHeader = false; 20269 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 20270 while (it.hasNext()) { 20271 String libName = it.next(); 20272 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName); 20273 if (versionedLib == null) { 20274 continue; 20275 } 20276 final int versionCount = versionedLib.size(); 20277 for (int i = 0; i < versionCount; i++) { 20278 SharedLibraryEntry libEntry = versionedLib.valueAt(i); 20279 if (!checkin) { 20280 if (!printedHeader) { 20281 if (dumpState.onTitlePrinted()) 20282 pw.println(); 20283 pw.println("Libraries:"); 20284 printedHeader = true; 20285 } 20286 pw.print(" "); 20287 } else { 20288 pw.print("lib,"); 20289 } 20290 pw.print(libEntry.info.getName()); 20291 if (libEntry.info.isStatic()) { 20292 pw.print(" version=" + libEntry.info.getVersion()); 20293 } 20294 if (!checkin) { 20295 pw.print(" -> "); 20296 } 20297 if (libEntry.path != null) { 20298 pw.print(" (jar) "); 20299 pw.print(libEntry.path); 20300 } else { 20301 pw.print(" (apk) "); 20302 pw.print(libEntry.apk); 20303 } 20304 pw.println(); 20305 } 20306 } 20307 } 20308 20309 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 20310 if (dumpState.onTitlePrinted()) 20311 pw.println(); 20312 if (!checkin) { 20313 pw.println("Features:"); 20314 } 20315 20316 for (FeatureInfo feat : mAvailableFeatures.values()) { 20317 if (checkin) { 20318 pw.print("feat,"); 20319 pw.print(feat.name); 20320 pw.print(","); 20321 pw.println(feat.version); 20322 } else { 20323 pw.print(" "); 20324 pw.print(feat.name); 20325 if (feat.version > 0) { 20326 pw.print(" version="); 20327 pw.print(feat.version); 20328 } 20329 pw.println(); 20330 } 20331 } 20332 } 20333 20334 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 20335 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 20336 : "Activity Resolver Table:", " ", packageName, 20337 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20338 dumpState.setTitlePrinted(true); 20339 } 20340 } 20341 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 20342 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 20343 : "Receiver Resolver Table:", " ", packageName, 20344 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20345 dumpState.setTitlePrinted(true); 20346 } 20347 } 20348 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 20349 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 20350 : "Service Resolver Table:", " ", packageName, 20351 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20352 dumpState.setTitlePrinted(true); 20353 } 20354 } 20355 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 20356 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 20357 : "Provider Resolver Table:", " ", packageName, 20358 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20359 dumpState.setTitlePrinted(true); 20360 } 20361 } 20362 20363 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 20364 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 20365 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 20366 int user = mSettings.mPreferredActivities.keyAt(i); 20367 if (pir.dump(pw, 20368 dumpState.getTitlePrinted() 20369 ? "\nPreferred Activities User " + user + ":" 20370 : "Preferred Activities User " + user + ":", " ", 20371 packageName, true, false)) { 20372 dumpState.setTitlePrinted(true); 20373 } 20374 } 20375 } 20376 20377 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 20378 pw.flush(); 20379 FileOutputStream fout = new FileOutputStream(fd); 20380 BufferedOutputStream str = new BufferedOutputStream(fout); 20381 XmlSerializer serializer = new FastXmlSerializer(); 20382 try { 20383 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 20384 serializer.startDocument(null, true); 20385 serializer.setFeature( 20386 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 20387 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 20388 serializer.endDocument(); 20389 serializer.flush(); 20390 } catch (IllegalArgumentException e) { 20391 pw.println("Failed writing: " + e); 20392 } catch (IllegalStateException e) { 20393 pw.println("Failed writing: " + e); 20394 } catch (IOException e) { 20395 pw.println("Failed writing: " + e); 20396 } 20397 } 20398 20399 if (!checkin 20400 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 20401 && packageName == null) { 20402 pw.println(); 20403 int count = mSettings.mPackages.size(); 20404 if (count == 0) { 20405 pw.println("No applications!"); 20406 pw.println(); 20407 } else { 20408 final String prefix = " "; 20409 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 20410 if (allPackageSettings.size() == 0) { 20411 pw.println("No domain preferred apps!"); 20412 pw.println(); 20413 } else { 20414 pw.println("App verification status:"); 20415 pw.println(); 20416 count = 0; 20417 for (PackageSetting ps : allPackageSettings) { 20418 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 20419 if (ivi == null || ivi.getPackageName() == null) continue; 20420 pw.println(prefix + "Package: " + ivi.getPackageName()); 20421 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 20422 pw.println(prefix + "Status: " + ivi.getStatusString()); 20423 pw.println(); 20424 count++; 20425 } 20426 if (count == 0) { 20427 pw.println(prefix + "No app verification established."); 20428 pw.println(); 20429 } 20430 for (int userId : sUserManager.getUserIds()) { 20431 pw.println("App linkages for user " + userId + ":"); 20432 pw.println(); 20433 count = 0; 20434 for (PackageSetting ps : allPackageSettings) { 20435 final long status = ps.getDomainVerificationStatusForUser(userId); 20436 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 20437 && !DEBUG_DOMAIN_VERIFICATION) { 20438 continue; 20439 } 20440 pw.println(prefix + "Package: " + ps.name); 20441 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 20442 String statusStr = IntentFilterVerificationInfo. 20443 getStatusStringFromValue(status); 20444 pw.println(prefix + "Status: " + statusStr); 20445 pw.println(); 20446 count++; 20447 } 20448 if (count == 0) { 20449 pw.println(prefix + "No configured app linkages."); 20450 pw.println(); 20451 } 20452 } 20453 } 20454 } 20455 } 20456 20457 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 20458 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 20459 if (packageName == null && permissionNames == null) { 20460 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 20461 if (iperm == 0) { 20462 if (dumpState.onTitlePrinted()) 20463 pw.println(); 20464 pw.println("AppOp Permissions:"); 20465 } 20466 pw.print(" AppOp Permission "); 20467 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 20468 pw.println(":"); 20469 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 20470 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 20471 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 20472 } 20473 } 20474 } 20475 } 20476 20477 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 20478 boolean printedSomething = false; 20479 for (PackageParser.Provider p : mProviders.mProviders.values()) { 20480 if (packageName != null && !packageName.equals(p.info.packageName)) { 20481 continue; 20482 } 20483 if (!printedSomething) { 20484 if (dumpState.onTitlePrinted()) 20485 pw.println(); 20486 pw.println("Registered ContentProviders:"); 20487 printedSomething = true; 20488 } 20489 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 20490 pw.print(" "); pw.println(p.toString()); 20491 } 20492 printedSomething = false; 20493 for (Map.Entry<String, PackageParser.Provider> entry : 20494 mProvidersByAuthority.entrySet()) { 20495 PackageParser.Provider p = entry.getValue(); 20496 if (packageName != null && !packageName.equals(p.info.packageName)) { 20497 continue; 20498 } 20499 if (!printedSomething) { 20500 if (dumpState.onTitlePrinted()) 20501 pw.println(); 20502 pw.println("ContentProvider Authorities:"); 20503 printedSomething = true; 20504 } 20505 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 20506 pw.print(" "); pw.println(p.toString()); 20507 if (p.info != null && p.info.applicationInfo != null) { 20508 final String appInfo = p.info.applicationInfo.toString(); 20509 pw.print(" applicationInfo="); pw.println(appInfo); 20510 } 20511 } 20512 } 20513 20514 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 20515 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 20516 } 20517 20518 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 20519 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 20520 } 20521 20522 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 20523 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 20524 } 20525 20526 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 20527 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 20528 } 20529 20530 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 20531 // XXX should handle packageName != null by dumping only install data that 20532 // the given package is involved with. 20533 if (dumpState.onTitlePrinted()) pw.println(); 20534 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 20535 } 20536 20537 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 20538 // XXX should handle packageName != null by dumping only install data that 20539 // the given package is involved with. 20540 if (dumpState.onTitlePrinted()) pw.println(); 20541 20542 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 20543 ipw.println(); 20544 ipw.println("Frozen packages:"); 20545 ipw.increaseIndent(); 20546 if (mFrozenPackages.size() == 0) { 20547 ipw.println("(none)"); 20548 } else { 20549 for (int i = 0; i < mFrozenPackages.size(); i++) { 20550 ipw.println(mFrozenPackages.valueAt(i)); 20551 } 20552 } 20553 ipw.decreaseIndent(); 20554 } 20555 20556 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 20557 if (dumpState.onTitlePrinted()) pw.println(); 20558 dumpDexoptStateLPr(pw, packageName); 20559 } 20560 20561 if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) { 20562 if (dumpState.onTitlePrinted()) pw.println(); 20563 dumpCompilerStatsLPr(pw, packageName); 20564 } 20565 20566 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 20567 if (dumpState.onTitlePrinted()) pw.println(); 20568 mSettings.dumpReadMessagesLPr(pw, dumpState); 20569 20570 pw.println(); 20571 pw.println("Package warning messages:"); 20572 BufferedReader in = null; 20573 String line = null; 20574 try { 20575 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 20576 while ((line = in.readLine()) != null) { 20577 if (line.contains("ignored: updated version")) continue; 20578 pw.println(line); 20579 } 20580 } catch (IOException ignored) { 20581 } finally { 20582 IoUtils.closeQuietly(in); 20583 } 20584 } 20585 20586 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 20587 BufferedReader in = null; 20588 String line = null; 20589 try { 20590 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 20591 while ((line = in.readLine()) != null) { 20592 if (line.contains("ignored: updated version")) continue; 20593 pw.print("msg,"); 20594 pw.println(line); 20595 } 20596 } catch (IOException ignored) { 20597 } finally { 20598 IoUtils.closeQuietly(in); 20599 } 20600 } 20601 } 20602 } 20603 20604 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 20605 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 20606 ipw.println(); 20607 ipw.println("Dexopt state:"); 20608 ipw.increaseIndent(); 20609 Collection<PackageParser.Package> packages = null; 20610 if (packageName != null) { 20611 PackageParser.Package targetPackage = mPackages.get(packageName); 20612 if (targetPackage != null) { 20613 packages = Collections.singletonList(targetPackage); 20614 } else { 20615 ipw.println("Unable to find package: " + packageName); 20616 return; 20617 } 20618 } else { 20619 packages = mPackages.values(); 20620 } 20621 20622 for (PackageParser.Package pkg : packages) { 20623 ipw.println("[" + pkg.packageName + "]"); 20624 ipw.increaseIndent(); 20625 mPackageDexOptimizer.dumpDexoptState(ipw, pkg); 20626 ipw.decreaseIndent(); 20627 } 20628 } 20629 20630 private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) { 20631 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 20632 ipw.println(); 20633 ipw.println("Compiler stats:"); 20634 ipw.increaseIndent(); 20635 Collection<PackageParser.Package> packages = null; 20636 if (packageName != null) { 20637 PackageParser.Package targetPackage = mPackages.get(packageName); 20638 if (targetPackage != null) { 20639 packages = Collections.singletonList(targetPackage); 20640 } else { 20641 ipw.println("Unable to find package: " + packageName); 20642 return; 20643 } 20644 } else { 20645 packages = mPackages.values(); 20646 } 20647 20648 for (PackageParser.Package pkg : packages) { 20649 ipw.println("[" + pkg.packageName + "]"); 20650 ipw.increaseIndent(); 20651 20652 CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName); 20653 if (stats == null) { 20654 ipw.println("(No recorded stats)"); 20655 } else { 20656 stats.dump(ipw); 20657 } 20658 ipw.decreaseIndent(); 20659 } 20660 } 20661 20662 private String dumpDomainString(String packageName) { 20663 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 20664 .getList(); 20665 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 20666 20667 ArraySet<String> result = new ArraySet<>(); 20668 if (iviList.size() > 0) { 20669 for (IntentFilterVerificationInfo ivi : iviList) { 20670 for (String host : ivi.getDomains()) { 20671 result.add(host); 20672 } 20673 } 20674 } 20675 if (filters != null && filters.size() > 0) { 20676 for (IntentFilter filter : filters) { 20677 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 20678 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 20679 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 20680 result.addAll(filter.getHostsList()); 20681 } 20682 } 20683 } 20684 20685 StringBuilder sb = new StringBuilder(result.size() * 16); 20686 for (String domain : result) { 20687 if (sb.length() > 0) sb.append(" "); 20688 sb.append(domain); 20689 } 20690 return sb.toString(); 20691 } 20692 20693 // ------- apps on sdcard specific code ------- 20694 static final boolean DEBUG_SD_INSTALL = false; 20695 20696 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 20697 20698 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 20699 20700 private boolean mMediaMounted = false; 20701 20702 static String getEncryptKey() { 20703 try { 20704 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 20705 SD_ENCRYPTION_KEYSTORE_NAME); 20706 if (sdEncKey == null) { 20707 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 20708 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 20709 if (sdEncKey == null) { 20710 Slog.e(TAG, "Failed to create encryption keys"); 20711 return null; 20712 } 20713 } 20714 return sdEncKey; 20715 } catch (NoSuchAlgorithmException nsae) { 20716 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 20717 return null; 20718 } catch (IOException ioe) { 20719 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 20720 return null; 20721 } 20722 } 20723 20724 /* 20725 * Update media status on PackageManager. 20726 */ 20727 @Override 20728 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 20729 int callingUid = Binder.getCallingUid(); 20730 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 20731 throw new SecurityException("Media status can only be updated by the system"); 20732 } 20733 // reader; this apparently protects mMediaMounted, but should probably 20734 // be a different lock in that case. 20735 synchronized (mPackages) { 20736 Log.i(TAG, "Updating external media status from " 20737 + (mMediaMounted ? "mounted" : "unmounted") + " to " 20738 + (mediaStatus ? "mounted" : "unmounted")); 20739 if (DEBUG_SD_INSTALL) 20740 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 20741 + ", mMediaMounted=" + mMediaMounted); 20742 if (mediaStatus == mMediaMounted) { 20743 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 20744 : 0, -1); 20745 mHandler.sendMessage(msg); 20746 return; 20747 } 20748 mMediaMounted = mediaStatus; 20749 } 20750 // Queue up an async operation since the package installation may take a 20751 // little while. 20752 mHandler.post(new Runnable() { 20753 public void run() { 20754 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 20755 } 20756 }); 20757 } 20758 20759 /** 20760 * Called by StorageManagerService when the initial ASECs to scan are available. 20761 * Should block until all the ASEC containers are finished being scanned. 20762 */ 20763 public void scanAvailableAsecs() { 20764 updateExternalMediaStatusInner(true, false, false); 20765 } 20766 20767 /* 20768 * Collect information of applications on external media, map them against 20769 * existing containers and update information based on current mount status. 20770 * Please note that we always have to report status if reportStatus has been 20771 * set to true especially when unloading packages. 20772 */ 20773 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 20774 boolean externalStorage) { 20775 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 20776 int[] uidArr = EmptyArray.INT; 20777 20778 final String[] list = PackageHelper.getSecureContainerList(); 20779 if (ArrayUtils.isEmpty(list)) { 20780 Log.i(TAG, "No secure containers found"); 20781 } else { 20782 // Process list of secure containers and categorize them 20783 // as active or stale based on their package internal state. 20784 20785 // reader 20786 synchronized (mPackages) { 20787 for (String cid : list) { 20788 // Leave stages untouched for now; installer service owns them 20789 if (PackageInstallerService.isStageName(cid)) continue; 20790 20791 if (DEBUG_SD_INSTALL) 20792 Log.i(TAG, "Processing container " + cid); 20793 String pkgName = getAsecPackageName(cid); 20794 if (pkgName == null) { 20795 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 20796 continue; 20797 } 20798 if (DEBUG_SD_INSTALL) 20799 Log.i(TAG, "Looking for pkg : " + pkgName); 20800 20801 final PackageSetting ps = mSettings.mPackages.get(pkgName); 20802 if (ps == null) { 20803 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 20804 continue; 20805 } 20806 20807 /* 20808 * Skip packages that are not external if we're unmounting 20809 * external storage. 20810 */ 20811 if (externalStorage && !isMounted && !isExternal(ps)) { 20812 continue; 20813 } 20814 20815 final AsecInstallArgs args = new AsecInstallArgs(cid, 20816 getAppDexInstructionSets(ps), ps.isForwardLocked()); 20817 // The package status is changed only if the code path 20818 // matches between settings and the container id. 20819 if (ps.codePathString != null 20820 && ps.codePathString.startsWith(args.getCodePath())) { 20821 if (DEBUG_SD_INSTALL) { 20822 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 20823 + " at code path: " + ps.codePathString); 20824 } 20825 20826 // We do have a valid package installed on sdcard 20827 processCids.put(args, ps.codePathString); 20828 final int uid = ps.appId; 20829 if (uid != -1) { 20830 uidArr = ArrayUtils.appendInt(uidArr, uid); 20831 } 20832 } else { 20833 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 20834 + ps.codePathString); 20835 } 20836 } 20837 } 20838 20839 Arrays.sort(uidArr); 20840 } 20841 20842 // Process packages with valid entries. 20843 if (isMounted) { 20844 if (DEBUG_SD_INSTALL) 20845 Log.i(TAG, "Loading packages"); 20846 loadMediaPackages(processCids, uidArr, externalStorage); 20847 startCleaningPackages(); 20848 mInstallerService.onSecureContainersAvailable(); 20849 } else { 20850 if (DEBUG_SD_INSTALL) 20851 Log.i(TAG, "Unloading packages"); 20852 unloadMediaPackages(processCids, uidArr, reportStatus); 20853 } 20854 } 20855 20856 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 20857 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 20858 final int size = infos.size(); 20859 final String[] packageNames = new String[size]; 20860 final int[] packageUids = new int[size]; 20861 for (int i = 0; i < size; i++) { 20862 final ApplicationInfo info = infos.get(i); 20863 packageNames[i] = info.packageName; 20864 packageUids[i] = info.uid; 20865 } 20866 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 20867 finishedReceiver); 20868 } 20869 20870 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 20871 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 20872 sendResourcesChangedBroadcast(mediaStatus, replacing, 20873 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 20874 } 20875 20876 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 20877 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 20878 int size = pkgList.length; 20879 if (size > 0) { 20880 // Send broadcasts here 20881 Bundle extras = new Bundle(); 20882 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 20883 if (uidArr != null) { 20884 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 20885 } 20886 if (replacing) { 20887 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 20888 } 20889 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 20890 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 20891 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 20892 } 20893 } 20894 20895 /* 20896 * Look at potentially valid container ids from processCids If package 20897 * information doesn't match the one on record or package scanning fails, 20898 * the cid is added to list of removeCids. We currently don't delete stale 20899 * containers. 20900 */ 20901 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 20902 boolean externalStorage) { 20903 ArrayList<String> pkgList = new ArrayList<String>(); 20904 Set<AsecInstallArgs> keys = processCids.keySet(); 20905 20906 for (AsecInstallArgs args : keys) { 20907 String codePath = processCids.get(args); 20908 if (DEBUG_SD_INSTALL) 20909 Log.i(TAG, "Loading container : " + args.cid); 20910 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 20911 try { 20912 // Make sure there are no container errors first. 20913 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 20914 Slog.e(TAG, "Failed to mount cid : " + args.cid 20915 + " when installing from sdcard"); 20916 continue; 20917 } 20918 // Check code path here. 20919 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 20920 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 20921 + " does not match one in settings " + codePath); 20922 continue; 20923 } 20924 // Parse package 20925 int parseFlags = mDefParseFlags; 20926 if (args.isExternalAsec()) { 20927 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 20928 } 20929 if (args.isFwdLocked()) { 20930 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 20931 } 20932 20933 synchronized (mInstallLock) { 20934 PackageParser.Package pkg = null; 20935 try { 20936 // Sadly we don't know the package name yet to freeze it 20937 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 20938 SCAN_IGNORE_FROZEN, 0, null); 20939 } catch (PackageManagerException e) { 20940 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 20941 } 20942 // Scan the package 20943 if (pkg != null) { 20944 /* 20945 * TODO why is the lock being held? doPostInstall is 20946 * called in other places without the lock. This needs 20947 * to be straightened out. 20948 */ 20949 // writer 20950 synchronized (mPackages) { 20951 retCode = PackageManager.INSTALL_SUCCEEDED; 20952 pkgList.add(pkg.packageName); 20953 // Post process args 20954 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 20955 pkg.applicationInfo.uid); 20956 } 20957 } else { 20958 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 20959 } 20960 } 20961 20962 } finally { 20963 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 20964 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 20965 } 20966 } 20967 } 20968 // writer 20969 synchronized (mPackages) { 20970 // If the platform SDK has changed since the last time we booted, 20971 // we need to re-grant app permission to catch any new ones that 20972 // appear. This is really a hack, and means that apps can in some 20973 // cases get permissions that the user didn't initially explicitly 20974 // allow... it would be nice to have some better way to handle 20975 // this situation. 20976 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 20977 : mSettings.getInternalVersion(); 20978 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 20979 : StorageManager.UUID_PRIVATE_INTERNAL; 20980 20981 int updateFlags = UPDATE_PERMISSIONS_ALL; 20982 if (ver.sdkVersion != mSdkVersion) { 20983 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 20984 + mSdkVersion + "; regranting permissions for external"); 20985 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 20986 } 20987 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 20988 20989 // Yay, everything is now upgraded 20990 ver.forceCurrent(); 20991 20992 // can downgrade to reader 20993 // Persist settings 20994 mSettings.writeLPr(); 20995 } 20996 // Send a broadcast to let everyone know we are done processing 20997 if (pkgList.size() > 0) { 20998 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 20999 } 21000 } 21001 21002 /* 21003 * Utility method to unload a list of specified containers 21004 */ 21005 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 21006 // Just unmount all valid containers. 21007 for (AsecInstallArgs arg : cidArgs) { 21008 synchronized (mInstallLock) { 21009 arg.doPostDeleteLI(false); 21010 } 21011 } 21012 } 21013 21014 /* 21015 * Unload packages mounted on external media. This involves deleting package 21016 * data from internal structures, sending broadcasts about disabled packages, 21017 * gc'ing to free up references, unmounting all secure containers 21018 * corresponding to packages on external media, and posting a 21019 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 21020 * that we always have to post this message if status has been requested no 21021 * matter what. 21022 */ 21023 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 21024 final boolean reportStatus) { 21025 if (DEBUG_SD_INSTALL) 21026 Log.i(TAG, "unloading media packages"); 21027 ArrayList<String> pkgList = new ArrayList<String>(); 21028 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 21029 final Set<AsecInstallArgs> keys = processCids.keySet(); 21030 for (AsecInstallArgs args : keys) { 21031 String pkgName = args.getPackageName(); 21032 if (DEBUG_SD_INSTALL) 21033 Log.i(TAG, "Trying to unload pkg : " + pkgName); 21034 // Delete package internally 21035 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 21036 synchronized (mInstallLock) { 21037 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 21038 final boolean res; 21039 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 21040 "unloadMediaPackages")) { 21041 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 21042 null); 21043 } 21044 if (res) { 21045 pkgList.add(pkgName); 21046 } else { 21047 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 21048 failedList.add(args); 21049 } 21050 } 21051 } 21052 21053 // reader 21054 synchronized (mPackages) { 21055 // We didn't update the settings after removing each package; 21056 // write them now for all packages. 21057 mSettings.writeLPr(); 21058 } 21059 21060 // We have to absolutely send UPDATED_MEDIA_STATUS only 21061 // after confirming that all the receivers processed the ordered 21062 // broadcast when packages get disabled, force a gc to clean things up. 21063 // and unload all the containers. 21064 if (pkgList.size() > 0) { 21065 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 21066 new IIntentReceiver.Stub() { 21067 public void performReceive(Intent intent, int resultCode, String data, 21068 Bundle extras, boolean ordered, boolean sticky, 21069 int sendingUser) throws RemoteException { 21070 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 21071 reportStatus ? 1 : 0, 1, keys); 21072 mHandler.sendMessage(msg); 21073 } 21074 }); 21075 } else { 21076 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 21077 keys); 21078 mHandler.sendMessage(msg); 21079 } 21080 } 21081 21082 private void loadPrivatePackages(final VolumeInfo vol) { 21083 mHandler.post(new Runnable() { 21084 @Override 21085 public void run() { 21086 loadPrivatePackagesInner(vol); 21087 } 21088 }); 21089 } 21090 21091 private void loadPrivatePackagesInner(VolumeInfo vol) { 21092 final String volumeUuid = vol.fsUuid; 21093 if (TextUtils.isEmpty(volumeUuid)) { 21094 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 21095 return; 21096 } 21097 21098 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 21099 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 21100 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 21101 21102 final VersionInfo ver; 21103 final List<PackageSetting> packages; 21104 synchronized (mPackages) { 21105 ver = mSettings.findOrCreateVersion(volumeUuid); 21106 packages = mSettings.getVolumePackagesLPr(volumeUuid); 21107 } 21108 21109 for (PackageSetting ps : packages) { 21110 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 21111 synchronized (mInstallLock) { 21112 final PackageParser.Package pkg; 21113 try { 21114 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 21115 loaded.add(pkg.applicationInfo); 21116 21117 } catch (PackageManagerException e) { 21118 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 21119 } 21120 21121 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 21122 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 21123 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 21124 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 21125 } 21126 } 21127 } 21128 21129 // Reconcile app data for all started/unlocked users 21130 final StorageManager sm = mContext.getSystemService(StorageManager.class); 21131 final UserManager um = mContext.getSystemService(UserManager.class); 21132 UserManagerInternal umInternal = getUserManagerInternal(); 21133 for (UserInfo user : um.getUsers()) { 21134 final int flags; 21135 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 21136 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 21137 } else if (umInternal.isUserRunning(user.id)) { 21138 flags = StorageManager.FLAG_STORAGE_DE; 21139 } else { 21140 continue; 21141 } 21142 21143 try { 21144 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 21145 synchronized (mInstallLock) { 21146 reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */); 21147 } 21148 } catch (IllegalStateException e) { 21149 // Device was probably ejected, and we'll process that event momentarily 21150 Slog.w(TAG, "Failed to prepare storage: " + e); 21151 } 21152 } 21153 21154 synchronized (mPackages) { 21155 int updateFlags = UPDATE_PERMISSIONS_ALL; 21156 if (ver.sdkVersion != mSdkVersion) { 21157 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 21158 + mSdkVersion + "; regranting permissions for " + volumeUuid); 21159 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 21160 } 21161 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 21162 21163 // Yay, everything is now upgraded 21164 ver.forceCurrent(); 21165 21166 mSettings.writeLPr(); 21167 } 21168 21169 for (PackageFreezer freezer : freezers) { 21170 freezer.close(); 21171 } 21172 21173 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 21174 sendResourcesChangedBroadcast(true, false, loaded, null); 21175 } 21176 21177 private void unloadPrivatePackages(final VolumeInfo vol) { 21178 mHandler.post(new Runnable() { 21179 @Override 21180 public void run() { 21181 unloadPrivatePackagesInner(vol); 21182 } 21183 }); 21184 } 21185 21186 private void unloadPrivatePackagesInner(VolumeInfo vol) { 21187 final String volumeUuid = vol.fsUuid; 21188 if (TextUtils.isEmpty(volumeUuid)) { 21189 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 21190 return; 21191 } 21192 21193 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 21194 synchronized (mInstallLock) { 21195 synchronized (mPackages) { 21196 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 21197 for (PackageSetting ps : packages) { 21198 if (ps.pkg == null) continue; 21199 21200 final ApplicationInfo info = ps.pkg.applicationInfo; 21201 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 21202 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 21203 21204 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 21205 "unloadPrivatePackagesInner")) { 21206 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 21207 false, null)) { 21208 unloaded.add(info); 21209 } else { 21210 Slog.w(TAG, "Failed to unload " + ps.codePath); 21211 } 21212 } 21213 21214 // Try very hard to release any references to this package 21215 // so we don't risk the system server being killed due to 21216 // open FDs 21217 AttributeCache.instance().removePackage(ps.name); 21218 } 21219 21220 mSettings.writeLPr(); 21221 } 21222 } 21223 21224 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 21225 sendResourcesChangedBroadcast(false, false, unloaded, null); 21226 21227 // Try very hard to release any references to this path so we don't risk 21228 // the system server being killed due to open FDs 21229 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 21230 21231 for (int i = 0; i < 3; i++) { 21232 System.gc(); 21233 System.runFinalization(); 21234 } 21235 } 21236 21237 /** 21238 * Prepare storage areas for given user on all mounted devices. 21239 */ 21240 void prepareUserData(int userId, int userSerial, int flags) { 21241 synchronized (mInstallLock) { 21242 final StorageManager storage = mContext.getSystemService(StorageManager.class); 21243 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 21244 final String volumeUuid = vol.getFsUuid(); 21245 prepareUserDataLI(volumeUuid, userId, userSerial, flags, true); 21246 } 21247 } 21248 } 21249 21250 private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags, 21251 boolean allowRecover) { 21252 // Prepare storage and verify that serial numbers are consistent; if 21253 // there's a mismatch we need to destroy to avoid leaking data 21254 final StorageManager storage = mContext.getSystemService(StorageManager.class); 21255 try { 21256 storage.prepareUserStorage(volumeUuid, userId, userSerial, flags); 21257 21258 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) { 21259 UserManagerService.enforceSerialNumber( 21260 Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial); 21261 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 21262 UserManagerService.enforceSerialNumber( 21263 Environment.getDataSystemDeDirectory(userId), userSerial); 21264 } 21265 } 21266 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) { 21267 UserManagerService.enforceSerialNumber( 21268 Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial); 21269 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 21270 UserManagerService.enforceSerialNumber( 21271 Environment.getDataSystemCeDirectory(userId), userSerial); 21272 } 21273 } 21274 21275 synchronized (mInstallLock) { 21276 mInstaller.createUserData(volumeUuid, userId, userSerial, flags); 21277 } 21278 } catch (Exception e) { 21279 logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid 21280 + " because we failed to prepare: " + e); 21281 destroyUserDataLI(volumeUuid, userId, 21282 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 21283 21284 if (allowRecover) { 21285 // Try one last time; if we fail again we're really in trouble 21286 prepareUserDataLI(volumeUuid, userId, userSerial, flags, false); 21287 } 21288 } 21289 } 21290 21291 /** 21292 * Destroy storage areas for given user on all mounted devices. 21293 */ 21294 void destroyUserData(int userId, int flags) { 21295 synchronized (mInstallLock) { 21296 final StorageManager storage = mContext.getSystemService(StorageManager.class); 21297 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 21298 final String volumeUuid = vol.getFsUuid(); 21299 destroyUserDataLI(volumeUuid, userId, flags); 21300 } 21301 } 21302 } 21303 21304 private void destroyUserDataLI(String volumeUuid, int userId, int flags) { 21305 final StorageManager storage = mContext.getSystemService(StorageManager.class); 21306 try { 21307 // Clean up app data, profile data, and media data 21308 mInstaller.destroyUserData(volumeUuid, userId, flags); 21309 21310 // Clean up system data 21311 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 21312 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 21313 FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId)); 21314 FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId)); 21315 } 21316 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 21317 FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId)); 21318 } 21319 } 21320 21321 // Data with special labels is now gone, so finish the job 21322 storage.destroyUserStorage(volumeUuid, userId, flags); 21323 21324 } catch (Exception e) { 21325 logCriticalInfo(Log.WARN, 21326 "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e); 21327 } 21328 } 21329 21330 /** 21331 * Examine all users present on given mounted volume, and destroy data 21332 * belonging to users that are no longer valid, or whose user ID has been 21333 * recycled. 21334 */ 21335 private void reconcileUsers(String volumeUuid) { 21336 final List<File> files = new ArrayList<>(); 21337 Collections.addAll(files, FileUtils 21338 .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid))); 21339 Collections.addAll(files, FileUtils 21340 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid))); 21341 Collections.addAll(files, FileUtils 21342 .listFilesOrEmpty(Environment.getDataSystemDeDirectory())); 21343 Collections.addAll(files, FileUtils 21344 .listFilesOrEmpty(Environment.getDataSystemCeDirectory())); 21345 for (File file : files) { 21346 if (!file.isDirectory()) continue; 21347 21348 final int userId; 21349 final UserInfo info; 21350 try { 21351 userId = Integer.parseInt(file.getName()); 21352 info = sUserManager.getUserInfo(userId); 21353 } catch (NumberFormatException e) { 21354 Slog.w(TAG, "Invalid user directory " + file); 21355 continue; 21356 } 21357 21358 boolean destroyUser = false; 21359 if (info == null) { 21360 logCriticalInfo(Log.WARN, "Destroying user directory " + file 21361 + " because no matching user was found"); 21362 destroyUser = true; 21363 } else if (!mOnlyCore) { 21364 try { 21365 UserManagerService.enforceSerialNumber(file, info.serialNumber); 21366 } catch (IOException e) { 21367 logCriticalInfo(Log.WARN, "Destroying user directory " + file 21368 + " because we failed to enforce serial number: " + e); 21369 destroyUser = true; 21370 } 21371 } 21372 21373 if (destroyUser) { 21374 synchronized (mInstallLock) { 21375 destroyUserDataLI(volumeUuid, userId, 21376 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 21377 } 21378 } 21379 } 21380 } 21381 21382 private void assertPackageKnown(String volumeUuid, String packageName) 21383 throws PackageManagerException { 21384 synchronized (mPackages) { 21385 // Normalize package name to handle renamed packages 21386 packageName = normalizePackageNameLPr(packageName); 21387 21388 final PackageSetting ps = mSettings.mPackages.get(packageName); 21389 if (ps == null) { 21390 throw new PackageManagerException("Package " + packageName + " is unknown"); 21391 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 21392 throw new PackageManagerException( 21393 "Package " + packageName + " found on unknown volume " + volumeUuid 21394 + "; expected volume " + ps.volumeUuid); 21395 } 21396 } 21397 } 21398 21399 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 21400 throws PackageManagerException { 21401 synchronized (mPackages) { 21402 // Normalize package name to handle renamed packages 21403 packageName = normalizePackageNameLPr(packageName); 21404 21405 final PackageSetting ps = mSettings.mPackages.get(packageName); 21406 if (ps == null) { 21407 throw new PackageManagerException("Package " + packageName + " is unknown"); 21408 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 21409 throw new PackageManagerException( 21410 "Package " + packageName + " found on unknown volume " + volumeUuid 21411 + "; expected volume " + ps.volumeUuid); 21412 } else if (!ps.getInstalled(userId)) { 21413 throw new PackageManagerException( 21414 "Package " + packageName + " not installed for user " + userId); 21415 } 21416 } 21417 } 21418 21419 private List<String> collectAbsoluteCodePaths() { 21420 synchronized (mPackages) { 21421 List<String> codePaths = new ArrayList<>(); 21422 final int packageCount = mSettings.mPackages.size(); 21423 for (int i = 0; i < packageCount; i++) { 21424 final PackageSetting ps = mSettings.mPackages.valueAt(i); 21425 codePaths.add(ps.codePath.getAbsolutePath()); 21426 } 21427 return codePaths; 21428 } 21429 } 21430 21431 /** 21432 * Examine all apps present on given mounted volume, and destroy apps that 21433 * aren't expected, either due to uninstallation or reinstallation on 21434 * another volume. 21435 */ 21436 private void reconcileApps(String volumeUuid) { 21437 List<String> absoluteCodePaths = collectAbsoluteCodePaths(); 21438 List<File> filesToDelete = null; 21439 21440 final File[] files = FileUtils.listFilesOrEmpty( 21441 Environment.getDataAppDirectory(volumeUuid)); 21442 for (File file : files) { 21443 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 21444 && !PackageInstallerService.isStageName(file.getName()); 21445 if (!isPackage) { 21446 // Ignore entries which are not packages 21447 continue; 21448 } 21449 21450 String absolutePath = file.getAbsolutePath(); 21451 21452 boolean pathValid = false; 21453 final int absoluteCodePathCount = absoluteCodePaths.size(); 21454 for (int i = 0; i < absoluteCodePathCount; i++) { 21455 String absoluteCodePath = absoluteCodePaths.get(i); 21456 if (absolutePath.startsWith(absoluteCodePath)) { 21457 pathValid = true; 21458 break; 21459 } 21460 } 21461 21462 if (!pathValid) { 21463 if (filesToDelete == null) { 21464 filesToDelete = new ArrayList<>(); 21465 } 21466 filesToDelete.add(file); 21467 } 21468 } 21469 21470 if (filesToDelete != null) { 21471 final int fileToDeleteCount = filesToDelete.size(); 21472 for (int i = 0; i < fileToDeleteCount; i++) { 21473 File fileToDelete = filesToDelete.get(i); 21474 logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete); 21475 synchronized (mInstallLock) { 21476 removeCodePathLI(fileToDelete); 21477 } 21478 } 21479 } 21480 } 21481 21482 /** 21483 * Reconcile all app data for the given user. 21484 * <p> 21485 * Verifies that directories exist and that ownership and labeling is 21486 * correct for all installed apps on all mounted volumes. 21487 */ 21488 void reconcileAppsData(int userId, int flags, boolean migrateAppsData) { 21489 final StorageManager storage = mContext.getSystemService(StorageManager.class); 21490 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 21491 final String volumeUuid = vol.getFsUuid(); 21492 synchronized (mInstallLock) { 21493 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData); 21494 } 21495 } 21496 } 21497 21498 /** 21499 * Reconcile all app data on given mounted volume. 21500 * <p> 21501 * Destroys app data that isn't expected, either due to uninstallation or 21502 * reinstallation on another volume. 21503 * <p> 21504 * Verifies that directories exist and that ownership and labeling is 21505 * correct for all installed apps. 21506 */ 21507 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags, 21508 boolean migrateAppData) { 21509 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 21510 + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData); 21511 21512 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 21513 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 21514 21515 // First look for stale data that doesn't belong, and check if things 21516 // have changed since we did our last restorecon 21517 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 21518 if (StorageManager.isFileEncryptedNativeOrEmulated() 21519 && !StorageManager.isUserKeyUnlocked(userId)) { 21520 throw new RuntimeException( 21521 "Yikes, someone asked us to reconcile CE storage while " + userId 21522 + " was still locked; this would have caused massive data loss!"); 21523 } 21524 21525 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 21526 for (File file : files) { 21527 final String packageName = file.getName(); 21528 try { 21529 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 21530 } catch (PackageManagerException e) { 21531 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 21532 try { 21533 mInstaller.destroyAppData(volumeUuid, packageName, userId, 21534 StorageManager.FLAG_STORAGE_CE, 0); 21535 } catch (InstallerException e2) { 21536 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 21537 } 21538 } 21539 } 21540 } 21541 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 21542 final File[] files = FileUtils.listFilesOrEmpty(deDir); 21543 for (File file : files) { 21544 final String packageName = file.getName(); 21545 try { 21546 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 21547 } catch (PackageManagerException e) { 21548 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 21549 try { 21550 mInstaller.destroyAppData(volumeUuid, packageName, userId, 21551 StorageManager.FLAG_STORAGE_DE, 0); 21552 } catch (InstallerException e2) { 21553 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 21554 } 21555 } 21556 } 21557 } 21558 21559 // Ensure that data directories are ready to roll for all packages 21560 // installed for this volume and user 21561 final List<PackageSetting> packages; 21562 synchronized (mPackages) { 21563 packages = mSettings.getVolumePackagesLPr(volumeUuid); 21564 } 21565 int preparedCount = 0; 21566 for (PackageSetting ps : packages) { 21567 final String packageName = ps.name; 21568 if (ps.pkg == null) { 21569 Slog.w(TAG, "Odd, missing scanned package " + packageName); 21570 // TODO: might be due to legacy ASEC apps; we should circle back 21571 // and reconcile again once they're scanned 21572 continue; 21573 } 21574 21575 if (ps.getInstalled(userId)) { 21576 prepareAppDataLIF(ps.pkg, userId, flags); 21577 21578 if (migrateAppData && maybeMigrateAppDataLIF(ps.pkg, userId)) { 21579 // We may have just shuffled around app data directories, so 21580 // prepare them one more time 21581 prepareAppDataLIF(ps.pkg, userId, flags); 21582 } 21583 21584 preparedCount++; 21585 } 21586 } 21587 21588 Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages"); 21589 } 21590 21591 /** 21592 * Prepare app data for the given app just after it was installed or 21593 * upgraded. This method carefully only touches users that it's installed 21594 * for, and it forces a restorecon to handle any seinfo changes. 21595 * <p> 21596 * Verifies that directories exist and that ownership and labeling is 21597 * correct for all installed apps. If there is an ownership mismatch, it 21598 * will try recovering system apps by wiping data; third-party app data is 21599 * left intact. 21600 * <p> 21601 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 21602 */ 21603 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 21604 final PackageSetting ps; 21605 synchronized (mPackages) { 21606 ps = mSettings.mPackages.get(pkg.packageName); 21607 mSettings.writeKernelMappingLPr(ps); 21608 } 21609 21610 final UserManager um = mContext.getSystemService(UserManager.class); 21611 UserManagerInternal umInternal = getUserManagerInternal(); 21612 for (UserInfo user : um.getUsers()) { 21613 final int flags; 21614 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 21615 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 21616 } else if (umInternal.isUserRunning(user.id)) { 21617 flags = StorageManager.FLAG_STORAGE_DE; 21618 } else { 21619 continue; 21620 } 21621 21622 if (ps.getInstalled(user.id)) { 21623 // TODO: when user data is locked, mark that we're still dirty 21624 prepareAppDataLIF(pkg, user.id, flags); 21625 } 21626 } 21627 } 21628 21629 /** 21630 * Prepare app data for the given app. 21631 * <p> 21632 * Verifies that directories exist and that ownership and labeling is 21633 * correct for all installed apps. If there is an ownership mismatch, this 21634 * will try recovering system apps by wiping data; third-party app data is 21635 * left intact. 21636 */ 21637 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 21638 if (pkg == null) { 21639 Slog.wtf(TAG, "Package was null!", new Throwable()); 21640 return; 21641 } 21642 prepareAppDataLeafLIF(pkg, userId, flags); 21643 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 21644 for (int i = 0; i < childCount; i++) { 21645 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 21646 } 21647 } 21648 21649 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 21650 if (DEBUG_APP_DATA) { 21651 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 21652 + Integer.toHexString(flags)); 21653 } 21654 21655 final String volumeUuid = pkg.volumeUuid; 21656 final String packageName = pkg.packageName; 21657 final ApplicationInfo app = pkg.applicationInfo; 21658 final int appId = UserHandle.getAppId(app.uid); 21659 21660 Preconditions.checkNotNull(app.seinfo); 21661 21662 long ceDataInode = -1; 21663 try { 21664 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 21665 appId, app.seinfo, app.targetSdkVersion); 21666 } catch (InstallerException e) { 21667 if (app.isSystemApp()) { 21668 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 21669 + ", but trying to recover: " + e); 21670 destroyAppDataLeafLIF(pkg, userId, flags); 21671 try { 21672 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 21673 appId, app.seinfo, app.targetSdkVersion); 21674 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 21675 } catch (InstallerException e2) { 21676 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 21677 } 21678 } else { 21679 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 21680 } 21681 } 21682 21683 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) { 21684 // TODO: mark this structure as dirty so we persist it! 21685 synchronized (mPackages) { 21686 final PackageSetting ps = mSettings.mPackages.get(packageName); 21687 if (ps != null) { 21688 ps.setCeDataInode(ceDataInode, userId); 21689 } 21690 } 21691 } 21692 21693 prepareAppDataContentsLeafLIF(pkg, userId, flags); 21694 } 21695 21696 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 21697 if (pkg == null) { 21698 Slog.wtf(TAG, "Package was null!", new Throwable()); 21699 return; 21700 } 21701 prepareAppDataContentsLeafLIF(pkg, userId, flags); 21702 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 21703 for (int i = 0; i < childCount; i++) { 21704 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 21705 } 21706 } 21707 21708 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 21709 final String volumeUuid = pkg.volumeUuid; 21710 final String packageName = pkg.packageName; 21711 final ApplicationInfo app = pkg.applicationInfo; 21712 21713 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 21714 // Create a native library symlink only if we have native libraries 21715 // and if the native libraries are 32 bit libraries. We do not provide 21716 // this symlink for 64 bit libraries. 21717 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 21718 final String nativeLibPath = app.nativeLibraryDir; 21719 try { 21720 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 21721 nativeLibPath, userId); 21722 } catch (InstallerException e) { 21723 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 21724 } 21725 } 21726 } 21727 } 21728 21729 /** 21730 * For system apps on non-FBE devices, this method migrates any existing 21731 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 21732 * requested by the app. 21733 */ 21734 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 21735 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 21736 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 21737 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 21738 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 21739 try { 21740 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 21741 storageTarget); 21742 } catch (InstallerException e) { 21743 logCriticalInfo(Log.WARN, 21744 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 21745 } 21746 return true; 21747 } else { 21748 return false; 21749 } 21750 } 21751 21752 public PackageFreezer freezePackage(String packageName, String killReason) { 21753 return freezePackage(packageName, UserHandle.USER_ALL, killReason); 21754 } 21755 21756 public PackageFreezer freezePackage(String packageName, int userId, String killReason) { 21757 return new PackageFreezer(packageName, userId, killReason); 21758 } 21759 21760 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 21761 String killReason) { 21762 return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason); 21763 } 21764 21765 public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags, 21766 String killReason) { 21767 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 21768 return new PackageFreezer(); 21769 } else { 21770 return freezePackage(packageName, userId, killReason); 21771 } 21772 } 21773 21774 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 21775 String killReason) { 21776 return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason); 21777 } 21778 21779 public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags, 21780 String killReason) { 21781 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 21782 return new PackageFreezer(); 21783 } else { 21784 return freezePackage(packageName, userId, killReason); 21785 } 21786 } 21787 21788 /** 21789 * Class that freezes and kills the given package upon creation, and 21790 * unfreezes it upon closing. This is typically used when doing surgery on 21791 * app code/data to prevent the app from running while you're working. 21792 */ 21793 private class PackageFreezer implements AutoCloseable { 21794 private final String mPackageName; 21795 private final PackageFreezer[] mChildren; 21796 21797 private final boolean mWeFroze; 21798 21799 private final AtomicBoolean mClosed = new AtomicBoolean(); 21800 private final CloseGuard mCloseGuard = CloseGuard.get(); 21801 21802 /** 21803 * Create and return a stub freezer that doesn't actually do anything, 21804 * typically used when someone requested 21805 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 21806 * {@link PackageManager#DELETE_DONT_KILL_APP}. 21807 */ 21808 public PackageFreezer() { 21809 mPackageName = null; 21810 mChildren = null; 21811 mWeFroze = false; 21812 mCloseGuard.open("close"); 21813 } 21814 21815 public PackageFreezer(String packageName, int userId, String killReason) { 21816 synchronized (mPackages) { 21817 mPackageName = packageName; 21818 mWeFroze = mFrozenPackages.add(mPackageName); 21819 21820 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 21821 if (ps != null) { 21822 killApplication(ps.name, ps.appId, userId, killReason); 21823 } 21824 21825 final PackageParser.Package p = mPackages.get(packageName); 21826 if (p != null && p.childPackages != null) { 21827 final int N = p.childPackages.size(); 21828 mChildren = new PackageFreezer[N]; 21829 for (int i = 0; i < N; i++) { 21830 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 21831 userId, killReason); 21832 } 21833 } else { 21834 mChildren = null; 21835 } 21836 } 21837 mCloseGuard.open("close"); 21838 } 21839 21840 @Override 21841 protected void finalize() throws Throwable { 21842 try { 21843 mCloseGuard.warnIfOpen(); 21844 close(); 21845 } finally { 21846 super.finalize(); 21847 } 21848 } 21849 21850 @Override 21851 public void close() { 21852 mCloseGuard.close(); 21853 if (mClosed.compareAndSet(false, true)) { 21854 synchronized (mPackages) { 21855 if (mWeFroze) { 21856 mFrozenPackages.remove(mPackageName); 21857 } 21858 21859 if (mChildren != null) { 21860 for (PackageFreezer freezer : mChildren) { 21861 freezer.close(); 21862 } 21863 } 21864 } 21865 } 21866 } 21867 } 21868 21869 /** 21870 * Verify that given package is currently frozen. 21871 */ 21872 private void checkPackageFrozen(String packageName) { 21873 synchronized (mPackages) { 21874 if (!mFrozenPackages.contains(packageName)) { 21875 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 21876 } 21877 } 21878 } 21879 21880 @Override 21881 public int movePackage(final String packageName, final String volumeUuid) { 21882 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 21883 21884 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 21885 final int moveId = mNextMoveId.getAndIncrement(); 21886 mHandler.post(new Runnable() { 21887 @Override 21888 public void run() { 21889 try { 21890 movePackageInternal(packageName, volumeUuid, moveId, user); 21891 } catch (PackageManagerException e) { 21892 Slog.w(TAG, "Failed to move " + packageName, e); 21893 mMoveCallbacks.notifyStatusChanged(moveId, 21894 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 21895 } 21896 } 21897 }); 21898 return moveId; 21899 } 21900 21901 private void movePackageInternal(final String packageName, final String volumeUuid, 21902 final int moveId, UserHandle user) throws PackageManagerException { 21903 final StorageManager storage = mContext.getSystemService(StorageManager.class); 21904 final PackageManager pm = mContext.getPackageManager(); 21905 21906 final boolean currentAsec; 21907 final String currentVolumeUuid; 21908 final File codeFile; 21909 final String installerPackageName; 21910 final String packageAbiOverride; 21911 final int appId; 21912 final String seinfo; 21913 final String label; 21914 final int targetSdkVersion; 21915 final PackageFreezer freezer; 21916 final int[] installedUserIds; 21917 21918 // reader 21919 synchronized (mPackages) { 21920 final PackageParser.Package pkg = mPackages.get(packageName); 21921 final PackageSetting ps = mSettings.mPackages.get(packageName); 21922 if (pkg == null || ps == null) { 21923 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 21924 } 21925 21926 if (pkg.applicationInfo.isSystemApp()) { 21927 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 21928 "Cannot move system application"); 21929 } 21930 21931 final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid); 21932 final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean( 21933 com.android.internal.R.bool.config_allow3rdPartyAppOnInternal); 21934 if (isInternalStorage && !allow3rdPartyOnInternal) { 21935 throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL, 21936 "3rd party apps are not allowed on internal storage"); 21937 } 21938 21939 if (pkg.applicationInfo.isExternalAsec()) { 21940 currentAsec = true; 21941 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 21942 } else if (pkg.applicationInfo.isForwardLocked()) { 21943 currentAsec = true; 21944 currentVolumeUuid = "forward_locked"; 21945 } else { 21946 currentAsec = false; 21947 currentVolumeUuid = ps.volumeUuid; 21948 21949 final File probe = new File(pkg.codePath); 21950 final File probeOat = new File(probe, "oat"); 21951 if (!probe.isDirectory() || !probeOat.isDirectory()) { 21952 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 21953 "Move only supported for modern cluster style installs"); 21954 } 21955 } 21956 21957 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 21958 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 21959 "Package already moved to " + volumeUuid); 21960 } 21961 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 21962 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 21963 "Device admin cannot be moved"); 21964 } 21965 21966 if (mFrozenPackages.contains(packageName)) { 21967 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 21968 "Failed to move already frozen package"); 21969 } 21970 21971 codeFile = new File(pkg.codePath); 21972 installerPackageName = ps.installerPackageName; 21973 packageAbiOverride = ps.cpuAbiOverrideString; 21974 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 21975 seinfo = pkg.applicationInfo.seinfo; 21976 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 21977 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 21978 freezer = freezePackage(packageName, "movePackageInternal"); 21979 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 21980 } 21981 21982 final Bundle extras = new Bundle(); 21983 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 21984 extras.putString(Intent.EXTRA_TITLE, label); 21985 mMoveCallbacks.notifyCreated(moveId, extras); 21986 21987 int installFlags; 21988 final boolean moveCompleteApp; 21989 final File measurePath; 21990 21991 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 21992 installFlags = INSTALL_INTERNAL; 21993 moveCompleteApp = !currentAsec; 21994 measurePath = Environment.getDataAppDirectory(volumeUuid); 21995 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 21996 installFlags = INSTALL_EXTERNAL; 21997 moveCompleteApp = false; 21998 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 21999 } else { 22000 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 22001 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 22002 || !volume.isMountedWritable()) { 22003 freezer.close(); 22004 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22005 "Move location not mounted private volume"); 22006 } 22007 22008 Preconditions.checkState(!currentAsec); 22009 22010 installFlags = INSTALL_INTERNAL; 22011 moveCompleteApp = true; 22012 measurePath = Environment.getDataAppDirectory(volumeUuid); 22013 } 22014 22015 final PackageStats stats = new PackageStats(null, -1); 22016 synchronized (mInstaller) { 22017 for (int userId : installedUserIds) { 22018 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 22019 freezer.close(); 22020 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22021 "Failed to measure package size"); 22022 } 22023 } 22024 } 22025 22026 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 22027 + stats.dataSize); 22028 22029 final long startFreeBytes = measurePath.getFreeSpace(); 22030 final long sizeBytes; 22031 if (moveCompleteApp) { 22032 sizeBytes = stats.codeSize + stats.dataSize; 22033 } else { 22034 sizeBytes = stats.codeSize; 22035 } 22036 22037 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 22038 freezer.close(); 22039 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22040 "Not enough free space to move"); 22041 } 22042 22043 mMoveCallbacks.notifyStatusChanged(moveId, 10); 22044 22045 final CountDownLatch installedLatch = new CountDownLatch(1); 22046 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 22047 @Override 22048 public void onUserActionRequired(Intent intent) throws RemoteException { 22049 throw new IllegalStateException(); 22050 } 22051 22052 @Override 22053 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 22054 Bundle extras) throws RemoteException { 22055 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 22056 + PackageManager.installStatusToString(returnCode, msg)); 22057 22058 installedLatch.countDown(); 22059 freezer.close(); 22060 22061 final int status = PackageManager.installStatusToPublicStatus(returnCode); 22062 switch (status) { 22063 case PackageInstaller.STATUS_SUCCESS: 22064 mMoveCallbacks.notifyStatusChanged(moveId, 22065 PackageManager.MOVE_SUCCEEDED); 22066 break; 22067 case PackageInstaller.STATUS_FAILURE_STORAGE: 22068 mMoveCallbacks.notifyStatusChanged(moveId, 22069 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 22070 break; 22071 default: 22072 mMoveCallbacks.notifyStatusChanged(moveId, 22073 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 22074 break; 22075 } 22076 } 22077 }; 22078 22079 final MoveInfo move; 22080 if (moveCompleteApp) { 22081 // Kick off a thread to report progress estimates 22082 new Thread() { 22083 @Override 22084 public void run() { 22085 while (true) { 22086 try { 22087 if (installedLatch.await(1, TimeUnit.SECONDS)) { 22088 break; 22089 } 22090 } catch (InterruptedException ignored) { 22091 } 22092 22093 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 22094 final int progress = 10 + (int) MathUtils.constrain( 22095 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 22096 mMoveCallbacks.notifyStatusChanged(moveId, progress); 22097 } 22098 } 22099 }.start(); 22100 22101 final String dataAppName = codeFile.getName(); 22102 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 22103 dataAppName, appId, seinfo, targetSdkVersion); 22104 } else { 22105 move = null; 22106 } 22107 22108 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 22109 22110 final Message msg = mHandler.obtainMessage(INIT_COPY); 22111 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 22112 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 22113 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 22114 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/, 22115 PackageManager.INSTALL_REASON_UNKNOWN); 22116 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 22117 msg.obj = params; 22118 22119 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 22120 System.identityHashCode(msg.obj)); 22121 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 22122 System.identityHashCode(msg.obj)); 22123 22124 mHandler.sendMessage(msg); 22125 } 22126 22127 @Override 22128 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 22129 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 22130 22131 final int realMoveId = mNextMoveId.getAndIncrement(); 22132 final Bundle extras = new Bundle(); 22133 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 22134 mMoveCallbacks.notifyCreated(realMoveId, extras); 22135 22136 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 22137 @Override 22138 public void onCreated(int moveId, Bundle extras) { 22139 // Ignored 22140 } 22141 22142 @Override 22143 public void onStatusChanged(int moveId, int status, long estMillis) { 22144 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 22145 } 22146 }; 22147 22148 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22149 storage.setPrimaryStorageUuid(volumeUuid, callback); 22150 return realMoveId; 22151 } 22152 22153 @Override 22154 public int getMoveStatus(int moveId) { 22155 mContext.enforceCallingOrSelfPermission( 22156 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22157 return mMoveCallbacks.mLastStatus.get(moveId); 22158 } 22159 22160 @Override 22161 public void registerMoveCallback(IPackageMoveObserver callback) { 22162 mContext.enforceCallingOrSelfPermission( 22163 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22164 mMoveCallbacks.register(callback); 22165 } 22166 22167 @Override 22168 public void unregisterMoveCallback(IPackageMoveObserver callback) { 22169 mContext.enforceCallingOrSelfPermission( 22170 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22171 mMoveCallbacks.unregister(callback); 22172 } 22173 22174 @Override 22175 public boolean setInstallLocation(int loc) { 22176 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 22177 null); 22178 if (getInstallLocation() == loc) { 22179 return true; 22180 } 22181 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 22182 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 22183 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 22184 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 22185 return true; 22186 } 22187 return false; 22188 } 22189 22190 @Override 22191 public int getInstallLocation() { 22192 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 22193 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 22194 PackageHelper.APP_INSTALL_AUTO); 22195 } 22196 22197 /** Called by UserManagerService */ 22198 void cleanUpUser(UserManagerService userManager, int userHandle) { 22199 synchronized (mPackages) { 22200 mDirtyUsers.remove(userHandle); 22201 mUserNeedsBadging.delete(userHandle); 22202 mSettings.removeUserLPw(userHandle); 22203 mPendingBroadcasts.remove(userHandle); 22204 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 22205 removeUnusedPackagesLPw(userManager, userHandle); 22206 } 22207 } 22208 22209 /** 22210 * We're removing userHandle and would like to remove any downloaded packages 22211 * that are no longer in use by any other user. 22212 * @param userHandle the user being removed 22213 */ 22214 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 22215 final boolean DEBUG_CLEAN_APKS = false; 22216 int [] users = userManager.getUserIds(); 22217 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 22218 while (psit.hasNext()) { 22219 PackageSetting ps = psit.next(); 22220 if (ps.pkg == null) { 22221 continue; 22222 } 22223 final String packageName = ps.pkg.packageName; 22224 // Skip over if system app 22225 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 22226 continue; 22227 } 22228 if (DEBUG_CLEAN_APKS) { 22229 Slog.i(TAG, "Checking package " + packageName); 22230 } 22231 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 22232 if (keep) { 22233 if (DEBUG_CLEAN_APKS) { 22234 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 22235 } 22236 } else { 22237 for (int i = 0; i < users.length; i++) { 22238 if (users[i] != userHandle && ps.getInstalled(users[i])) { 22239 keep = true; 22240 if (DEBUG_CLEAN_APKS) { 22241 Slog.i(TAG, " Keeping package " + packageName + " for user " 22242 + users[i]); 22243 } 22244 break; 22245 } 22246 } 22247 } 22248 if (!keep) { 22249 if (DEBUG_CLEAN_APKS) { 22250 Slog.i(TAG, " Removing package " + packageName); 22251 } 22252 mHandler.post(new Runnable() { 22253 public void run() { 22254 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 22255 userHandle, 0); 22256 } //end run 22257 }); 22258 } 22259 } 22260 } 22261 22262 /** Called by UserManagerService */ 22263 void createNewUser(int userId, String[] disallowedPackages) { 22264 synchronized (mInstallLock) { 22265 mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages); 22266 } 22267 synchronized (mPackages) { 22268 scheduleWritePackageRestrictionsLocked(userId); 22269 scheduleWritePackageListLocked(userId); 22270 applyFactoryDefaultBrowserLPw(userId); 22271 primeDomainVerificationsLPw(userId); 22272 } 22273 } 22274 22275 void onNewUserCreated(final int userId) { 22276 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 22277 // If permission review for legacy apps is required, we represent 22278 // dagerous permissions for such apps as always granted runtime 22279 // permissions to keep per user flag state whether review is needed. 22280 // Hence, if a new user is added we have to propagate dangerous 22281 // permission grants for these legacy apps. 22282 if (mPermissionReviewRequired) { 22283 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 22284 | UPDATE_PERMISSIONS_REPLACE_ALL); 22285 } 22286 } 22287 22288 @Override 22289 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 22290 mContext.enforceCallingOrSelfPermission( 22291 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 22292 "Only package verification agents can read the verifier device identity"); 22293 22294 synchronized (mPackages) { 22295 return mSettings.getVerifierDeviceIdentityLPw(); 22296 } 22297 } 22298 22299 @Override 22300 public void setPermissionEnforced(String permission, boolean enforced) { 22301 // TODO: Now that we no longer change GID for storage, this should to away. 22302 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 22303 "setPermissionEnforced"); 22304 if (READ_EXTERNAL_STORAGE.equals(permission)) { 22305 synchronized (mPackages) { 22306 if (mSettings.mReadExternalStorageEnforced == null 22307 || mSettings.mReadExternalStorageEnforced != enforced) { 22308 mSettings.mReadExternalStorageEnforced = enforced; 22309 mSettings.writeLPr(); 22310 } 22311 } 22312 // kill any non-foreground processes so we restart them and 22313 // grant/revoke the GID. 22314 final IActivityManager am = ActivityManager.getService(); 22315 if (am != null) { 22316 final long token = Binder.clearCallingIdentity(); 22317 try { 22318 am.killProcessesBelowForeground("setPermissionEnforcement"); 22319 } catch (RemoteException e) { 22320 } finally { 22321 Binder.restoreCallingIdentity(token); 22322 } 22323 } 22324 } else { 22325 throw new IllegalArgumentException("No selective enforcement for " + permission); 22326 } 22327 } 22328 22329 @Override 22330 @Deprecated 22331 public boolean isPermissionEnforced(String permission) { 22332 return true; 22333 } 22334 22335 @Override 22336 public boolean isStorageLow() { 22337 final long token = Binder.clearCallingIdentity(); 22338 try { 22339 final DeviceStorageMonitorInternal 22340 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 22341 if (dsm != null) { 22342 return dsm.isMemoryLow(); 22343 } else { 22344 return false; 22345 } 22346 } finally { 22347 Binder.restoreCallingIdentity(token); 22348 } 22349 } 22350 22351 @Override 22352 public IPackageInstaller getPackageInstaller() { 22353 return mInstallerService; 22354 } 22355 22356 private boolean userNeedsBadging(int userId) { 22357 int index = mUserNeedsBadging.indexOfKey(userId); 22358 if (index < 0) { 22359 final UserInfo userInfo; 22360 final long token = Binder.clearCallingIdentity(); 22361 try { 22362 userInfo = sUserManager.getUserInfo(userId); 22363 } finally { 22364 Binder.restoreCallingIdentity(token); 22365 } 22366 final boolean b; 22367 if (userInfo != null && userInfo.isManagedProfile()) { 22368 b = true; 22369 } else { 22370 b = false; 22371 } 22372 mUserNeedsBadging.put(userId, b); 22373 return b; 22374 } 22375 return mUserNeedsBadging.valueAt(index); 22376 } 22377 22378 @Override 22379 public KeySet getKeySetByAlias(String packageName, String alias) { 22380 if (packageName == null || alias == null) { 22381 return null; 22382 } 22383 synchronized(mPackages) { 22384 final PackageParser.Package pkg = mPackages.get(packageName); 22385 if (pkg == null) { 22386 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22387 throw new IllegalArgumentException("Unknown package: " + packageName); 22388 } 22389 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22390 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 22391 } 22392 } 22393 22394 @Override 22395 public KeySet getSigningKeySet(String packageName) { 22396 if (packageName == null) { 22397 return null; 22398 } 22399 synchronized(mPackages) { 22400 final PackageParser.Package pkg = mPackages.get(packageName); 22401 if (pkg == null) { 22402 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22403 throw new IllegalArgumentException("Unknown package: " + packageName); 22404 } 22405 if (pkg.applicationInfo.uid != Binder.getCallingUid() 22406 && Process.SYSTEM_UID != Binder.getCallingUid()) { 22407 throw new SecurityException("May not access signing KeySet of other apps."); 22408 } 22409 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22410 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 22411 } 22412 } 22413 22414 @Override 22415 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 22416 if (packageName == null || ks == null) { 22417 return false; 22418 } 22419 synchronized(mPackages) { 22420 final PackageParser.Package pkg = mPackages.get(packageName); 22421 if (pkg == null) { 22422 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22423 throw new IllegalArgumentException("Unknown package: " + packageName); 22424 } 22425 IBinder ksh = ks.getToken(); 22426 if (ksh instanceof KeySetHandle) { 22427 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22428 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 22429 } 22430 return false; 22431 } 22432 } 22433 22434 @Override 22435 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 22436 if (packageName == null || ks == null) { 22437 return false; 22438 } 22439 synchronized(mPackages) { 22440 final PackageParser.Package pkg = mPackages.get(packageName); 22441 if (pkg == null) { 22442 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22443 throw new IllegalArgumentException("Unknown package: " + packageName); 22444 } 22445 IBinder ksh = ks.getToken(); 22446 if (ksh instanceof KeySetHandle) { 22447 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22448 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 22449 } 22450 return false; 22451 } 22452 } 22453 22454 private void deletePackageIfUnusedLPr(final String packageName) { 22455 PackageSetting ps = mSettings.mPackages.get(packageName); 22456 if (ps == null) { 22457 return; 22458 } 22459 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 22460 // TODO Implement atomic delete if package is unused 22461 // It is currently possible that the package will be deleted even if it is installed 22462 // after this method returns. 22463 mHandler.post(new Runnable() { 22464 public void run() { 22465 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 22466 0, PackageManager.DELETE_ALL_USERS); 22467 } 22468 }); 22469 } 22470 } 22471 22472 /** 22473 * Check and throw if the given before/after packages would be considered a 22474 * downgrade. 22475 */ 22476 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 22477 throws PackageManagerException { 22478 if (after.versionCode < before.mVersionCode) { 22479 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 22480 "Update version code " + after.versionCode + " is older than current " 22481 + before.mVersionCode); 22482 } else if (after.versionCode == before.mVersionCode) { 22483 if (after.baseRevisionCode < before.baseRevisionCode) { 22484 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 22485 "Update base revision code " + after.baseRevisionCode 22486 + " is older than current " + before.baseRevisionCode); 22487 } 22488 22489 if (!ArrayUtils.isEmpty(after.splitNames)) { 22490 for (int i = 0; i < after.splitNames.length; i++) { 22491 final String splitName = after.splitNames[i]; 22492 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 22493 if (j != -1) { 22494 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 22495 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 22496 "Update split " + splitName + " revision code " 22497 + after.splitRevisionCodes[i] + " is older than current " 22498 + before.splitRevisionCodes[j]); 22499 } 22500 } 22501 } 22502 } 22503 } 22504 } 22505 22506 private static class MoveCallbacks extends Handler { 22507 private static final int MSG_CREATED = 1; 22508 private static final int MSG_STATUS_CHANGED = 2; 22509 22510 private final RemoteCallbackList<IPackageMoveObserver> 22511 mCallbacks = new RemoteCallbackList<>(); 22512 22513 private final SparseIntArray mLastStatus = new SparseIntArray(); 22514 22515 public MoveCallbacks(Looper looper) { 22516 super(looper); 22517 } 22518 22519 public void register(IPackageMoveObserver callback) { 22520 mCallbacks.register(callback); 22521 } 22522 22523 public void unregister(IPackageMoveObserver callback) { 22524 mCallbacks.unregister(callback); 22525 } 22526 22527 @Override 22528 public void handleMessage(Message msg) { 22529 final SomeArgs args = (SomeArgs) msg.obj; 22530 final int n = mCallbacks.beginBroadcast(); 22531 for (int i = 0; i < n; i++) { 22532 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 22533 try { 22534 invokeCallback(callback, msg.what, args); 22535 } catch (RemoteException ignored) { 22536 } 22537 } 22538 mCallbacks.finishBroadcast(); 22539 args.recycle(); 22540 } 22541 22542 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 22543 throws RemoteException { 22544 switch (what) { 22545 case MSG_CREATED: { 22546 callback.onCreated(args.argi1, (Bundle) args.arg2); 22547 break; 22548 } 22549 case MSG_STATUS_CHANGED: { 22550 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 22551 break; 22552 } 22553 } 22554 } 22555 22556 private void notifyCreated(int moveId, Bundle extras) { 22557 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 22558 22559 final SomeArgs args = SomeArgs.obtain(); 22560 args.argi1 = moveId; 22561 args.arg2 = extras; 22562 obtainMessage(MSG_CREATED, args).sendToTarget(); 22563 } 22564 22565 private void notifyStatusChanged(int moveId, int status) { 22566 notifyStatusChanged(moveId, status, -1); 22567 } 22568 22569 private void notifyStatusChanged(int moveId, int status, long estMillis) { 22570 Slog.v(TAG, "Move " + moveId + " status " + status); 22571 22572 final SomeArgs args = SomeArgs.obtain(); 22573 args.argi1 = moveId; 22574 args.argi2 = status; 22575 args.arg3 = estMillis; 22576 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 22577 22578 synchronized (mLastStatus) { 22579 mLastStatus.put(moveId, status); 22580 } 22581 } 22582 } 22583 22584 private final static class OnPermissionChangeListeners extends Handler { 22585 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 22586 22587 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 22588 new RemoteCallbackList<>(); 22589 22590 public OnPermissionChangeListeners(Looper looper) { 22591 super(looper); 22592 } 22593 22594 @Override 22595 public void handleMessage(Message msg) { 22596 switch (msg.what) { 22597 case MSG_ON_PERMISSIONS_CHANGED: { 22598 final int uid = msg.arg1; 22599 handleOnPermissionsChanged(uid); 22600 } break; 22601 } 22602 } 22603 22604 public void addListenerLocked(IOnPermissionsChangeListener listener) { 22605 mPermissionListeners.register(listener); 22606 22607 } 22608 22609 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 22610 mPermissionListeners.unregister(listener); 22611 } 22612 22613 public void onPermissionsChanged(int uid) { 22614 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 22615 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 22616 } 22617 } 22618 22619 private void handleOnPermissionsChanged(int uid) { 22620 final int count = mPermissionListeners.beginBroadcast(); 22621 try { 22622 for (int i = 0; i < count; i++) { 22623 IOnPermissionsChangeListener callback = mPermissionListeners 22624 .getBroadcastItem(i); 22625 try { 22626 callback.onPermissionsChanged(uid); 22627 } catch (RemoteException e) { 22628 Log.e(TAG, "Permission listener is dead", e); 22629 } 22630 } 22631 } finally { 22632 mPermissionListeners.finishBroadcast(); 22633 } 22634 } 22635 } 22636 22637 private class PackageManagerInternalImpl extends PackageManagerInternal { 22638 @Override 22639 public void setLocationPackagesProvider(PackagesProvider provider) { 22640 synchronized (mPackages) { 22641 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 22642 } 22643 } 22644 22645 @Override 22646 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 22647 synchronized (mPackages) { 22648 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 22649 } 22650 } 22651 22652 @Override 22653 public void setSmsAppPackagesProvider(PackagesProvider provider) { 22654 synchronized (mPackages) { 22655 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 22656 } 22657 } 22658 22659 @Override 22660 public void setDialerAppPackagesProvider(PackagesProvider provider) { 22661 synchronized (mPackages) { 22662 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 22663 } 22664 } 22665 22666 @Override 22667 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 22668 synchronized (mPackages) { 22669 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 22670 } 22671 } 22672 22673 @Override 22674 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 22675 synchronized (mPackages) { 22676 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 22677 } 22678 } 22679 22680 @Override 22681 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 22682 synchronized (mPackages) { 22683 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 22684 packageName, userId); 22685 } 22686 } 22687 22688 @Override 22689 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 22690 synchronized (mPackages) { 22691 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 22692 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 22693 packageName, userId); 22694 } 22695 } 22696 22697 @Override 22698 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 22699 synchronized (mPackages) { 22700 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 22701 packageName, userId); 22702 } 22703 } 22704 22705 @Override 22706 public void setKeepUninstalledPackages(final List<String> packageList) { 22707 Preconditions.checkNotNull(packageList); 22708 List<String> removedFromList = null; 22709 synchronized (mPackages) { 22710 if (mKeepUninstalledPackages != null) { 22711 final int packagesCount = mKeepUninstalledPackages.size(); 22712 for (int i = 0; i < packagesCount; i++) { 22713 String oldPackage = mKeepUninstalledPackages.get(i); 22714 if (packageList != null && packageList.contains(oldPackage)) { 22715 continue; 22716 } 22717 if (removedFromList == null) { 22718 removedFromList = new ArrayList<>(); 22719 } 22720 removedFromList.add(oldPackage); 22721 } 22722 } 22723 mKeepUninstalledPackages = new ArrayList<>(packageList); 22724 if (removedFromList != null) { 22725 final int removedCount = removedFromList.size(); 22726 for (int i = 0; i < removedCount; i++) { 22727 deletePackageIfUnusedLPr(removedFromList.get(i)); 22728 } 22729 } 22730 } 22731 } 22732 22733 @Override 22734 public boolean isPermissionsReviewRequired(String packageName, int userId) { 22735 synchronized (mPackages) { 22736 // If we do not support permission review, done. 22737 if (!mPermissionReviewRequired) { 22738 return false; 22739 } 22740 22741 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 22742 if (packageSetting == null) { 22743 return false; 22744 } 22745 22746 // Permission review applies only to apps not supporting the new permission model. 22747 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 22748 return false; 22749 } 22750 22751 // Legacy apps have the permission and get user consent on launch. 22752 PermissionsState permissionsState = packageSetting.getPermissionsState(); 22753 return permissionsState.isPermissionReviewRequired(userId); 22754 } 22755 } 22756 22757 @Override 22758 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 22759 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 22760 } 22761 22762 @Override 22763 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 22764 int userId) { 22765 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 22766 } 22767 22768 @Override 22769 public void setDeviceAndProfileOwnerPackages( 22770 int deviceOwnerUserId, String deviceOwnerPackage, 22771 SparseArray<String> profileOwnerPackages) { 22772 mProtectedPackages.setDeviceAndProfileOwnerPackages( 22773 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages); 22774 } 22775 22776 @Override 22777 public boolean isPackageDataProtected(int userId, String packageName) { 22778 return mProtectedPackages.isPackageDataProtected(userId, packageName); 22779 } 22780 22781 @Override 22782 public boolean isPackageEphemeral(int userId, String packageName) { 22783 synchronized (mPackages) { 22784 PackageParser.Package p = mPackages.get(packageName); 22785 return p != null ? p.applicationInfo.isEphemeralApp() : false; 22786 } 22787 } 22788 22789 @Override 22790 public boolean wasPackageEverLaunched(String packageName, int userId) { 22791 synchronized (mPackages) { 22792 return mSettings.wasPackageEverLaunchedLPr(packageName, userId); 22793 } 22794 } 22795 22796 @Override 22797 public void grantRuntimePermission(String packageName, String name, int userId, 22798 boolean overridePolicy) { 22799 PackageManagerService.this.grantRuntimePermission(packageName, name, userId, 22800 overridePolicy); 22801 } 22802 22803 @Override 22804 public void revokeRuntimePermission(String packageName, String name, int userId, 22805 boolean overridePolicy) { 22806 PackageManagerService.this.revokeRuntimePermission(packageName, name, userId, 22807 overridePolicy); 22808 } 22809 22810 @Override 22811 public String getNameForUid(int uid) { 22812 return PackageManagerService.this.getNameForUid(uid); 22813 } 22814 22815 @Override 22816 public void requestEphemeralResolutionPhaseTwo(EphemeralResponse responseObj, 22817 Intent origIntent, String resolvedType, Intent launchIntent, 22818 String callingPackage, int userId) { 22819 PackageManagerService.this.requestEphemeralResolutionPhaseTwo( 22820 responseObj, origIntent, resolvedType, launchIntent, callingPackage, userId); 22821 } 22822 22823 @Override 22824 public void grantEphemeralAccess(int userId, Intent intent, 22825 int targetAppId, int ephemeralAppId) { 22826 synchronized (mPackages) { 22827 mEphemeralApplicationRegistry.grantEphemeralAccessLPw(userId, intent, 22828 targetAppId, ephemeralAppId); 22829 } 22830 } 22831 22832 public String getSetupWizardPackageName() { 22833 return mSetupWizardPackage; 22834 } 22835 22836 public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) { 22837 if (policy != null) { 22838 mExternalSourcesPolicy = policy; 22839 } 22840 } 22841 } 22842 22843 @Override 22844 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 22845 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 22846 synchronized (mPackages) { 22847 final long identity = Binder.clearCallingIdentity(); 22848 try { 22849 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 22850 packageNames, userId); 22851 } finally { 22852 Binder.restoreCallingIdentity(identity); 22853 } 22854 } 22855 } 22856 22857 private static void enforceSystemOrPhoneCaller(String tag) { 22858 int callingUid = Binder.getCallingUid(); 22859 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 22860 throw new SecurityException( 22861 "Cannot call " + tag + " from UID " + callingUid); 22862 } 22863 } 22864 22865 boolean isHistoricalPackageUsageAvailable() { 22866 return mPackageUsage.isHistoricalPackageUsageAvailable(); 22867 } 22868 22869 /** 22870 * Return a <b>copy</b> of the collection of packages known to the package manager. 22871 * @return A copy of the values of mPackages. 22872 */ 22873 Collection<PackageParser.Package> getPackages() { 22874 synchronized (mPackages) { 22875 return new ArrayList<>(mPackages.values()); 22876 } 22877 } 22878 22879 /** 22880 * Logs process start information (including base APK hash) to the security log. 22881 * @hide 22882 */ 22883 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 22884 String apkFile, int pid) { 22885 if (!SecurityLog.isLoggingEnabled()) { 22886 return; 22887 } 22888 Bundle data = new Bundle(); 22889 data.putLong("startTimestamp", System.currentTimeMillis()); 22890 data.putString("processName", processName); 22891 data.putInt("uid", uid); 22892 data.putString("seinfo", seinfo); 22893 data.putString("apkFile", apkFile); 22894 data.putInt("pid", pid); 22895 Message msg = mProcessLoggingHandler.obtainMessage( 22896 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 22897 msg.setData(data); 22898 mProcessLoggingHandler.sendMessage(msg); 22899 } 22900 22901 public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) { 22902 return mCompilerStats.getPackageStats(pkgName); 22903 } 22904 22905 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) { 22906 return getOrCreateCompilerPackageStats(pkg.packageName); 22907 } 22908 22909 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) { 22910 return mCompilerStats.getOrCreatePackageStats(pkgName); 22911 } 22912 22913 public void deleteCompilerPackageStats(String pkgName) { 22914 mCompilerStats.deletePackageStats(pkgName); 22915 } 22916 22917 @Override 22918 public int getInstallReason(String packageName, int userId) { 22919 enforceCrossUserPermission(Binder.getCallingUid(), userId, 22920 true /* requireFullPermission */, false /* checkShell */, 22921 "get install reason"); 22922 synchronized (mPackages) { 22923 final PackageSetting ps = mSettings.mPackages.get(packageName); 22924 if (ps != null) { 22925 return ps.getInstallReason(userId); 22926 } 22927 } 22928 return PackageManager.INSTALL_REASON_UNKNOWN; 22929 } 22930 22931 @Override 22932 public boolean canRequestPackageInstalls(String packageName, int userId) { 22933 int callingUid = Binder.getCallingUid(); 22934 int uid = getPackageUid(packageName, 0, userId); 22935 if (callingUid != uid && callingUid != Process.ROOT_UID 22936 && callingUid != Process.SYSTEM_UID) { 22937 throw new SecurityException( 22938 "Caller uid " + callingUid + " does not own package " + packageName); 22939 } 22940 ApplicationInfo info = getApplicationInfo(packageName, 0, userId); 22941 if (info == null) { 22942 return false; 22943 } 22944 if (info.targetSdkVersion < Build.VERSION_CODES.O) { 22945 throw new UnsupportedOperationException( 22946 "Operation only supported on apps targeting Android O or higher"); 22947 } 22948 String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES; 22949 String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission); 22950 if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) { 22951 throw new SecurityException("Need to declare " + appOpPermission + " to call this api"); 22952 } 22953 if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) { 22954 return false; 22955 } 22956 if (mExternalSourcesPolicy != null) { 22957 int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid); 22958 if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) { 22959 return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED; 22960 } 22961 } 22962 return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED; 22963 } 22964} 22965