PackageManagerService.java revision 5c0ecfdb37b082bd6bd490270193b676ecb481c2
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 private final UserDataPreparer mUserDataPreparer; 835 836 private File mCacheDir; 837 838 private static class IFVerificationParams { 839 PackageParser.Package pkg; 840 boolean replacing; 841 int userId; 842 int verifierUid; 843 844 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 845 int _userId, int _verifierUid) { 846 pkg = _pkg; 847 replacing = _replacing; 848 userId = _userId; 849 replacing = _replacing; 850 verifierUid = _verifierUid; 851 } 852 } 853 854 private interface IntentFilterVerifier<T extends IntentFilter> { 855 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 856 T filter, String packageName); 857 void startVerifications(int userId); 858 void receiveVerificationResponse(int verificationId); 859 } 860 861 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 862 private Context mContext; 863 private ComponentName mIntentFilterVerifierComponent; 864 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 865 866 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 867 mContext = context; 868 mIntentFilterVerifierComponent = verifierComponent; 869 } 870 871 private String getDefaultScheme() { 872 return IntentFilter.SCHEME_HTTPS; 873 } 874 875 @Override 876 public void startVerifications(int userId) { 877 // Launch verifications requests 878 int count = mCurrentIntentFilterVerifications.size(); 879 for (int n=0; n<count; n++) { 880 int verificationId = mCurrentIntentFilterVerifications.get(n); 881 final IntentFilterVerificationState ivs = 882 mIntentFilterVerificationStates.get(verificationId); 883 884 String packageName = ivs.getPackageName(); 885 886 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 887 final int filterCount = filters.size(); 888 ArraySet<String> domainsSet = new ArraySet<>(); 889 for (int m=0; m<filterCount; m++) { 890 PackageParser.ActivityIntentInfo filter = filters.get(m); 891 domainsSet.addAll(filter.getHostsList()); 892 } 893 synchronized (mPackages) { 894 if (mSettings.createIntentFilterVerificationIfNeededLPw( 895 packageName, domainsSet) != null) { 896 scheduleWriteSettingsLocked(); 897 } 898 } 899 sendVerificationRequest(userId, verificationId, ivs); 900 } 901 mCurrentIntentFilterVerifications.clear(); 902 } 903 904 private void sendVerificationRequest(int userId, int verificationId, 905 IntentFilterVerificationState ivs) { 906 907 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 908 verificationIntent.putExtra( 909 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 910 verificationId); 911 verificationIntent.putExtra( 912 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 913 getDefaultScheme()); 914 verificationIntent.putExtra( 915 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 916 ivs.getHostsString()); 917 verificationIntent.putExtra( 918 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 919 ivs.getPackageName()); 920 verificationIntent.setComponent(mIntentFilterVerifierComponent); 921 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 922 923 UserHandle user = new UserHandle(userId); 924 mContext.sendBroadcastAsUser(verificationIntent, user); 925 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 926 "Sending IntentFilter verification broadcast"); 927 } 928 929 public void receiveVerificationResponse(int verificationId) { 930 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 931 932 final boolean verified = ivs.isVerified(); 933 934 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 935 final int count = filters.size(); 936 if (DEBUG_DOMAIN_VERIFICATION) { 937 Slog.i(TAG, "Received verification response " + verificationId 938 + " for " + count + " filters, verified=" + verified); 939 } 940 for (int n=0; n<count; n++) { 941 PackageParser.ActivityIntentInfo filter = filters.get(n); 942 filter.setVerified(verified); 943 944 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 945 + " verified with result:" + verified + " and hosts:" 946 + ivs.getHostsString()); 947 } 948 949 mIntentFilterVerificationStates.remove(verificationId); 950 951 final String packageName = ivs.getPackageName(); 952 IntentFilterVerificationInfo ivi = null; 953 954 synchronized (mPackages) { 955 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 956 } 957 if (ivi == null) { 958 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 959 + verificationId + " packageName:" + packageName); 960 return; 961 } 962 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 963 "Updating IntentFilterVerificationInfo for package " + packageName 964 +" verificationId:" + verificationId); 965 966 synchronized (mPackages) { 967 if (verified) { 968 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 969 } else { 970 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 971 } 972 scheduleWriteSettingsLocked(); 973 974 final int userId = ivs.getUserId(); 975 if (userId != UserHandle.USER_ALL) { 976 final int userStatus = 977 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 978 979 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 980 boolean needUpdate = false; 981 982 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 983 // already been set by the User thru the Disambiguation dialog 984 switch (userStatus) { 985 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 986 if (verified) { 987 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 988 } else { 989 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 990 } 991 needUpdate = true; 992 break; 993 994 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 995 if (verified) { 996 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 997 needUpdate = true; 998 } 999 break; 1000 1001 default: 1002 // Nothing to do 1003 } 1004 1005 if (needUpdate) { 1006 mSettings.updateIntentFilterVerificationStatusLPw( 1007 packageName, updatedStatus, userId); 1008 scheduleWritePackageRestrictionsLocked(userId); 1009 } 1010 } 1011 } 1012 } 1013 1014 @Override 1015 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 1016 ActivityIntentInfo filter, String packageName) { 1017 if (!hasValidDomains(filter)) { 1018 return false; 1019 } 1020 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 1021 if (ivs == null) { 1022 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 1023 packageName); 1024 } 1025 if (DEBUG_DOMAIN_VERIFICATION) { 1026 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 1027 } 1028 ivs.addFilter(filter); 1029 return true; 1030 } 1031 1032 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 1033 int userId, int verificationId, String packageName) { 1034 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 1035 verifierUid, userId, packageName); 1036 ivs.setPendingState(); 1037 synchronized (mPackages) { 1038 mIntentFilterVerificationStates.append(verificationId, ivs); 1039 mCurrentIntentFilterVerifications.add(verificationId); 1040 } 1041 return ivs; 1042 } 1043 } 1044 1045 private static boolean hasValidDomains(ActivityIntentInfo filter) { 1046 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 1047 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 1048 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 1049 } 1050 1051 // Set of pending broadcasts for aggregating enable/disable of components. 1052 static class PendingPackageBroadcasts { 1053 // for each user id, a map of <package name -> components within that package> 1054 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 1055 1056 public PendingPackageBroadcasts() { 1057 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 1058 } 1059 1060 public ArrayList<String> get(int userId, String packageName) { 1061 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1062 return packages.get(packageName); 1063 } 1064 1065 public void put(int userId, String packageName, ArrayList<String> components) { 1066 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1067 packages.put(packageName, components); 1068 } 1069 1070 public void remove(int userId, String packageName) { 1071 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 1072 if (packages != null) { 1073 packages.remove(packageName); 1074 } 1075 } 1076 1077 public void remove(int userId) { 1078 mUidMap.remove(userId); 1079 } 1080 1081 public int userIdCount() { 1082 return mUidMap.size(); 1083 } 1084 1085 public int userIdAt(int n) { 1086 return mUidMap.keyAt(n); 1087 } 1088 1089 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 1090 return mUidMap.get(userId); 1091 } 1092 1093 public int size() { 1094 // total number of pending broadcast entries across all userIds 1095 int num = 0; 1096 for (int i = 0; i< mUidMap.size(); i++) { 1097 num += mUidMap.valueAt(i).size(); 1098 } 1099 return num; 1100 } 1101 1102 public void clear() { 1103 mUidMap.clear(); 1104 } 1105 1106 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1107 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1108 if (map == null) { 1109 map = new ArrayMap<String, ArrayList<String>>(); 1110 mUidMap.put(userId, map); 1111 } 1112 return map; 1113 } 1114 } 1115 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1116 1117 // Service Connection to remote media container service to copy 1118 // package uri's from external media onto secure containers 1119 // or internal storage. 1120 private IMediaContainerService mContainerService = null; 1121 1122 static final int SEND_PENDING_BROADCAST = 1; 1123 static final int MCS_BOUND = 3; 1124 static final int END_COPY = 4; 1125 static final int INIT_COPY = 5; 1126 static final int MCS_UNBIND = 6; 1127 static final int START_CLEANING_PACKAGE = 7; 1128 static final int FIND_INSTALL_LOC = 8; 1129 static final int POST_INSTALL = 9; 1130 static final int MCS_RECONNECT = 10; 1131 static final int MCS_GIVE_UP = 11; 1132 static final int UPDATED_MEDIA_STATUS = 12; 1133 static final int WRITE_SETTINGS = 13; 1134 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1135 static final int PACKAGE_VERIFIED = 15; 1136 static final int CHECK_PENDING_VERIFICATION = 16; 1137 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1138 static final int INTENT_FILTER_VERIFIED = 18; 1139 static final int WRITE_PACKAGE_LIST = 19; 1140 static final int EPHEMERAL_RESOLUTION_PHASE_TWO = 20; 1141 1142 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1143 1144 // Delay time in millisecs 1145 static final int BROADCAST_DELAY = 10 * 1000; 1146 1147 static UserManagerService sUserManager; 1148 1149 // Stores a list of users whose package restrictions file needs to be updated 1150 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1151 1152 final private DefaultContainerConnection mDefContainerConn = 1153 new DefaultContainerConnection(); 1154 class DefaultContainerConnection implements ServiceConnection { 1155 public void onServiceConnected(ComponentName name, IBinder service) { 1156 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1157 final IMediaContainerService imcs = IMediaContainerService.Stub 1158 .asInterface(Binder.allowBlocking(service)); 1159 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1160 } 1161 1162 public void onServiceDisconnected(ComponentName name) { 1163 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1164 } 1165 } 1166 1167 // Recordkeeping of restore-after-install operations that are currently in flight 1168 // between the Package Manager and the Backup Manager 1169 static class PostInstallData { 1170 public InstallArgs args; 1171 public PackageInstalledInfo res; 1172 1173 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1174 args = _a; 1175 res = _r; 1176 } 1177 } 1178 1179 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1180 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1181 1182 // XML tags for backup/restore of various bits of state 1183 private static final String TAG_PREFERRED_BACKUP = "pa"; 1184 private static final String TAG_DEFAULT_APPS = "da"; 1185 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1186 1187 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1188 private static final String TAG_ALL_GRANTS = "rt-grants"; 1189 private static final String TAG_GRANT = "grant"; 1190 private static final String ATTR_PACKAGE_NAME = "pkg"; 1191 1192 private static final String TAG_PERMISSION = "perm"; 1193 private static final String ATTR_PERMISSION_NAME = "name"; 1194 private static final String ATTR_IS_GRANTED = "g"; 1195 private static final String ATTR_USER_SET = "set"; 1196 private static final String ATTR_USER_FIXED = "fixed"; 1197 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1198 1199 // System/policy permission grants are not backed up 1200 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1201 FLAG_PERMISSION_POLICY_FIXED 1202 | FLAG_PERMISSION_SYSTEM_FIXED 1203 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1204 1205 // And we back up these user-adjusted states 1206 private static final int USER_RUNTIME_GRANT_MASK = 1207 FLAG_PERMISSION_USER_SET 1208 | FLAG_PERMISSION_USER_FIXED 1209 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1210 1211 final @Nullable String mRequiredVerifierPackage; 1212 final @NonNull String mRequiredInstallerPackage; 1213 final @NonNull String mRequiredUninstallerPackage; 1214 final @Nullable String mSetupWizardPackage; 1215 final @Nullable String mStorageManagerPackage; 1216 final @NonNull String mServicesSystemSharedLibraryPackageName; 1217 final @NonNull String mSharedSystemSharedLibraryPackageName; 1218 1219 final boolean mPermissionReviewRequired; 1220 1221 private final PackageUsage mPackageUsage = new PackageUsage(); 1222 private final CompilerStats mCompilerStats = new CompilerStats(); 1223 1224 class PackageHandler extends Handler { 1225 private boolean mBound = false; 1226 final ArrayList<HandlerParams> mPendingInstalls = 1227 new ArrayList<HandlerParams>(); 1228 1229 private boolean connectToService() { 1230 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1231 " DefaultContainerService"); 1232 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1233 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1234 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1235 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1236 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1237 mBound = true; 1238 return true; 1239 } 1240 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1241 return false; 1242 } 1243 1244 private void disconnectService() { 1245 mContainerService = null; 1246 mBound = false; 1247 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1248 mContext.unbindService(mDefContainerConn); 1249 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1250 } 1251 1252 PackageHandler(Looper looper) { 1253 super(looper); 1254 } 1255 1256 public void handleMessage(Message msg) { 1257 try { 1258 doHandleMessage(msg); 1259 } finally { 1260 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1261 } 1262 } 1263 1264 void doHandleMessage(Message msg) { 1265 switch (msg.what) { 1266 case INIT_COPY: { 1267 HandlerParams params = (HandlerParams) msg.obj; 1268 int idx = mPendingInstalls.size(); 1269 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1270 // If a bind was already initiated we dont really 1271 // need to do anything. The pending install 1272 // will be processed later on. 1273 if (!mBound) { 1274 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1275 System.identityHashCode(mHandler)); 1276 // If this is the only one pending we might 1277 // have to bind to the service again. 1278 if (!connectToService()) { 1279 Slog.e(TAG, "Failed to bind to media container service"); 1280 params.serviceError(); 1281 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1282 System.identityHashCode(mHandler)); 1283 if (params.traceMethod != null) { 1284 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1285 params.traceCookie); 1286 } 1287 return; 1288 } else { 1289 // Once we bind to the service, the first 1290 // pending request will be processed. 1291 mPendingInstalls.add(idx, params); 1292 } 1293 } else { 1294 mPendingInstalls.add(idx, params); 1295 // Already bound to the service. Just make 1296 // sure we trigger off processing the first request. 1297 if (idx == 0) { 1298 mHandler.sendEmptyMessage(MCS_BOUND); 1299 } 1300 } 1301 break; 1302 } 1303 case MCS_BOUND: { 1304 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1305 if (msg.obj != null) { 1306 mContainerService = (IMediaContainerService) msg.obj; 1307 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1308 System.identityHashCode(mHandler)); 1309 } 1310 if (mContainerService == null) { 1311 if (!mBound) { 1312 // Something seriously wrong since we are not bound and we are not 1313 // waiting for connection. Bail out. 1314 Slog.e(TAG, "Cannot bind to media container service"); 1315 for (HandlerParams params : mPendingInstalls) { 1316 // Indicate service bind error 1317 params.serviceError(); 1318 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1319 System.identityHashCode(params)); 1320 if (params.traceMethod != null) { 1321 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1322 params.traceMethod, params.traceCookie); 1323 } 1324 return; 1325 } 1326 mPendingInstalls.clear(); 1327 } else { 1328 Slog.w(TAG, "Waiting to connect to media container service"); 1329 } 1330 } else if (mPendingInstalls.size() > 0) { 1331 HandlerParams params = mPendingInstalls.get(0); 1332 if (params != null) { 1333 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1334 System.identityHashCode(params)); 1335 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1336 if (params.startCopy()) { 1337 // We are done... look for more work or to 1338 // go idle. 1339 if (DEBUG_SD_INSTALL) Log.i(TAG, 1340 "Checking for more work or unbind..."); 1341 // Delete pending install 1342 if (mPendingInstalls.size() > 0) { 1343 mPendingInstalls.remove(0); 1344 } 1345 if (mPendingInstalls.size() == 0) { 1346 if (mBound) { 1347 if (DEBUG_SD_INSTALL) Log.i(TAG, 1348 "Posting delayed MCS_UNBIND"); 1349 removeMessages(MCS_UNBIND); 1350 Message ubmsg = obtainMessage(MCS_UNBIND); 1351 // Unbind after a little delay, to avoid 1352 // continual thrashing. 1353 sendMessageDelayed(ubmsg, 10000); 1354 } 1355 } else { 1356 // There are more pending requests in queue. 1357 // Just post MCS_BOUND message to trigger processing 1358 // of next pending install. 1359 if (DEBUG_SD_INSTALL) Log.i(TAG, 1360 "Posting MCS_BOUND for next work"); 1361 mHandler.sendEmptyMessage(MCS_BOUND); 1362 } 1363 } 1364 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1365 } 1366 } else { 1367 // Should never happen ideally. 1368 Slog.w(TAG, "Empty queue"); 1369 } 1370 break; 1371 } 1372 case MCS_RECONNECT: { 1373 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1374 if (mPendingInstalls.size() > 0) { 1375 if (mBound) { 1376 disconnectService(); 1377 } 1378 if (!connectToService()) { 1379 Slog.e(TAG, "Failed to bind to media container service"); 1380 for (HandlerParams params : mPendingInstalls) { 1381 // Indicate service bind error 1382 params.serviceError(); 1383 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1384 System.identityHashCode(params)); 1385 } 1386 mPendingInstalls.clear(); 1387 } 1388 } 1389 break; 1390 } 1391 case MCS_UNBIND: { 1392 // If there is no actual work left, then time to unbind. 1393 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1394 1395 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1396 if (mBound) { 1397 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1398 1399 disconnectService(); 1400 } 1401 } else if (mPendingInstalls.size() > 0) { 1402 // There are more pending requests in queue. 1403 // Just post MCS_BOUND message to trigger processing 1404 // of next pending install. 1405 mHandler.sendEmptyMessage(MCS_BOUND); 1406 } 1407 1408 break; 1409 } 1410 case MCS_GIVE_UP: { 1411 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1412 HandlerParams params = mPendingInstalls.remove(0); 1413 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1414 System.identityHashCode(params)); 1415 break; 1416 } 1417 case SEND_PENDING_BROADCAST: { 1418 String packages[]; 1419 ArrayList<String> components[]; 1420 int size = 0; 1421 int uids[]; 1422 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1423 synchronized (mPackages) { 1424 if (mPendingBroadcasts == null) { 1425 return; 1426 } 1427 size = mPendingBroadcasts.size(); 1428 if (size <= 0) { 1429 // Nothing to be done. Just return 1430 return; 1431 } 1432 packages = new String[size]; 1433 components = new ArrayList[size]; 1434 uids = new int[size]; 1435 int i = 0; // filling out the above arrays 1436 1437 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1438 int packageUserId = mPendingBroadcasts.userIdAt(n); 1439 Iterator<Map.Entry<String, ArrayList<String>>> it 1440 = mPendingBroadcasts.packagesForUserId(packageUserId) 1441 .entrySet().iterator(); 1442 while (it.hasNext() && i < size) { 1443 Map.Entry<String, ArrayList<String>> ent = it.next(); 1444 packages[i] = ent.getKey(); 1445 components[i] = ent.getValue(); 1446 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1447 uids[i] = (ps != null) 1448 ? UserHandle.getUid(packageUserId, ps.appId) 1449 : -1; 1450 i++; 1451 } 1452 } 1453 size = i; 1454 mPendingBroadcasts.clear(); 1455 } 1456 // Send broadcasts 1457 for (int i = 0; i < size; i++) { 1458 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1459 } 1460 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1461 break; 1462 } 1463 case START_CLEANING_PACKAGE: { 1464 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1465 final String packageName = (String)msg.obj; 1466 final int userId = msg.arg1; 1467 final boolean andCode = msg.arg2 != 0; 1468 synchronized (mPackages) { 1469 if (userId == UserHandle.USER_ALL) { 1470 int[] users = sUserManager.getUserIds(); 1471 for (int user : users) { 1472 mSettings.addPackageToCleanLPw( 1473 new PackageCleanItem(user, packageName, andCode)); 1474 } 1475 } else { 1476 mSettings.addPackageToCleanLPw( 1477 new PackageCleanItem(userId, packageName, andCode)); 1478 } 1479 } 1480 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1481 startCleaningPackages(); 1482 } break; 1483 case POST_INSTALL: { 1484 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1485 1486 PostInstallData data = mRunningInstalls.get(msg.arg1); 1487 final boolean didRestore = (msg.arg2 != 0); 1488 mRunningInstalls.delete(msg.arg1); 1489 1490 if (data != null) { 1491 InstallArgs args = data.args; 1492 PackageInstalledInfo parentRes = data.res; 1493 1494 final boolean grantPermissions = (args.installFlags 1495 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1496 final boolean killApp = (args.installFlags 1497 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1498 final String[] grantedPermissions = args.installGrantPermissions; 1499 1500 // Handle the parent package 1501 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1502 grantedPermissions, didRestore, args.installerPackageName, 1503 args.observer); 1504 1505 // Handle the child packages 1506 final int childCount = (parentRes.addedChildPackages != null) 1507 ? parentRes.addedChildPackages.size() : 0; 1508 for (int i = 0; i < childCount; i++) { 1509 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1510 handlePackagePostInstall(childRes, grantPermissions, killApp, 1511 grantedPermissions, false, args.installerPackageName, 1512 args.observer); 1513 } 1514 1515 // Log tracing if needed 1516 if (args.traceMethod != null) { 1517 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1518 args.traceCookie); 1519 } 1520 } else { 1521 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1522 } 1523 1524 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1525 } break; 1526 case UPDATED_MEDIA_STATUS: { 1527 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1528 boolean reportStatus = msg.arg1 == 1; 1529 boolean doGc = msg.arg2 == 1; 1530 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1531 if (doGc) { 1532 // Force a gc to clear up stale containers. 1533 Runtime.getRuntime().gc(); 1534 } 1535 if (msg.obj != null) { 1536 @SuppressWarnings("unchecked") 1537 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1538 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1539 // Unload containers 1540 unloadAllContainers(args); 1541 } 1542 if (reportStatus) { 1543 try { 1544 if (DEBUG_SD_INSTALL) Log.i(TAG, 1545 "Invoking StorageManagerService call back"); 1546 PackageHelper.getStorageManager().finishMediaUpdate(); 1547 } catch (RemoteException e) { 1548 Log.e(TAG, "StorageManagerService not running?"); 1549 } 1550 } 1551 } break; 1552 case WRITE_SETTINGS: { 1553 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1554 synchronized (mPackages) { 1555 removeMessages(WRITE_SETTINGS); 1556 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1557 mSettings.writeLPr(); 1558 mDirtyUsers.clear(); 1559 } 1560 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1561 } break; 1562 case WRITE_PACKAGE_RESTRICTIONS: { 1563 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1564 synchronized (mPackages) { 1565 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1566 for (int userId : mDirtyUsers) { 1567 mSettings.writePackageRestrictionsLPr(userId); 1568 } 1569 mDirtyUsers.clear(); 1570 } 1571 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1572 } break; 1573 case WRITE_PACKAGE_LIST: { 1574 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1575 synchronized (mPackages) { 1576 removeMessages(WRITE_PACKAGE_LIST); 1577 mSettings.writePackageListLPr(msg.arg1); 1578 } 1579 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1580 } break; 1581 case CHECK_PENDING_VERIFICATION: { 1582 final int verificationId = msg.arg1; 1583 final PackageVerificationState state = mPendingVerification.get(verificationId); 1584 1585 if ((state != null) && !state.timeoutExtended()) { 1586 final InstallArgs args = state.getInstallArgs(); 1587 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1588 1589 Slog.i(TAG, "Verification timed out for " + originUri); 1590 mPendingVerification.remove(verificationId); 1591 1592 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1593 1594 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1595 Slog.i(TAG, "Continuing with installation of " + originUri); 1596 state.setVerifierResponse(Binder.getCallingUid(), 1597 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1598 broadcastPackageVerified(verificationId, originUri, 1599 PackageManager.VERIFICATION_ALLOW, 1600 state.getInstallArgs().getUser()); 1601 try { 1602 ret = args.copyApk(mContainerService, true); 1603 } catch (RemoteException e) { 1604 Slog.e(TAG, "Could not contact the ContainerService"); 1605 } 1606 } else { 1607 broadcastPackageVerified(verificationId, originUri, 1608 PackageManager.VERIFICATION_REJECT, 1609 state.getInstallArgs().getUser()); 1610 } 1611 1612 Trace.asyncTraceEnd( 1613 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1614 1615 processPendingInstall(args, ret); 1616 mHandler.sendEmptyMessage(MCS_UNBIND); 1617 } 1618 break; 1619 } 1620 case PACKAGE_VERIFIED: { 1621 final int verificationId = msg.arg1; 1622 1623 final PackageVerificationState state = mPendingVerification.get(verificationId); 1624 if (state == null) { 1625 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1626 break; 1627 } 1628 1629 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1630 1631 state.setVerifierResponse(response.callerUid, response.code); 1632 1633 if (state.isVerificationComplete()) { 1634 mPendingVerification.remove(verificationId); 1635 1636 final InstallArgs args = state.getInstallArgs(); 1637 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1638 1639 int ret; 1640 if (state.isInstallAllowed()) { 1641 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1642 broadcastPackageVerified(verificationId, originUri, 1643 response.code, state.getInstallArgs().getUser()); 1644 try { 1645 ret = args.copyApk(mContainerService, true); 1646 } catch (RemoteException e) { 1647 Slog.e(TAG, "Could not contact the ContainerService"); 1648 } 1649 } else { 1650 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1651 } 1652 1653 Trace.asyncTraceEnd( 1654 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1655 1656 processPendingInstall(args, ret); 1657 mHandler.sendEmptyMessage(MCS_UNBIND); 1658 } 1659 1660 break; 1661 } 1662 case START_INTENT_FILTER_VERIFICATIONS: { 1663 IFVerificationParams params = (IFVerificationParams) msg.obj; 1664 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1665 params.replacing, params.pkg); 1666 break; 1667 } 1668 case INTENT_FILTER_VERIFIED: { 1669 final int verificationId = msg.arg1; 1670 1671 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1672 verificationId); 1673 if (state == null) { 1674 Slog.w(TAG, "Invalid IntentFilter verification token " 1675 + verificationId + " received"); 1676 break; 1677 } 1678 1679 final int userId = state.getUserId(); 1680 1681 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1682 "Processing IntentFilter verification with token:" 1683 + verificationId + " and userId:" + userId); 1684 1685 final IntentFilterVerificationResponse response = 1686 (IntentFilterVerificationResponse) msg.obj; 1687 1688 state.setVerifierResponse(response.callerUid, response.code); 1689 1690 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1691 "IntentFilter verification with token:" + verificationId 1692 + " and userId:" + userId 1693 + " is settings verifier response with response code:" 1694 + response.code); 1695 1696 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1697 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1698 + response.getFailedDomainsString()); 1699 } 1700 1701 if (state.isVerificationComplete()) { 1702 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1703 } else { 1704 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1705 "IntentFilter verification with token:" + verificationId 1706 + " was not said to be complete"); 1707 } 1708 1709 break; 1710 } 1711 case EPHEMERAL_RESOLUTION_PHASE_TWO: { 1712 EphemeralResolver.doEphemeralResolutionPhaseTwo(mContext, 1713 mEphemeralResolverConnection, 1714 (EphemeralRequest) msg.obj, 1715 mEphemeralInstallerActivity, 1716 mHandler); 1717 } 1718 } 1719 } 1720 } 1721 1722 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1723 boolean killApp, String[] grantedPermissions, 1724 boolean launchedForRestore, String installerPackage, 1725 IPackageInstallObserver2 installObserver) { 1726 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1727 // Send the removed broadcasts 1728 if (res.removedInfo != null) { 1729 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1730 } 1731 1732 // Now that we successfully installed the package, grant runtime 1733 // permissions if requested before broadcasting the install. Also 1734 // for legacy apps in permission review mode we clear the permission 1735 // review flag which is used to emulate runtime permissions for 1736 // legacy apps. 1737 if (grantPermissions) { 1738 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1739 } 1740 1741 final boolean update = res.removedInfo != null 1742 && res.removedInfo.removedPackage != null; 1743 1744 // If this is the first time we have child packages for a disabled privileged 1745 // app that had no children, we grant requested runtime permissions to the new 1746 // children if the parent on the system image had them already granted. 1747 if (res.pkg.parentPackage != null) { 1748 synchronized (mPackages) { 1749 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1750 } 1751 } 1752 1753 synchronized (mPackages) { 1754 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1755 } 1756 1757 final String packageName = res.pkg.applicationInfo.packageName; 1758 1759 // Determine the set of users who are adding this package for 1760 // the first time vs. those who are seeing an update. 1761 int[] firstUsers = EMPTY_INT_ARRAY; 1762 int[] updateUsers = EMPTY_INT_ARRAY; 1763 if (res.origUsers == null || res.origUsers.length == 0) { 1764 firstUsers = res.newUsers; 1765 } else { 1766 for (int newUser : res.newUsers) { 1767 boolean isNew = true; 1768 for (int origUser : res.origUsers) { 1769 if (origUser == newUser) { 1770 isNew = false; 1771 break; 1772 } 1773 } 1774 if (isNew) { 1775 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1776 } else { 1777 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1778 } 1779 } 1780 } 1781 1782 // Send installed broadcasts if the install/update is not ephemeral 1783 // and the package is not a static shared lib. 1784 if (!isEphemeral(res.pkg) && res.pkg.staticSharedLibName == null) { 1785 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1786 1787 // Send added for users that see the package for the first time 1788 // sendPackageAddedForNewUsers also deals with system apps 1789 int appId = UserHandle.getAppId(res.uid); 1790 boolean isSystem = res.pkg.applicationInfo.isSystemApp(); 1791 sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers); 1792 1793 // Send added for users that don't see the package for the first time 1794 Bundle extras = new Bundle(1); 1795 extras.putInt(Intent.EXTRA_UID, res.uid); 1796 if (update) { 1797 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1798 } 1799 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1800 extras, 0 /*flags*/, null /*targetPackage*/, 1801 null /*finishedReceiver*/, updateUsers); 1802 1803 // Send replaced for users that don't see the package for the first time 1804 if (update) { 1805 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1806 packageName, extras, 0 /*flags*/, 1807 null /*targetPackage*/, null /*finishedReceiver*/, 1808 updateUsers); 1809 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1810 null /*package*/, null /*extras*/, 0 /*flags*/, 1811 packageName /*targetPackage*/, 1812 null /*finishedReceiver*/, updateUsers); 1813 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 1814 // First-install and we did a restore, so we're responsible for the 1815 // first-launch broadcast. 1816 if (DEBUG_BACKUP) { 1817 Slog.i(TAG, "Post-restore of " + packageName 1818 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers)); 1819 } 1820 sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers); 1821 } 1822 1823 // Send broadcast package appeared if forward locked/external for all users 1824 // treat asec-hosted packages like removable media on upgrade 1825 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1826 if (DEBUG_INSTALL) { 1827 Slog.i(TAG, "upgrading pkg " + res.pkg 1828 + " is ASEC-hosted -> AVAILABLE"); 1829 } 1830 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1831 ArrayList<String> pkgList = new ArrayList<>(1); 1832 pkgList.add(packageName); 1833 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1834 } 1835 } 1836 1837 // Work that needs to happen on first install within each user 1838 if (firstUsers != null && firstUsers.length > 0) { 1839 synchronized (mPackages) { 1840 for (int userId : firstUsers) { 1841 // If this app is a browser and it's newly-installed for some 1842 // users, clear any default-browser state in those users. The 1843 // app's nature doesn't depend on the user, so we can just check 1844 // its browser nature in any user and generalize. 1845 if (packageIsBrowser(packageName, userId)) { 1846 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1847 } 1848 1849 // We may also need to apply pending (restored) runtime 1850 // permission grants within these users. 1851 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1852 } 1853 } 1854 } 1855 1856 // Log current value of "unknown sources" setting 1857 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1858 getUnknownSourcesSettings()); 1859 1860 // Force a gc to clear up things 1861 Runtime.getRuntime().gc(); 1862 1863 // Remove the replaced package's older resources safely now 1864 // We delete after a gc for applications on sdcard. 1865 if (res.removedInfo != null && res.removedInfo.args != null) { 1866 synchronized (mInstallLock) { 1867 res.removedInfo.args.doPostDeleteLI(true); 1868 } 1869 } 1870 1871 if (!isEphemeral(res.pkg)) { 1872 // Notify DexManager that the package was installed for new users. 1873 // The updated users should already be indexed and the package code paths 1874 // should not change. 1875 // Don't notify the manager for ephemeral apps as they are not expected to 1876 // survive long enough to benefit of background optimizations. 1877 for (int userId : firstUsers) { 1878 PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId); 1879 mDexManager.notifyPackageInstalled(info, userId); 1880 } 1881 } 1882 } 1883 1884 // If someone is watching installs - notify them 1885 if (installObserver != null) { 1886 try { 1887 Bundle extras = extrasForInstallResult(res); 1888 installObserver.onPackageInstalled(res.name, res.returnCode, 1889 res.returnMsg, extras); 1890 } catch (RemoteException e) { 1891 Slog.i(TAG, "Observer no longer exists."); 1892 } 1893 } 1894 } 1895 1896 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1897 PackageParser.Package pkg) { 1898 if (pkg.parentPackage == null) { 1899 return; 1900 } 1901 if (pkg.requestedPermissions == null) { 1902 return; 1903 } 1904 final PackageSetting disabledSysParentPs = mSettings 1905 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1906 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1907 || !disabledSysParentPs.isPrivileged() 1908 || (disabledSysParentPs.childPackageNames != null 1909 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1910 return; 1911 } 1912 final int[] allUserIds = sUserManager.getUserIds(); 1913 final int permCount = pkg.requestedPermissions.size(); 1914 for (int i = 0; i < permCount; i++) { 1915 String permission = pkg.requestedPermissions.get(i); 1916 BasePermission bp = mSettings.mPermissions.get(permission); 1917 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1918 continue; 1919 } 1920 for (int userId : allUserIds) { 1921 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1922 permission, userId)) { 1923 grantRuntimePermission(pkg.packageName, permission, userId); 1924 } 1925 } 1926 } 1927 } 1928 1929 private StorageEventListener mStorageListener = new StorageEventListener() { 1930 @Override 1931 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1932 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1933 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1934 final String volumeUuid = vol.getFsUuid(); 1935 1936 // Clean up any users or apps that were removed or recreated 1937 // while this volume was missing 1938 reconcileUsers(volumeUuid); 1939 reconcileApps(volumeUuid); 1940 1941 // Clean up any install sessions that expired or were 1942 // cancelled while this volume was missing 1943 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1944 1945 loadPrivatePackages(vol); 1946 1947 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1948 unloadPrivatePackages(vol); 1949 } 1950 } 1951 1952 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1953 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1954 updateExternalMediaStatus(true, false); 1955 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1956 updateExternalMediaStatus(false, false); 1957 } 1958 } 1959 } 1960 1961 @Override 1962 public void onVolumeForgotten(String fsUuid) { 1963 if (TextUtils.isEmpty(fsUuid)) { 1964 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1965 return; 1966 } 1967 1968 // Remove any apps installed on the forgotten volume 1969 synchronized (mPackages) { 1970 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1971 for (PackageSetting ps : packages) { 1972 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1973 deletePackageVersioned(new VersionedPackage(ps.name, 1974 PackageManager.VERSION_CODE_HIGHEST), 1975 new LegacyPackageDeleteObserver(null).getBinder(), 1976 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 1977 // Try very hard to release any references to this package 1978 // so we don't risk the system server being killed due to 1979 // open FDs 1980 AttributeCache.instance().removePackage(ps.name); 1981 } 1982 1983 mSettings.onVolumeForgotten(fsUuid); 1984 mSettings.writeLPr(); 1985 } 1986 } 1987 }; 1988 1989 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 1990 String[] grantedPermissions) { 1991 for (int userId : userIds) { 1992 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1993 } 1994 } 1995 1996 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1997 String[] grantedPermissions) { 1998 SettingBase sb = (SettingBase) pkg.mExtras; 1999 if (sb == null) { 2000 return; 2001 } 2002 2003 PermissionsState permissionsState = sb.getPermissionsState(); 2004 2005 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 2006 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 2007 2008 final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 2009 >= Build.VERSION_CODES.M; 2010 2011 for (String permission : pkg.requestedPermissions) { 2012 final BasePermission bp; 2013 synchronized (mPackages) { 2014 bp = mSettings.mPermissions.get(permission); 2015 } 2016 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 2017 && (grantedPermissions == null 2018 || ArrayUtils.contains(grantedPermissions, permission))) { 2019 final int flags = permissionsState.getPermissionFlags(permission, userId); 2020 if (supportsRuntimePermissions) { 2021 // Installer cannot change immutable permissions. 2022 if ((flags & immutableFlags) == 0) { 2023 grantRuntimePermission(pkg.packageName, permission, userId); 2024 } 2025 } else if (mPermissionReviewRequired) { 2026 // In permission review mode we clear the review flag when we 2027 // are asked to install the app with all permissions granted. 2028 if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 2029 updatePermissionFlags(permission, pkg.packageName, 2030 PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId); 2031 } 2032 } 2033 } 2034 } 2035 } 2036 2037 Bundle extrasForInstallResult(PackageInstalledInfo res) { 2038 Bundle extras = null; 2039 switch (res.returnCode) { 2040 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 2041 extras = new Bundle(); 2042 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 2043 res.origPermission); 2044 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 2045 res.origPackage); 2046 break; 2047 } 2048 case PackageManager.INSTALL_SUCCEEDED: { 2049 extras = new Bundle(); 2050 extras.putBoolean(Intent.EXTRA_REPLACING, 2051 res.removedInfo != null && res.removedInfo.removedPackage != null); 2052 break; 2053 } 2054 } 2055 return extras; 2056 } 2057 2058 void scheduleWriteSettingsLocked() { 2059 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2060 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2061 } 2062 } 2063 2064 void scheduleWritePackageListLocked(int userId) { 2065 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) { 2066 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST); 2067 msg.arg1 = userId; 2068 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY); 2069 } 2070 } 2071 2072 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2073 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2074 scheduleWritePackageRestrictionsLocked(userId); 2075 } 2076 2077 void scheduleWritePackageRestrictionsLocked(int userId) { 2078 final int[] userIds = (userId == UserHandle.USER_ALL) 2079 ? sUserManager.getUserIds() : new int[]{userId}; 2080 for (int nextUserId : userIds) { 2081 if (!sUserManager.exists(nextUserId)) return; 2082 mDirtyUsers.add(nextUserId); 2083 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2084 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2085 } 2086 } 2087 } 2088 2089 public static PackageManagerService main(Context context, Installer installer, 2090 boolean factoryTest, boolean onlyCore) { 2091 // Self-check for initial settings. 2092 PackageManagerServiceCompilerMapping.checkProperties(); 2093 2094 PackageManagerService m = new PackageManagerService(context, installer, 2095 factoryTest, onlyCore); 2096 m.enableSystemUserPackages(); 2097 ServiceManager.addService("package", m); 2098 return m; 2099 } 2100 2101 private void enableSystemUserPackages() { 2102 if (!UserManager.isSplitSystemUser()) { 2103 return; 2104 } 2105 // For system user, enable apps based on the following conditions: 2106 // - app is whitelisted or belong to one of these groups: 2107 // -- system app which has no launcher icons 2108 // -- system app which has INTERACT_ACROSS_USERS permission 2109 // -- system IME app 2110 // - app is not in the blacklist 2111 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2112 Set<String> enableApps = new ArraySet<>(); 2113 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2114 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2115 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2116 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2117 enableApps.addAll(wlApps); 2118 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2119 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2120 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2121 enableApps.removeAll(blApps); 2122 Log.i(TAG, "Applications installed for system user: " + enableApps); 2123 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2124 UserHandle.SYSTEM); 2125 final int allAppsSize = allAps.size(); 2126 synchronized (mPackages) { 2127 for (int i = 0; i < allAppsSize; i++) { 2128 String pName = allAps.get(i); 2129 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2130 // Should not happen, but we shouldn't be failing if it does 2131 if (pkgSetting == null) { 2132 continue; 2133 } 2134 boolean install = enableApps.contains(pName); 2135 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2136 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2137 + " for system user"); 2138 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2139 } 2140 } 2141 } 2142 } 2143 2144 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2145 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2146 Context.DISPLAY_SERVICE); 2147 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2148 } 2149 2150 /** 2151 * Requests that files preopted on a secondary system partition be copied to the data partition 2152 * if possible. Note that the actual copying of the files is accomplished by init for security 2153 * reasons. This simply requests that the copy takes place and awaits confirmation of its 2154 * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy. 2155 */ 2156 private static void requestCopyPreoptedFiles() { 2157 final int WAIT_TIME_MS = 100; 2158 final String CP_PREOPT_PROPERTY = "sys.cppreopt"; 2159 if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) { 2160 SystemProperties.set(CP_PREOPT_PROPERTY, "requested"); 2161 // We will wait for up to 100 seconds. 2162 final long timeEnd = SystemClock.uptimeMillis() + 100 * 1000; 2163 while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) { 2164 try { 2165 Thread.sleep(WAIT_TIME_MS); 2166 } catch (InterruptedException e) { 2167 // Do nothing 2168 } 2169 if (SystemClock.uptimeMillis() > timeEnd) { 2170 SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out"); 2171 Slog.wtf(TAG, "cppreopt did not finish!"); 2172 break; 2173 } 2174 } 2175 } 2176 } 2177 2178 public PackageManagerService(Context context, Installer installer, 2179 boolean factoryTest, boolean onlyCore) { 2180 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager"); 2181 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2182 SystemClock.uptimeMillis()); 2183 2184 if (mSdkVersion <= 0) { 2185 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2186 } 2187 2188 mContext = context; 2189 2190 mPermissionReviewRequired = context.getResources().getBoolean( 2191 R.bool.config_permissionReviewRequired); 2192 2193 mFactoryTest = factoryTest; 2194 mOnlyCore = onlyCore; 2195 mMetrics = new DisplayMetrics(); 2196 mSettings = new Settings(mPackages); 2197 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2198 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2199 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2200 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2201 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2202 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2203 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2204 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2205 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2206 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2207 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2208 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2209 2210 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2211 if (separateProcesses != null && separateProcesses.length() > 0) { 2212 if ("*".equals(separateProcesses)) { 2213 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2214 mSeparateProcesses = null; 2215 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2216 } else { 2217 mDefParseFlags = 0; 2218 mSeparateProcesses = separateProcesses.split(","); 2219 Slog.w(TAG, "Running with debug.separate_processes: " 2220 + separateProcesses); 2221 } 2222 } else { 2223 mDefParseFlags = 0; 2224 mSeparateProcesses = null; 2225 } 2226 2227 mInstaller = installer; 2228 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2229 "*dexopt*"); 2230 mDexManager = new DexManager(); 2231 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2232 2233 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2234 FgThread.get().getLooper()); 2235 2236 getDefaultDisplayMetrics(context, mMetrics); 2237 2238 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config"); 2239 SystemConfig systemConfig = SystemConfig.getInstance(); 2240 mGlobalGids = systemConfig.getGlobalGids(); 2241 mSystemPermissions = systemConfig.getSystemPermissions(); 2242 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2243 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2244 2245 mProtectedPackages = new ProtectedPackages(mContext); 2246 2247 synchronized (mInstallLock) { 2248 // writer 2249 synchronized (mPackages) { 2250 mHandlerThread = new ServiceThread(TAG, 2251 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2252 mHandlerThread.start(); 2253 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2254 mProcessLoggingHandler = new ProcessLoggingHandler(); 2255 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2256 2257 mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this); 2258 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2259 2260 File dataDir = Environment.getDataDirectory(); 2261 mAppInstallDir = new File(dataDir, "app"); 2262 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2263 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2264 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2265 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2266 mUserDataPreparer = new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore); 2267 sUserManager = new UserManagerService(context, this, mUserDataPreparer, mPackages); 2268 2269 // Propagate permission configuration in to package manager. 2270 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2271 = systemConfig.getPermissions(); 2272 for (int i=0; i<permConfig.size(); i++) { 2273 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2274 BasePermission bp = mSettings.mPermissions.get(perm.name); 2275 if (bp == null) { 2276 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2277 mSettings.mPermissions.put(perm.name, bp); 2278 } 2279 if (perm.gids != null) { 2280 bp.setGids(perm.gids, perm.perUser); 2281 } 2282 } 2283 2284 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2285 final int builtInLibCount = libConfig.size(); 2286 for (int i = 0; i < builtInLibCount; i++) { 2287 String name = libConfig.keyAt(i); 2288 String path = libConfig.valueAt(i); 2289 addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED, 2290 SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0); 2291 } 2292 2293 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2294 2295 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings"); 2296 mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false)); 2297 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2298 2299 // Clean up orphaned packages for which the code path doesn't exist 2300 // and they are an update to a system app - caused by bug/32321269 2301 final int packageSettingCount = mSettings.mPackages.size(); 2302 for (int i = packageSettingCount - 1; i >= 0; i--) { 2303 PackageSetting ps = mSettings.mPackages.valueAt(i); 2304 if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists()) 2305 && mSettings.getDisabledSystemPkgLPr(ps.name) != null) { 2306 mSettings.mPackages.removeAt(i); 2307 mSettings.enableSystemPackageLPw(ps.name); 2308 } 2309 } 2310 2311 if (mFirstBoot) { 2312 requestCopyPreoptedFiles(); 2313 } 2314 2315 String customResolverActivity = Resources.getSystem().getString( 2316 R.string.config_customResolverActivity); 2317 if (TextUtils.isEmpty(customResolverActivity)) { 2318 customResolverActivity = null; 2319 } else { 2320 mCustomResolverComponentName = ComponentName.unflattenFromString( 2321 customResolverActivity); 2322 } 2323 2324 long startTime = SystemClock.uptimeMillis(); 2325 2326 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2327 startTime); 2328 2329 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2330 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2331 2332 if (bootClassPath == null) { 2333 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2334 } 2335 2336 if (systemServerClassPath == null) { 2337 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2338 } 2339 2340 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2341 final String[] dexCodeInstructionSets = 2342 getDexCodeInstructionSets( 2343 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2344 2345 /** 2346 * Ensure all external libraries have had dexopt run on them. 2347 */ 2348 if (mSharedLibraries.size() > 0) { 2349 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 2350 // NOTE: For now, we're compiling these system "shared libraries" 2351 // (and framework jars) into all available architectures. It's possible 2352 // to compile them only when we come across an app that uses them (there's 2353 // already logic for that in scanPackageLI) but that adds some complexity. 2354 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2355 final int libCount = mSharedLibraries.size(); 2356 for (int i = 0; i < libCount; i++) { 2357 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 2358 final int versionCount = versionedLib.size(); 2359 for (int j = 0; j < versionCount; j++) { 2360 SharedLibraryEntry libEntry = versionedLib.valueAt(j); 2361 final String libPath = libEntry.path != null 2362 ? libEntry.path : libEntry.apk; 2363 if (libPath == null) { 2364 continue; 2365 } 2366 try { 2367 // Shared libraries do not have profiles so we perform a full 2368 // AOT compilation (if needed). 2369 int dexoptNeeded = DexFile.getDexOptNeeded( 2370 libPath, dexCodeInstructionSet, 2371 getCompilerFilterForReason(REASON_SHARED_APK), 2372 false /* newProfile */); 2373 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2374 mInstaller.dexopt(libPath, Process.SYSTEM_UID, "*", 2375 dexCodeInstructionSet, dexoptNeeded, null, 2376 DEXOPT_PUBLIC, 2377 getCompilerFilterForReason(REASON_SHARED_APK), 2378 StorageManager.UUID_PRIVATE_INTERNAL, 2379 SKIP_SHARED_LIBRARY_CHECK); 2380 } 2381 } catch (FileNotFoundException e) { 2382 Slog.w(TAG, "Library not found: " + libPath); 2383 } catch (IOException | InstallerException e) { 2384 Slog.w(TAG, "Cannot dexopt " + libPath + "; is it an APK or JAR? " 2385 + e.getMessage()); 2386 } 2387 } 2388 } 2389 } 2390 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2391 } 2392 2393 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2394 2395 final VersionInfo ver = mSettings.getInternalVersion(); 2396 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2397 2398 // when upgrading from pre-M, promote system app permissions from install to runtime 2399 mPromoteSystemApps = 2400 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2401 2402 // When upgrading from pre-N, we need to handle package extraction like first boot, 2403 // as there is no profiling data available. 2404 mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N; 2405 2406 mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1; 2407 2408 // save off the names of pre-existing system packages prior to scanning; we don't 2409 // want to automatically grant runtime permissions for new system apps 2410 if (mPromoteSystemApps) { 2411 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2412 while (pkgSettingIter.hasNext()) { 2413 PackageSetting ps = pkgSettingIter.next(); 2414 if (isSystemApp(ps)) { 2415 mExistingSystemPackages.add(ps.name); 2416 } 2417 } 2418 } 2419 2420 mCacheDir = preparePackageParserCache(mIsUpgrade); 2421 2422 // Set flag to monitor and not change apk file paths when 2423 // scanning install directories. 2424 int scanFlags = SCAN_BOOTING | SCAN_INITIAL; 2425 2426 if (mIsUpgrade || mFirstBoot) { 2427 scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE; 2428 } 2429 2430 // Collect vendor overlay packages. (Do this before scanning any apps.) 2431 // For security and version matching reason, only consider 2432 // overlay packages if they reside in the right directory. 2433 String overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PERSIST_PROPERTY); 2434 if (overlayThemeDir.isEmpty()) { 2435 overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PROPERTY); 2436 } 2437 if (!overlayThemeDir.isEmpty()) { 2438 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR, overlayThemeDir), mDefParseFlags 2439 | PackageParser.PARSE_IS_SYSTEM 2440 | PackageParser.PARSE_IS_SYSTEM_DIR 2441 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2442 } 2443 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags 2444 | PackageParser.PARSE_IS_SYSTEM 2445 | PackageParser.PARSE_IS_SYSTEM_DIR 2446 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2447 2448 // Find base frameworks (resource packages without code). 2449 scanDirTracedLI(frameworkDir, mDefParseFlags 2450 | PackageParser.PARSE_IS_SYSTEM 2451 | PackageParser.PARSE_IS_SYSTEM_DIR 2452 | PackageParser.PARSE_IS_PRIVILEGED, 2453 scanFlags | SCAN_NO_DEX, 0); 2454 2455 // Collected privileged system packages. 2456 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2457 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2458 | PackageParser.PARSE_IS_SYSTEM 2459 | PackageParser.PARSE_IS_SYSTEM_DIR 2460 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2461 2462 // Collect ordinary system packages. 2463 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2464 scanDirTracedLI(systemAppDir, mDefParseFlags 2465 | PackageParser.PARSE_IS_SYSTEM 2466 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2467 2468 // Collect all vendor packages. 2469 File vendorAppDir = new File("/vendor/app"); 2470 try { 2471 vendorAppDir = vendorAppDir.getCanonicalFile(); 2472 } catch (IOException e) { 2473 // failed to look up canonical path, continue with original one 2474 } 2475 scanDirTracedLI(vendorAppDir, mDefParseFlags 2476 | PackageParser.PARSE_IS_SYSTEM 2477 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2478 2479 // Collect all OEM packages. 2480 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2481 scanDirTracedLI(oemAppDir, mDefParseFlags 2482 | PackageParser.PARSE_IS_SYSTEM 2483 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2484 2485 // Prune any system packages that no longer exist. 2486 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2487 if (!mOnlyCore) { 2488 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2489 while (psit.hasNext()) { 2490 PackageSetting ps = psit.next(); 2491 2492 /* 2493 * If this is not a system app, it can't be a 2494 * disable system app. 2495 */ 2496 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2497 continue; 2498 } 2499 2500 /* 2501 * If the package is scanned, it's not erased. 2502 */ 2503 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2504 if (scannedPkg != null) { 2505 /* 2506 * If the system app is both scanned and in the 2507 * disabled packages list, then it must have been 2508 * added via OTA. Remove it from the currently 2509 * scanned package so the previously user-installed 2510 * application can be scanned. 2511 */ 2512 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2513 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2514 + ps.name + "; removing system app. Last known codePath=" 2515 + ps.codePathString + ", installStatus=" + ps.installStatus 2516 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2517 + scannedPkg.mVersionCode); 2518 removePackageLI(scannedPkg, true); 2519 mExpectingBetter.put(ps.name, ps.codePath); 2520 } 2521 2522 continue; 2523 } 2524 2525 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2526 psit.remove(); 2527 logCriticalInfo(Log.WARN, "System package " + ps.name 2528 + " no longer exists; it's data will be wiped"); 2529 // Actual deletion of code and data will be handled by later 2530 // reconciliation step 2531 } else { 2532 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2533 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2534 possiblyDeletedUpdatedSystemApps.add(ps.name); 2535 } 2536 } 2537 } 2538 } 2539 2540 //look for any incomplete package installations 2541 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2542 for (int i = 0; i < deletePkgsList.size(); i++) { 2543 // Actual deletion of code and data will be handled by later 2544 // reconciliation step 2545 final String packageName = deletePkgsList.get(i).name; 2546 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2547 synchronized (mPackages) { 2548 mSettings.removePackageLPw(packageName); 2549 } 2550 } 2551 2552 //delete tmp files 2553 deleteTempPackageFiles(); 2554 2555 // Remove any shared userIDs that have no associated packages 2556 mSettings.pruneSharedUsersLPw(); 2557 2558 if (!mOnlyCore) { 2559 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2560 SystemClock.uptimeMillis()); 2561 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2562 2563 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2564 | PackageParser.PARSE_FORWARD_LOCK, 2565 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2566 2567 scanDirLI(mEphemeralInstallDir, mDefParseFlags 2568 | PackageParser.PARSE_IS_EPHEMERAL, 2569 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2570 2571 /** 2572 * Remove disable package settings for any updated system 2573 * apps that were removed via an OTA. If they're not a 2574 * previously-updated app, remove them completely. 2575 * Otherwise, just revoke their system-level permissions. 2576 */ 2577 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2578 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2579 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2580 2581 String msg; 2582 if (deletedPkg == null) { 2583 msg = "Updated system package " + deletedAppName 2584 + " no longer exists; it's data will be wiped"; 2585 // Actual deletion of code and data will be handled by later 2586 // reconciliation step 2587 } else { 2588 msg = "Updated system app + " + deletedAppName 2589 + " no longer present; removing system privileges for " 2590 + deletedAppName; 2591 2592 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2593 2594 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2595 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2596 } 2597 logCriticalInfo(Log.WARN, msg); 2598 } 2599 2600 /** 2601 * Make sure all system apps that we expected to appear on 2602 * the userdata partition actually showed up. If they never 2603 * appeared, crawl back and revive the system version. 2604 */ 2605 for (int i = 0; i < mExpectingBetter.size(); i++) { 2606 final String packageName = mExpectingBetter.keyAt(i); 2607 if (!mPackages.containsKey(packageName)) { 2608 final File scanFile = mExpectingBetter.valueAt(i); 2609 2610 logCriticalInfo(Log.WARN, "Expected better " + packageName 2611 + " but never showed up; reverting to system"); 2612 2613 int reparseFlags = mDefParseFlags; 2614 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2615 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2616 | PackageParser.PARSE_IS_SYSTEM_DIR 2617 | PackageParser.PARSE_IS_PRIVILEGED; 2618 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2619 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2620 | PackageParser.PARSE_IS_SYSTEM_DIR; 2621 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2622 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2623 | PackageParser.PARSE_IS_SYSTEM_DIR; 2624 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2625 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2626 | PackageParser.PARSE_IS_SYSTEM_DIR; 2627 } else { 2628 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2629 continue; 2630 } 2631 2632 mSettings.enableSystemPackageLPw(packageName); 2633 2634 try { 2635 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2636 } catch (PackageManagerException e) { 2637 Slog.e(TAG, "Failed to parse original system package: " 2638 + e.getMessage()); 2639 } 2640 } 2641 } 2642 } 2643 mExpectingBetter.clear(); 2644 2645 // Resolve the storage manager. 2646 mStorageManagerPackage = getStorageManagerPackageName(); 2647 2648 // Resolve protected action filters. Only the setup wizard is allowed to 2649 // have a high priority filter for these actions. 2650 mSetupWizardPackage = getSetupWizardPackageName(); 2651 if (mProtectedFilters.size() > 0) { 2652 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2653 Slog.i(TAG, "No setup wizard;" 2654 + " All protected intents capped to priority 0"); 2655 } 2656 for (ActivityIntentInfo filter : mProtectedFilters) { 2657 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2658 if (DEBUG_FILTERS) { 2659 Slog.i(TAG, "Found setup wizard;" 2660 + " allow priority " + filter.getPriority() + ";" 2661 + " package: " + filter.activity.info.packageName 2662 + " activity: " + filter.activity.className 2663 + " priority: " + filter.getPriority()); 2664 } 2665 // skip setup wizard; allow it to keep the high priority filter 2666 continue; 2667 } 2668 Slog.w(TAG, "Protected action; cap priority to 0;" 2669 + " package: " + filter.activity.info.packageName 2670 + " activity: " + filter.activity.className 2671 + " origPrio: " + filter.getPriority()); 2672 filter.setPriority(0); 2673 } 2674 } 2675 mDeferProtectedFilters = false; 2676 mProtectedFilters.clear(); 2677 2678 // Now that we know all of the shared libraries, update all clients to have 2679 // the correct library paths. 2680 updateAllSharedLibrariesLPw(null); 2681 2682 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2683 // NOTE: We ignore potential failures here during a system scan (like 2684 // the rest of the commands above) because there's precious little we 2685 // can do about it. A settings error is reported, though. 2686 adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/); 2687 } 2688 2689 // Now that we know all the packages we are keeping, 2690 // read and update their last usage times. 2691 mPackageUsage.read(mPackages); 2692 mCompilerStats.read(); 2693 2694 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2695 SystemClock.uptimeMillis()); 2696 Slog.i(TAG, "Time to scan packages: " 2697 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2698 + " seconds"); 2699 2700 // If the platform SDK has changed since the last time we booted, 2701 // we need to re-grant app permission to catch any new ones that 2702 // appear. This is really a hack, and means that apps can in some 2703 // cases get permissions that the user didn't initially explicitly 2704 // allow... it would be nice to have some better way to handle 2705 // this situation. 2706 int updateFlags = UPDATE_PERMISSIONS_ALL; 2707 if (ver.sdkVersion != mSdkVersion) { 2708 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2709 + mSdkVersion + "; regranting permissions for internal storage"); 2710 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2711 } 2712 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2713 ver.sdkVersion = mSdkVersion; 2714 2715 // If this is the first boot or an update from pre-M, and it is a normal 2716 // boot, then we need to initialize the default preferred apps across 2717 // all defined users. 2718 if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) { 2719 for (UserInfo user : sUserManager.getUsers(true)) { 2720 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2721 applyFactoryDefaultBrowserLPw(user.id); 2722 primeDomainVerificationsLPw(user.id); 2723 } 2724 } 2725 2726 // Prepare storage for system user really early during boot, 2727 // since core system apps like SettingsProvider and SystemUI 2728 // can't wait for user to start 2729 final int storageFlags; 2730 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2731 storageFlags = StorageManager.FLAG_STORAGE_DE; 2732 } else { 2733 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2734 } 2735 reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2736 storageFlags, true /* migrateAppData */); 2737 2738 // If this is first boot after an OTA, and a normal boot, then 2739 // we need to clear code cache directories. 2740 // Note that we do *not* clear the application profiles. These remain valid 2741 // across OTAs and are used to drive profile verification (post OTA) and 2742 // profile compilation (without waiting to collect a fresh set of profiles). 2743 if (mIsUpgrade && !onlyCore) { 2744 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2745 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2746 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2747 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2748 // No apps are running this early, so no need to freeze 2749 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2750 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2751 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2752 } 2753 } 2754 ver.fingerprint = Build.FINGERPRINT; 2755 } 2756 2757 checkDefaultBrowser(); 2758 2759 // clear only after permissions and other defaults have been updated 2760 mExistingSystemPackages.clear(); 2761 mPromoteSystemApps = false; 2762 2763 // All the changes are done during package scanning. 2764 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2765 2766 // can downgrade to reader 2767 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings"); 2768 mSettings.writeLPr(); 2769 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2770 2771 // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty 2772 // early on (before the package manager declares itself as early) because other 2773 // components in the system server might ask for package contexts for these apps. 2774 // 2775 // Note that "onlyCore" in this context means the system is encrypted or encrypting 2776 // (i.e, that the data partition is unavailable). 2777 if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) { 2778 long start = System.nanoTime(); 2779 List<PackageParser.Package> coreApps = new ArrayList<>(); 2780 for (PackageParser.Package pkg : mPackages.values()) { 2781 if (pkg.coreApp) { 2782 coreApps.add(pkg); 2783 } 2784 } 2785 2786 int[] stats = performDexOptUpgrade(coreApps, false, 2787 getCompilerFilterForReason(REASON_CORE_APP)); 2788 2789 final int elapsedTimeSeconds = 2790 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start); 2791 MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds); 2792 2793 if (DEBUG_DEXOPT) { 2794 Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" + 2795 stats[0] + ", " + stats[1] + ", " + stats[2] + ")"); 2796 } 2797 2798 2799 // TODO: Should we log these stats to tron too ? 2800 // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]); 2801 // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]); 2802 // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]); 2803 // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size()); 2804 } 2805 2806 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2807 SystemClock.uptimeMillis()); 2808 2809 if (!mOnlyCore) { 2810 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2811 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2812 mRequiredUninstallerPackage = getRequiredUninstallerLPr(); 2813 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2814 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2815 mIntentFilterVerifierComponent); 2816 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2817 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES, 2818 SharedLibraryInfo.VERSION_UNDEFINED); 2819 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2820 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED, 2821 SharedLibraryInfo.VERSION_UNDEFINED); 2822 } else { 2823 mRequiredVerifierPackage = null; 2824 mRequiredInstallerPackage = null; 2825 mRequiredUninstallerPackage = null; 2826 mIntentFilterVerifierComponent = null; 2827 mIntentFilterVerifier = null; 2828 mServicesSystemSharedLibraryPackageName = null; 2829 mSharedSystemSharedLibraryPackageName = null; 2830 } 2831 2832 mInstallerService = new PackageInstallerService(context, this); 2833 2834 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2835 if (ephemeralResolverComponent != null) { 2836 if (DEBUG_EPHEMERAL) { 2837 Slog.i(TAG, "Ephemeral resolver: " + ephemeralResolverComponent); 2838 } 2839 mEphemeralResolverConnection = 2840 new EphemeralResolverConnection(mContext, ephemeralResolverComponent); 2841 } else { 2842 mEphemeralResolverConnection = null; 2843 } 2844 mEphemeralInstallerComponent = getEphemeralInstallerLPr(); 2845 if (mEphemeralInstallerComponent != null) { 2846 if (DEBUG_EPHEMERAL) { 2847 Slog.i(TAG, "Ephemeral installer: " + mEphemeralInstallerComponent); 2848 } 2849 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2850 } 2851 2852 // Read and update the usage of dex files. 2853 // Do this at the end of PM init so that all the packages have their 2854 // data directory reconciled. 2855 // At this point we know the code paths of the packages, so we can validate 2856 // the disk file and build the internal cache. 2857 // The usage file is expected to be small so loading and verifying it 2858 // should take a fairly small time compare to the other activities (e.g. package 2859 // scanning). 2860 final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>(); 2861 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 2862 for (int userId : currentUserIds) { 2863 userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList()); 2864 } 2865 mDexManager.load(userPackages); 2866 } // synchronized (mPackages) 2867 } // synchronized (mInstallLock) 2868 2869 // Now after opening every single application zip, make sure they 2870 // are all flushed. Not really needed, but keeps things nice and 2871 // tidy. 2872 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC"); 2873 Runtime.getRuntime().gc(); 2874 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2875 2876 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks"); 2877 FallbackCategoryProvider.loadFallbacks(); 2878 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2879 2880 // The initial scanning above does many calls into installd while 2881 // holding the mPackages lock, but we're mostly interested in yelling 2882 // once we have a booted system. 2883 mInstaller.setWarnIfHeld(mPackages); 2884 2885 // Expose private service for system components to use. 2886 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2887 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2888 } 2889 2890 private static File preparePackageParserCache(boolean isUpgrade) { 2891 if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) { 2892 return null; 2893 } 2894 2895 // Disable package parsing on eng builds to allow for faster incremental development. 2896 if ("eng".equals(Build.TYPE)) { 2897 return null; 2898 } 2899 2900 if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) { 2901 Slog.i(TAG, "Disabling package parser cache due to system property."); 2902 return null; 2903 } 2904 2905 // The base directory for the package parser cache lives under /data/system/. 2906 final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(), 2907 "package_cache"); 2908 if (cacheBaseDir == null) { 2909 return null; 2910 } 2911 2912 // If this is a system upgrade scenario, delete the contents of the package cache dir. 2913 // This also serves to "GC" unused entries when the package cache version changes (which 2914 // can only happen during upgrades). 2915 if (isUpgrade) { 2916 FileUtils.deleteContents(cacheBaseDir); 2917 } 2918 2919 2920 // Return the versioned package cache directory. This is something like 2921 // "/data/system/package_cache/1" 2922 File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION); 2923 2924 // The following is a workaround to aid development on non-numbered userdebug 2925 // builds or cases where "adb sync" is used on userdebug builds. If we detect that 2926 // the system partition is newer. 2927 // 2928 // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build 2929 // that starts with "eng." to signify that this is an engineering build and not 2930 // destined for release. 2931 if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) { 2932 Slog.w(TAG, "Wiping cache directory because the system partition changed."); 2933 2934 // Heuristic: If the /system directory has been modified recently due to an "adb sync" 2935 // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable 2936 // in general and should not be used for production changes. In this specific case, 2937 // we know that they will work. 2938 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2939 if (cacheDir.lastModified() < frameworkDir.lastModified()) { 2940 FileUtils.deleteContents(cacheBaseDir); 2941 cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION); 2942 } 2943 } 2944 2945 return cacheDir; 2946 } 2947 2948 @Override 2949 public boolean isFirstBoot() { 2950 return mFirstBoot; 2951 } 2952 2953 @Override 2954 public boolean isOnlyCoreApps() { 2955 return mOnlyCore; 2956 } 2957 2958 @Override 2959 public boolean isUpgrade() { 2960 return mIsUpgrade; 2961 } 2962 2963 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2964 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2965 2966 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2967 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2968 UserHandle.USER_SYSTEM); 2969 if (matches.size() == 1) { 2970 return matches.get(0).getComponentInfo().packageName; 2971 } else if (matches.size() == 0) { 2972 Log.e(TAG, "There should probably be a verifier, but, none were found"); 2973 return null; 2974 } 2975 throw new RuntimeException("There must be exactly one verifier; found " + matches); 2976 } 2977 2978 private @NonNull String getRequiredSharedLibraryLPr(String name, int version) { 2979 synchronized (mPackages) { 2980 SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version); 2981 if (libraryEntry == null) { 2982 throw new IllegalStateException("Missing required shared library:" + name); 2983 } 2984 return libraryEntry.apk; 2985 } 2986 } 2987 2988 private @NonNull String getRequiredInstallerLPr() { 2989 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2990 intent.addCategory(Intent.CATEGORY_DEFAULT); 2991 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2992 2993 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2994 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2995 UserHandle.USER_SYSTEM); 2996 if (matches.size() == 1) { 2997 ResolveInfo resolveInfo = matches.get(0); 2998 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 2999 throw new RuntimeException("The installer must be a privileged app"); 3000 } 3001 return matches.get(0).getComponentInfo().packageName; 3002 } else { 3003 throw new RuntimeException("There must be exactly one installer; found " + matches); 3004 } 3005 } 3006 3007 private @NonNull String getRequiredUninstallerLPr() { 3008 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 3009 intent.addCategory(Intent.CATEGORY_DEFAULT); 3010 intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null)); 3011 3012 final ResolveInfo resolveInfo = resolveIntent(intent, null, 3013 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3014 UserHandle.USER_SYSTEM); 3015 if (resolveInfo == null || 3016 mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) { 3017 throw new RuntimeException("There must be exactly one uninstaller; found " 3018 + resolveInfo); 3019 } 3020 return resolveInfo.getComponentInfo().packageName; 3021 } 3022 3023 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 3024 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 3025 3026 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 3027 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3028 UserHandle.USER_SYSTEM); 3029 ResolveInfo best = null; 3030 final int N = matches.size(); 3031 for (int i = 0; i < N; i++) { 3032 final ResolveInfo cur = matches.get(i); 3033 final String packageName = cur.getComponentInfo().packageName; 3034 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 3035 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 3036 continue; 3037 } 3038 3039 if (best == null || cur.priority > best.priority) { 3040 best = cur; 3041 } 3042 } 3043 3044 if (best != null) { 3045 return best.getComponentInfo().getComponentName(); 3046 } else { 3047 throw new RuntimeException("There must be at least one intent filter verifier"); 3048 } 3049 } 3050 3051 private @Nullable ComponentName getEphemeralResolverLPr() { 3052 final String[] packageArray = 3053 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 3054 if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) { 3055 if (DEBUG_EPHEMERAL) { 3056 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 3057 } 3058 return null; 3059 } 3060 3061 final int resolveFlags = 3062 MATCH_DIRECT_BOOT_AWARE 3063 | MATCH_DIRECT_BOOT_UNAWARE 3064 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3065 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 3066 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 3067 resolveFlags, UserHandle.USER_SYSTEM); 3068 3069 final int N = resolvers.size(); 3070 if (N == 0) { 3071 if (DEBUG_EPHEMERAL) { 3072 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 3073 } 3074 return null; 3075 } 3076 3077 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 3078 for (int i = 0; i < N; i++) { 3079 final ResolveInfo info = resolvers.get(i); 3080 3081 if (info.serviceInfo == null) { 3082 continue; 3083 } 3084 3085 final String packageName = info.serviceInfo.packageName; 3086 if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) { 3087 if (DEBUG_EPHEMERAL) { 3088 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 3089 + " pkg: " + packageName + ", info:" + info); 3090 } 3091 continue; 3092 } 3093 3094 if (DEBUG_EPHEMERAL) { 3095 Slog.v(TAG, "Ephemeral resolver found;" 3096 + " pkg: " + packageName + ", info:" + info); 3097 } 3098 return new ComponentName(packageName, info.serviceInfo.name); 3099 } 3100 if (DEBUG_EPHEMERAL) { 3101 Slog.v(TAG, "Ephemeral resolver NOT found"); 3102 } 3103 return null; 3104 } 3105 3106 private @Nullable ComponentName getEphemeralInstallerLPr() { 3107 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 3108 intent.addCategory(Intent.CATEGORY_DEFAULT); 3109 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 3110 3111 final int resolveFlags = 3112 MATCH_DIRECT_BOOT_AWARE 3113 | MATCH_DIRECT_BOOT_UNAWARE 3114 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3115 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3116 resolveFlags, UserHandle.USER_SYSTEM); 3117 Iterator<ResolveInfo> iter = matches.iterator(); 3118 while (iter.hasNext()) { 3119 final ResolveInfo rInfo = iter.next(); 3120 final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName); 3121 if (ps != null) { 3122 final PermissionsState permissionsState = ps.getPermissionsState(); 3123 if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) { 3124 continue; 3125 } 3126 } 3127 iter.remove(); 3128 } 3129 if (matches.size() == 0) { 3130 return null; 3131 } else if (matches.size() == 1) { 3132 return matches.get(0).getComponentInfo().getComponentName(); 3133 } else { 3134 throw new RuntimeException( 3135 "There must be at most one ephemeral installer; found " + matches); 3136 } 3137 } 3138 3139 private void primeDomainVerificationsLPw(int userId) { 3140 if (DEBUG_DOMAIN_VERIFICATION) { 3141 Slog.d(TAG, "Priming domain verifications in user " + userId); 3142 } 3143 3144 SystemConfig systemConfig = SystemConfig.getInstance(); 3145 ArraySet<String> packages = systemConfig.getLinkedApps(); 3146 3147 for (String packageName : packages) { 3148 PackageParser.Package pkg = mPackages.get(packageName); 3149 if (pkg != null) { 3150 if (!pkg.isSystemApp()) { 3151 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 3152 continue; 3153 } 3154 3155 ArraySet<String> domains = null; 3156 for (PackageParser.Activity a : pkg.activities) { 3157 for (ActivityIntentInfo filter : a.intents) { 3158 if (hasValidDomains(filter)) { 3159 if (domains == null) { 3160 domains = new ArraySet<String>(); 3161 } 3162 domains.addAll(filter.getHostsList()); 3163 } 3164 } 3165 } 3166 3167 if (domains != null && domains.size() > 0) { 3168 if (DEBUG_DOMAIN_VERIFICATION) { 3169 Slog.v(TAG, " + " + packageName); 3170 } 3171 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 3172 // state w.r.t. the formal app-linkage "no verification attempted" state; 3173 // and then 'always' in the per-user state actually used for intent resolution. 3174 final IntentFilterVerificationInfo ivi; 3175 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains); 3176 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 3177 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 3178 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 3179 } else { 3180 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 3181 + "' does not handle web links"); 3182 } 3183 } else { 3184 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 3185 } 3186 } 3187 3188 scheduleWritePackageRestrictionsLocked(userId); 3189 scheduleWriteSettingsLocked(); 3190 } 3191 3192 private void applyFactoryDefaultBrowserLPw(int userId) { 3193 // The default browser app's package name is stored in a string resource, 3194 // with a product-specific overlay used for vendor customization. 3195 String browserPkg = mContext.getResources().getString( 3196 com.android.internal.R.string.default_browser); 3197 if (!TextUtils.isEmpty(browserPkg)) { 3198 // non-empty string => required to be a known package 3199 PackageSetting ps = mSettings.mPackages.get(browserPkg); 3200 if (ps == null) { 3201 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 3202 browserPkg = null; 3203 } else { 3204 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3205 } 3206 } 3207 3208 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3209 // default. If there's more than one, just leave everything alone. 3210 if (browserPkg == null) { 3211 calculateDefaultBrowserLPw(userId); 3212 } 3213 } 3214 3215 private void calculateDefaultBrowserLPw(int userId) { 3216 List<String> allBrowsers = resolveAllBrowserApps(userId); 3217 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3218 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3219 } 3220 3221 private List<String> resolveAllBrowserApps(int userId) { 3222 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3223 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3224 PackageManager.MATCH_ALL, userId); 3225 3226 final int count = list.size(); 3227 List<String> result = new ArrayList<String>(count); 3228 for (int i=0; i<count; i++) { 3229 ResolveInfo info = list.get(i); 3230 if (info.activityInfo == null 3231 || !info.handleAllWebDataURI 3232 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3233 || result.contains(info.activityInfo.packageName)) { 3234 continue; 3235 } 3236 result.add(info.activityInfo.packageName); 3237 } 3238 3239 return result; 3240 } 3241 3242 private boolean packageIsBrowser(String packageName, int userId) { 3243 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3244 PackageManager.MATCH_ALL, userId); 3245 final int N = list.size(); 3246 for (int i = 0; i < N; i++) { 3247 ResolveInfo info = list.get(i); 3248 if (packageName.equals(info.activityInfo.packageName)) { 3249 return true; 3250 } 3251 } 3252 return false; 3253 } 3254 3255 private void checkDefaultBrowser() { 3256 final int myUserId = UserHandle.myUserId(); 3257 final String packageName = getDefaultBrowserPackageName(myUserId); 3258 if (packageName != null) { 3259 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3260 if (info == null) { 3261 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3262 synchronized (mPackages) { 3263 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3264 } 3265 } 3266 } 3267 } 3268 3269 @Override 3270 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3271 throws RemoteException { 3272 try { 3273 return super.onTransact(code, data, reply, flags); 3274 } catch (RuntimeException e) { 3275 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3276 Slog.wtf(TAG, "Package Manager Crash", e); 3277 } 3278 throw e; 3279 } 3280 } 3281 3282 static int[] appendInts(int[] cur, int[] add) { 3283 if (add == null) return cur; 3284 if (cur == null) return add; 3285 final int N = add.length; 3286 for (int i=0; i<N; i++) { 3287 cur = appendInt(cur, add[i]); 3288 } 3289 return cur; 3290 } 3291 3292 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3293 if (!sUserManager.exists(userId)) return null; 3294 if (ps == null) { 3295 return null; 3296 } 3297 final PackageParser.Package p = ps.pkg; 3298 if (p == null) { 3299 return null; 3300 } 3301 // Filter out ephemeral app metadata: 3302 // * The system/shell/root can see metadata for any app 3303 // * An installed app can see metadata for 1) other installed apps 3304 // and 2) ephemeral apps that have explicitly interacted with it 3305 // * Ephemeral apps can only see their own metadata 3306 final int callingAppId = UserHandle.getAppId(Binder.getCallingUid()); 3307 if (callingAppId != Process.SYSTEM_UID 3308 && callingAppId != Process.SHELL_UID 3309 && callingAppId != Process.ROOT_UID) { 3310 final String ephemeralPackageName = getEphemeralPackageName(Binder.getCallingUid()); 3311 if (ephemeralPackageName != null) { 3312 // ephemeral apps can only get information on themselves 3313 if (!ephemeralPackageName.equals(p.packageName)) { 3314 return null; 3315 } 3316 } else { 3317 if (p.applicationInfo.isEphemeralApp()) { 3318 // only get access to the ephemeral app if we've been granted access 3319 if (!mEphemeralApplicationRegistry.isEphemeralAccessGranted( 3320 userId, callingAppId, ps.appId)) { 3321 return null; 3322 } 3323 } 3324 } 3325 } 3326 3327 final PermissionsState permissionsState = ps.getPermissionsState(); 3328 3329 // Compute GIDs only if requested 3330 final int[] gids = (flags & PackageManager.GET_GIDS) == 0 3331 ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId); 3332 // Compute granted permissions only if package has requested permissions 3333 final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions) 3334 ? Collections.<String>emptySet() : permissionsState.getPermissions(userId); 3335 final PackageUserState state = ps.readUserState(userId); 3336 3337 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0 3338 && ps.isSystem()) { 3339 flags |= MATCH_ANY_USER; 3340 } 3341 3342 PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags, 3343 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3344 3345 if (packageInfo == null) { 3346 return null; 3347 } 3348 3349 packageInfo.packageName = packageInfo.applicationInfo.packageName = 3350 resolveExternalPackageNameLPr(p); 3351 3352 return packageInfo; 3353 } 3354 3355 @Override 3356 public void checkPackageStartable(String packageName, int userId) { 3357 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3358 3359 synchronized (mPackages) { 3360 final PackageSetting ps = mSettings.mPackages.get(packageName); 3361 if (ps == null) { 3362 throw new SecurityException("Package " + packageName + " was not found!"); 3363 } 3364 3365 if (!ps.getInstalled(userId)) { 3366 throw new SecurityException( 3367 "Package " + packageName + " was not installed for user " + userId + "!"); 3368 } 3369 3370 if (mSafeMode && !ps.isSystem()) { 3371 throw new SecurityException("Package " + packageName + " not a system app!"); 3372 } 3373 3374 if (mFrozenPackages.contains(packageName)) { 3375 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3376 } 3377 3378 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3379 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3380 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3381 } 3382 } 3383 } 3384 3385 @Override 3386 public boolean isPackageAvailable(String packageName, int userId) { 3387 if (!sUserManager.exists(userId)) return false; 3388 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3389 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3390 synchronized (mPackages) { 3391 PackageParser.Package p = mPackages.get(packageName); 3392 if (p != null) { 3393 final PackageSetting ps = (PackageSetting) p.mExtras; 3394 if (ps != null) { 3395 final PackageUserState state = ps.readUserState(userId); 3396 if (state != null) { 3397 return PackageParser.isAvailable(state); 3398 } 3399 } 3400 } 3401 } 3402 return false; 3403 } 3404 3405 @Override 3406 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3407 return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST, 3408 flags, userId); 3409 } 3410 3411 @Override 3412 public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage, 3413 int flags, int userId) { 3414 return getPackageInfoInternal(versionedPackage.getPackageName(), 3415 // TODO: We will change version code to long, so in the new API it is long 3416 (int) versionedPackage.getVersionCode(), flags, userId); 3417 } 3418 3419 private PackageInfo getPackageInfoInternal(String packageName, int versionCode, 3420 int flags, int userId) { 3421 if (!sUserManager.exists(userId)) return null; 3422 flags = updateFlagsForPackage(flags, userId, packageName); 3423 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3424 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3425 3426 // reader 3427 synchronized (mPackages) { 3428 // Normalize package name to handle renamed packages and static libs 3429 packageName = resolveInternalPackageNameLPr(packageName, versionCode); 3430 3431 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3432 if (matchFactoryOnly) { 3433 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3434 if (ps != null) { 3435 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 3436 return null; 3437 } 3438 return generatePackageInfo(ps, flags, userId); 3439 } 3440 } 3441 3442 PackageParser.Package p = mPackages.get(packageName); 3443 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3444 return null; 3445 } 3446 if (DEBUG_PACKAGE_INFO) 3447 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3448 if (p != null) { 3449 if (filterSharedLibPackageLPr((PackageSetting) p.mExtras, 3450 Binder.getCallingUid(), userId)) { 3451 return null; 3452 } 3453 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3454 } 3455 if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) { 3456 final PackageSetting ps = mSettings.mPackages.get(packageName); 3457 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 3458 return null; 3459 } 3460 return generatePackageInfo(ps, flags, userId); 3461 } 3462 } 3463 return null; 3464 } 3465 3466 3467 private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId) { 3468 // System/shell/root get to see all static libs 3469 final int appId = UserHandle.getAppId(uid); 3470 if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID 3471 || appId == Process.ROOT_UID) { 3472 return false; 3473 } 3474 3475 // No package means no static lib as it is always on internal storage 3476 if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) { 3477 return false; 3478 } 3479 3480 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName, 3481 ps.pkg.staticSharedLibVersion); 3482 if (libEntry == null) { 3483 return false; 3484 } 3485 3486 final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid)); 3487 final String[] uidPackageNames = getPackagesForUid(resolvedUid); 3488 if (uidPackageNames == null) { 3489 return true; 3490 } 3491 3492 for (String uidPackageName : uidPackageNames) { 3493 if (ps.name.equals(uidPackageName)) { 3494 return false; 3495 } 3496 PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName); 3497 if (uidPs != null) { 3498 final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries, 3499 libEntry.info.getName()); 3500 if (index < 0) { 3501 continue; 3502 } 3503 if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) { 3504 return false; 3505 } 3506 } 3507 } 3508 return true; 3509 } 3510 3511 @Override 3512 public String[] currentToCanonicalPackageNames(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 PackageSetting ps = mSettings.mPackages.get(names[i]); 3518 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3519 } 3520 } 3521 return out; 3522 } 3523 3524 @Override 3525 public String[] canonicalToCurrentPackageNames(String[] names) { 3526 String[] out = new String[names.length]; 3527 // reader 3528 synchronized (mPackages) { 3529 for (int i=names.length-1; i>=0; i--) { 3530 String cur = mSettings.getRenamedPackageLPr(names[i]); 3531 out[i] = cur != null ? cur : names[i]; 3532 } 3533 } 3534 return out; 3535 } 3536 3537 @Override 3538 public int getPackageUid(String packageName, int flags, int userId) { 3539 if (!sUserManager.exists(userId)) return -1; 3540 flags = updateFlagsForPackage(flags, userId, packageName); 3541 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3542 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3543 3544 // reader 3545 synchronized (mPackages) { 3546 final PackageParser.Package p = mPackages.get(packageName); 3547 if (p != null && p.isMatch(flags)) { 3548 return UserHandle.getUid(userId, p.applicationInfo.uid); 3549 } 3550 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3551 final PackageSetting ps = mSettings.mPackages.get(packageName); 3552 if (ps != null && ps.isMatch(flags)) { 3553 return UserHandle.getUid(userId, ps.appId); 3554 } 3555 } 3556 } 3557 3558 return -1; 3559 } 3560 3561 @Override 3562 public int[] getPackageGids(String packageName, int flags, int userId) { 3563 if (!sUserManager.exists(userId)) return null; 3564 flags = updateFlagsForPackage(flags, userId, packageName); 3565 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3566 false /* requireFullPermission */, false /* checkShell */, 3567 "getPackageGids"); 3568 3569 // reader 3570 synchronized (mPackages) { 3571 final PackageParser.Package p = mPackages.get(packageName); 3572 if (p != null && p.isMatch(flags)) { 3573 PackageSetting ps = (PackageSetting) p.mExtras; 3574 // TODO: Shouldn't this be checking for package installed state for userId and 3575 // return null? 3576 return ps.getPermissionsState().computeGids(userId); 3577 } 3578 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3579 final PackageSetting ps = mSettings.mPackages.get(packageName); 3580 if (ps != null && ps.isMatch(flags)) { 3581 return ps.getPermissionsState().computeGids(userId); 3582 } 3583 } 3584 } 3585 3586 return null; 3587 } 3588 3589 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3590 if (bp.perm != null) { 3591 return PackageParser.generatePermissionInfo(bp.perm, flags); 3592 } 3593 PermissionInfo pi = new PermissionInfo(); 3594 pi.name = bp.name; 3595 pi.packageName = bp.sourcePackage; 3596 pi.nonLocalizedLabel = bp.name; 3597 pi.protectionLevel = bp.protectionLevel; 3598 return pi; 3599 } 3600 3601 @Override 3602 public PermissionInfo getPermissionInfo(String name, int flags) { 3603 // reader 3604 synchronized (mPackages) { 3605 final BasePermission p = mSettings.mPermissions.get(name); 3606 if (p != null) { 3607 return generatePermissionInfo(p, flags); 3608 } 3609 return null; 3610 } 3611 } 3612 3613 @Override 3614 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3615 int flags) { 3616 // reader 3617 synchronized (mPackages) { 3618 if (group != null && !mPermissionGroups.containsKey(group)) { 3619 // This is thrown as NameNotFoundException 3620 return null; 3621 } 3622 3623 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3624 for (BasePermission p : mSettings.mPermissions.values()) { 3625 if (group == null) { 3626 if (p.perm == null || p.perm.info.group == null) { 3627 out.add(generatePermissionInfo(p, flags)); 3628 } 3629 } else { 3630 if (p.perm != null && group.equals(p.perm.info.group)) { 3631 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3632 } 3633 } 3634 } 3635 return new ParceledListSlice<>(out); 3636 } 3637 } 3638 3639 @Override 3640 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3641 // reader 3642 synchronized (mPackages) { 3643 return PackageParser.generatePermissionGroupInfo( 3644 mPermissionGroups.get(name), flags); 3645 } 3646 } 3647 3648 @Override 3649 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3650 // reader 3651 synchronized (mPackages) { 3652 final int N = mPermissionGroups.size(); 3653 ArrayList<PermissionGroupInfo> out 3654 = new ArrayList<PermissionGroupInfo>(N); 3655 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3656 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3657 } 3658 return new ParceledListSlice<>(out); 3659 } 3660 } 3661 3662 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3663 int uid, int userId) { 3664 if (!sUserManager.exists(userId)) return null; 3665 PackageSetting ps = mSettings.mPackages.get(packageName); 3666 if (ps != null) { 3667 if (filterSharedLibPackageLPr(ps, uid, userId)) { 3668 return null; 3669 } 3670 if (ps.pkg == null) { 3671 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3672 if (pInfo != null) { 3673 return pInfo.applicationInfo; 3674 } 3675 return null; 3676 } 3677 ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 3678 ps.readUserState(userId), userId); 3679 if (ai != null) { 3680 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 3681 } 3682 return ai; 3683 } 3684 return null; 3685 } 3686 3687 @Override 3688 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3689 if (!sUserManager.exists(userId)) return null; 3690 flags = updateFlagsForApplication(flags, userId, packageName); 3691 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3692 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3693 3694 // writer 3695 synchronized (mPackages) { 3696 // Normalize package name to handle renamed packages and static libs 3697 packageName = resolveInternalPackageNameLPr(packageName, 3698 PackageManager.VERSION_CODE_HIGHEST); 3699 3700 PackageParser.Package p = mPackages.get(packageName); 3701 if (DEBUG_PACKAGE_INFO) Log.v( 3702 TAG, "getApplicationInfo " + packageName 3703 + ": " + p); 3704 if (p != null) { 3705 PackageSetting ps = mSettings.mPackages.get(packageName); 3706 if (ps == null) return null; 3707 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 3708 return null; 3709 } 3710 // Note: isEnabledLP() does not apply here - always return info 3711 ApplicationInfo ai = PackageParser.generateApplicationInfo( 3712 p, flags, ps.readUserState(userId), userId); 3713 if (ai != null) { 3714 ai.packageName = resolveExternalPackageNameLPr(p); 3715 } 3716 return ai; 3717 } 3718 if ("android".equals(packageName)||"system".equals(packageName)) { 3719 return mAndroidApplication; 3720 } 3721 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3722 // Already generates the external package name 3723 return generateApplicationInfoFromSettingsLPw(packageName, 3724 Binder.getCallingUid(), flags, userId); 3725 } 3726 } 3727 return null; 3728 } 3729 3730 private String normalizePackageNameLPr(String packageName) { 3731 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 3732 return normalizedPackageName != null ? normalizedPackageName : packageName; 3733 } 3734 3735 @Override 3736 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3737 final IPackageDataObserver observer) { 3738 mContext.enforceCallingOrSelfPermission( 3739 android.Manifest.permission.CLEAR_APP_CACHE, null); 3740 // Queue up an async operation since clearing cache may take a little while. 3741 mHandler.post(new Runnable() { 3742 public void run() { 3743 mHandler.removeCallbacks(this); 3744 boolean success = true; 3745 synchronized (mInstallLock) { 3746 try { 3747 mInstaller.freeCache(volumeUuid, freeStorageSize, 0); 3748 } catch (InstallerException e) { 3749 Slog.w(TAG, "Couldn't clear application caches: " + e); 3750 success = false; 3751 } 3752 } 3753 if (observer != null) { 3754 try { 3755 observer.onRemoveCompleted(null, success); 3756 } catch (RemoteException e) { 3757 Slog.w(TAG, "RemoveException when invoking call back"); 3758 } 3759 } 3760 } 3761 }); 3762 } 3763 3764 @Override 3765 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3766 final IntentSender pi) { 3767 mContext.enforceCallingOrSelfPermission( 3768 android.Manifest.permission.CLEAR_APP_CACHE, null); 3769 // Queue up an async operation since clearing cache may take a little while. 3770 mHandler.post(new Runnable() { 3771 public void run() { 3772 mHandler.removeCallbacks(this); 3773 boolean success = true; 3774 synchronized (mInstallLock) { 3775 try { 3776 mInstaller.freeCache(volumeUuid, freeStorageSize, 0); 3777 } catch (InstallerException e) { 3778 Slog.w(TAG, "Couldn't clear application caches: " + e); 3779 success = false; 3780 } 3781 } 3782 if(pi != null) { 3783 try { 3784 // Callback via pending intent 3785 int code = success ? 1 : 0; 3786 pi.sendIntent(null, code, null, 3787 null, null); 3788 } catch (SendIntentException e1) { 3789 Slog.i(TAG, "Failed to send pending intent"); 3790 } 3791 } 3792 } 3793 }); 3794 } 3795 3796 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3797 synchronized (mInstallLock) { 3798 try { 3799 mInstaller.freeCache(volumeUuid, freeStorageSize, 0); 3800 } catch (InstallerException e) { 3801 throw new IOException("Failed to free enough space", e); 3802 } 3803 } 3804 } 3805 3806 /** 3807 * Update given flags based on encryption status of current user. 3808 */ 3809 private int updateFlags(int flags, int userId) { 3810 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3811 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3812 // Caller expressed an explicit opinion about what encryption 3813 // aware/unaware components they want to see, so fall through and 3814 // give them what they want 3815 } else { 3816 // Caller expressed no opinion, so match based on user state 3817 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 3818 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3819 } else { 3820 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3821 } 3822 } 3823 return flags; 3824 } 3825 3826 private UserManagerInternal getUserManagerInternal() { 3827 if (mUserManagerInternal == null) { 3828 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 3829 } 3830 return mUserManagerInternal; 3831 } 3832 3833 /** 3834 * Update given flags when being used to request {@link PackageInfo}. 3835 */ 3836 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3837 final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM; 3838 boolean triaged = true; 3839 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3840 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3841 // Caller is asking for component details, so they'd better be 3842 // asking for specific encryption matching behavior, or be triaged 3843 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3844 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3845 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3846 triaged = false; 3847 } 3848 } 3849 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3850 | PackageManager.MATCH_SYSTEM_ONLY 3851 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3852 triaged = false; 3853 } 3854 if ((flags & PackageManager.MATCH_ANY_USER) != 0) { 3855 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 3856 "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at " 3857 + Debug.getCallers(5)); 3858 } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser 3859 && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) { 3860 // If the caller wants all packages and has a restricted profile associated with it, 3861 // then match all users. This is to make sure that launchers that need to access work 3862 // profile apps don't start breaking. TODO: Remove this hack when launchers stop using 3863 // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380 3864 flags |= PackageManager.MATCH_ANY_USER; 3865 } 3866 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3867 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3868 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3869 } 3870 return updateFlags(flags, userId); 3871 } 3872 3873 /** 3874 * Update given flags when being used to request {@link ApplicationInfo}. 3875 */ 3876 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3877 return updateFlagsForPackage(flags, userId, cookie); 3878 } 3879 3880 /** 3881 * Update given flags when being used to request {@link ComponentInfo}. 3882 */ 3883 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3884 if (cookie instanceof Intent) { 3885 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3886 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3887 } 3888 } 3889 3890 boolean triaged = true; 3891 // Caller is asking for component details, so they'd better be 3892 // asking for specific encryption matching behavior, or be triaged 3893 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3894 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3895 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3896 triaged = false; 3897 } 3898 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3899 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3900 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3901 } 3902 3903 return updateFlags(flags, userId); 3904 } 3905 3906 /** 3907 * Update given intent when being used to request {@link ResolveInfo}. 3908 */ 3909 private Intent updateIntentForResolve(Intent intent) { 3910 if (intent.getSelector() != null) { 3911 intent = intent.getSelector(); 3912 } 3913 if (DEBUG_PREFERRED) { 3914 intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3915 } 3916 return intent; 3917 } 3918 3919 /** 3920 * Update given flags when being used to request {@link ResolveInfo}. 3921 */ 3922 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3923 // Safe mode means we shouldn't match any third-party components 3924 if (mSafeMode) { 3925 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3926 } 3927 final int callingUid = Binder.getCallingUid(); 3928 if (callingUid == Process.SYSTEM_UID || callingUid == 0) { 3929 // The system sees all components 3930 flags |= PackageManager.MATCH_EPHEMERAL; 3931 } else if (getEphemeralPackageName(callingUid) != null) { 3932 // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components 3933 flags |= PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY; 3934 flags |= PackageManager.MATCH_EPHEMERAL; 3935 } else { 3936 // Otherwise, prevent leaking ephemeral components 3937 flags &= ~PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY; 3938 flags &= ~PackageManager.MATCH_EPHEMERAL; 3939 } 3940 return updateFlagsForComponent(flags, userId, cookie); 3941 } 3942 3943 @Override 3944 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3945 if (!sUserManager.exists(userId)) return null; 3946 flags = updateFlagsForComponent(flags, userId, component); 3947 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3948 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 3949 synchronized (mPackages) { 3950 PackageParser.Activity a = mActivities.mActivities.get(component); 3951 3952 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3953 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3954 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3955 if (ps == null) return null; 3956 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3957 userId); 3958 } 3959 if (mResolveComponentName.equals(component)) { 3960 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3961 new PackageUserState(), userId); 3962 } 3963 } 3964 return null; 3965 } 3966 3967 @Override 3968 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3969 String resolvedType) { 3970 synchronized (mPackages) { 3971 if (component.equals(mResolveComponentName)) { 3972 // The resolver supports EVERYTHING! 3973 return true; 3974 } 3975 PackageParser.Activity a = mActivities.mActivities.get(component); 3976 if (a == null) { 3977 return false; 3978 } 3979 for (int i=0; i<a.intents.size(); i++) { 3980 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3981 intent.getData(), intent.getCategories(), TAG) >= 0) { 3982 return true; 3983 } 3984 } 3985 return false; 3986 } 3987 } 3988 3989 @Override 3990 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3991 if (!sUserManager.exists(userId)) return null; 3992 flags = updateFlagsForComponent(flags, userId, component); 3993 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3994 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 3995 synchronized (mPackages) { 3996 PackageParser.Activity a = mReceivers.mActivities.get(component); 3997 if (DEBUG_PACKAGE_INFO) Log.v( 3998 TAG, "getReceiverInfo " + component + ": " + a); 3999 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 4000 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4001 if (ps == null) return null; 4002 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 4003 userId); 4004 } 4005 } 4006 return null; 4007 } 4008 4009 @Override 4010 public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(int flags, int userId) { 4011 if (!sUserManager.exists(userId)) return null; 4012 Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0"); 4013 4014 flags = updateFlagsForPackage(flags, userId, null); 4015 4016 final boolean canSeeStaticLibraries = 4017 mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES) 4018 == PERMISSION_GRANTED 4019 || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES) 4020 == PERMISSION_GRANTED 4021 || mContext.checkCallingOrSelfPermission(REQUEST_INSTALL_PACKAGES) 4022 == PERMISSION_GRANTED 4023 || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES) 4024 == PERMISSION_GRANTED; 4025 4026 synchronized (mPackages) { 4027 List<SharedLibraryInfo> result = null; 4028 4029 final int libCount = mSharedLibraries.size(); 4030 for (int i = 0; i < libCount; i++) { 4031 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 4032 if (versionedLib == null) { 4033 continue; 4034 } 4035 4036 final int versionCount = versionedLib.size(); 4037 for (int j = 0; j < versionCount; j++) { 4038 SharedLibraryInfo libInfo = versionedLib.valueAt(j).info; 4039 if (!canSeeStaticLibraries && libInfo.isStatic()) { 4040 break; 4041 } 4042 final long identity = Binder.clearCallingIdentity(); 4043 try { 4044 // TODO: We will change version code to long, so in the new API it is long 4045 PackageInfo packageInfo = getPackageInfoVersioned( 4046 libInfo.getDeclaringPackage(), flags, userId); 4047 if (packageInfo == null) { 4048 continue; 4049 } 4050 } finally { 4051 Binder.restoreCallingIdentity(identity); 4052 } 4053 4054 SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(), 4055 libInfo.getVersion(), libInfo.getType(), libInfo.getDeclaringPackage(), 4056 getPackagesUsingSharedLibraryLPr(libInfo, flags, userId)); 4057 4058 if (result == null) { 4059 result = new ArrayList<>(); 4060 } 4061 result.add(resLibInfo); 4062 } 4063 } 4064 4065 return result != null ? new ParceledListSlice<>(result) : null; 4066 } 4067 } 4068 4069 private List<VersionedPackage> getPackagesUsingSharedLibraryLPr( 4070 SharedLibraryInfo libInfo, int flags, int userId) { 4071 List<VersionedPackage> versionedPackages = null; 4072 final int packageCount = mSettings.mPackages.size(); 4073 for (int i = 0; i < packageCount; i++) { 4074 PackageSetting ps = mSettings.mPackages.valueAt(i); 4075 4076 if (ps == null) { 4077 continue; 4078 } 4079 4080 if (!ps.getUserState().get(userId).isAvailable(flags)) { 4081 continue; 4082 } 4083 4084 final String libName = libInfo.getName(); 4085 if (libInfo.isStatic()) { 4086 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 4087 if (libIdx < 0) { 4088 continue; 4089 } 4090 if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) { 4091 continue; 4092 } 4093 if (versionedPackages == null) { 4094 versionedPackages = new ArrayList<>(); 4095 } 4096 // If the dependent is a static shared lib, use the public package name 4097 String dependentPackageName = ps.name; 4098 if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) { 4099 dependentPackageName = ps.pkg.manifestPackageName; 4100 } 4101 versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode)); 4102 } else if (ps.pkg != null) { 4103 if (ArrayUtils.contains(ps.pkg.usesLibraries, libName) 4104 || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) { 4105 if (versionedPackages == null) { 4106 versionedPackages = new ArrayList<>(); 4107 } 4108 versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode)); 4109 } 4110 } 4111 } 4112 4113 return versionedPackages; 4114 } 4115 4116 @Override 4117 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 4118 if (!sUserManager.exists(userId)) return null; 4119 flags = updateFlagsForComponent(flags, userId, component); 4120 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4121 false /* requireFullPermission */, false /* checkShell */, "get service info"); 4122 synchronized (mPackages) { 4123 PackageParser.Service s = mServices.mServices.get(component); 4124 if (DEBUG_PACKAGE_INFO) Log.v( 4125 TAG, "getServiceInfo " + component + ": " + s); 4126 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 4127 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4128 if (ps == null) return null; 4129 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 4130 userId); 4131 } 4132 } 4133 return null; 4134 } 4135 4136 @Override 4137 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 4138 if (!sUserManager.exists(userId)) return null; 4139 flags = updateFlagsForComponent(flags, userId, component); 4140 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4141 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 4142 synchronized (mPackages) { 4143 PackageParser.Provider p = mProviders.mProviders.get(component); 4144 if (DEBUG_PACKAGE_INFO) Log.v( 4145 TAG, "getProviderInfo " + component + ": " + p); 4146 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 4147 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4148 if (ps == null) return null; 4149 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 4150 userId); 4151 } 4152 } 4153 return null; 4154 } 4155 4156 @Override 4157 public String[] getSystemSharedLibraryNames() { 4158 synchronized (mPackages) { 4159 Set<String> libs = null; 4160 final int libCount = mSharedLibraries.size(); 4161 for (int i = 0; i < libCount; i++) { 4162 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 4163 if (versionedLib == null) { 4164 continue; 4165 } 4166 final int versionCount = versionedLib.size(); 4167 for (int j = 0; j < versionCount; j++) { 4168 SharedLibraryEntry libEntry = versionedLib.valueAt(j); 4169 if (!libEntry.info.isStatic()) { 4170 if (libs == null) { 4171 libs = new ArraySet<>(); 4172 } 4173 libs.add(libEntry.info.getName()); 4174 break; 4175 } 4176 PackageSetting ps = mSettings.getPackageLPr(libEntry.apk); 4177 if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(), 4178 UserHandle.getUserId(Binder.getCallingUid()))) { 4179 if (libs == null) { 4180 libs = new ArraySet<>(); 4181 } 4182 libs.add(libEntry.info.getName()); 4183 break; 4184 } 4185 } 4186 } 4187 4188 if (libs != null) { 4189 String[] libsArray = new String[libs.size()]; 4190 libs.toArray(libsArray); 4191 return libsArray; 4192 } 4193 4194 return null; 4195 } 4196 } 4197 4198 @Override 4199 public @NonNull String getServicesSystemSharedLibraryPackageName() { 4200 synchronized (mPackages) { 4201 return mServicesSystemSharedLibraryPackageName; 4202 } 4203 } 4204 4205 @Override 4206 public @NonNull String getSharedSystemSharedLibraryPackageName() { 4207 synchronized (mPackages) { 4208 return mSharedSystemSharedLibraryPackageName; 4209 } 4210 } 4211 4212 @Override 4213 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 4214 synchronized (mPackages) { 4215 final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values()); 4216 4217 final FeatureInfo fi = new FeatureInfo(); 4218 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 4219 FeatureInfo.GL_ES_VERSION_UNDEFINED); 4220 res.add(fi); 4221 4222 return new ParceledListSlice<>(res); 4223 } 4224 } 4225 4226 @Override 4227 public boolean hasSystemFeature(String name, int version) { 4228 synchronized (mPackages) { 4229 final FeatureInfo feat = mAvailableFeatures.get(name); 4230 if (feat == null) { 4231 return false; 4232 } else { 4233 return feat.version >= version; 4234 } 4235 } 4236 } 4237 4238 @Override 4239 public int checkPermission(String permName, String pkgName, int userId) { 4240 if (!sUserManager.exists(userId)) { 4241 return PackageManager.PERMISSION_DENIED; 4242 } 4243 4244 synchronized (mPackages) { 4245 final PackageParser.Package p = mPackages.get(pkgName); 4246 if (p != null && p.mExtras != null) { 4247 final PackageSetting ps = (PackageSetting) p.mExtras; 4248 final PermissionsState permissionsState = ps.getPermissionsState(); 4249 if (permissionsState.hasPermission(permName, userId)) { 4250 return PackageManager.PERMISSION_GRANTED; 4251 } 4252 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 4253 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 4254 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 4255 return PackageManager.PERMISSION_GRANTED; 4256 } 4257 } 4258 } 4259 4260 return PackageManager.PERMISSION_DENIED; 4261 } 4262 4263 @Override 4264 public int checkUidPermission(String permName, int uid) { 4265 final int userId = UserHandle.getUserId(uid); 4266 4267 if (!sUserManager.exists(userId)) { 4268 return PackageManager.PERMISSION_DENIED; 4269 } 4270 4271 synchronized (mPackages) { 4272 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4273 if (obj != null) { 4274 final SettingBase ps = (SettingBase) obj; 4275 final PermissionsState permissionsState = ps.getPermissionsState(); 4276 if (permissionsState.hasPermission(permName, userId)) { 4277 return PackageManager.PERMISSION_GRANTED; 4278 } 4279 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 4280 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 4281 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 4282 return PackageManager.PERMISSION_GRANTED; 4283 } 4284 } else { 4285 ArraySet<String> perms = mSystemPermissions.get(uid); 4286 if (perms != null) { 4287 if (perms.contains(permName)) { 4288 return PackageManager.PERMISSION_GRANTED; 4289 } 4290 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 4291 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 4292 return PackageManager.PERMISSION_GRANTED; 4293 } 4294 } 4295 } 4296 } 4297 4298 return PackageManager.PERMISSION_DENIED; 4299 } 4300 4301 @Override 4302 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 4303 if (UserHandle.getCallingUserId() != userId) { 4304 mContext.enforceCallingPermission( 4305 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4306 "isPermissionRevokedByPolicy for user " + userId); 4307 } 4308 4309 if (checkPermission(permission, packageName, userId) 4310 == PackageManager.PERMISSION_GRANTED) { 4311 return false; 4312 } 4313 4314 final long identity = Binder.clearCallingIdentity(); 4315 try { 4316 final int flags = getPermissionFlags(permission, packageName, userId); 4317 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 4318 } finally { 4319 Binder.restoreCallingIdentity(identity); 4320 } 4321 } 4322 4323 @Override 4324 public String getPermissionControllerPackageName() { 4325 synchronized (mPackages) { 4326 return mRequiredInstallerPackage; 4327 } 4328 } 4329 4330 /** 4331 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 4332 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 4333 * @param checkShell whether to prevent shell from access if there's a debugging restriction 4334 * @param message the message to log on security exception 4335 */ 4336 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 4337 boolean checkShell, String message) { 4338 if (userId < 0) { 4339 throw new IllegalArgumentException("Invalid userId " + userId); 4340 } 4341 if (checkShell) { 4342 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 4343 } 4344 if (userId == UserHandle.getUserId(callingUid)) return; 4345 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4346 if (requireFullPermission) { 4347 mContext.enforceCallingOrSelfPermission( 4348 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 4349 } else { 4350 try { 4351 mContext.enforceCallingOrSelfPermission( 4352 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 4353 } catch (SecurityException se) { 4354 mContext.enforceCallingOrSelfPermission( 4355 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 4356 } 4357 } 4358 } 4359 } 4360 4361 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 4362 if (callingUid == Process.SHELL_UID) { 4363 if (userHandle >= 0 4364 && sUserManager.hasUserRestriction(restriction, userHandle)) { 4365 throw new SecurityException("Shell does not have permission to access user " 4366 + userHandle); 4367 } else if (userHandle < 0) { 4368 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 4369 + Debug.getCallers(3)); 4370 } 4371 } 4372 } 4373 4374 private BasePermission findPermissionTreeLP(String permName) { 4375 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 4376 if (permName.startsWith(bp.name) && 4377 permName.length() > bp.name.length() && 4378 permName.charAt(bp.name.length()) == '.') { 4379 return bp; 4380 } 4381 } 4382 return null; 4383 } 4384 4385 private BasePermission checkPermissionTreeLP(String permName) { 4386 if (permName != null) { 4387 BasePermission bp = findPermissionTreeLP(permName); 4388 if (bp != null) { 4389 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 4390 return bp; 4391 } 4392 throw new SecurityException("Calling uid " 4393 + Binder.getCallingUid() 4394 + " is not allowed to add to permission tree " 4395 + bp.name + " owned by uid " + bp.uid); 4396 } 4397 } 4398 throw new SecurityException("No permission tree found for " + permName); 4399 } 4400 4401 static boolean compareStrings(CharSequence s1, CharSequence s2) { 4402 if (s1 == null) { 4403 return s2 == null; 4404 } 4405 if (s2 == null) { 4406 return false; 4407 } 4408 if (s1.getClass() != s2.getClass()) { 4409 return false; 4410 } 4411 return s1.equals(s2); 4412 } 4413 4414 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 4415 if (pi1.icon != pi2.icon) return false; 4416 if (pi1.logo != pi2.logo) return false; 4417 if (pi1.protectionLevel != pi2.protectionLevel) return false; 4418 if (!compareStrings(pi1.name, pi2.name)) return false; 4419 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 4420 // We'll take care of setting this one. 4421 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 4422 // These are not currently stored in settings. 4423 //if (!compareStrings(pi1.group, pi2.group)) return false; 4424 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 4425 //if (pi1.labelRes != pi2.labelRes) return false; 4426 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 4427 return true; 4428 } 4429 4430 int permissionInfoFootprint(PermissionInfo info) { 4431 int size = info.name.length(); 4432 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 4433 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 4434 return size; 4435 } 4436 4437 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 4438 int size = 0; 4439 for (BasePermission perm : mSettings.mPermissions.values()) { 4440 if (perm.uid == tree.uid) { 4441 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 4442 } 4443 } 4444 return size; 4445 } 4446 4447 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 4448 // We calculate the max size of permissions defined by this uid and throw 4449 // if that plus the size of 'info' would exceed our stated maximum. 4450 if (tree.uid != Process.SYSTEM_UID) { 4451 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 4452 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 4453 throw new SecurityException("Permission tree size cap exceeded"); 4454 } 4455 } 4456 } 4457 4458 boolean addPermissionLocked(PermissionInfo info, boolean async) { 4459 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 4460 throw new SecurityException("Label must be specified in permission"); 4461 } 4462 BasePermission tree = checkPermissionTreeLP(info.name); 4463 BasePermission bp = mSettings.mPermissions.get(info.name); 4464 boolean added = bp == null; 4465 boolean changed = true; 4466 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 4467 if (added) { 4468 enforcePermissionCapLocked(info, tree); 4469 bp = new BasePermission(info.name, tree.sourcePackage, 4470 BasePermission.TYPE_DYNAMIC); 4471 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 4472 throw new SecurityException( 4473 "Not allowed to modify non-dynamic permission " 4474 + info.name); 4475 } else { 4476 if (bp.protectionLevel == fixedLevel 4477 && bp.perm.owner.equals(tree.perm.owner) 4478 && bp.uid == tree.uid 4479 && comparePermissionInfos(bp.perm.info, info)) { 4480 changed = false; 4481 } 4482 } 4483 bp.protectionLevel = fixedLevel; 4484 info = new PermissionInfo(info); 4485 info.protectionLevel = fixedLevel; 4486 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 4487 bp.perm.info.packageName = tree.perm.info.packageName; 4488 bp.uid = tree.uid; 4489 if (added) { 4490 mSettings.mPermissions.put(info.name, bp); 4491 } 4492 if (changed) { 4493 if (!async) { 4494 mSettings.writeLPr(); 4495 } else { 4496 scheduleWriteSettingsLocked(); 4497 } 4498 } 4499 return added; 4500 } 4501 4502 @Override 4503 public boolean addPermission(PermissionInfo info) { 4504 synchronized (mPackages) { 4505 return addPermissionLocked(info, false); 4506 } 4507 } 4508 4509 @Override 4510 public boolean addPermissionAsync(PermissionInfo info) { 4511 synchronized (mPackages) { 4512 return addPermissionLocked(info, true); 4513 } 4514 } 4515 4516 @Override 4517 public void removePermission(String name) { 4518 synchronized (mPackages) { 4519 checkPermissionTreeLP(name); 4520 BasePermission bp = mSettings.mPermissions.get(name); 4521 if (bp != null) { 4522 if (bp.type != BasePermission.TYPE_DYNAMIC) { 4523 throw new SecurityException( 4524 "Not allowed to modify non-dynamic permission " 4525 + name); 4526 } 4527 mSettings.mPermissions.remove(name); 4528 mSettings.writeLPr(); 4529 } 4530 } 4531 } 4532 4533 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 4534 BasePermission bp) { 4535 int index = pkg.requestedPermissions.indexOf(bp.name); 4536 if (index == -1) { 4537 throw new SecurityException("Package " + pkg.packageName 4538 + " has not requested permission " + bp.name); 4539 } 4540 if (!bp.isRuntime() && !bp.isDevelopment()) { 4541 throw new SecurityException("Permission " + bp.name 4542 + " is not a changeable permission type"); 4543 } 4544 } 4545 4546 @Override 4547 public void grantRuntimePermission(String packageName, String name, final int userId) { 4548 grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */); 4549 } 4550 4551 private void grantRuntimePermission(String packageName, String name, final int userId, 4552 boolean overridePolicy) { 4553 if (!sUserManager.exists(userId)) { 4554 Log.e(TAG, "No such user:" + userId); 4555 return; 4556 } 4557 4558 mContext.enforceCallingOrSelfPermission( 4559 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 4560 "grantRuntimePermission"); 4561 4562 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4563 true /* requireFullPermission */, true /* checkShell */, 4564 "grantRuntimePermission"); 4565 4566 final int uid; 4567 final SettingBase sb; 4568 4569 synchronized (mPackages) { 4570 final PackageParser.Package pkg = mPackages.get(packageName); 4571 if (pkg == null) { 4572 throw new IllegalArgumentException("Unknown package: " + packageName); 4573 } 4574 4575 final BasePermission bp = mSettings.mPermissions.get(name); 4576 if (bp == null) { 4577 throw new IllegalArgumentException("Unknown permission: " + name); 4578 } 4579 4580 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4581 4582 // If a permission review is required for legacy apps we represent 4583 // their permissions as always granted runtime ones since we need 4584 // to keep the review required permission flag per user while an 4585 // install permission's state is shared across all users. 4586 if (mPermissionReviewRequired 4587 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4588 && bp.isRuntime()) { 4589 return; 4590 } 4591 4592 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 4593 sb = (SettingBase) pkg.mExtras; 4594 if (sb == null) { 4595 throw new IllegalArgumentException("Unknown package: " + packageName); 4596 } 4597 4598 final PermissionsState permissionsState = sb.getPermissionsState(); 4599 4600 final int flags = permissionsState.getPermissionFlags(name, userId); 4601 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4602 throw new SecurityException("Cannot grant system fixed permission " 4603 + name + " for package " + packageName); 4604 } 4605 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) { 4606 throw new SecurityException("Cannot grant policy fixed permission " 4607 + name + " for package " + packageName); 4608 } 4609 4610 if (bp.isDevelopment()) { 4611 // Development permissions must be handled specially, since they are not 4612 // normal runtime permissions. For now they apply to all users. 4613 if (permissionsState.grantInstallPermission(bp) != 4614 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4615 scheduleWriteSettingsLocked(); 4616 } 4617 return; 4618 } 4619 4620 if (pkg.applicationInfo.isEphemeralApp() && !bp.isEphemeral()) { 4621 throw new SecurityException("Cannot grant non-ephemeral permission" 4622 + name + " for package " + packageName); 4623 } 4624 4625 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4626 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4627 return; 4628 } 4629 4630 final int result = permissionsState.grantRuntimePermission(bp, userId); 4631 switch (result) { 4632 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4633 return; 4634 } 4635 4636 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4637 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4638 mHandler.post(new Runnable() { 4639 @Override 4640 public void run() { 4641 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4642 } 4643 }); 4644 } 4645 break; 4646 } 4647 4648 if (bp.isRuntime()) { 4649 logPermissionGranted(mContext, name, packageName); 4650 } 4651 4652 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4653 4654 // Not critical if that is lost - app has to request again. 4655 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4656 } 4657 4658 // Only need to do this if user is initialized. Otherwise it's a new user 4659 // and there are no processes running as the user yet and there's no need 4660 // to make an expensive call to remount processes for the changed permissions. 4661 if (READ_EXTERNAL_STORAGE.equals(name) 4662 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4663 final long token = Binder.clearCallingIdentity(); 4664 try { 4665 if (sUserManager.isInitialized(userId)) { 4666 StorageManagerInternal storageManagerInternal = LocalServices.getService( 4667 StorageManagerInternal.class); 4668 storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName); 4669 } 4670 } finally { 4671 Binder.restoreCallingIdentity(token); 4672 } 4673 } 4674 } 4675 4676 @Override 4677 public void revokeRuntimePermission(String packageName, String name, int userId) { 4678 revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */); 4679 } 4680 4681 private void revokeRuntimePermission(String packageName, String name, int userId, 4682 boolean overridePolicy) { 4683 if (!sUserManager.exists(userId)) { 4684 Log.e(TAG, "No such user:" + userId); 4685 return; 4686 } 4687 4688 mContext.enforceCallingOrSelfPermission( 4689 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4690 "revokeRuntimePermission"); 4691 4692 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4693 true /* requireFullPermission */, true /* checkShell */, 4694 "revokeRuntimePermission"); 4695 4696 final int appId; 4697 4698 synchronized (mPackages) { 4699 final PackageParser.Package pkg = mPackages.get(packageName); 4700 if (pkg == null) { 4701 throw new IllegalArgumentException("Unknown package: " + packageName); 4702 } 4703 4704 final BasePermission bp = mSettings.mPermissions.get(name); 4705 if (bp == null) { 4706 throw new IllegalArgumentException("Unknown permission: " + name); 4707 } 4708 4709 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4710 4711 // If a permission review is required for legacy apps we represent 4712 // their permissions as always granted runtime ones since we need 4713 // to keep the review required permission flag per user while an 4714 // install permission's state is shared across all users. 4715 if (mPermissionReviewRequired 4716 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4717 && bp.isRuntime()) { 4718 return; 4719 } 4720 4721 SettingBase sb = (SettingBase) pkg.mExtras; 4722 if (sb == null) { 4723 throw new IllegalArgumentException("Unknown package: " + packageName); 4724 } 4725 4726 final PermissionsState permissionsState = sb.getPermissionsState(); 4727 4728 final int flags = permissionsState.getPermissionFlags(name, userId); 4729 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4730 throw new SecurityException("Cannot revoke system fixed permission " 4731 + name + " for package " + packageName); 4732 } 4733 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) { 4734 throw new SecurityException("Cannot revoke policy fixed permission " 4735 + name + " for package " + packageName); 4736 } 4737 4738 if (bp.isDevelopment()) { 4739 // Development permissions must be handled specially, since they are not 4740 // normal runtime permissions. For now they apply to all users. 4741 if (permissionsState.revokeInstallPermission(bp) != 4742 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4743 scheduleWriteSettingsLocked(); 4744 } 4745 return; 4746 } 4747 4748 if (permissionsState.revokeRuntimePermission(bp, userId) == 4749 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4750 return; 4751 } 4752 4753 if (bp.isRuntime()) { 4754 logPermissionRevoked(mContext, name, packageName); 4755 } 4756 4757 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4758 4759 // Critical, after this call app should never have the permission. 4760 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4761 4762 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4763 } 4764 4765 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4766 } 4767 4768 /** 4769 * Get the first event id for the permission. 4770 * 4771 * <p>There are four events for each permission: <ul> 4772 * <li>Request permission: first id + 0</li> 4773 * <li>Grant permission: first id + 1</li> 4774 * <li>Request for permission denied: first id + 2</li> 4775 * <li>Revoke permission: first id + 3</li> 4776 * </ul></p> 4777 * 4778 * @param name name of the permission 4779 * 4780 * @return The first event id for the permission 4781 */ 4782 private static int getBaseEventId(@NonNull String name) { 4783 int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name); 4784 4785 if (eventIdIndex == -1) { 4786 if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE 4787 || "user".equals(Build.TYPE)) { 4788 Log.i(TAG, "Unknown permission " + name); 4789 4790 return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN; 4791 } else { 4792 // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated. 4793 // 4794 // Also update 4795 // - EventLogger#ALL_DANGEROUS_PERMISSIONS 4796 // - metrics_constants.proto 4797 throw new IllegalStateException("Unknown permission " + name); 4798 } 4799 } 4800 4801 return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4; 4802 } 4803 4804 /** 4805 * Log that a permission was revoked. 4806 * 4807 * @param context Context of the caller 4808 * @param name name of the permission 4809 * @param packageName package permission if for 4810 */ 4811 private static void logPermissionRevoked(@NonNull Context context, @NonNull String name, 4812 @NonNull String packageName) { 4813 MetricsLogger.action(context, getBaseEventId(name) + 3, packageName); 4814 } 4815 4816 /** 4817 * Log that a permission request was granted. 4818 * 4819 * @param context Context of the caller 4820 * @param name name of the permission 4821 * @param packageName package permission if for 4822 */ 4823 private static void logPermissionGranted(@NonNull Context context, @NonNull String name, 4824 @NonNull String packageName) { 4825 MetricsLogger.action(context, getBaseEventId(name) + 1, packageName); 4826 } 4827 4828 @Override 4829 public void resetRuntimePermissions() { 4830 mContext.enforceCallingOrSelfPermission( 4831 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4832 "revokeRuntimePermission"); 4833 4834 int callingUid = Binder.getCallingUid(); 4835 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4836 mContext.enforceCallingOrSelfPermission( 4837 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4838 "resetRuntimePermissions"); 4839 } 4840 4841 synchronized (mPackages) { 4842 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4843 for (int userId : UserManagerService.getInstance().getUserIds()) { 4844 final int packageCount = mPackages.size(); 4845 for (int i = 0; i < packageCount; i++) { 4846 PackageParser.Package pkg = mPackages.valueAt(i); 4847 if (!(pkg.mExtras instanceof PackageSetting)) { 4848 continue; 4849 } 4850 PackageSetting ps = (PackageSetting) pkg.mExtras; 4851 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4852 } 4853 } 4854 } 4855 } 4856 4857 @Override 4858 public int getPermissionFlags(String name, String packageName, int userId) { 4859 if (!sUserManager.exists(userId)) { 4860 return 0; 4861 } 4862 4863 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4864 4865 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4866 true /* requireFullPermission */, false /* checkShell */, 4867 "getPermissionFlags"); 4868 4869 synchronized (mPackages) { 4870 final PackageParser.Package pkg = mPackages.get(packageName); 4871 if (pkg == null) { 4872 return 0; 4873 } 4874 4875 final BasePermission bp = mSettings.mPermissions.get(name); 4876 if (bp == null) { 4877 return 0; 4878 } 4879 4880 SettingBase sb = (SettingBase) pkg.mExtras; 4881 if (sb == null) { 4882 return 0; 4883 } 4884 4885 PermissionsState permissionsState = sb.getPermissionsState(); 4886 return permissionsState.getPermissionFlags(name, userId); 4887 } 4888 } 4889 4890 @Override 4891 public void updatePermissionFlags(String name, String packageName, int flagMask, 4892 int flagValues, int userId) { 4893 if (!sUserManager.exists(userId)) { 4894 return; 4895 } 4896 4897 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4898 4899 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4900 true /* requireFullPermission */, true /* checkShell */, 4901 "updatePermissionFlags"); 4902 4903 // Only the system can change these flags and nothing else. 4904 if (getCallingUid() != Process.SYSTEM_UID) { 4905 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4906 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4907 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4908 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4909 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4910 } 4911 4912 synchronized (mPackages) { 4913 final PackageParser.Package pkg = mPackages.get(packageName); 4914 if (pkg == null) { 4915 throw new IllegalArgumentException("Unknown package: " + packageName); 4916 } 4917 4918 final BasePermission bp = mSettings.mPermissions.get(name); 4919 if (bp == null) { 4920 throw new IllegalArgumentException("Unknown permission: " + name); 4921 } 4922 4923 SettingBase sb = (SettingBase) pkg.mExtras; 4924 if (sb == null) { 4925 throw new IllegalArgumentException("Unknown package: " + packageName); 4926 } 4927 4928 PermissionsState permissionsState = sb.getPermissionsState(); 4929 4930 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4931 4932 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4933 // Install and runtime permissions are stored in different places, 4934 // so figure out what permission changed and persist the change. 4935 if (permissionsState.getInstallPermissionState(name) != null) { 4936 scheduleWriteSettingsLocked(); 4937 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4938 || hadState) { 4939 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4940 } 4941 } 4942 } 4943 } 4944 4945 /** 4946 * Update the permission flags for all packages and runtime permissions of a user in order 4947 * to allow device or profile owner to remove POLICY_FIXED. 4948 */ 4949 @Override 4950 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4951 if (!sUserManager.exists(userId)) { 4952 return; 4953 } 4954 4955 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4956 4957 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4958 true /* requireFullPermission */, true /* checkShell */, 4959 "updatePermissionFlagsForAllApps"); 4960 4961 // Only the system can change system fixed flags. 4962 if (getCallingUid() != Process.SYSTEM_UID) { 4963 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4964 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4965 } 4966 4967 synchronized (mPackages) { 4968 boolean changed = false; 4969 final int packageCount = mPackages.size(); 4970 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4971 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4972 SettingBase sb = (SettingBase) pkg.mExtras; 4973 if (sb == null) { 4974 continue; 4975 } 4976 PermissionsState permissionsState = sb.getPermissionsState(); 4977 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4978 userId, flagMask, flagValues); 4979 } 4980 if (changed) { 4981 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4982 } 4983 } 4984 } 4985 4986 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4987 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4988 != PackageManager.PERMISSION_GRANTED 4989 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4990 != PackageManager.PERMISSION_GRANTED) { 4991 throw new SecurityException(message + " requires " 4992 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4993 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4994 } 4995 } 4996 4997 @Override 4998 public boolean shouldShowRequestPermissionRationale(String permissionName, 4999 String packageName, int userId) { 5000 if (UserHandle.getCallingUserId() != userId) { 5001 mContext.enforceCallingPermission( 5002 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5003 "canShowRequestPermissionRationale for user " + userId); 5004 } 5005 5006 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 5007 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 5008 return false; 5009 } 5010 5011 if (checkPermission(permissionName, packageName, userId) 5012 == PackageManager.PERMISSION_GRANTED) { 5013 return false; 5014 } 5015 5016 final int flags; 5017 5018 final long identity = Binder.clearCallingIdentity(); 5019 try { 5020 flags = getPermissionFlags(permissionName, 5021 packageName, userId); 5022 } finally { 5023 Binder.restoreCallingIdentity(identity); 5024 } 5025 5026 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 5027 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 5028 | PackageManager.FLAG_PERMISSION_USER_FIXED; 5029 5030 if ((flags & fixedFlags) != 0) { 5031 return false; 5032 } 5033 5034 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 5035 } 5036 5037 @Override 5038 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 5039 mContext.enforceCallingOrSelfPermission( 5040 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 5041 "addOnPermissionsChangeListener"); 5042 5043 synchronized (mPackages) { 5044 mOnPermissionChangeListeners.addListenerLocked(listener); 5045 } 5046 } 5047 5048 @Override 5049 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 5050 synchronized (mPackages) { 5051 mOnPermissionChangeListeners.removeListenerLocked(listener); 5052 } 5053 } 5054 5055 @Override 5056 public boolean isProtectedBroadcast(String actionName) { 5057 synchronized (mPackages) { 5058 if (mProtectedBroadcasts.contains(actionName)) { 5059 return true; 5060 } else if (actionName != null) { 5061 // TODO: remove these terrible hacks 5062 if (actionName.startsWith("android.net.netmon.lingerExpired") 5063 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 5064 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 5065 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 5066 return true; 5067 } 5068 } 5069 } 5070 return false; 5071 } 5072 5073 @Override 5074 public int checkSignatures(String pkg1, String pkg2) { 5075 synchronized (mPackages) { 5076 final PackageParser.Package p1 = mPackages.get(pkg1); 5077 final PackageParser.Package p2 = mPackages.get(pkg2); 5078 if (p1 == null || p1.mExtras == null 5079 || p2 == null || p2.mExtras == null) { 5080 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5081 } 5082 return compareSignatures(p1.mSignatures, p2.mSignatures); 5083 } 5084 } 5085 5086 @Override 5087 public int checkUidSignatures(int uid1, int uid2) { 5088 // Map to base uids. 5089 uid1 = UserHandle.getAppId(uid1); 5090 uid2 = UserHandle.getAppId(uid2); 5091 // reader 5092 synchronized (mPackages) { 5093 Signature[] s1; 5094 Signature[] s2; 5095 Object obj = mSettings.getUserIdLPr(uid1); 5096 if (obj != null) { 5097 if (obj instanceof SharedUserSetting) { 5098 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 5099 } else if (obj instanceof PackageSetting) { 5100 s1 = ((PackageSetting)obj).signatures.mSignatures; 5101 } else { 5102 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5103 } 5104 } else { 5105 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5106 } 5107 obj = mSettings.getUserIdLPr(uid2); 5108 if (obj != null) { 5109 if (obj instanceof SharedUserSetting) { 5110 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 5111 } else if (obj instanceof PackageSetting) { 5112 s2 = ((PackageSetting)obj).signatures.mSignatures; 5113 } else { 5114 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5115 } 5116 } else { 5117 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5118 } 5119 return compareSignatures(s1, s2); 5120 } 5121 } 5122 5123 /** 5124 * This method should typically only be used when granting or revoking 5125 * permissions, since the app may immediately restart after this call. 5126 * <p> 5127 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 5128 * guard your work against the app being relaunched. 5129 */ 5130 private void killUid(int appId, int userId, String reason) { 5131 final long identity = Binder.clearCallingIdentity(); 5132 try { 5133 IActivityManager am = ActivityManager.getService(); 5134 if (am != null) { 5135 try { 5136 am.killUid(appId, userId, reason); 5137 } catch (RemoteException e) { 5138 /* ignore - same process */ 5139 } 5140 } 5141 } finally { 5142 Binder.restoreCallingIdentity(identity); 5143 } 5144 } 5145 5146 /** 5147 * Compares two sets of signatures. Returns: 5148 * <br /> 5149 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 5150 * <br /> 5151 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 5152 * <br /> 5153 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 5154 * <br /> 5155 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 5156 * <br /> 5157 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 5158 */ 5159 static int compareSignatures(Signature[] s1, Signature[] s2) { 5160 if (s1 == null) { 5161 return s2 == null 5162 ? PackageManager.SIGNATURE_NEITHER_SIGNED 5163 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 5164 } 5165 5166 if (s2 == null) { 5167 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 5168 } 5169 5170 if (s1.length != s2.length) { 5171 return PackageManager.SIGNATURE_NO_MATCH; 5172 } 5173 5174 // Since both signature sets are of size 1, we can compare without HashSets. 5175 if (s1.length == 1) { 5176 return s1[0].equals(s2[0]) ? 5177 PackageManager.SIGNATURE_MATCH : 5178 PackageManager.SIGNATURE_NO_MATCH; 5179 } 5180 5181 ArraySet<Signature> set1 = new ArraySet<Signature>(); 5182 for (Signature sig : s1) { 5183 set1.add(sig); 5184 } 5185 ArraySet<Signature> set2 = new ArraySet<Signature>(); 5186 for (Signature sig : s2) { 5187 set2.add(sig); 5188 } 5189 // Make sure s2 contains all signatures in s1. 5190 if (set1.equals(set2)) { 5191 return PackageManager.SIGNATURE_MATCH; 5192 } 5193 return PackageManager.SIGNATURE_NO_MATCH; 5194 } 5195 5196 /** 5197 * If the database version for this type of package (internal storage or 5198 * external storage) is less than the version where package signatures 5199 * were updated, return true. 5200 */ 5201 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 5202 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 5203 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 5204 } 5205 5206 /** 5207 * Used for backward compatibility to make sure any packages with 5208 * certificate chains get upgraded to the new style. {@code existingSigs} 5209 * will be in the old format (since they were stored on disk from before the 5210 * system upgrade) and {@code scannedSigs} will be in the newer format. 5211 */ 5212 private int compareSignaturesCompat(PackageSignatures existingSigs, 5213 PackageParser.Package scannedPkg) { 5214 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 5215 return PackageManager.SIGNATURE_NO_MATCH; 5216 } 5217 5218 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 5219 for (Signature sig : existingSigs.mSignatures) { 5220 existingSet.add(sig); 5221 } 5222 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 5223 for (Signature sig : scannedPkg.mSignatures) { 5224 try { 5225 Signature[] chainSignatures = sig.getChainSignatures(); 5226 for (Signature chainSig : chainSignatures) { 5227 scannedCompatSet.add(chainSig); 5228 } 5229 } catch (CertificateEncodingException e) { 5230 scannedCompatSet.add(sig); 5231 } 5232 } 5233 /* 5234 * Make sure the expanded scanned set contains all signatures in the 5235 * existing one. 5236 */ 5237 if (scannedCompatSet.equals(existingSet)) { 5238 // Migrate the old signatures to the new scheme. 5239 existingSigs.assignSignatures(scannedPkg.mSignatures); 5240 // The new KeySets will be re-added later in the scanning process. 5241 synchronized (mPackages) { 5242 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 5243 } 5244 return PackageManager.SIGNATURE_MATCH; 5245 } 5246 return PackageManager.SIGNATURE_NO_MATCH; 5247 } 5248 5249 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 5250 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 5251 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 5252 } 5253 5254 private int compareSignaturesRecover(PackageSignatures existingSigs, 5255 PackageParser.Package scannedPkg) { 5256 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 5257 return PackageManager.SIGNATURE_NO_MATCH; 5258 } 5259 5260 String msg = null; 5261 try { 5262 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 5263 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 5264 + scannedPkg.packageName); 5265 return PackageManager.SIGNATURE_MATCH; 5266 } 5267 } catch (CertificateException e) { 5268 msg = e.getMessage(); 5269 } 5270 5271 logCriticalInfo(Log.INFO, 5272 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 5273 return PackageManager.SIGNATURE_NO_MATCH; 5274 } 5275 5276 @Override 5277 public List<String> getAllPackages() { 5278 synchronized (mPackages) { 5279 return new ArrayList<String>(mPackages.keySet()); 5280 } 5281 } 5282 5283 @Override 5284 public String[] getPackagesForUid(int uid) { 5285 final int userId = UserHandle.getUserId(uid); 5286 uid = UserHandle.getAppId(uid); 5287 // reader 5288 synchronized (mPackages) { 5289 Object obj = mSettings.getUserIdLPr(uid); 5290 if (obj instanceof SharedUserSetting) { 5291 final SharedUserSetting sus = (SharedUserSetting) obj; 5292 final int N = sus.packages.size(); 5293 String[] res = new String[N]; 5294 final Iterator<PackageSetting> it = sus.packages.iterator(); 5295 int i = 0; 5296 while (it.hasNext()) { 5297 PackageSetting ps = it.next(); 5298 if (ps.getInstalled(userId)) { 5299 res[i++] = ps.name; 5300 } else { 5301 res = ArrayUtils.removeElement(String.class, res, res[i]); 5302 } 5303 } 5304 return res; 5305 } else if (obj instanceof PackageSetting) { 5306 final PackageSetting ps = (PackageSetting) obj; 5307 if (ps.getInstalled(userId)) { 5308 return new String[]{ps.name}; 5309 } 5310 } 5311 } 5312 return null; 5313 } 5314 5315 @Override 5316 public String getNameForUid(int uid) { 5317 // reader 5318 synchronized (mPackages) { 5319 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5320 if (obj instanceof SharedUserSetting) { 5321 final SharedUserSetting sus = (SharedUserSetting) obj; 5322 return sus.name + ":" + sus.userId; 5323 } else if (obj instanceof PackageSetting) { 5324 final PackageSetting ps = (PackageSetting) obj; 5325 return ps.name; 5326 } 5327 } 5328 return null; 5329 } 5330 5331 @Override 5332 public int getUidForSharedUser(String sharedUserName) { 5333 if(sharedUserName == null) { 5334 return -1; 5335 } 5336 // reader 5337 synchronized (mPackages) { 5338 SharedUserSetting suid; 5339 try { 5340 suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 5341 if (suid != null) { 5342 return suid.userId; 5343 } 5344 } catch (PackageManagerException ignore) { 5345 // can't happen, but, still need to catch it 5346 } 5347 return -1; 5348 } 5349 } 5350 5351 @Override 5352 public int getFlagsForUid(int uid) { 5353 synchronized (mPackages) { 5354 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5355 if (obj instanceof SharedUserSetting) { 5356 final SharedUserSetting sus = (SharedUserSetting) obj; 5357 return sus.pkgFlags; 5358 } else if (obj instanceof PackageSetting) { 5359 final PackageSetting ps = (PackageSetting) obj; 5360 return ps.pkgFlags; 5361 } 5362 } 5363 return 0; 5364 } 5365 5366 @Override 5367 public int getPrivateFlagsForUid(int uid) { 5368 synchronized (mPackages) { 5369 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5370 if (obj instanceof SharedUserSetting) { 5371 final SharedUserSetting sus = (SharedUserSetting) obj; 5372 return sus.pkgPrivateFlags; 5373 } else if (obj instanceof PackageSetting) { 5374 final PackageSetting ps = (PackageSetting) obj; 5375 return ps.pkgPrivateFlags; 5376 } 5377 } 5378 return 0; 5379 } 5380 5381 @Override 5382 public boolean isUidPrivileged(int uid) { 5383 uid = UserHandle.getAppId(uid); 5384 // reader 5385 synchronized (mPackages) { 5386 Object obj = mSettings.getUserIdLPr(uid); 5387 if (obj instanceof SharedUserSetting) { 5388 final SharedUserSetting sus = (SharedUserSetting) obj; 5389 final Iterator<PackageSetting> it = sus.packages.iterator(); 5390 while (it.hasNext()) { 5391 if (it.next().isPrivileged()) { 5392 return true; 5393 } 5394 } 5395 } else if (obj instanceof PackageSetting) { 5396 final PackageSetting ps = (PackageSetting) obj; 5397 return ps.isPrivileged(); 5398 } 5399 } 5400 return false; 5401 } 5402 5403 @Override 5404 public String[] getAppOpPermissionPackages(String permissionName) { 5405 synchronized (mPackages) { 5406 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 5407 if (pkgs == null) { 5408 return null; 5409 } 5410 return pkgs.toArray(new String[pkgs.size()]); 5411 } 5412 } 5413 5414 @Override 5415 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 5416 int flags, int userId) { 5417 try { 5418 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 5419 5420 if (!sUserManager.exists(userId)) return null; 5421 flags = updateFlagsForResolve(flags, userId, intent); 5422 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5423 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 5424 5425 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5426 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 5427 flags, userId); 5428 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5429 5430 final ResolveInfo bestChoice = 5431 chooseBestActivity(intent, resolvedType, flags, query, userId); 5432 return bestChoice; 5433 } finally { 5434 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5435 } 5436 } 5437 5438 @Override 5439 public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) { 5440 if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) { 5441 throw new SecurityException( 5442 "findPersistentPreferredActivity can only be run by the system"); 5443 } 5444 if (!sUserManager.exists(userId)) { 5445 return null; 5446 } 5447 intent = updateIntentForResolve(intent); 5448 final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver()); 5449 final int flags = updateFlagsForResolve(0, userId, intent); 5450 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5451 userId); 5452 synchronized (mPackages) { 5453 return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false, 5454 userId); 5455 } 5456 } 5457 5458 @Override 5459 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 5460 IntentFilter filter, int match, ComponentName activity) { 5461 final int userId = UserHandle.getCallingUserId(); 5462 if (DEBUG_PREFERRED) { 5463 Log.v(TAG, "setLastChosenActivity intent=" + intent 5464 + " resolvedType=" + resolvedType 5465 + " flags=" + flags 5466 + " filter=" + filter 5467 + " match=" + match 5468 + " activity=" + activity); 5469 filter.dump(new PrintStreamPrinter(System.out), " "); 5470 } 5471 intent.setComponent(null); 5472 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5473 userId); 5474 // Find any earlier preferred or last chosen entries and nuke them 5475 findPreferredActivity(intent, resolvedType, 5476 flags, query, 0, false, true, false, userId); 5477 // Add the new activity as the last chosen for this filter 5478 addPreferredActivityInternal(filter, match, null, activity, false, userId, 5479 "Setting last chosen"); 5480 } 5481 5482 @Override 5483 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 5484 final int userId = UserHandle.getCallingUserId(); 5485 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 5486 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5487 userId); 5488 return findPreferredActivity(intent, resolvedType, flags, query, 0, 5489 false, false, false, userId); 5490 } 5491 5492 private boolean isEphemeralDisabled() { 5493 // ephemeral apps have been disabled across the board 5494 if (DISABLE_EPHEMERAL_APPS) { 5495 return true; 5496 } 5497 // system isn't up yet; can't read settings, so, assume no ephemeral apps 5498 if (!mSystemReady) { 5499 return true; 5500 } 5501 // we can't get a content resolver until the system is ready; these checks must happen last 5502 final ContentResolver resolver = mContext.getContentResolver(); 5503 if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) { 5504 return true; 5505 } 5506 return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0; 5507 } 5508 5509 private boolean isEphemeralAllowed( 5510 Intent intent, List<ResolveInfo> resolvedActivities, int userId, 5511 boolean skipPackageCheck) { 5512 // Short circuit and return early if possible. 5513 if (isEphemeralDisabled()) { 5514 return false; 5515 } 5516 final int callingUser = UserHandle.getCallingUserId(); 5517 if (callingUser != UserHandle.USER_SYSTEM) { 5518 return false; 5519 } 5520 if (mEphemeralResolverConnection == null) { 5521 return false; 5522 } 5523 if (mEphemeralInstallerComponent == null) { 5524 return false; 5525 } 5526 if (intent.getComponent() != null) { 5527 return false; 5528 } 5529 if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) { 5530 return false; 5531 } 5532 if (!skipPackageCheck && intent.getPackage() != null) { 5533 return false; 5534 } 5535 final boolean isWebUri = hasWebURI(intent); 5536 if (!isWebUri || intent.getData().getHost() == null) { 5537 return false; 5538 } 5539 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 5540 synchronized (mPackages) { 5541 final int count = (resolvedActivities == null ? 0 : resolvedActivities.size()); 5542 for (int n = 0; n < count; n++) { 5543 ResolveInfo info = resolvedActivities.get(n); 5544 String packageName = info.activityInfo.packageName; 5545 PackageSetting ps = mSettings.mPackages.get(packageName); 5546 if (ps != null) { 5547 // Try to get the status from User settings first 5548 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5549 int status = (int) (packedStatus >> 32); 5550 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 5551 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5552 if (DEBUG_EPHEMERAL) { 5553 Slog.v(TAG, "DENY ephemeral apps;" 5554 + " pkg: " + packageName + ", status: " + status); 5555 } 5556 return false; 5557 } 5558 } 5559 } 5560 } 5561 // We've exhausted all ways to deny ephemeral application; let the system look for them. 5562 return true; 5563 } 5564 5565 private void requestEphemeralResolutionPhaseTwo(EphemeralResponse responseObj, 5566 Intent origIntent, String resolvedType, Intent launchIntent, String callingPackage, 5567 int userId) { 5568 final Message msg = mHandler.obtainMessage(EPHEMERAL_RESOLUTION_PHASE_TWO, 5569 new EphemeralRequest(responseObj, origIntent, resolvedType, launchIntent, 5570 callingPackage, userId)); 5571 mHandler.sendMessage(msg); 5572 } 5573 5574 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 5575 int flags, List<ResolveInfo> query, int userId) { 5576 if (query != null) { 5577 final int N = query.size(); 5578 if (N == 1) { 5579 return query.get(0); 5580 } else if (N > 1) { 5581 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 5582 // If there is more than one activity with the same priority, 5583 // then let the user decide between them. 5584 ResolveInfo r0 = query.get(0); 5585 ResolveInfo r1 = query.get(1); 5586 if (DEBUG_INTENT_MATCHING || debug) { 5587 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 5588 + r1.activityInfo.name + "=" + r1.priority); 5589 } 5590 // If the first activity has a higher priority, or a different 5591 // default, then it is always desirable to pick it. 5592 if (r0.priority != r1.priority 5593 || r0.preferredOrder != r1.preferredOrder 5594 || r0.isDefault != r1.isDefault) { 5595 return query.get(0); 5596 } 5597 // If we have saved a preference for a preferred activity for 5598 // this Intent, use that. 5599 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 5600 flags, query, r0.priority, true, false, debug, userId); 5601 if (ri != null) { 5602 return ri; 5603 } 5604 ri = new ResolveInfo(mResolveInfo); 5605 ri.activityInfo = new ActivityInfo(ri.activityInfo); 5606 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 5607 // If all of the options come from the same package, show the application's 5608 // label and icon instead of the generic resolver's. 5609 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 5610 // and then throw away the ResolveInfo itself, meaning that the caller loses 5611 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 5612 // a fallback for this case; we only set the target package's resources on 5613 // the ResolveInfo, not the ActivityInfo. 5614 final String intentPackage = intent.getPackage(); 5615 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 5616 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 5617 ri.resolvePackageName = intentPackage; 5618 if (userNeedsBadging(userId)) { 5619 ri.noResourceId = true; 5620 } else { 5621 ri.icon = appi.icon; 5622 } 5623 ri.iconResourceId = appi.icon; 5624 ri.labelRes = appi.labelRes; 5625 } 5626 ri.activityInfo.applicationInfo = new ApplicationInfo( 5627 ri.activityInfo.applicationInfo); 5628 if (userId != 0) { 5629 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 5630 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 5631 } 5632 // Make sure that the resolver is displayable in car mode 5633 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 5634 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 5635 return ri; 5636 } 5637 } 5638 return null; 5639 } 5640 5641 /** 5642 * Return true if the given list is not empty and all of its contents have 5643 * an activityInfo with the given package name. 5644 */ 5645 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 5646 if (ArrayUtils.isEmpty(list)) { 5647 return false; 5648 } 5649 for (int i = 0, N = list.size(); i < N; i++) { 5650 final ResolveInfo ri = list.get(i); 5651 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 5652 if (ai == null || !packageName.equals(ai.packageName)) { 5653 return false; 5654 } 5655 } 5656 return true; 5657 } 5658 5659 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 5660 int flags, List<ResolveInfo> query, boolean debug, int userId) { 5661 final int N = query.size(); 5662 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 5663 .get(userId); 5664 // Get the list of persistent preferred activities that handle the intent 5665 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 5666 List<PersistentPreferredActivity> pprefs = ppir != null 5667 ? ppir.queryIntent(intent, resolvedType, 5668 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 5669 (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0, 5670 (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId) 5671 : null; 5672 if (pprefs != null && pprefs.size() > 0) { 5673 final int M = pprefs.size(); 5674 for (int i=0; i<M; i++) { 5675 final PersistentPreferredActivity ppa = pprefs.get(i); 5676 if (DEBUG_PREFERRED || debug) { 5677 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 5678 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 5679 + "\n component=" + ppa.mComponent); 5680 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5681 } 5682 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 5683 flags | MATCH_DISABLED_COMPONENTS, userId); 5684 if (DEBUG_PREFERRED || debug) { 5685 Slog.v(TAG, "Found persistent preferred activity:"); 5686 if (ai != null) { 5687 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5688 } else { 5689 Slog.v(TAG, " null"); 5690 } 5691 } 5692 if (ai == null) { 5693 // This previously registered persistent preferred activity 5694 // component is no longer known. Ignore it and do NOT remove it. 5695 continue; 5696 } 5697 for (int j=0; j<N; j++) { 5698 final ResolveInfo ri = query.get(j); 5699 if (!ri.activityInfo.applicationInfo.packageName 5700 .equals(ai.applicationInfo.packageName)) { 5701 continue; 5702 } 5703 if (!ri.activityInfo.name.equals(ai.name)) { 5704 continue; 5705 } 5706 // Found a persistent preference that can handle the intent. 5707 if (DEBUG_PREFERRED || debug) { 5708 Slog.v(TAG, "Returning persistent preferred activity: " + 5709 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5710 } 5711 return ri; 5712 } 5713 } 5714 } 5715 return null; 5716 } 5717 5718 // TODO: handle preferred activities missing while user has amnesia 5719 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5720 List<ResolveInfo> query, int priority, boolean always, 5721 boolean removeMatches, boolean debug, int userId) { 5722 if (!sUserManager.exists(userId)) return null; 5723 flags = updateFlagsForResolve(flags, userId, intent); 5724 intent = updateIntentForResolve(intent); 5725 // writer 5726 synchronized (mPackages) { 5727 // Try to find a matching persistent preferred activity. 5728 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5729 debug, userId); 5730 5731 // If a persistent preferred activity matched, use it. 5732 if (pri != null) { 5733 return pri; 5734 } 5735 5736 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5737 // Get the list of preferred activities that handle the intent 5738 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5739 List<PreferredActivity> prefs = pir != null 5740 ? pir.queryIntent(intent, resolvedType, 5741 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 5742 (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0, 5743 (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId) 5744 : null; 5745 if (prefs != null && prefs.size() > 0) { 5746 boolean changed = false; 5747 try { 5748 // First figure out how good the original match set is. 5749 // We will only allow preferred activities that came 5750 // from the same match quality. 5751 int match = 0; 5752 5753 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5754 5755 final int N = query.size(); 5756 for (int j=0; j<N; j++) { 5757 final ResolveInfo ri = query.get(j); 5758 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5759 + ": 0x" + Integer.toHexString(match)); 5760 if (ri.match > match) { 5761 match = ri.match; 5762 } 5763 } 5764 5765 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5766 + Integer.toHexString(match)); 5767 5768 match &= IntentFilter.MATCH_CATEGORY_MASK; 5769 final int M = prefs.size(); 5770 for (int i=0; i<M; i++) { 5771 final PreferredActivity pa = prefs.get(i); 5772 if (DEBUG_PREFERRED || debug) { 5773 Slog.v(TAG, "Checking PreferredActivity ds=" 5774 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5775 + "\n component=" + pa.mPref.mComponent); 5776 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5777 } 5778 if (pa.mPref.mMatch != match) { 5779 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5780 + Integer.toHexString(pa.mPref.mMatch)); 5781 continue; 5782 } 5783 // If it's not an "always" type preferred activity and that's what we're 5784 // looking for, skip it. 5785 if (always && !pa.mPref.mAlways) { 5786 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5787 continue; 5788 } 5789 final ActivityInfo ai = getActivityInfo( 5790 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5791 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5792 userId); 5793 if (DEBUG_PREFERRED || debug) { 5794 Slog.v(TAG, "Found preferred activity:"); 5795 if (ai != null) { 5796 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5797 } else { 5798 Slog.v(TAG, " null"); 5799 } 5800 } 5801 if (ai == null) { 5802 // This previously registered preferred activity 5803 // component is no longer known. Most likely an update 5804 // to the app was installed and in the new version this 5805 // component no longer exists. Clean it up by removing 5806 // it from the preferred activities list, and skip it. 5807 Slog.w(TAG, "Removing dangling preferred activity: " 5808 + pa.mPref.mComponent); 5809 pir.removeFilter(pa); 5810 changed = true; 5811 continue; 5812 } 5813 for (int j=0; j<N; j++) { 5814 final ResolveInfo ri = query.get(j); 5815 if (!ri.activityInfo.applicationInfo.packageName 5816 .equals(ai.applicationInfo.packageName)) { 5817 continue; 5818 } 5819 if (!ri.activityInfo.name.equals(ai.name)) { 5820 continue; 5821 } 5822 5823 if (removeMatches) { 5824 pir.removeFilter(pa); 5825 changed = true; 5826 if (DEBUG_PREFERRED) { 5827 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 5828 } 5829 break; 5830 } 5831 5832 // Okay we found a previously set preferred or last chosen app. 5833 // If the result set is different from when this 5834 // was created, we need to clear it and re-ask the 5835 // user their preference, if we're looking for an "always" type entry. 5836 if (always && !pa.mPref.sameSet(query)) { 5837 Slog.i(TAG, "Result set changed, dropping preferred activity for " 5838 + intent + " type " + resolvedType); 5839 if (DEBUG_PREFERRED) { 5840 Slog.v(TAG, "Removing preferred activity since set changed " 5841 + pa.mPref.mComponent); 5842 } 5843 pir.removeFilter(pa); 5844 // Re-add the filter as a "last chosen" entry (!always) 5845 PreferredActivity lastChosen = new PreferredActivity( 5846 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 5847 pir.addFilter(lastChosen); 5848 changed = true; 5849 return null; 5850 } 5851 5852 // Yay! Either the set matched or we're looking for the last chosen 5853 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 5854 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5855 return ri; 5856 } 5857 } 5858 } finally { 5859 if (changed) { 5860 if (DEBUG_PREFERRED) { 5861 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 5862 } 5863 scheduleWritePackageRestrictionsLocked(userId); 5864 } 5865 } 5866 } 5867 } 5868 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 5869 return null; 5870 } 5871 5872 /* 5873 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 5874 */ 5875 @Override 5876 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 5877 int targetUserId) { 5878 mContext.enforceCallingOrSelfPermission( 5879 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 5880 List<CrossProfileIntentFilter> matches = 5881 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 5882 if (matches != null) { 5883 int size = matches.size(); 5884 for (int i = 0; i < size; i++) { 5885 if (matches.get(i).getTargetUserId() == targetUserId) return true; 5886 } 5887 } 5888 if (hasWebURI(intent)) { 5889 // cross-profile app linking works only towards the parent. 5890 final UserInfo parent = getProfileParent(sourceUserId); 5891 synchronized(mPackages) { 5892 int flags = updateFlagsForResolve(0, parent.id, intent); 5893 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5894 intent, resolvedType, flags, sourceUserId, parent.id); 5895 return xpDomainInfo != null; 5896 } 5897 } 5898 return false; 5899 } 5900 5901 private UserInfo getProfileParent(int userId) { 5902 final long identity = Binder.clearCallingIdentity(); 5903 try { 5904 return sUserManager.getProfileParent(userId); 5905 } finally { 5906 Binder.restoreCallingIdentity(identity); 5907 } 5908 } 5909 5910 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5911 String resolvedType, int userId) { 5912 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5913 if (resolver != null) { 5914 return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, 5915 false /*visibleToEphemeral*/, false /*isEphemeral*/, userId); 5916 } 5917 return null; 5918 } 5919 5920 @Override 5921 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 5922 String resolvedType, int flags, int userId) { 5923 try { 5924 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5925 5926 return new ParceledListSlice<>( 5927 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 5928 } finally { 5929 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5930 } 5931 } 5932 5933 /** 5934 * Returns the package name of the calling Uid if it's an ephemeral app. If it isn't 5935 * ephemeral, returns {@code null}. 5936 */ 5937 private String getEphemeralPackageName(int callingUid) { 5938 final int appId = UserHandle.getAppId(callingUid); 5939 synchronized (mPackages) { 5940 final Object obj = mSettings.getUserIdLPr(appId); 5941 if (obj instanceof PackageSetting) { 5942 final PackageSetting ps = (PackageSetting) obj; 5943 return ps.pkg.applicationInfo.isEphemeralApp() ? ps.pkg.packageName : null; 5944 } 5945 } 5946 return null; 5947 } 5948 5949 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 5950 String resolvedType, int flags, int userId) { 5951 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5952 final String ephemeralPkgName = getEphemeralPackageName(Binder.getCallingUid()); 5953 flags = updateFlagsForResolve(flags, userId, intent); 5954 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5955 false /* requireFullPermission */, false /* checkShell */, 5956 "query intent activities"); 5957 ComponentName comp = intent.getComponent(); 5958 if (comp == null) { 5959 if (intent.getSelector() != null) { 5960 intent = intent.getSelector(); 5961 comp = intent.getComponent(); 5962 } 5963 } 5964 5965 if (comp != null) { 5966 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5967 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5968 if (ai != null) { 5969 // When specifying an explicit component, we prevent the activity from being 5970 // used when either 1) the calling package is normal and the activity is within 5971 // an ephemeral application or 2) the calling package is ephemeral and the 5972 // activity is not visible to ephemeral applications. 5973 boolean matchEphemeral = 5974 (flags & PackageManager.MATCH_EPHEMERAL) != 0; 5975 boolean ephemeralVisibleOnly = 5976 (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0; 5977 boolean blockResolution = 5978 (!matchEphemeral && ephemeralPkgName == null 5979 && (ai.applicationInfo.privateFlags 5980 & ApplicationInfo.PRIVATE_FLAG_EPHEMERAL) != 0) 5981 || (ephemeralVisibleOnly && ephemeralPkgName != null 5982 && (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0); 5983 if (!blockResolution) { 5984 final ResolveInfo ri = new ResolveInfo(); 5985 ri.activityInfo = ai; 5986 list.add(ri); 5987 } 5988 } 5989 return list; 5990 } 5991 5992 // reader 5993 boolean sortResult = false; 5994 boolean addEphemeral = false; 5995 List<ResolveInfo> result; 5996 final String pkgName = intent.getPackage(); 5997 synchronized (mPackages) { 5998 if (pkgName == null) { 5999 List<CrossProfileIntentFilter> matchingFilters = 6000 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 6001 // Check for results that need to skip the current profile. 6002 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 6003 resolvedType, flags, userId); 6004 if (xpResolveInfo != null) { 6005 List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1); 6006 xpResult.add(xpResolveInfo); 6007 return filterForEphemeral( 6008 filterIfNotSystemUser(xpResult, userId), ephemeralPkgName); 6009 } 6010 6011 // Check for results in the current profile. 6012 result = filterIfNotSystemUser(mActivities.queryIntent( 6013 intent, resolvedType, flags, userId), userId); 6014 addEphemeral = 6015 isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/); 6016 6017 // Check for cross profile results. 6018 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 6019 xpResolveInfo = queryCrossProfileIntents( 6020 matchingFilters, intent, resolvedType, flags, userId, 6021 hasNonNegativePriorityResult); 6022 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 6023 boolean isVisibleToUser = filterIfNotSystemUser( 6024 Collections.singletonList(xpResolveInfo), userId).size() > 0; 6025 if (isVisibleToUser) { 6026 result.add(xpResolveInfo); 6027 sortResult = true; 6028 } 6029 } 6030 if (hasWebURI(intent)) { 6031 CrossProfileDomainInfo xpDomainInfo = null; 6032 final UserInfo parent = getProfileParent(userId); 6033 if (parent != null) { 6034 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 6035 flags, userId, parent.id); 6036 } 6037 if (xpDomainInfo != null) { 6038 if (xpResolveInfo != null) { 6039 // If we didn't remove it, the cross-profile ResolveInfo would be twice 6040 // in the result. 6041 result.remove(xpResolveInfo); 6042 } 6043 if (result.size() == 0 && !addEphemeral) { 6044 // No result in current profile, but found candidate in parent user. 6045 // And we are not going to add emphemeral app, so we can return the 6046 // result straight away. 6047 result.add(xpDomainInfo.resolveInfo); 6048 return filterForEphemeral(result, ephemeralPkgName); 6049 } 6050 } else if (result.size() <= 1 && !addEphemeral) { 6051 // No result in parent user and <= 1 result in current profile, and we 6052 // are not going to add emphemeral app, so we can return the result without 6053 // further processing. 6054 return filterForEphemeral(result, ephemeralPkgName); 6055 } 6056 // We have more than one candidate (combining results from current and parent 6057 // profile), so we need filtering and sorting. 6058 result = filterCandidatesWithDomainPreferredActivitiesLPr( 6059 intent, flags, result, xpDomainInfo, userId); 6060 sortResult = true; 6061 } 6062 } else { 6063 final PackageParser.Package pkg = mPackages.get(pkgName); 6064 if (pkg != null) { 6065 result = filterForEphemeral(filterIfNotSystemUser( 6066 mActivities.queryIntentForPackage( 6067 intent, resolvedType, flags, pkg.activities, userId), 6068 userId), ephemeralPkgName); 6069 } else { 6070 // the caller wants to resolve for a particular package; however, there 6071 // were no installed results, so, try to find an ephemeral result 6072 addEphemeral = isEphemeralAllowed( 6073 intent, null /*result*/, userId, true /*skipPackageCheck*/); 6074 result = new ArrayList<ResolveInfo>(); 6075 } 6076 } 6077 } 6078 if (addEphemeral) { 6079 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 6080 final EphemeralRequest requestObject = new EphemeralRequest( 6081 null /*responseObj*/, intent /*origIntent*/, resolvedType, 6082 null /*launchIntent*/, null /*callingPackage*/, userId); 6083 final EphemeralResponse intentInfo = EphemeralResolver.doEphemeralResolutionPhaseOne( 6084 mContext, mEphemeralResolverConnection, requestObject); 6085 if (intentInfo != null) { 6086 if (DEBUG_EPHEMERAL) { 6087 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 6088 } 6089 final ResolveInfo ephemeralInstaller = new ResolveInfo(mEphemeralInstallerInfo); 6090 ephemeralInstaller.ephemeralResponse = intentInfo; 6091 // make sure this resolver is the default 6092 ephemeralInstaller.isDefault = true; 6093 ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 6094 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 6095 // add a non-generic filter 6096 ephemeralInstaller.filter = new IntentFilter(intent.getAction()); 6097 ephemeralInstaller.filter.addDataPath( 6098 intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL); 6099 result.add(ephemeralInstaller); 6100 } 6101 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6102 } 6103 if (sortResult) { 6104 Collections.sort(result, mResolvePrioritySorter); 6105 } 6106 return filterForEphemeral(result, ephemeralPkgName); 6107 } 6108 6109 private static class CrossProfileDomainInfo { 6110 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 6111 ResolveInfo resolveInfo; 6112 /* Best domain verification status of the activities found in the other profile */ 6113 int bestDomainVerificationStatus; 6114 } 6115 6116 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 6117 String resolvedType, int flags, int sourceUserId, int parentUserId) { 6118 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 6119 sourceUserId)) { 6120 return null; 6121 } 6122 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 6123 resolvedType, flags, parentUserId); 6124 6125 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 6126 return null; 6127 } 6128 CrossProfileDomainInfo result = null; 6129 int size = resultTargetUser.size(); 6130 for (int i = 0; i < size; i++) { 6131 ResolveInfo riTargetUser = resultTargetUser.get(i); 6132 // Intent filter verification is only for filters that specify a host. So don't return 6133 // those that handle all web uris. 6134 if (riTargetUser.handleAllWebDataURI) { 6135 continue; 6136 } 6137 String packageName = riTargetUser.activityInfo.packageName; 6138 PackageSetting ps = mSettings.mPackages.get(packageName); 6139 if (ps == null) { 6140 continue; 6141 } 6142 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 6143 int status = (int)(verificationState >> 32); 6144 if (result == null) { 6145 result = new CrossProfileDomainInfo(); 6146 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 6147 sourceUserId, parentUserId); 6148 result.bestDomainVerificationStatus = status; 6149 } else { 6150 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 6151 result.bestDomainVerificationStatus); 6152 } 6153 } 6154 // Don't consider matches with status NEVER across profiles. 6155 if (result != null && result.bestDomainVerificationStatus 6156 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6157 return null; 6158 } 6159 return result; 6160 } 6161 6162 /** 6163 * Verification statuses are ordered from the worse to the best, except for 6164 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 6165 */ 6166 private int bestDomainVerificationStatus(int status1, int status2) { 6167 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6168 return status2; 6169 } 6170 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6171 return status1; 6172 } 6173 return (int) MathUtils.max(status1, status2); 6174 } 6175 6176 private boolean isUserEnabled(int userId) { 6177 long callingId = Binder.clearCallingIdentity(); 6178 try { 6179 UserInfo userInfo = sUserManager.getUserInfo(userId); 6180 return userInfo != null && userInfo.isEnabled(); 6181 } finally { 6182 Binder.restoreCallingIdentity(callingId); 6183 } 6184 } 6185 6186 /** 6187 * Filter out activities with systemUserOnly flag set, when current user is not System. 6188 * 6189 * @return filtered list 6190 */ 6191 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 6192 if (userId == UserHandle.USER_SYSTEM) { 6193 return resolveInfos; 6194 } 6195 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 6196 ResolveInfo info = resolveInfos.get(i); 6197 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 6198 resolveInfos.remove(i); 6199 } 6200 } 6201 return resolveInfos; 6202 } 6203 6204 /** 6205 * Filters out ephemeral activities. 6206 * <p>When resolving for an ephemeral app, only activities that 1) are defined in the 6207 * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned. 6208 * 6209 * @param resolveInfos The pre-filtered list of resolved activities 6210 * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering 6211 * is performed. 6212 * @return A filtered list of resolved activities. 6213 */ 6214 private List<ResolveInfo> filterForEphemeral(List<ResolveInfo> resolveInfos, 6215 String ephemeralPkgName) { 6216 if (ephemeralPkgName == null) { 6217 return resolveInfos; 6218 } 6219 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 6220 ResolveInfo info = resolveInfos.get(i); 6221 final boolean isEphemeralApp = info.activityInfo.applicationInfo.isEphemeralApp(); 6222 // allow activities that are defined in the provided package 6223 if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) { 6224 continue; 6225 } 6226 // allow activities that have been explicitly exposed to ephemeral apps 6227 if (!isEphemeralApp 6228 && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) { 6229 continue; 6230 } 6231 resolveInfos.remove(i); 6232 } 6233 return resolveInfos; 6234 } 6235 6236 /** 6237 * @param resolveInfos list of resolve infos in descending priority order 6238 * @return if the list contains a resolve info with non-negative priority 6239 */ 6240 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 6241 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 6242 } 6243 6244 private static boolean hasWebURI(Intent intent) { 6245 if (intent.getData() == null) { 6246 return false; 6247 } 6248 final String scheme = intent.getScheme(); 6249 if (TextUtils.isEmpty(scheme)) { 6250 return false; 6251 } 6252 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 6253 } 6254 6255 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 6256 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 6257 int userId) { 6258 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 6259 6260 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 6261 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 6262 candidates.size()); 6263 } 6264 6265 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 6266 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 6267 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 6268 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 6269 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 6270 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 6271 6272 synchronized (mPackages) { 6273 final int count = candidates.size(); 6274 // First, try to use linked apps. Partition the candidates into four lists: 6275 // one for the final results, one for the "do not use ever", one for "undefined status" 6276 // and finally one for "browser app type". 6277 for (int n=0; n<count; n++) { 6278 ResolveInfo info = candidates.get(n); 6279 String packageName = info.activityInfo.packageName; 6280 PackageSetting ps = mSettings.mPackages.get(packageName); 6281 if (ps != null) { 6282 // Add to the special match all list (Browser use case) 6283 if (info.handleAllWebDataURI) { 6284 matchAllList.add(info); 6285 continue; 6286 } 6287 // Try to get the status from User settings first 6288 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 6289 int status = (int)(packedStatus >> 32); 6290 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 6291 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 6292 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6293 Slog.i(TAG, " + always: " + info.activityInfo.packageName 6294 + " : linkgen=" + linkGeneration); 6295 } 6296 // Use link-enabled generation as preferredOrder, i.e. 6297 // prefer newly-enabled over earlier-enabled. 6298 info.preferredOrder = linkGeneration; 6299 alwaysList.add(info); 6300 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6301 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6302 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 6303 } 6304 neverList.add(info); 6305 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 6306 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6307 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 6308 } 6309 alwaysAskList.add(info); 6310 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 6311 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 6312 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6313 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 6314 } 6315 undefinedList.add(info); 6316 } 6317 } 6318 } 6319 6320 // We'll want to include browser possibilities in a few cases 6321 boolean includeBrowser = false; 6322 6323 // First try to add the "always" resolution(s) for the current user, if any 6324 if (alwaysList.size() > 0) { 6325 result.addAll(alwaysList); 6326 } else { 6327 // Add all undefined apps as we want them to appear in the disambiguation dialog. 6328 result.addAll(undefinedList); 6329 // Maybe add one for the other profile. 6330 if (xpDomainInfo != null && ( 6331 xpDomainInfo.bestDomainVerificationStatus 6332 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 6333 result.add(xpDomainInfo.resolveInfo); 6334 } 6335 includeBrowser = true; 6336 } 6337 6338 // The presence of any 'always ask' alternatives means we'll also offer browsers. 6339 // If there were 'always' entries their preferred order has been set, so we also 6340 // back that off to make the alternatives equivalent 6341 if (alwaysAskList.size() > 0) { 6342 for (ResolveInfo i : result) { 6343 i.preferredOrder = 0; 6344 } 6345 result.addAll(alwaysAskList); 6346 includeBrowser = true; 6347 } 6348 6349 if (includeBrowser) { 6350 // Also add browsers (all of them or only the default one) 6351 if (DEBUG_DOMAIN_VERIFICATION) { 6352 Slog.v(TAG, " ...including browsers in candidate set"); 6353 } 6354 if ((matchFlags & MATCH_ALL) != 0) { 6355 result.addAll(matchAllList); 6356 } else { 6357 // Browser/generic handling case. If there's a default browser, go straight 6358 // to that (but only if there is no other higher-priority match). 6359 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 6360 int maxMatchPrio = 0; 6361 ResolveInfo defaultBrowserMatch = null; 6362 final int numCandidates = matchAllList.size(); 6363 for (int n = 0; n < numCandidates; n++) { 6364 ResolveInfo info = matchAllList.get(n); 6365 // track the highest overall match priority... 6366 if (info.priority > maxMatchPrio) { 6367 maxMatchPrio = info.priority; 6368 } 6369 // ...and the highest-priority default browser match 6370 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 6371 if (defaultBrowserMatch == null 6372 || (defaultBrowserMatch.priority < info.priority)) { 6373 if (debug) { 6374 Slog.v(TAG, "Considering default browser match " + info); 6375 } 6376 defaultBrowserMatch = info; 6377 } 6378 } 6379 } 6380 if (defaultBrowserMatch != null 6381 && defaultBrowserMatch.priority >= maxMatchPrio 6382 && !TextUtils.isEmpty(defaultBrowserPackageName)) 6383 { 6384 if (debug) { 6385 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 6386 } 6387 result.add(defaultBrowserMatch); 6388 } else { 6389 result.addAll(matchAllList); 6390 } 6391 } 6392 6393 // If there is nothing selected, add all candidates and remove the ones that the user 6394 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 6395 if (result.size() == 0) { 6396 result.addAll(candidates); 6397 result.removeAll(neverList); 6398 } 6399 } 6400 } 6401 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 6402 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 6403 result.size()); 6404 for (ResolveInfo info : result) { 6405 Slog.v(TAG, " + " + info.activityInfo); 6406 } 6407 } 6408 return result; 6409 } 6410 6411 // Returns a packed value as a long: 6412 // 6413 // high 'int'-sized word: link status: undefined/ask/never/always. 6414 // low 'int'-sized word: relative priority among 'always' results. 6415 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 6416 long result = ps.getDomainVerificationStatusForUser(userId); 6417 // if none available, get the master status 6418 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 6419 if (ps.getIntentFilterVerificationInfo() != null) { 6420 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 6421 } 6422 } 6423 return result; 6424 } 6425 6426 private ResolveInfo querySkipCurrentProfileIntents( 6427 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 6428 int flags, int sourceUserId) { 6429 if (matchingFilters != null) { 6430 int size = matchingFilters.size(); 6431 for (int i = 0; i < size; i ++) { 6432 CrossProfileIntentFilter filter = matchingFilters.get(i); 6433 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 6434 // Checking if there are activities in the target user that can handle the 6435 // intent. 6436 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 6437 resolvedType, flags, sourceUserId); 6438 if (resolveInfo != null) { 6439 return resolveInfo; 6440 } 6441 } 6442 } 6443 } 6444 return null; 6445 } 6446 6447 // Return matching ResolveInfo in target user if any. 6448 private ResolveInfo queryCrossProfileIntents( 6449 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 6450 int flags, int sourceUserId, boolean matchInCurrentProfile) { 6451 if (matchingFilters != null) { 6452 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 6453 // match the same intent. For performance reasons, it is better not to 6454 // run queryIntent twice for the same userId 6455 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 6456 int size = matchingFilters.size(); 6457 for (int i = 0; i < size; i++) { 6458 CrossProfileIntentFilter filter = matchingFilters.get(i); 6459 int targetUserId = filter.getTargetUserId(); 6460 boolean skipCurrentProfile = 6461 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 6462 boolean skipCurrentProfileIfNoMatchFound = 6463 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 6464 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 6465 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 6466 // Checking if there are activities in the target user that can handle the 6467 // intent. 6468 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 6469 resolvedType, flags, sourceUserId); 6470 if (resolveInfo != null) return resolveInfo; 6471 alreadyTriedUserIds.put(targetUserId, true); 6472 } 6473 } 6474 } 6475 return null; 6476 } 6477 6478 /** 6479 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 6480 * will forward the intent to the filter's target user. 6481 * Otherwise, returns null. 6482 */ 6483 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 6484 String resolvedType, int flags, int sourceUserId) { 6485 int targetUserId = filter.getTargetUserId(); 6486 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 6487 resolvedType, flags, targetUserId); 6488 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 6489 // If all the matches in the target profile are suspended, return null. 6490 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 6491 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 6492 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 6493 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 6494 targetUserId); 6495 } 6496 } 6497 } 6498 return null; 6499 } 6500 6501 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 6502 int sourceUserId, int targetUserId) { 6503 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 6504 long ident = Binder.clearCallingIdentity(); 6505 boolean targetIsProfile; 6506 try { 6507 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 6508 } finally { 6509 Binder.restoreCallingIdentity(ident); 6510 } 6511 String className; 6512 if (targetIsProfile) { 6513 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 6514 } else { 6515 className = FORWARD_INTENT_TO_PARENT; 6516 } 6517 ComponentName forwardingActivityComponentName = new ComponentName( 6518 mAndroidApplication.packageName, className); 6519 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 6520 sourceUserId); 6521 if (!targetIsProfile) { 6522 forwardingActivityInfo.showUserIcon = targetUserId; 6523 forwardingResolveInfo.noResourceId = true; 6524 } 6525 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 6526 forwardingResolveInfo.priority = 0; 6527 forwardingResolveInfo.preferredOrder = 0; 6528 forwardingResolveInfo.match = 0; 6529 forwardingResolveInfo.isDefault = true; 6530 forwardingResolveInfo.filter = filter; 6531 forwardingResolveInfo.targetUserId = targetUserId; 6532 return forwardingResolveInfo; 6533 } 6534 6535 @Override 6536 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 6537 Intent[] specifics, String[] specificTypes, Intent intent, 6538 String resolvedType, int flags, int userId) { 6539 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 6540 specificTypes, intent, resolvedType, flags, userId)); 6541 } 6542 6543 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 6544 Intent[] specifics, String[] specificTypes, Intent intent, 6545 String resolvedType, int flags, int userId) { 6546 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6547 flags = updateFlagsForResolve(flags, userId, intent); 6548 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6549 false /* requireFullPermission */, false /* checkShell */, 6550 "query intent activity options"); 6551 final String resultsAction = intent.getAction(); 6552 6553 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 6554 | PackageManager.GET_RESOLVED_FILTER, userId); 6555 6556 if (DEBUG_INTENT_MATCHING) { 6557 Log.v(TAG, "Query " + intent + ": " + results); 6558 } 6559 6560 int specificsPos = 0; 6561 int N; 6562 6563 // todo: note that the algorithm used here is O(N^2). This 6564 // isn't a problem in our current environment, but if we start running 6565 // into situations where we have more than 5 or 10 matches then this 6566 // should probably be changed to something smarter... 6567 6568 // First we go through and resolve each of the specific items 6569 // that were supplied, taking care of removing any corresponding 6570 // duplicate items in the generic resolve list. 6571 if (specifics != null) { 6572 for (int i=0; i<specifics.length; i++) { 6573 final Intent sintent = specifics[i]; 6574 if (sintent == null) { 6575 continue; 6576 } 6577 6578 if (DEBUG_INTENT_MATCHING) { 6579 Log.v(TAG, "Specific #" + i + ": " + sintent); 6580 } 6581 6582 String action = sintent.getAction(); 6583 if (resultsAction != null && resultsAction.equals(action)) { 6584 // If this action was explicitly requested, then don't 6585 // remove things that have it. 6586 action = null; 6587 } 6588 6589 ResolveInfo ri = null; 6590 ActivityInfo ai = null; 6591 6592 ComponentName comp = sintent.getComponent(); 6593 if (comp == null) { 6594 ri = resolveIntent( 6595 sintent, 6596 specificTypes != null ? specificTypes[i] : null, 6597 flags, userId); 6598 if (ri == null) { 6599 continue; 6600 } 6601 if (ri == mResolveInfo) { 6602 // ACK! Must do something better with this. 6603 } 6604 ai = ri.activityInfo; 6605 comp = new ComponentName(ai.applicationInfo.packageName, 6606 ai.name); 6607 } else { 6608 ai = getActivityInfo(comp, flags, userId); 6609 if (ai == null) { 6610 continue; 6611 } 6612 } 6613 6614 // Look for any generic query activities that are duplicates 6615 // of this specific one, and remove them from the results. 6616 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 6617 N = results.size(); 6618 int j; 6619 for (j=specificsPos; j<N; j++) { 6620 ResolveInfo sri = results.get(j); 6621 if ((sri.activityInfo.name.equals(comp.getClassName()) 6622 && sri.activityInfo.applicationInfo.packageName.equals( 6623 comp.getPackageName())) 6624 || (action != null && sri.filter.matchAction(action))) { 6625 results.remove(j); 6626 if (DEBUG_INTENT_MATCHING) Log.v( 6627 TAG, "Removing duplicate item from " + j 6628 + " due to specific " + specificsPos); 6629 if (ri == null) { 6630 ri = sri; 6631 } 6632 j--; 6633 N--; 6634 } 6635 } 6636 6637 // Add this specific item to its proper place. 6638 if (ri == null) { 6639 ri = new ResolveInfo(); 6640 ri.activityInfo = ai; 6641 } 6642 results.add(specificsPos, ri); 6643 ri.specificIndex = i; 6644 specificsPos++; 6645 } 6646 } 6647 6648 // Now we go through the remaining generic results and remove any 6649 // duplicate actions that are found here. 6650 N = results.size(); 6651 for (int i=specificsPos; i<N-1; i++) { 6652 final ResolveInfo rii = results.get(i); 6653 if (rii.filter == null) { 6654 continue; 6655 } 6656 6657 // Iterate over all of the actions of this result's intent 6658 // filter... typically this should be just one. 6659 final Iterator<String> it = rii.filter.actionsIterator(); 6660 if (it == null) { 6661 continue; 6662 } 6663 while (it.hasNext()) { 6664 final String action = it.next(); 6665 if (resultsAction != null && resultsAction.equals(action)) { 6666 // If this action was explicitly requested, then don't 6667 // remove things that have it. 6668 continue; 6669 } 6670 for (int j=i+1; j<N; j++) { 6671 final ResolveInfo rij = results.get(j); 6672 if (rij.filter != null && rij.filter.hasAction(action)) { 6673 results.remove(j); 6674 if (DEBUG_INTENT_MATCHING) Log.v( 6675 TAG, "Removing duplicate item from " + j 6676 + " due to action " + action + " at " + i); 6677 j--; 6678 N--; 6679 } 6680 } 6681 } 6682 6683 // If the caller didn't request filter information, drop it now 6684 // so we don't have to marshall/unmarshall it. 6685 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6686 rii.filter = null; 6687 } 6688 } 6689 6690 // Filter out the caller activity if so requested. 6691 if (caller != null) { 6692 N = results.size(); 6693 for (int i=0; i<N; i++) { 6694 ActivityInfo ainfo = results.get(i).activityInfo; 6695 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 6696 && caller.getClassName().equals(ainfo.name)) { 6697 results.remove(i); 6698 break; 6699 } 6700 } 6701 } 6702 6703 // If the caller didn't request filter information, 6704 // drop them now so we don't have to 6705 // marshall/unmarshall it. 6706 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6707 N = results.size(); 6708 for (int i=0; i<N; i++) { 6709 results.get(i).filter = null; 6710 } 6711 } 6712 6713 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 6714 return results; 6715 } 6716 6717 @Override 6718 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 6719 String resolvedType, int flags, int userId) { 6720 return new ParceledListSlice<>( 6721 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 6722 } 6723 6724 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 6725 String resolvedType, int flags, int userId) { 6726 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6727 flags = updateFlagsForResolve(flags, userId, intent); 6728 ComponentName comp = intent.getComponent(); 6729 if (comp == null) { 6730 if (intent.getSelector() != null) { 6731 intent = intent.getSelector(); 6732 comp = intent.getComponent(); 6733 } 6734 } 6735 if (comp != null) { 6736 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6737 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 6738 if (ai != null) { 6739 ResolveInfo ri = new ResolveInfo(); 6740 ri.activityInfo = ai; 6741 list.add(ri); 6742 } 6743 return list; 6744 } 6745 6746 // reader 6747 synchronized (mPackages) { 6748 String pkgName = intent.getPackage(); 6749 if (pkgName == null) { 6750 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 6751 } 6752 final PackageParser.Package pkg = mPackages.get(pkgName); 6753 if (pkg != null) { 6754 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 6755 userId); 6756 } 6757 return Collections.emptyList(); 6758 } 6759 } 6760 6761 @Override 6762 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 6763 if (!sUserManager.exists(userId)) return null; 6764 flags = updateFlagsForResolve(flags, userId, intent); 6765 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 6766 if (query != null) { 6767 if (query.size() >= 1) { 6768 // If there is more than one service with the same priority, 6769 // just arbitrarily pick the first one. 6770 return query.get(0); 6771 } 6772 } 6773 return null; 6774 } 6775 6776 @Override 6777 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 6778 String resolvedType, int flags, int userId) { 6779 return new ParceledListSlice<>( 6780 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 6781 } 6782 6783 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 6784 String resolvedType, int flags, int userId) { 6785 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6786 flags = updateFlagsForResolve(flags, userId, intent); 6787 ComponentName comp = intent.getComponent(); 6788 if (comp == null) { 6789 if (intent.getSelector() != null) { 6790 intent = intent.getSelector(); 6791 comp = intent.getComponent(); 6792 } 6793 } 6794 if (comp != null) { 6795 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6796 final ServiceInfo si = getServiceInfo(comp, flags, userId); 6797 if (si != null) { 6798 final ResolveInfo ri = new ResolveInfo(); 6799 ri.serviceInfo = si; 6800 list.add(ri); 6801 } 6802 return list; 6803 } 6804 6805 // reader 6806 synchronized (mPackages) { 6807 String pkgName = intent.getPackage(); 6808 if (pkgName == null) { 6809 return mServices.queryIntent(intent, resolvedType, flags, userId); 6810 } 6811 final PackageParser.Package pkg = mPackages.get(pkgName); 6812 if (pkg != null) { 6813 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 6814 userId); 6815 } 6816 return Collections.emptyList(); 6817 } 6818 } 6819 6820 @Override 6821 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 6822 String resolvedType, int flags, int userId) { 6823 return new ParceledListSlice<>( 6824 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 6825 } 6826 6827 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 6828 Intent intent, String resolvedType, int flags, int userId) { 6829 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6830 flags = updateFlagsForResolve(flags, userId, intent); 6831 ComponentName comp = intent.getComponent(); 6832 if (comp == null) { 6833 if (intent.getSelector() != null) { 6834 intent = intent.getSelector(); 6835 comp = intent.getComponent(); 6836 } 6837 } 6838 if (comp != null) { 6839 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6840 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 6841 if (pi != null) { 6842 final ResolveInfo ri = new ResolveInfo(); 6843 ri.providerInfo = pi; 6844 list.add(ri); 6845 } 6846 return list; 6847 } 6848 6849 // reader 6850 synchronized (mPackages) { 6851 String pkgName = intent.getPackage(); 6852 if (pkgName == null) { 6853 return mProviders.queryIntent(intent, resolvedType, flags, userId); 6854 } 6855 final PackageParser.Package pkg = mPackages.get(pkgName); 6856 if (pkg != null) { 6857 return mProviders.queryIntentForPackage( 6858 intent, resolvedType, flags, pkg.providers, userId); 6859 } 6860 return Collections.emptyList(); 6861 } 6862 } 6863 6864 @Override 6865 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 6866 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6867 flags = updateFlagsForPackage(flags, userId, null); 6868 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 6869 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6870 true /* requireFullPermission */, false /* checkShell */, 6871 "get installed packages"); 6872 6873 // writer 6874 synchronized (mPackages) { 6875 ArrayList<PackageInfo> list; 6876 if (listUninstalled) { 6877 list = new ArrayList<>(mSettings.mPackages.size()); 6878 for (PackageSetting ps : mSettings.mPackages.values()) { 6879 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 6880 continue; 6881 } 6882 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 6883 if (pi != null) { 6884 list.add(pi); 6885 } 6886 } 6887 } else { 6888 list = new ArrayList<>(mPackages.size()); 6889 for (PackageParser.Package p : mPackages.values()) { 6890 if (filterSharedLibPackageLPr((PackageSetting) p.mExtras, 6891 Binder.getCallingUid(), userId)) { 6892 continue; 6893 } 6894 final PackageInfo pi = generatePackageInfo((PackageSetting) 6895 p.mExtras, flags, userId); 6896 if (pi != null) { 6897 list.add(pi); 6898 } 6899 } 6900 } 6901 6902 return new ParceledListSlice<>(list); 6903 } 6904 } 6905 6906 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 6907 String[] permissions, boolean[] tmp, int flags, int userId) { 6908 int numMatch = 0; 6909 final PermissionsState permissionsState = ps.getPermissionsState(); 6910 for (int i=0; i<permissions.length; i++) { 6911 final String permission = permissions[i]; 6912 if (permissionsState.hasPermission(permission, userId)) { 6913 tmp[i] = true; 6914 numMatch++; 6915 } else { 6916 tmp[i] = false; 6917 } 6918 } 6919 if (numMatch == 0) { 6920 return; 6921 } 6922 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 6923 6924 // The above might return null in cases of uninstalled apps or install-state 6925 // skew across users/profiles. 6926 if (pi != null) { 6927 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 6928 if (numMatch == permissions.length) { 6929 pi.requestedPermissions = permissions; 6930 } else { 6931 pi.requestedPermissions = new String[numMatch]; 6932 numMatch = 0; 6933 for (int i=0; i<permissions.length; i++) { 6934 if (tmp[i]) { 6935 pi.requestedPermissions[numMatch] = permissions[i]; 6936 numMatch++; 6937 } 6938 } 6939 } 6940 } 6941 list.add(pi); 6942 } 6943 } 6944 6945 @Override 6946 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 6947 String[] permissions, int flags, int userId) { 6948 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6949 flags = updateFlagsForPackage(flags, userId, permissions); 6950 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6951 true /* requireFullPermission */, false /* checkShell */, 6952 "get packages holding permissions"); 6953 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 6954 6955 // writer 6956 synchronized (mPackages) { 6957 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 6958 boolean[] tmpBools = new boolean[permissions.length]; 6959 if (listUninstalled) { 6960 for (PackageSetting ps : mSettings.mPackages.values()) { 6961 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6962 userId); 6963 } 6964 } else { 6965 for (PackageParser.Package pkg : mPackages.values()) { 6966 PackageSetting ps = (PackageSetting)pkg.mExtras; 6967 if (ps != null) { 6968 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6969 userId); 6970 } 6971 } 6972 } 6973 6974 return new ParceledListSlice<PackageInfo>(list); 6975 } 6976 } 6977 6978 @Override 6979 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 6980 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6981 flags = updateFlagsForApplication(flags, userId, null); 6982 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 6983 6984 // writer 6985 synchronized (mPackages) { 6986 ArrayList<ApplicationInfo> list; 6987 if (listUninstalled) { 6988 list = new ArrayList<>(mSettings.mPackages.size()); 6989 for (PackageSetting ps : mSettings.mPackages.values()) { 6990 ApplicationInfo ai; 6991 int effectiveFlags = flags; 6992 if (ps.isSystem()) { 6993 effectiveFlags |= PackageManager.MATCH_ANY_USER; 6994 } 6995 if (ps.pkg != null) { 6996 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 6997 continue; 6998 } 6999 ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags, 7000 ps.readUserState(userId), userId); 7001 if (ai != null) { 7002 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 7003 } 7004 } else { 7005 // Shared lib filtering done in generateApplicationInfoFromSettingsLPw 7006 // and already converts to externally visible package name 7007 ai = generateApplicationInfoFromSettingsLPw(ps.name, 7008 Binder.getCallingUid(), effectiveFlags, userId); 7009 } 7010 if (ai != null) { 7011 list.add(ai); 7012 } 7013 } 7014 } else { 7015 list = new ArrayList<>(mPackages.size()); 7016 for (PackageParser.Package p : mPackages.values()) { 7017 if (p.mExtras != null) { 7018 PackageSetting ps = (PackageSetting) p.mExtras; 7019 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 7020 continue; 7021 } 7022 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 7023 ps.readUserState(userId), userId); 7024 if (ai != null) { 7025 ai.packageName = resolveExternalPackageNameLPr(p); 7026 list.add(ai); 7027 } 7028 } 7029 } 7030 } 7031 7032 return new ParceledListSlice<>(list); 7033 } 7034 } 7035 7036 @Override 7037 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 7038 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7039 return null; 7040 } 7041 7042 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 7043 "getEphemeralApplications"); 7044 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7045 true /* requireFullPermission */, false /* checkShell */, 7046 "getEphemeralApplications"); 7047 synchronized (mPackages) { 7048 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 7049 .getEphemeralApplicationsLPw(userId); 7050 if (ephemeralApps != null) { 7051 return new ParceledListSlice<>(ephemeralApps); 7052 } 7053 } 7054 return null; 7055 } 7056 7057 @Override 7058 public boolean isEphemeralApplication(String packageName, int userId) { 7059 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7060 true /* requireFullPermission */, false /* checkShell */, 7061 "isEphemeral"); 7062 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7063 return false; 7064 } 7065 7066 if (!isCallerSameApp(packageName)) { 7067 return false; 7068 } 7069 synchronized (mPackages) { 7070 PackageParser.Package pkg = mPackages.get(packageName); 7071 if (pkg != null) { 7072 return pkg.applicationInfo.isEphemeralApp(); 7073 } 7074 } 7075 return false; 7076 } 7077 7078 @Override 7079 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 7080 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7081 return null; 7082 } 7083 7084 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7085 true /* requireFullPermission */, false /* checkShell */, 7086 "getCookie"); 7087 if (!isCallerSameApp(packageName)) { 7088 return null; 7089 } 7090 synchronized (mPackages) { 7091 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 7092 packageName, userId); 7093 } 7094 } 7095 7096 @Override 7097 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 7098 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7099 return true; 7100 } 7101 7102 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7103 true /* requireFullPermission */, true /* checkShell */, 7104 "setCookie"); 7105 if (!isCallerSameApp(packageName)) { 7106 return false; 7107 } 7108 synchronized (mPackages) { 7109 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 7110 packageName, cookie, userId); 7111 } 7112 } 7113 7114 @Override 7115 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 7116 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7117 return null; 7118 } 7119 7120 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 7121 "getEphemeralApplicationIcon"); 7122 7123 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7124 true /* requireFullPermission */, false /* checkShell */, 7125 "getEphemeralApplicationIcon"); 7126 synchronized (mPackages) { 7127 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 7128 packageName, userId); 7129 } 7130 } 7131 7132 private boolean isCallerSameApp(String packageName) { 7133 PackageParser.Package pkg = mPackages.get(packageName); 7134 return pkg != null 7135 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 7136 } 7137 7138 @Override 7139 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 7140 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 7141 } 7142 7143 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 7144 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 7145 7146 // reader 7147 synchronized (mPackages) { 7148 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 7149 final int userId = UserHandle.getCallingUserId(); 7150 while (i.hasNext()) { 7151 final PackageParser.Package p = i.next(); 7152 if (p.applicationInfo == null) continue; 7153 7154 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 7155 && !p.applicationInfo.isDirectBootAware(); 7156 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 7157 && p.applicationInfo.isDirectBootAware(); 7158 7159 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 7160 && (!mSafeMode || isSystemApp(p)) 7161 && (matchesUnaware || matchesAware)) { 7162 PackageSetting ps = mSettings.mPackages.get(p.packageName); 7163 if (ps != null) { 7164 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 7165 ps.readUserState(userId), userId); 7166 if (ai != null) { 7167 finalList.add(ai); 7168 } 7169 } 7170 } 7171 } 7172 } 7173 7174 return finalList; 7175 } 7176 7177 @Override 7178 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 7179 if (!sUserManager.exists(userId)) return null; 7180 flags = updateFlagsForComponent(flags, userId, name); 7181 // reader 7182 synchronized (mPackages) { 7183 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 7184 PackageSetting ps = provider != null 7185 ? mSettings.mPackages.get(provider.owner.packageName) 7186 : null; 7187 return ps != null 7188 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 7189 ? PackageParser.generateProviderInfo(provider, flags, 7190 ps.readUserState(userId), userId) 7191 : null; 7192 } 7193 } 7194 7195 /** 7196 * @deprecated 7197 */ 7198 @Deprecated 7199 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 7200 // reader 7201 synchronized (mPackages) { 7202 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 7203 .entrySet().iterator(); 7204 final int userId = UserHandle.getCallingUserId(); 7205 while (i.hasNext()) { 7206 Map.Entry<String, PackageParser.Provider> entry = i.next(); 7207 PackageParser.Provider p = entry.getValue(); 7208 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 7209 7210 if (ps != null && p.syncable 7211 && (!mSafeMode || (p.info.applicationInfo.flags 7212 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 7213 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 7214 ps.readUserState(userId), userId); 7215 if (info != null) { 7216 outNames.add(entry.getKey()); 7217 outInfo.add(info); 7218 } 7219 } 7220 } 7221 } 7222 } 7223 7224 @Override 7225 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 7226 int uid, int flags) { 7227 final int userId = processName != null ? UserHandle.getUserId(uid) 7228 : UserHandle.getCallingUserId(); 7229 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7230 flags = updateFlagsForComponent(flags, userId, processName); 7231 7232 ArrayList<ProviderInfo> finalList = null; 7233 // reader 7234 synchronized (mPackages) { 7235 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 7236 while (i.hasNext()) { 7237 final PackageParser.Provider p = i.next(); 7238 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 7239 if (ps != null && p.info.authority != null 7240 && (processName == null 7241 || (p.info.processName.equals(processName) 7242 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 7243 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 7244 if (finalList == null) { 7245 finalList = new ArrayList<ProviderInfo>(3); 7246 } 7247 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 7248 ps.readUserState(userId), userId); 7249 if (info != null) { 7250 finalList.add(info); 7251 } 7252 } 7253 } 7254 } 7255 7256 if (finalList != null) { 7257 Collections.sort(finalList, mProviderInitOrderSorter); 7258 return new ParceledListSlice<ProviderInfo>(finalList); 7259 } 7260 7261 return ParceledListSlice.emptyList(); 7262 } 7263 7264 @Override 7265 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 7266 // reader 7267 synchronized (mPackages) { 7268 final PackageParser.Instrumentation i = mInstrumentation.get(name); 7269 return PackageParser.generateInstrumentationInfo(i, flags); 7270 } 7271 } 7272 7273 @Override 7274 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 7275 String targetPackage, int flags) { 7276 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 7277 } 7278 7279 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 7280 int flags) { 7281 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 7282 7283 // reader 7284 synchronized (mPackages) { 7285 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 7286 while (i.hasNext()) { 7287 final PackageParser.Instrumentation p = i.next(); 7288 if (targetPackage == null 7289 || targetPackage.equals(p.info.targetPackage)) { 7290 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 7291 flags); 7292 if (ii != null) { 7293 finalList.add(ii); 7294 } 7295 } 7296 } 7297 } 7298 7299 return finalList; 7300 } 7301 7302 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 7303 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 7304 if (overlays == null) { 7305 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 7306 return; 7307 } 7308 for (PackageParser.Package opkg : overlays.values()) { 7309 // Not much to do if idmap fails: we already logged the error 7310 // and we certainly don't want to abort installation of pkg simply 7311 // because an overlay didn't fit properly. For these reasons, 7312 // ignore the return value of createIdmapForPackagePairLI. 7313 createIdmapForPackagePairLI(pkg, opkg); 7314 } 7315 } 7316 7317 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 7318 PackageParser.Package opkg) { 7319 if (!opkg.mTrustedOverlay) { 7320 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 7321 opkg.baseCodePath + ": overlay not trusted"); 7322 return false; 7323 } 7324 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 7325 if (overlaySet == null) { 7326 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 7327 opkg.baseCodePath + " but target package has no known overlays"); 7328 return false; 7329 } 7330 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 7331 // TODO: generate idmap for split APKs 7332 try { 7333 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 7334 } catch (InstallerException e) { 7335 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 7336 + opkg.baseCodePath); 7337 return false; 7338 } 7339 PackageParser.Package[] overlayArray = 7340 overlaySet.values().toArray(new PackageParser.Package[0]); 7341 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 7342 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 7343 return p1.mOverlayPriority - p2.mOverlayPriority; 7344 } 7345 }; 7346 Arrays.sort(overlayArray, cmp); 7347 7348 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 7349 int i = 0; 7350 for (PackageParser.Package p : overlayArray) { 7351 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 7352 } 7353 return true; 7354 } 7355 7356 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 7357 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]"); 7358 try { 7359 scanDirLI(dir, parseFlags, scanFlags, currentTime); 7360 } finally { 7361 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7362 } 7363 } 7364 7365 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 7366 final File[] files = dir.listFiles(); 7367 if (ArrayUtils.isEmpty(files)) { 7368 Log.d(TAG, "No files in app dir " + dir); 7369 return; 7370 } 7371 7372 if (DEBUG_PACKAGE_SCANNING) { 7373 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 7374 + " flags=0x" + Integer.toHexString(parseFlags)); 7375 } 7376 ParallelPackageParser parallelPackageParser = new ParallelPackageParser( 7377 mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir); 7378 7379 // Submit files for parsing in parallel 7380 int fileCount = 0; 7381 for (File file : files) { 7382 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 7383 && !PackageInstallerService.isStageName(file.getName()); 7384 if (!isPackage) { 7385 // Ignore entries which are not packages 7386 continue; 7387 } 7388 parallelPackageParser.submit(file, parseFlags); 7389 fileCount++; 7390 } 7391 7392 // Process results one by one 7393 for (; fileCount > 0; fileCount--) { 7394 ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take(); 7395 Throwable throwable = parseResult.throwable; 7396 int errorCode = PackageManager.INSTALL_SUCCEEDED; 7397 7398 if (throwable == null) { 7399 // Static shared libraries have synthetic package names 7400 if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) { 7401 renameStaticSharedLibraryPackage(parseResult.pkg); 7402 } 7403 try { 7404 if (errorCode == PackageManager.INSTALL_SUCCEEDED) { 7405 scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags, 7406 currentTime, null); 7407 } 7408 } catch (PackageManagerException e) { 7409 errorCode = e.error; 7410 Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage()); 7411 } 7412 } else if (throwable instanceof PackageParser.PackageParserException) { 7413 PackageParser.PackageParserException e = (PackageParser.PackageParserException) 7414 throwable; 7415 errorCode = e.error; 7416 Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage()); 7417 } else { 7418 throw new IllegalStateException("Unexpected exception occurred while parsing " 7419 + parseResult.scanFile, throwable); 7420 } 7421 7422 // Delete invalid userdata apps 7423 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 7424 errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) { 7425 logCriticalInfo(Log.WARN, 7426 "Deleting invalid package at " + parseResult.scanFile); 7427 removeCodePathLI(parseResult.scanFile); 7428 } 7429 } 7430 parallelPackageParser.close(); 7431 } 7432 7433 private static File getSettingsProblemFile() { 7434 File dataDir = Environment.getDataDirectory(); 7435 File systemDir = new File(dataDir, "system"); 7436 File fname = new File(systemDir, "uiderrors.txt"); 7437 return fname; 7438 } 7439 7440 static void reportSettingsProblem(int priority, String msg) { 7441 logCriticalInfo(priority, msg); 7442 } 7443 7444 static void logCriticalInfo(int priority, String msg) { 7445 Slog.println(priority, TAG, msg); 7446 EventLogTags.writePmCriticalInfo(msg); 7447 try { 7448 File fname = getSettingsProblemFile(); 7449 FileOutputStream out = new FileOutputStream(fname, true); 7450 PrintWriter pw = new FastPrintWriter(out); 7451 SimpleDateFormat formatter = new SimpleDateFormat(); 7452 String dateString = formatter.format(new Date(System.currentTimeMillis())); 7453 pw.println(dateString + ": " + msg); 7454 pw.close(); 7455 FileUtils.setPermissions( 7456 fname.toString(), 7457 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 7458 -1, -1); 7459 } catch (java.io.IOException e) { 7460 } 7461 } 7462 7463 private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) { 7464 if (srcFile.isDirectory()) { 7465 final File baseFile = new File(pkg.baseCodePath); 7466 long maxModifiedTime = baseFile.lastModified(); 7467 if (pkg.splitCodePaths != null) { 7468 for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) { 7469 final File splitFile = new File(pkg.splitCodePaths[i]); 7470 maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified()); 7471 } 7472 } 7473 return maxModifiedTime; 7474 } 7475 return srcFile.lastModified(); 7476 } 7477 7478 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 7479 final int policyFlags) throws PackageManagerException { 7480 // When upgrading from pre-N MR1, verify the package time stamp using the package 7481 // directory and not the APK file. 7482 final long lastModifiedTime = mIsPreNMR1Upgrade 7483 ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile); 7484 if (ps != null 7485 && ps.codePath.equals(srcFile) 7486 && ps.timeStamp == lastModifiedTime 7487 && !isCompatSignatureUpdateNeeded(pkg) 7488 && !isRecoverSignatureUpdateNeeded(pkg)) { 7489 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 7490 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7491 ArraySet<PublicKey> signingKs; 7492 synchronized (mPackages) { 7493 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 7494 } 7495 if (ps.signatures.mSignatures != null 7496 && ps.signatures.mSignatures.length != 0 7497 && signingKs != null) { 7498 // Optimization: reuse the existing cached certificates 7499 // if the package appears to be unchanged. 7500 pkg.mSignatures = ps.signatures.mSignatures; 7501 pkg.mSigningKeys = signingKs; 7502 return; 7503 } 7504 7505 Slog.w(TAG, "PackageSetting for " + ps.name 7506 + " is missing signatures. Collecting certs again to recover them."); 7507 } else { 7508 Slog.i(TAG, srcFile.toString() + " changed; collecting certs"); 7509 } 7510 7511 try { 7512 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 7513 PackageParser.collectCertificates(pkg, policyFlags); 7514 } catch (PackageParserException e) { 7515 throw PackageManagerException.from(e); 7516 } finally { 7517 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7518 } 7519 } 7520 7521 /** 7522 * Traces a package scan. 7523 * @see #scanPackageLI(File, int, int, long, UserHandle) 7524 */ 7525 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 7526 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7527 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]"); 7528 try { 7529 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 7530 } finally { 7531 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7532 } 7533 } 7534 7535 /** 7536 * Scans a package and returns the newly parsed package. 7537 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 7538 */ 7539 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 7540 long currentTime, UserHandle user) throws PackageManagerException { 7541 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 7542 PackageParser pp = new PackageParser(); 7543 pp.setSeparateProcesses(mSeparateProcesses); 7544 pp.setOnlyCoreApps(mOnlyCore); 7545 pp.setDisplayMetrics(mMetrics); 7546 7547 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 7548 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 7549 } 7550 7551 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 7552 final PackageParser.Package pkg; 7553 try { 7554 pkg = pp.parsePackage(scanFile, parseFlags); 7555 } catch (PackageParserException e) { 7556 throw PackageManagerException.from(e); 7557 } finally { 7558 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7559 } 7560 7561 // Static shared libraries have synthetic package names 7562 if (pkg.applicationInfo.isStaticSharedLibrary()) { 7563 renameStaticSharedLibraryPackage(pkg); 7564 } 7565 7566 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 7567 } 7568 7569 /** 7570 * Scans a package and returns the newly parsed package. 7571 * @throws PackageManagerException on a parse error. 7572 */ 7573 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 7574 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 7575 throws PackageManagerException { 7576 // If the package has children and this is the first dive in the function 7577 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 7578 // packages (parent and children) would be successfully scanned before the 7579 // actual scan since scanning mutates internal state and we want to atomically 7580 // install the package and its children. 7581 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7582 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7583 scanFlags |= SCAN_CHECK_ONLY; 7584 } 7585 } else { 7586 scanFlags &= ~SCAN_CHECK_ONLY; 7587 } 7588 7589 // Scan the parent 7590 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 7591 scanFlags, currentTime, user); 7592 7593 // Scan the children 7594 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7595 for (int i = 0; i < childCount; i++) { 7596 PackageParser.Package childPackage = pkg.childPackages.get(i); 7597 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 7598 currentTime, user); 7599 } 7600 7601 7602 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7603 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 7604 } 7605 7606 return scannedPkg; 7607 } 7608 7609 /** 7610 * Scans a package and returns the newly parsed package. 7611 * @throws PackageManagerException on a parse error. 7612 */ 7613 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 7614 int policyFlags, int scanFlags, long currentTime, UserHandle user) 7615 throws PackageManagerException { 7616 PackageSetting ps = null; 7617 PackageSetting updatedPkg; 7618 // reader 7619 synchronized (mPackages) { 7620 // Look to see if we already know about this package. 7621 String oldName = mSettings.getRenamedPackageLPr(pkg.packageName); 7622 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 7623 // This package has been renamed to its original name. Let's 7624 // use that. 7625 ps = mSettings.getPackageLPr(oldName); 7626 } 7627 // If there was no original package, see one for the real package name. 7628 if (ps == null) { 7629 ps = mSettings.getPackageLPr(pkg.packageName); 7630 } 7631 // Check to see if this package could be hiding/updating a system 7632 // package. Must look for it either under the original or real 7633 // package name depending on our state. 7634 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 7635 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 7636 7637 // If this is a package we don't know about on the system partition, we 7638 // may need to remove disabled child packages on the system partition 7639 // or may need to not add child packages if the parent apk is updated 7640 // on the data partition and no longer defines this child package. 7641 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 7642 // If this is a parent package for an updated system app and this system 7643 // app got an OTA update which no longer defines some of the child packages 7644 // we have to prune them from the disabled system packages. 7645 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 7646 if (disabledPs != null) { 7647 final int scannedChildCount = (pkg.childPackages != null) 7648 ? pkg.childPackages.size() : 0; 7649 final int disabledChildCount = disabledPs.childPackageNames != null 7650 ? disabledPs.childPackageNames.size() : 0; 7651 for (int i = 0; i < disabledChildCount; i++) { 7652 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 7653 boolean disabledPackageAvailable = false; 7654 for (int j = 0; j < scannedChildCount; j++) { 7655 PackageParser.Package childPkg = pkg.childPackages.get(j); 7656 if (childPkg.packageName.equals(disabledChildPackageName)) { 7657 disabledPackageAvailable = true; 7658 break; 7659 } 7660 } 7661 if (!disabledPackageAvailable) { 7662 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 7663 } 7664 } 7665 } 7666 } 7667 } 7668 7669 boolean updatedPkgBetter = false; 7670 // First check if this is a system package that may involve an update 7671 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 7672 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 7673 // it needs to drop FLAG_PRIVILEGED. 7674 if (locationIsPrivileged(scanFile)) { 7675 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7676 } else { 7677 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7678 } 7679 7680 if (ps != null && !ps.codePath.equals(scanFile)) { 7681 // The path has changed from what was last scanned... check the 7682 // version of the new path against what we have stored to determine 7683 // what to do. 7684 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 7685 if (pkg.mVersionCode <= ps.versionCode) { 7686 // The system package has been updated and the code path does not match 7687 // Ignore entry. Skip it. 7688 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 7689 + " ignored: updated version " + ps.versionCode 7690 + " better than this " + pkg.mVersionCode); 7691 if (!updatedPkg.codePath.equals(scanFile)) { 7692 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 7693 + ps.name + " changing from " + updatedPkg.codePathString 7694 + " to " + scanFile); 7695 updatedPkg.codePath = scanFile; 7696 updatedPkg.codePathString = scanFile.toString(); 7697 updatedPkg.resourcePath = scanFile; 7698 updatedPkg.resourcePathString = scanFile.toString(); 7699 } 7700 updatedPkg.pkg = pkg; 7701 updatedPkg.versionCode = pkg.mVersionCode; 7702 7703 // Update the disabled system child packages to point to the package too. 7704 final int childCount = updatedPkg.childPackageNames != null 7705 ? updatedPkg.childPackageNames.size() : 0; 7706 for (int i = 0; i < childCount; i++) { 7707 String childPackageName = updatedPkg.childPackageNames.get(i); 7708 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 7709 childPackageName); 7710 if (updatedChildPkg != null) { 7711 updatedChildPkg.pkg = pkg; 7712 updatedChildPkg.versionCode = pkg.mVersionCode; 7713 } 7714 } 7715 7716 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 7717 + scanFile + " ignored: updated version " + ps.versionCode 7718 + " better than this " + pkg.mVersionCode); 7719 } else { 7720 // The current app on the system partition is better than 7721 // what we have updated to on the data partition; switch 7722 // back to the system partition version. 7723 // At this point, its safely assumed that package installation for 7724 // apps in system partition will go through. If not there won't be a working 7725 // version of the app 7726 // writer 7727 synchronized (mPackages) { 7728 // Just remove the loaded entries from package lists. 7729 mPackages.remove(ps.name); 7730 } 7731 7732 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7733 + " reverting from " + ps.codePathString 7734 + ": new version " + pkg.mVersionCode 7735 + " better than installed " + ps.versionCode); 7736 7737 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7738 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7739 synchronized (mInstallLock) { 7740 args.cleanUpResourcesLI(); 7741 } 7742 synchronized (mPackages) { 7743 mSettings.enableSystemPackageLPw(ps.name); 7744 } 7745 updatedPkgBetter = true; 7746 } 7747 } 7748 } 7749 7750 if (updatedPkg != null) { 7751 // An updated system app will not have the PARSE_IS_SYSTEM flag set 7752 // initially 7753 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 7754 7755 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 7756 // flag set initially 7757 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 7758 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 7759 } 7760 } 7761 7762 // Verify certificates against what was last scanned 7763 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 7764 7765 /* 7766 * A new system app appeared, but we already had a non-system one of the 7767 * same name installed earlier. 7768 */ 7769 boolean shouldHideSystemApp = false; 7770 if (updatedPkg == null && ps != null 7771 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 7772 /* 7773 * Check to make sure the signatures match first. If they don't, 7774 * wipe the installed application and its data. 7775 */ 7776 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 7777 != PackageManager.SIGNATURE_MATCH) { 7778 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 7779 + " signatures don't match existing userdata copy; removing"); 7780 try (PackageFreezer freezer = freezePackage(pkg.packageName, 7781 "scanPackageInternalLI")) { 7782 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 7783 } 7784 ps = null; 7785 } else { 7786 /* 7787 * If the newly-added system app is an older version than the 7788 * already installed version, hide it. It will be scanned later 7789 * and re-added like an update. 7790 */ 7791 if (pkg.mVersionCode <= ps.versionCode) { 7792 shouldHideSystemApp = true; 7793 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 7794 + " but new version " + pkg.mVersionCode + " better than installed " 7795 + ps.versionCode + "; hiding system"); 7796 } else { 7797 /* 7798 * The newly found system app is a newer version that the 7799 * one previously installed. Simply remove the 7800 * already-installed application and replace it with our own 7801 * while keeping the application data. 7802 */ 7803 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7804 + " reverting from " + ps.codePathString + ": new version " 7805 + pkg.mVersionCode + " better than installed " + ps.versionCode); 7806 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7807 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7808 synchronized (mInstallLock) { 7809 args.cleanUpResourcesLI(); 7810 } 7811 } 7812 } 7813 } 7814 7815 // The apk is forward locked (not public) if its code and resources 7816 // are kept in different files. (except for app in either system or 7817 // vendor path). 7818 // TODO grab this value from PackageSettings 7819 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7820 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 7821 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 7822 } 7823 } 7824 7825 // TODO: extend to support forward-locked splits 7826 String resourcePath = null; 7827 String baseResourcePath = null; 7828 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 7829 if (ps != null && ps.resourcePathString != null) { 7830 resourcePath = ps.resourcePathString; 7831 baseResourcePath = ps.resourcePathString; 7832 } else { 7833 // Should not happen at all. Just log an error. 7834 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 7835 } 7836 } else { 7837 resourcePath = pkg.codePath; 7838 baseResourcePath = pkg.baseCodePath; 7839 } 7840 7841 // Set application objects path explicitly. 7842 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 7843 pkg.setApplicationInfoCodePath(pkg.codePath); 7844 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 7845 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 7846 pkg.setApplicationInfoResourcePath(resourcePath); 7847 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 7848 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 7849 7850 // Note that we invoke the following method only if we are about to unpack an application 7851 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 7852 | SCAN_UPDATE_SIGNATURE, currentTime, user); 7853 7854 /* 7855 * If the system app should be overridden by a previously installed 7856 * data, hide the system app now and let the /data/app scan pick it up 7857 * again. 7858 */ 7859 if (shouldHideSystemApp) { 7860 synchronized (mPackages) { 7861 mSettings.disableSystemPackageLPw(pkg.packageName, true); 7862 } 7863 } 7864 7865 return scannedPkg; 7866 } 7867 7868 private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) { 7869 // Derive the new package synthetic package name 7870 pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER 7871 + pkg.staticSharedLibVersion); 7872 } 7873 7874 private static String fixProcessName(String defProcessName, 7875 String processName) { 7876 if (processName == null) { 7877 return defProcessName; 7878 } 7879 return processName; 7880 } 7881 7882 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 7883 throws PackageManagerException { 7884 if (pkgSetting.signatures.mSignatures != null) { 7885 // Already existing package. Make sure signatures match 7886 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 7887 == PackageManager.SIGNATURE_MATCH; 7888 if (!match) { 7889 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 7890 == PackageManager.SIGNATURE_MATCH; 7891 } 7892 if (!match) { 7893 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 7894 == PackageManager.SIGNATURE_MATCH; 7895 } 7896 if (!match) { 7897 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 7898 + pkg.packageName + " signatures do not match the " 7899 + "previously installed version; ignoring!"); 7900 } 7901 } 7902 7903 // Check for shared user signatures 7904 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 7905 // Already existing package. Make sure signatures match 7906 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7907 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 7908 if (!match) { 7909 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 7910 == PackageManager.SIGNATURE_MATCH; 7911 } 7912 if (!match) { 7913 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 7914 == PackageManager.SIGNATURE_MATCH; 7915 } 7916 if (!match) { 7917 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 7918 "Package " + pkg.packageName 7919 + " has no signatures that match those in shared user " 7920 + pkgSetting.sharedUser.name + "; ignoring!"); 7921 } 7922 } 7923 } 7924 7925 /** 7926 * Enforces that only the system UID or root's UID can call a method exposed 7927 * via Binder. 7928 * 7929 * @param message used as message if SecurityException is thrown 7930 * @throws SecurityException if the caller is not system or root 7931 */ 7932 private static final void enforceSystemOrRoot(String message) { 7933 final int uid = Binder.getCallingUid(); 7934 if (uid != Process.SYSTEM_UID && uid != 0) { 7935 throw new SecurityException(message); 7936 } 7937 } 7938 7939 @Override 7940 public void performFstrimIfNeeded() { 7941 enforceSystemOrRoot("Only the system can request fstrim"); 7942 7943 // Before everything else, see whether we need to fstrim. 7944 try { 7945 IStorageManager sm = PackageHelper.getStorageManager(); 7946 if (sm != null) { 7947 boolean doTrim = false; 7948 final long interval = android.provider.Settings.Global.getLong( 7949 mContext.getContentResolver(), 7950 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 7951 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 7952 if (interval > 0) { 7953 final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance(); 7954 if (timeSinceLast > interval) { 7955 doTrim = true; 7956 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 7957 + "; running immediately"); 7958 } 7959 } 7960 if (doTrim) { 7961 final boolean dexOptDialogShown; 7962 synchronized (mPackages) { 7963 dexOptDialogShown = mDexOptDialogShown; 7964 } 7965 if (!isFirstBoot() && dexOptDialogShown) { 7966 try { 7967 ActivityManager.getService().showBootMessage( 7968 mContext.getResources().getString( 7969 R.string.android_upgrading_fstrim), true); 7970 } catch (RemoteException e) { 7971 } 7972 } 7973 sm.runMaintenance(); 7974 } 7975 } else { 7976 Slog.e(TAG, "storageManager service unavailable!"); 7977 } 7978 } catch (RemoteException e) { 7979 // Can't happen; StorageManagerService is local 7980 } 7981 } 7982 7983 @Override 7984 public void updatePackagesIfNeeded() { 7985 enforceSystemOrRoot("Only the system can request package update"); 7986 7987 // We need to re-extract after an OTA. 7988 boolean causeUpgrade = isUpgrade(); 7989 7990 // First boot or factory reset. 7991 // Note: we also handle devices that are upgrading to N right now as if it is their 7992 // first boot, as they do not have profile data. 7993 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 7994 7995 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 7996 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 7997 7998 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 7999 return; 8000 } 8001 8002 List<PackageParser.Package> pkgs; 8003 synchronized (mPackages) { 8004 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 8005 } 8006 8007 final long startTime = System.nanoTime(); 8008 final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */, 8009 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT)); 8010 8011 final int elapsedTimeSeconds = 8012 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 8013 8014 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]); 8015 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]); 8016 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]); 8017 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 8018 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 8019 } 8020 8021 /** 8022 * Performs dexopt on the set of packages in {@code packages} and returns an int array 8023 * containing statistics about the invocation. The array consists of three elements, 8024 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped} 8025 * and {@code numberOfPackagesFailed}. 8026 */ 8027 private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog, 8028 String compilerFilter) { 8029 8030 int numberOfPackagesVisited = 0; 8031 int numberOfPackagesOptimized = 0; 8032 int numberOfPackagesSkipped = 0; 8033 int numberOfPackagesFailed = 0; 8034 final int numberOfPackagesToDexopt = pkgs.size(); 8035 8036 for (PackageParser.Package pkg : pkgs) { 8037 numberOfPackagesVisited++; 8038 8039 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 8040 if (DEBUG_DEXOPT) { 8041 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 8042 } 8043 numberOfPackagesSkipped++; 8044 continue; 8045 } 8046 8047 if (DEBUG_DEXOPT) { 8048 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 8049 numberOfPackagesToDexopt + ": " + pkg.packageName); 8050 } 8051 8052 if (showDialog) { 8053 try { 8054 ActivityManager.getService().showBootMessage( 8055 mContext.getResources().getString(R.string.android_upgrading_apk, 8056 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 8057 } catch (RemoteException e) { 8058 } 8059 synchronized (mPackages) { 8060 mDexOptDialogShown = true; 8061 } 8062 } 8063 8064 // If the OTA updates a system app which was previously preopted to a non-preopted state 8065 // the app might end up being verified at runtime. That's because by default the apps 8066 // are verify-profile but for preopted apps there's no profile. 8067 // Do a hacky check to ensure that if we have no profiles (a reasonable indication 8068 // that before the OTA the app was preopted) the app gets compiled with a non-profile 8069 // filter (by default interpret-only). 8070 // Note that at this stage unused apps are already filtered. 8071 if (isSystemApp(pkg) && 8072 DexFile.isProfileGuidedCompilerFilter(compilerFilter) && 8073 !Environment.getReferenceProfile(pkg.packageName).exists()) { 8074 compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter); 8075 } 8076 8077 // checkProfiles is false to avoid merging profiles during boot which 8078 // might interfere with background compilation (b/28612421). 8079 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 8080 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 8081 // trade-off worth doing to save boot time work. 8082 int dexOptStatus = performDexOptTraced(pkg.packageName, 8083 false /* checkProfiles */, 8084 compilerFilter, 8085 false /* force */); 8086 switch (dexOptStatus) { 8087 case PackageDexOptimizer.DEX_OPT_PERFORMED: 8088 numberOfPackagesOptimized++; 8089 break; 8090 case PackageDexOptimizer.DEX_OPT_SKIPPED: 8091 numberOfPackagesSkipped++; 8092 break; 8093 case PackageDexOptimizer.DEX_OPT_FAILED: 8094 numberOfPackagesFailed++; 8095 break; 8096 default: 8097 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus); 8098 break; 8099 } 8100 } 8101 8102 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped, 8103 numberOfPackagesFailed }; 8104 } 8105 8106 @Override 8107 public void notifyPackageUse(String packageName, int reason) { 8108 synchronized (mPackages) { 8109 PackageParser.Package p = mPackages.get(packageName); 8110 if (p == null) { 8111 return; 8112 } 8113 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 8114 } 8115 } 8116 8117 @Override 8118 public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) { 8119 int userId = UserHandle.getCallingUserId(); 8120 ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId); 8121 if (ai == null) { 8122 Slog.w(TAG, "Loading a package that does not exist for the calling user. package=" 8123 + loadingPackageName + ", user=" + userId); 8124 return; 8125 } 8126 mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId); 8127 } 8128 8129 // TODO: this is not used nor needed. Delete it. 8130 @Override 8131 public boolean performDexOptIfNeeded(String packageName) { 8132 int dexOptStatus = performDexOptTraced(packageName, 8133 false /* checkProfiles */, getFullCompilerFilter(), false /* force */); 8134 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 8135 } 8136 8137 @Override 8138 public boolean performDexOpt(String packageName, 8139 boolean checkProfiles, int compileReason, boolean force) { 8140 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 8141 getCompilerFilterForReason(compileReason), force); 8142 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 8143 } 8144 8145 @Override 8146 public boolean performDexOptMode(String packageName, 8147 boolean checkProfiles, String targetCompilerFilter, boolean force) { 8148 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 8149 targetCompilerFilter, force); 8150 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 8151 } 8152 8153 private int performDexOptTraced(String packageName, 8154 boolean checkProfiles, String targetCompilerFilter, boolean force) { 8155 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 8156 try { 8157 return performDexOptInternal(packageName, checkProfiles, 8158 targetCompilerFilter, force); 8159 } finally { 8160 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8161 } 8162 } 8163 8164 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 8165 // if the package can now be considered up to date for the given filter. 8166 private int performDexOptInternal(String packageName, 8167 boolean checkProfiles, String targetCompilerFilter, boolean force) { 8168 PackageParser.Package p; 8169 synchronized (mPackages) { 8170 p = mPackages.get(packageName); 8171 if (p == null) { 8172 // Package could not be found. Report failure. 8173 return PackageDexOptimizer.DEX_OPT_FAILED; 8174 } 8175 mPackageUsage.maybeWriteAsync(mPackages); 8176 mCompilerStats.maybeWriteAsync(); 8177 } 8178 long callingId = Binder.clearCallingIdentity(); 8179 try { 8180 synchronized (mInstallLock) { 8181 return performDexOptInternalWithDependenciesLI(p, checkProfiles, 8182 targetCompilerFilter, force); 8183 } 8184 } finally { 8185 Binder.restoreCallingIdentity(callingId); 8186 } 8187 } 8188 8189 public ArraySet<String> getOptimizablePackages() { 8190 ArraySet<String> pkgs = new ArraySet<String>(); 8191 synchronized (mPackages) { 8192 for (PackageParser.Package p : mPackages.values()) { 8193 if (PackageDexOptimizer.canOptimizePackage(p)) { 8194 pkgs.add(p.packageName); 8195 } 8196 } 8197 } 8198 return pkgs; 8199 } 8200 8201 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 8202 boolean checkProfiles, String targetCompilerFilter, 8203 boolean force) { 8204 // Select the dex optimizer based on the force parameter. 8205 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 8206 // allocate an object here. 8207 PackageDexOptimizer pdo = force 8208 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 8209 : mPackageDexOptimizer; 8210 8211 // Optimize all dependencies first. Note: we ignore the return value and march on 8212 // on errors. 8213 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 8214 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 8215 if (!deps.isEmpty()) { 8216 for (PackageParser.Package depPackage : deps) { 8217 // TODO: Analyze and investigate if we (should) profile libraries. 8218 // Currently this will do a full compilation of the library by default. 8219 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 8220 false /* checkProfiles */, 8221 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY), 8222 getOrCreateCompilerPackageStats(depPackage)); 8223 } 8224 } 8225 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 8226 targetCompilerFilter, getOrCreateCompilerPackageStats(p)); 8227 } 8228 8229 List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 8230 if (p.usesLibraries != null || p.usesOptionalLibraries != null 8231 || p.usesStaticLibraries != null) { 8232 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 8233 Set<String> collectedNames = new HashSet<>(); 8234 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 8235 8236 retValue.remove(p); 8237 8238 return retValue; 8239 } else { 8240 return Collections.emptyList(); 8241 } 8242 } 8243 8244 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 8245 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) { 8246 if (!collectedNames.contains(p.packageName)) { 8247 collectedNames.add(p.packageName); 8248 collected.add(p); 8249 8250 if (p.usesLibraries != null) { 8251 findSharedNonSystemLibrariesRecursive(p.usesLibraries, 8252 null, collected, collectedNames); 8253 } 8254 if (p.usesOptionalLibraries != null) { 8255 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, 8256 null, collected, collectedNames); 8257 } 8258 if (p.usesStaticLibraries != null) { 8259 findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries, 8260 p.usesStaticLibrariesVersions, collected, collectedNames); 8261 } 8262 } 8263 } 8264 8265 private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions, 8266 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) { 8267 final int libNameCount = libs.size(); 8268 for (int i = 0; i < libNameCount; i++) { 8269 String libName = libs.get(i); 8270 int version = (versions != null && versions.length == libNameCount) 8271 ? versions[i] : PackageManager.VERSION_CODE_HIGHEST; 8272 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version); 8273 if (libPkg != null) { 8274 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 8275 } 8276 } 8277 } 8278 8279 private PackageParser.Package findSharedNonSystemLibrary(String name, int version) { 8280 synchronized (mPackages) { 8281 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version); 8282 if (libEntry != null) { 8283 return mPackages.get(libEntry.apk); 8284 } 8285 return null; 8286 } 8287 } 8288 8289 private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) { 8290 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 8291 if (versionedLib == null) { 8292 return null; 8293 } 8294 return versionedLib.get(version); 8295 } 8296 8297 private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) { 8298 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get( 8299 pkg.staticSharedLibName); 8300 if (versionedLib == null) { 8301 return null; 8302 } 8303 int previousLibVersion = -1; 8304 final int versionCount = versionedLib.size(); 8305 for (int i = 0; i < versionCount; i++) { 8306 final int libVersion = versionedLib.keyAt(i); 8307 if (libVersion < pkg.staticSharedLibVersion) { 8308 previousLibVersion = Math.max(previousLibVersion, libVersion); 8309 } 8310 } 8311 if (previousLibVersion >= 0) { 8312 return versionedLib.get(previousLibVersion); 8313 } 8314 return null; 8315 } 8316 8317 public void shutdown() { 8318 mPackageUsage.writeNow(mPackages); 8319 mCompilerStats.writeNow(); 8320 } 8321 8322 @Override 8323 public void dumpProfiles(String packageName) { 8324 PackageParser.Package pkg; 8325 synchronized (mPackages) { 8326 pkg = mPackages.get(packageName); 8327 if (pkg == null) { 8328 throw new IllegalArgumentException("Unknown package: " + packageName); 8329 } 8330 } 8331 /* Only the shell, root, or the app user should be able to dump profiles. */ 8332 int callingUid = Binder.getCallingUid(); 8333 if (callingUid != Process.SHELL_UID && 8334 callingUid != Process.ROOT_UID && 8335 callingUid != pkg.applicationInfo.uid) { 8336 throw new SecurityException("dumpProfiles"); 8337 } 8338 8339 synchronized (mInstallLock) { 8340 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles"); 8341 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 8342 try { 8343 List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly(); 8344 String codePaths = TextUtils.join(";", allCodePaths); 8345 mInstaller.dumpProfiles(sharedGid, packageName, codePaths); 8346 } catch (InstallerException e) { 8347 Slog.w(TAG, "Failed to dump profiles", e); 8348 } 8349 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8350 } 8351 } 8352 8353 @Override 8354 public void forceDexOpt(String packageName) { 8355 enforceSystemOrRoot("forceDexOpt"); 8356 8357 PackageParser.Package pkg; 8358 synchronized (mPackages) { 8359 pkg = mPackages.get(packageName); 8360 if (pkg == null) { 8361 throw new IllegalArgumentException("Unknown package: " + packageName); 8362 } 8363 } 8364 8365 synchronized (mInstallLock) { 8366 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 8367 8368 // Whoever is calling forceDexOpt wants a fully compiled package. 8369 // Don't use profiles since that may cause compilation to be skipped. 8370 final int res = performDexOptInternalWithDependenciesLI(pkg, 8371 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 8372 true /* force */); 8373 8374 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8375 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 8376 throw new IllegalStateException("Failed to dexopt: " + res); 8377 } 8378 } 8379 } 8380 8381 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 8382 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 8383 Slog.w(TAG, "Unable to update from " + oldPkg.name 8384 + " to " + newPkg.packageName 8385 + ": old package not in system partition"); 8386 return false; 8387 } else if (mPackages.get(oldPkg.name) != null) { 8388 Slog.w(TAG, "Unable to update from " + oldPkg.name 8389 + " to " + newPkg.packageName 8390 + ": old package still exists"); 8391 return false; 8392 } 8393 return true; 8394 } 8395 8396 void removeCodePathLI(File codePath) { 8397 if (codePath.isDirectory()) { 8398 try { 8399 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 8400 } catch (InstallerException e) { 8401 Slog.w(TAG, "Failed to remove code path", e); 8402 } 8403 } else { 8404 codePath.delete(); 8405 } 8406 } 8407 8408 private int[] resolveUserIds(int userId) { 8409 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 8410 } 8411 8412 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 8413 if (pkg == null) { 8414 Slog.wtf(TAG, "Package was null!", new Throwable()); 8415 return; 8416 } 8417 clearAppDataLeafLIF(pkg, userId, flags); 8418 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8419 for (int i = 0; i < childCount; i++) { 8420 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 8421 } 8422 } 8423 8424 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 8425 final PackageSetting ps; 8426 synchronized (mPackages) { 8427 ps = mSettings.mPackages.get(pkg.packageName); 8428 } 8429 for (int realUserId : resolveUserIds(userId)) { 8430 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 8431 try { 8432 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 8433 ceDataInode); 8434 } catch (InstallerException e) { 8435 Slog.w(TAG, String.valueOf(e)); 8436 } 8437 } 8438 } 8439 8440 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 8441 if (pkg == null) { 8442 Slog.wtf(TAG, "Package was null!", new Throwable()); 8443 return; 8444 } 8445 destroyAppDataLeafLIF(pkg, userId, flags); 8446 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8447 for (int i = 0; i < childCount; i++) { 8448 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 8449 } 8450 } 8451 8452 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 8453 final PackageSetting ps; 8454 synchronized (mPackages) { 8455 ps = mSettings.mPackages.get(pkg.packageName); 8456 } 8457 for (int realUserId : resolveUserIds(userId)) { 8458 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 8459 try { 8460 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 8461 ceDataInode); 8462 } catch (InstallerException e) { 8463 Slog.w(TAG, String.valueOf(e)); 8464 } 8465 } 8466 } 8467 8468 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 8469 if (pkg == null) { 8470 Slog.wtf(TAG, "Package was null!", new Throwable()); 8471 return; 8472 } 8473 destroyAppProfilesLeafLIF(pkg); 8474 destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */); 8475 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8476 for (int i = 0; i < childCount; i++) { 8477 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 8478 destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId, 8479 true /* removeBaseMarker */); 8480 } 8481 } 8482 8483 private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId, 8484 boolean removeBaseMarker) { 8485 if (pkg.isForwardLocked()) { 8486 return; 8487 } 8488 8489 for (String path : pkg.getAllCodePathsExcludingResourceOnly()) { 8490 try { 8491 path = PackageManagerServiceUtils.realpath(new File(path)); 8492 } catch (IOException e) { 8493 // TODO: Should we return early here ? 8494 Slog.w(TAG, "Failed to get canonical path", e); 8495 continue; 8496 } 8497 8498 final String useMarker = path.replace('/', '@'); 8499 for (int realUserId : resolveUserIds(userId)) { 8500 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId); 8501 if (removeBaseMarker) { 8502 File foreignUseMark = new File(profileDir, useMarker); 8503 if (foreignUseMark.exists()) { 8504 if (!foreignUseMark.delete()) { 8505 Slog.w(TAG, "Unable to delete foreign user mark for package: " 8506 + pkg.packageName); 8507 } 8508 } 8509 } 8510 8511 File[] markers = profileDir.listFiles(); 8512 if (markers != null) { 8513 final String searchString = "@" + pkg.packageName + "@"; 8514 // We also delete all markers that contain the package name we're 8515 // uninstalling. These are associated with secondary dex-files belonging 8516 // to the package. Reconstructing the path of these dex files is messy 8517 // in general. 8518 for (File marker : markers) { 8519 if (marker.getName().indexOf(searchString) > 0) { 8520 if (!marker.delete()) { 8521 Slog.w(TAG, "Unable to delete foreign user mark for package: " 8522 + pkg.packageName); 8523 } 8524 } 8525 } 8526 } 8527 } 8528 } 8529 } 8530 8531 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 8532 try { 8533 mInstaller.destroyAppProfiles(pkg.packageName); 8534 } catch (InstallerException e) { 8535 Slog.w(TAG, String.valueOf(e)); 8536 } 8537 } 8538 8539 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 8540 if (pkg == null) { 8541 Slog.wtf(TAG, "Package was null!", new Throwable()); 8542 return; 8543 } 8544 clearAppProfilesLeafLIF(pkg); 8545 // We don't remove the base foreign use marker when clearing profiles because 8546 // we will rename it when the app is updated. Unlike the actual profile contents, 8547 // the foreign use marker is good across installs. 8548 destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */); 8549 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8550 for (int i = 0; i < childCount; i++) { 8551 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 8552 } 8553 } 8554 8555 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 8556 try { 8557 mInstaller.clearAppProfiles(pkg.packageName); 8558 } catch (InstallerException e) { 8559 Slog.w(TAG, String.valueOf(e)); 8560 } 8561 } 8562 8563 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 8564 long lastUpdateTime) { 8565 // Set parent install/update time 8566 PackageSetting ps = (PackageSetting) pkg.mExtras; 8567 if (ps != null) { 8568 ps.firstInstallTime = firstInstallTime; 8569 ps.lastUpdateTime = lastUpdateTime; 8570 } 8571 // Set children install/update time 8572 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8573 for (int i = 0; i < childCount; i++) { 8574 PackageParser.Package childPkg = pkg.childPackages.get(i); 8575 ps = (PackageSetting) childPkg.mExtras; 8576 if (ps != null) { 8577 ps.firstInstallTime = firstInstallTime; 8578 ps.lastUpdateTime = lastUpdateTime; 8579 } 8580 } 8581 } 8582 8583 private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 8584 PackageParser.Package changingLib) { 8585 if (file.path != null) { 8586 usesLibraryFiles.add(file.path); 8587 return; 8588 } 8589 PackageParser.Package p = mPackages.get(file.apk); 8590 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 8591 // If we are doing this while in the middle of updating a library apk, 8592 // then we need to make sure to use that new apk for determining the 8593 // dependencies here. (We haven't yet finished committing the new apk 8594 // to the package manager state.) 8595 if (p == null || p.packageName.equals(changingLib.packageName)) { 8596 p = changingLib; 8597 } 8598 } 8599 if (p != null) { 8600 usesLibraryFiles.addAll(p.getAllCodePaths()); 8601 } 8602 } 8603 8604 private void updateSharedLibrariesLPr(PackageParser.Package pkg, 8605 PackageParser.Package changingLib) throws PackageManagerException { 8606 if (pkg == null) { 8607 return; 8608 } 8609 ArraySet<String> usesLibraryFiles = null; 8610 if (pkg.usesLibraries != null) { 8611 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries, 8612 null, null, pkg.packageName, changingLib, true, null); 8613 } 8614 if (pkg.usesStaticLibraries != null) { 8615 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries, 8616 pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests, 8617 pkg.packageName, changingLib, true, usesLibraryFiles); 8618 } 8619 if (pkg.usesOptionalLibraries != null) { 8620 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries, 8621 null, null, pkg.packageName, changingLib, false, usesLibraryFiles); 8622 } 8623 if (!ArrayUtils.isEmpty(usesLibraryFiles)) { 8624 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]); 8625 } else { 8626 pkg.usesLibraryFiles = null; 8627 } 8628 } 8629 8630 private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries, 8631 @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests, 8632 @NonNull String packageName, @Nullable PackageParser.Package changingLib, 8633 boolean required, @Nullable ArraySet<String> outUsedLibraries) 8634 throws PackageManagerException { 8635 final int libCount = requestedLibraries.size(); 8636 for (int i = 0; i < libCount; i++) { 8637 final String libName = requestedLibraries.get(i); 8638 final int libVersion = requiredVersions != null ? requiredVersions[i] 8639 : SharedLibraryInfo.VERSION_UNDEFINED; 8640 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion); 8641 if (libEntry == null) { 8642 if (required) { 8643 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8644 "Package " + packageName + " requires unavailable shared library " 8645 + libName + "; failing!"); 8646 } else { 8647 Slog.w(TAG, "Package " + packageName 8648 + " desires unavailable shared library " 8649 + libName + "; ignoring!"); 8650 } 8651 } else { 8652 if (requiredVersions != null && requiredCertDigests != null) { 8653 if (libEntry.info.getVersion() != requiredVersions[i]) { 8654 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8655 "Package " + packageName + " requires unavailable static shared" 8656 + " library " + libName + " version " 8657 + libEntry.info.getVersion() + "; failing!"); 8658 } 8659 8660 PackageParser.Package libPkg = mPackages.get(libEntry.apk); 8661 if (libPkg == null) { 8662 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8663 "Package " + packageName + " requires unavailable static shared" 8664 + " library; failing!"); 8665 } 8666 8667 String expectedCertDigest = requiredCertDigests[i]; 8668 String libCertDigest = PackageUtils.computeCertSha256Digest( 8669 libPkg.mSignatures[0]); 8670 if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) { 8671 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8672 "Package " + packageName + " requires differently signed" + 8673 " static shared library; failing!"); 8674 } 8675 } 8676 8677 if (outUsedLibraries == null) { 8678 outUsedLibraries = new ArraySet<>(); 8679 } 8680 addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib); 8681 } 8682 } 8683 return outUsedLibraries; 8684 } 8685 8686 private static boolean hasString(List<String> list, List<String> which) { 8687 if (list == null) { 8688 return false; 8689 } 8690 for (int i=list.size()-1; i>=0; i--) { 8691 for (int j=which.size()-1; j>=0; j--) { 8692 if (which.get(j).equals(list.get(i))) { 8693 return true; 8694 } 8695 } 8696 } 8697 return false; 8698 } 8699 8700 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 8701 PackageParser.Package changingPkg) { 8702 ArrayList<PackageParser.Package> res = null; 8703 for (PackageParser.Package pkg : mPackages.values()) { 8704 if (changingPkg != null 8705 && !hasString(pkg.usesLibraries, changingPkg.libraryNames) 8706 && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames) 8707 && !ArrayUtils.contains(pkg.usesStaticLibraries, 8708 changingPkg.staticSharedLibName)) { 8709 return null; 8710 } 8711 if (res == null) { 8712 res = new ArrayList<>(); 8713 } 8714 res.add(pkg); 8715 try { 8716 updateSharedLibrariesLPr(pkg, changingPkg); 8717 } catch (PackageManagerException e) { 8718 // If a system app update or an app and a required lib missing we 8719 // delete the package and for updated system apps keep the data as 8720 // it is better for the user to reinstall than to be in an limbo 8721 // state. Also libs disappearing under an app should never happen 8722 // - just in case. 8723 if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) { 8724 final int flags = pkg.isUpdatedSystemApp() 8725 ? PackageManager.DELETE_KEEP_DATA : 0; 8726 deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(), 8727 flags , null, true, null); 8728 } 8729 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 8730 } 8731 } 8732 return res; 8733 } 8734 8735 /** 8736 * Derive the value of the {@code cpuAbiOverride} based on the provided 8737 * value and an optional stored value from the package settings. 8738 */ 8739 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 8740 String cpuAbiOverride = null; 8741 8742 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 8743 cpuAbiOverride = null; 8744 } else if (abiOverride != null) { 8745 cpuAbiOverride = abiOverride; 8746 } else if (settings != null) { 8747 cpuAbiOverride = settings.cpuAbiOverrideString; 8748 } 8749 8750 return cpuAbiOverride; 8751 } 8752 8753 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 8754 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 8755 throws PackageManagerException { 8756 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 8757 // If the package has children and this is the first dive in the function 8758 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 8759 // whether all packages (parent and children) would be successfully scanned 8760 // before the actual scan since scanning mutates internal state and we want 8761 // to atomically install the package and its children. 8762 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8763 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 8764 scanFlags |= SCAN_CHECK_ONLY; 8765 } 8766 } else { 8767 scanFlags &= ~SCAN_CHECK_ONLY; 8768 } 8769 8770 final PackageParser.Package scannedPkg; 8771 try { 8772 // Scan the parent 8773 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 8774 // Scan the children 8775 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8776 for (int i = 0; i < childCount; i++) { 8777 PackageParser.Package childPkg = pkg.childPackages.get(i); 8778 scanPackageLI(childPkg, policyFlags, 8779 scanFlags, currentTime, user); 8780 } 8781 } finally { 8782 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8783 } 8784 8785 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8786 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 8787 } 8788 8789 return scannedPkg; 8790 } 8791 8792 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 8793 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 8794 boolean success = false; 8795 try { 8796 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 8797 currentTime, user); 8798 success = true; 8799 return res; 8800 } finally { 8801 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 8802 // DELETE_DATA_ON_FAILURES is only used by frozen paths 8803 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 8804 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 8805 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 8806 } 8807 } 8808 } 8809 8810 /** 8811 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 8812 */ 8813 private static boolean apkHasCode(String fileName) { 8814 StrictJarFile jarFile = null; 8815 try { 8816 jarFile = new StrictJarFile(fileName, 8817 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 8818 return jarFile.findEntry("classes.dex") != null; 8819 } catch (IOException ignore) { 8820 } finally { 8821 try { 8822 if (jarFile != null) { 8823 jarFile.close(); 8824 } 8825 } catch (IOException ignore) {} 8826 } 8827 return false; 8828 } 8829 8830 /** 8831 * Enforces code policy for the package. This ensures that if an APK has 8832 * declared hasCode="true" in its manifest that the APK actually contains 8833 * code. 8834 * 8835 * @throws PackageManagerException If bytecode could not be found when it should exist 8836 */ 8837 private static void assertCodePolicy(PackageParser.Package pkg) 8838 throws PackageManagerException { 8839 final boolean shouldHaveCode = 8840 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 8841 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 8842 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8843 "Package " + pkg.baseCodePath + " code is missing"); 8844 } 8845 8846 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 8847 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 8848 final boolean splitShouldHaveCode = 8849 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 8850 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 8851 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8852 "Package " + pkg.splitCodePaths[i] + " code is missing"); 8853 } 8854 } 8855 } 8856 } 8857 8858 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 8859 final int policyFlags, final int scanFlags, long currentTime, UserHandle user) 8860 throws PackageManagerException { 8861 if (DEBUG_PACKAGE_SCANNING) { 8862 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8863 Log.d(TAG, "Scanning package " + pkg.packageName); 8864 } 8865 8866 applyPolicy(pkg, policyFlags); 8867 8868 assertPackageIsValid(pkg, policyFlags, scanFlags); 8869 8870 // Initialize package source and resource directories 8871 final File scanFile = new File(pkg.codePath); 8872 final File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 8873 final File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 8874 8875 SharedUserSetting suid = null; 8876 PackageSetting pkgSetting = null; 8877 8878 // Getting the package setting may have a side-effect, so if we 8879 // are only checking if scan would succeed, stash a copy of the 8880 // old setting to restore at the end. 8881 PackageSetting nonMutatedPs = null; 8882 8883 // We keep references to the derived CPU Abis from settings in oder to reuse 8884 // them in the case where we're not upgrading or booting for the first time. 8885 String primaryCpuAbiFromSettings = null; 8886 String secondaryCpuAbiFromSettings = null; 8887 8888 // writer 8889 synchronized (mPackages) { 8890 if (pkg.mSharedUserId != null) { 8891 // SIDE EFFECTS; may potentially allocate a new shared user 8892 suid = mSettings.getSharedUserLPw( 8893 pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/); 8894 if (DEBUG_PACKAGE_SCANNING) { 8895 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8896 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 8897 + "): packages=" + suid.packages); 8898 } 8899 } 8900 8901 // Check if we are renaming from an original package name. 8902 PackageSetting origPackage = null; 8903 String realName = null; 8904 if (pkg.mOriginalPackages != null) { 8905 // This package may need to be renamed to a previously 8906 // installed name. Let's check on that... 8907 final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage); 8908 if (pkg.mOriginalPackages.contains(renamed)) { 8909 // This package had originally been installed as the 8910 // original name, and we have already taken care of 8911 // transitioning to the new one. Just update the new 8912 // one to continue using the old name. 8913 realName = pkg.mRealPackage; 8914 if (!pkg.packageName.equals(renamed)) { 8915 // Callers into this function may have already taken 8916 // care of renaming the package; only do it here if 8917 // it is not already done. 8918 pkg.setPackageName(renamed); 8919 } 8920 } else { 8921 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 8922 if ((origPackage = mSettings.getPackageLPr( 8923 pkg.mOriginalPackages.get(i))) != null) { 8924 // We do have the package already installed under its 8925 // original name... should we use it? 8926 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 8927 // New package is not compatible with original. 8928 origPackage = null; 8929 continue; 8930 } else if (origPackage.sharedUser != null) { 8931 // Make sure uid is compatible between packages. 8932 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 8933 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 8934 + " to " + pkg.packageName + ": old uid " 8935 + origPackage.sharedUser.name 8936 + " differs from " + pkg.mSharedUserId); 8937 origPackage = null; 8938 continue; 8939 } 8940 // TODO: Add case when shared user id is added [b/28144775] 8941 } else { 8942 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 8943 + pkg.packageName + " to old name " + origPackage.name); 8944 } 8945 break; 8946 } 8947 } 8948 } 8949 } 8950 8951 if (mTransferedPackages.contains(pkg.packageName)) { 8952 Slog.w(TAG, "Package " + pkg.packageName 8953 + " was transferred to another, but its .apk remains"); 8954 } 8955 8956 // See comments in nonMutatedPs declaration 8957 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8958 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName); 8959 if (foundPs != null) { 8960 nonMutatedPs = new PackageSetting(foundPs); 8961 } 8962 } 8963 8964 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) { 8965 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName); 8966 if (foundPs != null) { 8967 primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString; 8968 secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString; 8969 } 8970 } 8971 8972 pkgSetting = mSettings.getPackageLPr(pkg.packageName); 8973 if (pkgSetting != null && pkgSetting.sharedUser != suid) { 8974 PackageManagerService.reportSettingsProblem(Log.WARN, 8975 "Package " + pkg.packageName + " shared user changed from " 8976 + (pkgSetting.sharedUser != null 8977 ? pkgSetting.sharedUser.name : "<nothing>") 8978 + " to " 8979 + (suid != null ? suid.name : "<nothing>") 8980 + "; replacing with new"); 8981 pkgSetting = null; 8982 } 8983 final PackageSetting oldPkgSetting = 8984 pkgSetting == null ? null : new PackageSetting(pkgSetting); 8985 final PackageSetting disabledPkgSetting = 8986 mSettings.getDisabledSystemPkgLPr(pkg.packageName); 8987 8988 String[] usesStaticLibraries = null; 8989 if (pkg.usesStaticLibraries != null) { 8990 usesStaticLibraries = new String[pkg.usesStaticLibraries.size()]; 8991 pkg.usesStaticLibraries.toArray(usesStaticLibraries); 8992 } 8993 8994 if (pkgSetting == null) { 8995 final String parentPackageName = (pkg.parentPackage != null) 8996 ? pkg.parentPackage.packageName : null; 8997 8998 // REMOVE SharedUserSetting from method; update in a separate call 8999 pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage, 9000 disabledPkgSetting, realName, suid, destCodeFile, destResourceFile, 9001 pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi, 9002 pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode, 9003 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user, 9004 true /*allowInstall*/, parentPackageName, pkg.getChildPackageNames(), 9005 UserManagerService.getInstance(), usesStaticLibraries, 9006 pkg.usesStaticLibrariesVersions); 9007 // SIDE EFFECTS; updates system state; move elsewhere 9008 if (origPackage != null) { 9009 mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name); 9010 } 9011 mSettings.addUserToSettingLPw(pkgSetting); 9012 } else { 9013 // REMOVE SharedUserSetting from method; update in a separate call. 9014 // 9015 // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi, 9016 // secondaryCpuAbi are not known at this point so we always update them 9017 // to null here, only to reset them at a later point. 9018 Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile, 9019 pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi, 9020 pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags, 9021 pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(), 9022 UserManagerService.getInstance(), usesStaticLibraries, 9023 pkg.usesStaticLibrariesVersions); 9024 } 9025 // SIDE EFFECTS; persists system state to files on disk; move elsewhere 9026 mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting); 9027 9028 // SIDE EFFECTS; modifies system state; move elsewhere 9029 if (pkgSetting.origPackage != null) { 9030 // If we are first transitioning from an original package, 9031 // fix up the new package's name now. We need to do this after 9032 // looking up the package under its new name, so getPackageLP 9033 // can take care of fiddling things correctly. 9034 pkg.setPackageName(origPackage.name); 9035 9036 // File a report about this. 9037 String msg = "New package " + pkgSetting.realName 9038 + " renamed to replace old package " + pkgSetting.name; 9039 reportSettingsProblem(Log.WARN, msg); 9040 9041 // Make a note of it. 9042 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 9043 mTransferedPackages.add(origPackage.name); 9044 } 9045 9046 // No longer need to retain this. 9047 pkgSetting.origPackage = null; 9048 } 9049 9050 // SIDE EFFECTS; modifies system state; move elsewhere 9051 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 9052 // Make a note of it. 9053 mTransferedPackages.add(pkg.packageName); 9054 } 9055 9056 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 9057 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 9058 } 9059 9060 if ((scanFlags & SCAN_BOOTING) == 0 9061 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 9062 // Check all shared libraries and map to their actual file path. 9063 // We only do this here for apps not on a system dir, because those 9064 // are the only ones that can fail an install due to this. We 9065 // will take care of the system apps by updating all of their 9066 // library paths after the scan is done. Also during the initial 9067 // scan don't update any libs as we do this wholesale after all 9068 // apps are scanned to avoid dependency based scanning. 9069 updateSharedLibrariesLPr(pkg, null); 9070 } 9071 9072 if (mFoundPolicyFile) { 9073 SELinuxMMAC.assignSeinfoValue(pkg); 9074 } 9075 9076 pkg.applicationInfo.uid = pkgSetting.appId; 9077 pkg.mExtras = pkgSetting; 9078 9079 9080 // Static shared libs have same package with different versions where 9081 // we internally use a synthetic package name to allow multiple versions 9082 // of the same package, therefore we need to compare signatures against 9083 // the package setting for the latest library version. 9084 PackageSetting signatureCheckPs = pkgSetting; 9085 if (pkg.applicationInfo.isStaticSharedLibrary()) { 9086 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg); 9087 if (libraryEntry != null) { 9088 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk); 9089 } 9090 } 9091 9092 if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) { 9093 if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) { 9094 // We just determined the app is signed correctly, so bring 9095 // over the latest parsed certs. 9096 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9097 } else { 9098 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 9099 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 9100 "Package " + pkg.packageName + " upgrade keys do not match the " 9101 + "previously installed version"); 9102 } else { 9103 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9104 String msg = "System package " + pkg.packageName 9105 + " signature changed; retaining data."; 9106 reportSettingsProblem(Log.WARN, msg); 9107 } 9108 } 9109 } else { 9110 try { 9111 // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService 9112 verifySignaturesLP(signatureCheckPs, pkg); 9113 // We just determined the app is signed correctly, so bring 9114 // over the latest parsed certs. 9115 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9116 } catch (PackageManagerException e) { 9117 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 9118 throw e; 9119 } 9120 // The signature has changed, but this package is in the system 9121 // image... let's recover! 9122 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9123 // However... if this package is part of a shared user, but it 9124 // doesn't match the signature of the shared user, let's fail. 9125 // What this means is that you can't change the signatures 9126 // associated with an overall shared user, which doesn't seem all 9127 // that unreasonable. 9128 if (signatureCheckPs.sharedUser != null) { 9129 if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures, 9130 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 9131 throw new PackageManagerException( 9132 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 9133 "Signature mismatch for shared user: " 9134 + pkgSetting.sharedUser); 9135 } 9136 } 9137 // File a report about this. 9138 String msg = "System package " + pkg.packageName 9139 + " signature changed; retaining data."; 9140 reportSettingsProblem(Log.WARN, msg); 9141 } 9142 } 9143 9144 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 9145 // This package wants to adopt ownership of permissions from 9146 // another package. 9147 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 9148 final String origName = pkg.mAdoptPermissions.get(i); 9149 final PackageSetting orig = mSettings.getPackageLPr(origName); 9150 if (orig != null) { 9151 if (verifyPackageUpdateLPr(orig, pkg)) { 9152 Slog.i(TAG, "Adopting permissions from " + origName + " to " 9153 + pkg.packageName); 9154 // SIDE EFFECTS; updates permissions system state; move elsewhere 9155 mSettings.transferPermissionsLPw(origName, pkg.packageName); 9156 } 9157 } 9158 } 9159 } 9160 } 9161 9162 pkg.applicationInfo.processName = fixProcessName( 9163 pkg.applicationInfo.packageName, 9164 pkg.applicationInfo.processName); 9165 9166 if (pkg != mPlatformPackage) { 9167 // Get all of our default paths setup 9168 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 9169 } 9170 9171 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 9172 9173 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 9174 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) { 9175 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi"); 9176 derivePackageAbi( 9177 pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir); 9178 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9179 9180 // Some system apps still use directory structure for native libraries 9181 // in which case we might end up not detecting abi solely based on apk 9182 // structure. Try to detect abi based on directory structure. 9183 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 9184 pkg.applicationInfo.primaryCpuAbi == null) { 9185 setBundledAppAbisAndRoots(pkg, pkgSetting); 9186 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 9187 } 9188 } else { 9189 // This is not a first boot or an upgrade, don't bother deriving the 9190 // ABI during the scan. Instead, trust the value that was stored in the 9191 // package setting. 9192 pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings; 9193 pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings; 9194 9195 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 9196 9197 if (DEBUG_ABI_SELECTION) { 9198 Slog.i(TAG, "Using ABIS and native lib paths from settings : " + 9199 pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " + 9200 pkg.applicationInfo.secondaryCpuAbi); 9201 } 9202 } 9203 } else { 9204 if ((scanFlags & SCAN_MOVE) != 0) { 9205 // We haven't run dex-opt for this move (since we've moved the compiled output too) 9206 // but we already have this packages package info in the PackageSetting. We just 9207 // use that and derive the native library path based on the new codepath. 9208 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 9209 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 9210 } 9211 9212 // Set native library paths again. For moves, the path will be updated based on the 9213 // ABIs we've determined above. For non-moves, the path will be updated based on the 9214 // ABIs we determined during compilation, but the path will depend on the final 9215 // package path (after the rename away from the stage path). 9216 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 9217 } 9218 9219 // This is a special case for the "system" package, where the ABI is 9220 // dictated by the zygote configuration (and init.rc). We should keep track 9221 // of this ABI so that we can deal with "normal" applications that run under 9222 // the same UID correctly. 9223 if (mPlatformPackage == pkg) { 9224 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 9225 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 9226 } 9227 9228 // If there's a mismatch between the abi-override in the package setting 9229 // and the abiOverride specified for the install. Warn about this because we 9230 // would've already compiled the app without taking the package setting into 9231 // account. 9232 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 9233 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 9234 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 9235 " for package " + pkg.packageName); 9236 } 9237 } 9238 9239 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9240 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9241 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 9242 9243 // Copy the derived override back to the parsed package, so that we can 9244 // update the package settings accordingly. 9245 pkg.cpuAbiOverride = cpuAbiOverride; 9246 9247 if (DEBUG_ABI_SELECTION) { 9248 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 9249 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 9250 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 9251 } 9252 9253 // Push the derived path down into PackageSettings so we know what to 9254 // clean up at uninstall time. 9255 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 9256 9257 if (DEBUG_ABI_SELECTION) { 9258 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 9259 " primary=" + pkg.applicationInfo.primaryCpuAbi + 9260 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 9261 } 9262 9263 // SIDE EFFECTS; removes DEX files from disk; move elsewhere 9264 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 9265 // We don't do this here during boot because we can do it all 9266 // at once after scanning all existing packages. 9267 // 9268 // We also do this *before* we perform dexopt on this package, so that 9269 // we can avoid redundant dexopts, and also to make sure we've got the 9270 // code and package path correct. 9271 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg); 9272 } 9273 9274 if (mFactoryTest && pkg.requestedPermissions.contains( 9275 android.Manifest.permission.FACTORY_TEST)) { 9276 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 9277 } 9278 9279 if (isSystemApp(pkg)) { 9280 pkgSetting.isOrphaned = true; 9281 } 9282 9283 // Take care of first install / last update times. 9284 final long scanFileTime = getLastModifiedTime(pkg, scanFile); 9285 if (currentTime != 0) { 9286 if (pkgSetting.firstInstallTime == 0) { 9287 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 9288 } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) { 9289 pkgSetting.lastUpdateTime = currentTime; 9290 } 9291 } else if (pkgSetting.firstInstallTime == 0) { 9292 // We need *something*. Take time time stamp of the file. 9293 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 9294 } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 9295 if (scanFileTime != pkgSetting.timeStamp) { 9296 // A package on the system image has changed; consider this 9297 // to be an update. 9298 pkgSetting.lastUpdateTime = scanFileTime; 9299 } 9300 } 9301 pkgSetting.setTimeStamp(scanFileTime); 9302 9303 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 9304 if (nonMutatedPs != null) { 9305 synchronized (mPackages) { 9306 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 9307 } 9308 } 9309 } else { 9310 // Modify state for the given package setting 9311 commitPackageSettings(pkg, pkgSetting, user, scanFlags, 9312 (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/); 9313 if (isEphemeral(pkg)) { 9314 final int userId = user == null ? 0 : user.getIdentifier(); 9315 mEphemeralApplicationRegistry.addEphemeralAppLPw(userId, pkgSetting.appId); 9316 } 9317 } 9318 return pkg; 9319 } 9320 9321 /** 9322 * Applies policy to the parsed package based upon the given policy flags. 9323 * Ensures the package is in a good state. 9324 * <p> 9325 * Implementation detail: This method must NOT have any side effect. It would 9326 * ideally be static, but, it requires locks to read system state. 9327 */ 9328 private void applyPolicy(PackageParser.Package pkg, int policyFlags) { 9329 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 9330 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 9331 if (pkg.applicationInfo.isDirectBootAware()) { 9332 // we're direct boot aware; set for all components 9333 for (PackageParser.Service s : pkg.services) { 9334 s.info.encryptionAware = s.info.directBootAware = true; 9335 } 9336 for (PackageParser.Provider p : pkg.providers) { 9337 p.info.encryptionAware = p.info.directBootAware = true; 9338 } 9339 for (PackageParser.Activity a : pkg.activities) { 9340 a.info.encryptionAware = a.info.directBootAware = true; 9341 } 9342 for (PackageParser.Activity r : pkg.receivers) { 9343 r.info.encryptionAware = r.info.directBootAware = true; 9344 } 9345 } 9346 } else { 9347 // Only allow system apps to be flagged as core apps. 9348 pkg.coreApp = false; 9349 // clear flags not applicable to regular apps 9350 pkg.applicationInfo.privateFlags &= 9351 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 9352 pkg.applicationInfo.privateFlags &= 9353 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 9354 } 9355 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 9356 9357 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 9358 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 9359 } 9360 9361 if (!isSystemApp(pkg)) { 9362 // Only system apps can use these features. 9363 pkg.mOriginalPackages = null; 9364 pkg.mRealPackage = null; 9365 pkg.mAdoptPermissions = null; 9366 } 9367 } 9368 9369 /** 9370 * Asserts the parsed package is valid according to the given policy. If the 9371 * package is invalid, for whatever reason, throws {@link PackgeManagerException}. 9372 * <p> 9373 * Implementation detail: This method must NOT have any side effects. It would 9374 * ideally be static, but, it requires locks to read system state. 9375 * 9376 * @throws PackageManagerException If the package fails any of the validation checks 9377 */ 9378 private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags) 9379 throws PackageManagerException { 9380 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 9381 assertCodePolicy(pkg); 9382 } 9383 9384 if (pkg.applicationInfo.getCodePath() == null || 9385 pkg.applicationInfo.getResourcePath() == null) { 9386 // Bail out. The resource and code paths haven't been set. 9387 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 9388 "Code and resource paths haven't been set correctly"); 9389 } 9390 9391 // Make sure we're not adding any bogus keyset info 9392 KeySetManagerService ksms = mSettings.mKeySetManagerService; 9393 ksms.assertScannedPackageValid(pkg); 9394 9395 synchronized (mPackages) { 9396 // The special "android" package can only be defined once 9397 if (pkg.packageName.equals("android")) { 9398 if (mAndroidApplication != null) { 9399 Slog.w(TAG, "*************************************************"); 9400 Slog.w(TAG, "Core android package being redefined. Skipping."); 9401 Slog.w(TAG, " codePath=" + pkg.codePath); 9402 Slog.w(TAG, "*************************************************"); 9403 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 9404 "Core android package being redefined. Skipping."); 9405 } 9406 } 9407 9408 // A package name must be unique; don't allow duplicates 9409 if (mPackages.containsKey(pkg.packageName)) { 9410 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 9411 "Application package " + pkg.packageName 9412 + " already installed. Skipping duplicate."); 9413 } 9414 9415 if (pkg.applicationInfo.isStaticSharedLibrary()) { 9416 // Static libs have a synthetic package name containing the version 9417 // but we still want the base name to be unique. 9418 if (mPackages.containsKey(pkg.manifestPackageName)) { 9419 throw new PackageManagerException( 9420 "Duplicate static shared lib provider package"); 9421 } 9422 9423 // Static shared libraries should have at least O target SDK 9424 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) { 9425 throw new PackageManagerException( 9426 "Packages declaring static-shared libs must target O SDK or higher"); 9427 } 9428 9429 // Package declaring static a shared lib cannot be ephemeral 9430 if (pkg.applicationInfo.isEphemeralApp()) { 9431 throw new PackageManagerException( 9432 "Packages declaring static-shared libs cannot be ephemeral"); 9433 } 9434 9435 // Package declaring static a shared lib cannot be renamed since the package 9436 // name is synthetic and apps can't code around package manager internals. 9437 if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) { 9438 throw new PackageManagerException( 9439 "Packages declaring static-shared libs cannot be renamed"); 9440 } 9441 9442 // Package declaring static a shared lib cannot declare child packages 9443 if (!ArrayUtils.isEmpty(pkg.childPackages)) { 9444 throw new PackageManagerException( 9445 "Packages declaring static-shared libs cannot have child packages"); 9446 } 9447 9448 // Package declaring static a shared lib cannot declare dynamic libs 9449 if (!ArrayUtils.isEmpty(pkg.libraryNames)) { 9450 throw new PackageManagerException( 9451 "Packages declaring static-shared libs cannot declare dynamic libs"); 9452 } 9453 9454 // Package declaring static a shared lib cannot declare shared users 9455 if (pkg.mSharedUserId != null) { 9456 throw new PackageManagerException( 9457 "Packages declaring static-shared libs cannot declare shared users"); 9458 } 9459 9460 // Static shared libs cannot declare activities 9461 if (!pkg.activities.isEmpty()) { 9462 throw new PackageManagerException( 9463 "Static shared libs cannot declare activities"); 9464 } 9465 9466 // Static shared libs cannot declare services 9467 if (!pkg.services.isEmpty()) { 9468 throw new PackageManagerException( 9469 "Static shared libs cannot declare services"); 9470 } 9471 9472 // Static shared libs cannot declare providers 9473 if (!pkg.providers.isEmpty()) { 9474 throw new PackageManagerException( 9475 "Static shared libs cannot declare content providers"); 9476 } 9477 9478 // Static shared libs cannot declare receivers 9479 if (!pkg.receivers.isEmpty()) { 9480 throw new PackageManagerException( 9481 "Static shared libs cannot declare broadcast receivers"); 9482 } 9483 9484 // Static shared libs cannot declare permission groups 9485 if (!pkg.permissionGroups.isEmpty()) { 9486 throw new PackageManagerException( 9487 "Static shared libs cannot declare permission groups"); 9488 } 9489 9490 // Static shared libs cannot declare permissions 9491 if (!pkg.permissions.isEmpty()) { 9492 throw new PackageManagerException( 9493 "Static shared libs cannot declare permissions"); 9494 } 9495 9496 // Static shared libs cannot declare protected broadcasts 9497 if (pkg.protectedBroadcasts != null) { 9498 throw new PackageManagerException( 9499 "Static shared libs cannot declare protected broadcasts"); 9500 } 9501 9502 // Static shared libs cannot be overlay targets 9503 if (pkg.mOverlayTarget != null) { 9504 throw new PackageManagerException( 9505 "Static shared libs cannot be overlay targets"); 9506 } 9507 9508 // The version codes must be ordered as lib versions 9509 int minVersionCode = Integer.MIN_VALUE; 9510 int maxVersionCode = Integer.MAX_VALUE; 9511 9512 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get( 9513 pkg.staticSharedLibName); 9514 if (versionedLib != null) { 9515 final int versionCount = versionedLib.size(); 9516 for (int i = 0; i < versionCount; i++) { 9517 SharedLibraryInfo libInfo = versionedLib.valueAt(i).info; 9518 // TODO: We will change version code to long, so in the new API it is long 9519 final int libVersionCode = (int) libInfo.getDeclaringPackage() 9520 .getVersionCode(); 9521 if (libInfo.getVersion() < pkg.staticSharedLibVersion) { 9522 minVersionCode = Math.max(minVersionCode, libVersionCode + 1); 9523 } else if (libInfo.getVersion() > pkg.staticSharedLibVersion) { 9524 maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1); 9525 } else { 9526 minVersionCode = maxVersionCode = libVersionCode; 9527 break; 9528 } 9529 } 9530 } 9531 if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) { 9532 throw new PackageManagerException("Static shared" 9533 + " lib version codes must be ordered as lib versions"); 9534 } 9535 } 9536 9537 // Only privileged apps and updated privileged apps can add child packages. 9538 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 9539 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 9540 throw new PackageManagerException("Only privileged apps can add child " 9541 + "packages. Ignoring package " + pkg.packageName); 9542 } 9543 final int childCount = pkg.childPackages.size(); 9544 for (int i = 0; i < childCount; i++) { 9545 PackageParser.Package childPkg = pkg.childPackages.get(i); 9546 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 9547 childPkg.packageName)) { 9548 throw new PackageManagerException("Can't override child of " 9549 + "another disabled app. Ignoring package " + pkg.packageName); 9550 } 9551 } 9552 } 9553 9554 // If we're only installing presumed-existing packages, require that the 9555 // scanned APK is both already known and at the path previously established 9556 // for it. Previously unknown packages we pick up normally, but if we have an 9557 // a priori expectation about this package's install presence, enforce it. 9558 // With a singular exception for new system packages. When an OTA contains 9559 // a new system package, we allow the codepath to change from a system location 9560 // to the user-installed location. If we don't allow this change, any newer, 9561 // user-installed version of the application will be ignored. 9562 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 9563 if (mExpectingBetter.containsKey(pkg.packageName)) { 9564 logCriticalInfo(Log.WARN, 9565 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 9566 } else { 9567 PackageSetting known = mSettings.getPackageLPr(pkg.packageName); 9568 if (known != null) { 9569 if (DEBUG_PACKAGE_SCANNING) { 9570 Log.d(TAG, "Examining " + pkg.codePath 9571 + " and requiring known paths " + known.codePathString 9572 + " & " + known.resourcePathString); 9573 } 9574 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 9575 || !pkg.applicationInfo.getResourcePath().equals( 9576 known.resourcePathString)) { 9577 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 9578 "Application package " + pkg.packageName 9579 + " found at " + pkg.applicationInfo.getCodePath() 9580 + " but expected at " + known.codePathString 9581 + "; ignoring."); 9582 } 9583 } 9584 } 9585 } 9586 9587 // Verify that this new package doesn't have any content providers 9588 // that conflict with existing packages. Only do this if the 9589 // package isn't already installed, since we don't want to break 9590 // things that are installed. 9591 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 9592 final int N = pkg.providers.size(); 9593 int i; 9594 for (i=0; i<N; i++) { 9595 PackageParser.Provider p = pkg.providers.get(i); 9596 if (p.info.authority != null) { 9597 String names[] = p.info.authority.split(";"); 9598 for (int j = 0; j < names.length; j++) { 9599 if (mProvidersByAuthority.containsKey(names[j])) { 9600 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 9601 final String otherPackageName = 9602 ((other != null && other.getComponentName() != null) ? 9603 other.getComponentName().getPackageName() : "?"); 9604 throw new PackageManagerException( 9605 INSTALL_FAILED_CONFLICTING_PROVIDER, 9606 "Can't install because provider name " + names[j] 9607 + " (in package " + pkg.applicationInfo.packageName 9608 + ") is already used by " + otherPackageName); 9609 } 9610 } 9611 } 9612 } 9613 } 9614 } 9615 } 9616 9617 private boolean addSharedLibraryLPw(String path, String apk, String name, int version, 9618 int type, String declaringPackageName, int declaringVersionCode) { 9619 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 9620 if (versionedLib == null) { 9621 versionedLib = new SparseArray<>(); 9622 mSharedLibraries.put(name, versionedLib); 9623 if (type == SharedLibraryInfo.TYPE_STATIC) { 9624 mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib); 9625 } 9626 } else if (versionedLib.indexOfKey(version) >= 0) { 9627 return false; 9628 } 9629 SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name, 9630 version, type, declaringPackageName, declaringVersionCode); 9631 versionedLib.put(version, libEntry); 9632 return true; 9633 } 9634 9635 private boolean removeSharedLibraryLPw(String name, int version) { 9636 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 9637 if (versionedLib == null) { 9638 return false; 9639 } 9640 final int libIdx = versionedLib.indexOfKey(version); 9641 if (libIdx < 0) { 9642 return false; 9643 } 9644 SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx); 9645 versionedLib.remove(version); 9646 if (versionedLib.size() <= 0) { 9647 mSharedLibraries.remove(name); 9648 if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) { 9649 mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage() 9650 .getPackageName()); 9651 } 9652 } 9653 return true; 9654 } 9655 9656 /** 9657 * Adds a scanned package to the system. When this method is finished, the package will 9658 * be available for query, resolution, etc... 9659 */ 9660 private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting, 9661 UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException { 9662 final String pkgName = pkg.packageName; 9663 if (mCustomResolverComponentName != null && 9664 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 9665 setUpCustomResolverActivity(pkg); 9666 } 9667 9668 if (pkg.packageName.equals("android")) { 9669 synchronized (mPackages) { 9670 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 9671 // Set up information for our fall-back user intent resolution activity. 9672 mPlatformPackage = pkg; 9673 pkg.mVersionCode = mSdkVersion; 9674 mAndroidApplication = pkg.applicationInfo; 9675 9676 if (!mResolverReplaced) { 9677 mResolveActivity.applicationInfo = mAndroidApplication; 9678 mResolveActivity.name = ResolverActivity.class.getName(); 9679 mResolveActivity.packageName = mAndroidApplication.packageName; 9680 mResolveActivity.processName = "system:ui"; 9681 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9682 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 9683 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 9684 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 9685 mResolveActivity.exported = true; 9686 mResolveActivity.enabled = true; 9687 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 9688 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 9689 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 9690 | ActivityInfo.CONFIG_SCREEN_LAYOUT 9691 | ActivityInfo.CONFIG_ORIENTATION 9692 | ActivityInfo.CONFIG_KEYBOARD 9693 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 9694 mResolveInfo.activityInfo = mResolveActivity; 9695 mResolveInfo.priority = 0; 9696 mResolveInfo.preferredOrder = 0; 9697 mResolveInfo.match = 0; 9698 mResolveComponentName = new ComponentName( 9699 mAndroidApplication.packageName, mResolveActivity.name); 9700 } 9701 } 9702 } 9703 } 9704 9705 ArrayList<PackageParser.Package> clientLibPkgs = null; 9706 // writer 9707 synchronized (mPackages) { 9708 boolean hasStaticSharedLibs = false; 9709 9710 // Any app can add new static shared libraries 9711 if (pkg.staticSharedLibName != null) { 9712 // Static shared libs don't allow renaming as they have synthetic package 9713 // names to allow install of multiple versions, so use name from manifest. 9714 if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName, 9715 pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC, 9716 pkg.manifestPackageName, pkg.mVersionCode)) { 9717 hasStaticSharedLibs = true; 9718 } else { 9719 Slog.w(TAG, "Package " + pkg.packageName + " library " 9720 + pkg.staticSharedLibName + " already exists; skipping"); 9721 } 9722 // Static shared libs cannot be updated once installed since they 9723 // use synthetic package name which includes the version code, so 9724 // not need to update other packages's shared lib dependencies. 9725 } 9726 9727 if (!hasStaticSharedLibs 9728 && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 9729 // Only system apps can add new dynamic shared libraries. 9730 if (pkg.libraryNames != null) { 9731 for (int i = 0; i < pkg.libraryNames.size(); i++) { 9732 String name = pkg.libraryNames.get(i); 9733 boolean allowed = false; 9734 if (pkg.isUpdatedSystemApp()) { 9735 // New library entries can only be added through the 9736 // system image. This is important to get rid of a lot 9737 // of nasty edge cases: for example if we allowed a non- 9738 // system update of the app to add a library, then uninstalling 9739 // the update would make the library go away, and assumptions 9740 // we made such as through app install filtering would now 9741 // have allowed apps on the device which aren't compatible 9742 // with it. Better to just have the restriction here, be 9743 // conservative, and create many fewer cases that can negatively 9744 // impact the user experience. 9745 final PackageSetting sysPs = mSettings 9746 .getDisabledSystemPkgLPr(pkg.packageName); 9747 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 9748 for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) { 9749 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 9750 allowed = true; 9751 break; 9752 } 9753 } 9754 } 9755 } else { 9756 allowed = true; 9757 } 9758 if (allowed) { 9759 if (!addSharedLibraryLPw(null, pkg.packageName, name, 9760 SharedLibraryInfo.VERSION_UNDEFINED, 9761 SharedLibraryInfo.TYPE_DYNAMIC, 9762 pkg.packageName, pkg.mVersionCode)) { 9763 Slog.w(TAG, "Package " + pkg.packageName + " library " 9764 + name + " already exists; skipping"); 9765 } 9766 } else { 9767 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 9768 + name + " that is not declared on system image; skipping"); 9769 } 9770 } 9771 9772 if ((scanFlags & SCAN_BOOTING) == 0) { 9773 // If we are not booting, we need to update any applications 9774 // that are clients of our shared library. If we are booting, 9775 // this will all be done once the scan is complete. 9776 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 9777 } 9778 } 9779 } 9780 } 9781 9782 if ((scanFlags & SCAN_BOOTING) != 0) { 9783 // No apps can run during boot scan, so they don't need to be frozen 9784 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 9785 // Caller asked to not kill app, so it's probably not frozen 9786 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 9787 // Caller asked us to ignore frozen check for some reason; they 9788 // probably didn't know the package name 9789 } else { 9790 // We're doing major surgery on this package, so it better be frozen 9791 // right now to keep it from launching 9792 checkPackageFrozen(pkgName); 9793 } 9794 9795 // Also need to kill any apps that are dependent on the library. 9796 if (clientLibPkgs != null) { 9797 for (int i=0; i<clientLibPkgs.size(); i++) { 9798 PackageParser.Package clientPkg = clientLibPkgs.get(i); 9799 killApplication(clientPkg.applicationInfo.packageName, 9800 clientPkg.applicationInfo.uid, "update lib"); 9801 } 9802 } 9803 9804 // writer 9805 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 9806 9807 boolean createIdmapFailed = false; 9808 synchronized (mPackages) { 9809 // We don't expect installation to fail beyond this point 9810 9811 if (pkgSetting.pkg != null) { 9812 // Note that |user| might be null during the initial boot scan. If a codePath 9813 // for an app has changed during a boot scan, it's due to an app update that's 9814 // part of the system partition and marker changes must be applied to all users. 9815 final int userId = ((user != null) ? user : UserHandle.ALL).getIdentifier(); 9816 final int[] userIds = resolveUserIds(userId); 9817 maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg, userIds); 9818 } 9819 9820 // Add the new setting to mSettings 9821 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 9822 // Add the new setting to mPackages 9823 mPackages.put(pkg.applicationInfo.packageName, pkg); 9824 // Make sure we don't accidentally delete its data. 9825 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 9826 while (iter.hasNext()) { 9827 PackageCleanItem item = iter.next(); 9828 if (pkgName.equals(item.packageName)) { 9829 iter.remove(); 9830 } 9831 } 9832 9833 // Add the package's KeySets to the global KeySetManagerService 9834 KeySetManagerService ksms = mSettings.mKeySetManagerService; 9835 ksms.addScannedPackageLPw(pkg); 9836 9837 int N = pkg.providers.size(); 9838 StringBuilder r = null; 9839 int i; 9840 for (i=0; i<N; i++) { 9841 PackageParser.Provider p = pkg.providers.get(i); 9842 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 9843 p.info.processName); 9844 mProviders.addProvider(p); 9845 p.syncable = p.info.isSyncable; 9846 if (p.info.authority != null) { 9847 String names[] = p.info.authority.split(";"); 9848 p.info.authority = null; 9849 for (int j = 0; j < names.length; j++) { 9850 if (j == 1 && p.syncable) { 9851 // We only want the first authority for a provider to possibly be 9852 // syncable, so if we already added this provider using a different 9853 // authority clear the syncable flag. We copy the provider before 9854 // changing it because the mProviders object contains a reference 9855 // to a provider that we don't want to change. 9856 // Only do this for the second authority since the resulting provider 9857 // object can be the same for all future authorities for this provider. 9858 p = new PackageParser.Provider(p); 9859 p.syncable = false; 9860 } 9861 if (!mProvidersByAuthority.containsKey(names[j])) { 9862 mProvidersByAuthority.put(names[j], p); 9863 if (p.info.authority == null) { 9864 p.info.authority = names[j]; 9865 } else { 9866 p.info.authority = p.info.authority + ";" + names[j]; 9867 } 9868 if (DEBUG_PACKAGE_SCANNING) { 9869 if (chatty) 9870 Log.d(TAG, "Registered content provider: " + names[j] 9871 + ", className = " + p.info.name + ", isSyncable = " 9872 + p.info.isSyncable); 9873 } 9874 } else { 9875 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 9876 Slog.w(TAG, "Skipping provider name " + names[j] + 9877 " (in package " + pkg.applicationInfo.packageName + 9878 "): name already used by " 9879 + ((other != null && other.getComponentName() != null) 9880 ? other.getComponentName().getPackageName() : "?")); 9881 } 9882 } 9883 } 9884 if (chatty) { 9885 if (r == null) { 9886 r = new StringBuilder(256); 9887 } else { 9888 r.append(' '); 9889 } 9890 r.append(p.info.name); 9891 } 9892 } 9893 if (r != null) { 9894 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 9895 } 9896 9897 N = pkg.services.size(); 9898 r = null; 9899 for (i=0; i<N; i++) { 9900 PackageParser.Service s = pkg.services.get(i); 9901 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 9902 s.info.processName); 9903 mServices.addService(s); 9904 if (chatty) { 9905 if (r == null) { 9906 r = new StringBuilder(256); 9907 } else { 9908 r.append(' '); 9909 } 9910 r.append(s.info.name); 9911 } 9912 } 9913 if (r != null) { 9914 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 9915 } 9916 9917 N = pkg.receivers.size(); 9918 r = null; 9919 for (i=0; i<N; i++) { 9920 PackageParser.Activity a = pkg.receivers.get(i); 9921 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 9922 a.info.processName); 9923 mReceivers.addActivity(a, "receiver"); 9924 if (chatty) { 9925 if (r == null) { 9926 r = new StringBuilder(256); 9927 } else { 9928 r.append(' '); 9929 } 9930 r.append(a.info.name); 9931 } 9932 } 9933 if (r != null) { 9934 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 9935 } 9936 9937 N = pkg.activities.size(); 9938 r = null; 9939 for (i=0; i<N; i++) { 9940 PackageParser.Activity a = pkg.activities.get(i); 9941 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 9942 a.info.processName); 9943 mActivities.addActivity(a, "activity"); 9944 if (chatty) { 9945 if (r == null) { 9946 r = new StringBuilder(256); 9947 } else { 9948 r.append(' '); 9949 } 9950 r.append(a.info.name); 9951 } 9952 } 9953 if (r != null) { 9954 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 9955 } 9956 9957 N = pkg.permissionGroups.size(); 9958 r = null; 9959 for (i=0; i<N; i++) { 9960 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 9961 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 9962 final String curPackageName = cur == null ? null : cur.info.packageName; 9963 // Dont allow ephemeral apps to define new permission groups. 9964 if (pkg.applicationInfo.isEphemeralApp()) { 9965 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 9966 + pg.info.packageName 9967 + " ignored: ephemeral apps cannot define new permission groups."); 9968 continue; 9969 } 9970 final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName); 9971 if (cur == null || isPackageUpdate) { 9972 mPermissionGroups.put(pg.info.name, pg); 9973 if (chatty) { 9974 if (r == null) { 9975 r = new StringBuilder(256); 9976 } else { 9977 r.append(' '); 9978 } 9979 if (isPackageUpdate) { 9980 r.append("UPD:"); 9981 } 9982 r.append(pg.info.name); 9983 } 9984 } else { 9985 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 9986 + pg.info.packageName + " ignored: original from " 9987 + cur.info.packageName); 9988 if (chatty) { 9989 if (r == null) { 9990 r = new StringBuilder(256); 9991 } else { 9992 r.append(' '); 9993 } 9994 r.append("DUP:"); 9995 r.append(pg.info.name); 9996 } 9997 } 9998 } 9999 if (r != null) { 10000 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 10001 } 10002 10003 N = pkg.permissions.size(); 10004 r = null; 10005 for (i=0; i<N; i++) { 10006 PackageParser.Permission p = pkg.permissions.get(i); 10007 10008 // Dont allow ephemeral apps to define new permissions. 10009 if (pkg.applicationInfo.isEphemeralApp()) { 10010 Slog.w(TAG, "Permission " + p.info.name + " from package " 10011 + p.info.packageName 10012 + " ignored: ephemeral apps cannot define new permissions."); 10013 continue; 10014 } 10015 10016 // Assume by default that we did not install this permission into the system. 10017 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 10018 10019 // Now that permission groups have a special meaning, we ignore permission 10020 // groups for legacy apps to prevent unexpected behavior. In particular, 10021 // permissions for one app being granted to someone just becase they happen 10022 // to be in a group defined by another app (before this had no implications). 10023 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 10024 p.group = mPermissionGroups.get(p.info.group); 10025 // Warn for a permission in an unknown group. 10026 if (p.info.group != null && p.group == null) { 10027 Slog.w(TAG, "Permission " + p.info.name + " from package " 10028 + p.info.packageName + " in an unknown group " + p.info.group); 10029 } 10030 } 10031 10032 ArrayMap<String, BasePermission> permissionMap = 10033 p.tree ? mSettings.mPermissionTrees 10034 : mSettings.mPermissions; 10035 BasePermission bp = permissionMap.get(p.info.name); 10036 10037 // Allow system apps to redefine non-system permissions 10038 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 10039 final boolean currentOwnerIsSystem = (bp.perm != null 10040 && isSystemApp(bp.perm.owner)); 10041 if (isSystemApp(p.owner)) { 10042 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 10043 // It's a built-in permission and no owner, take ownership now 10044 bp.packageSetting = pkgSetting; 10045 bp.perm = p; 10046 bp.uid = pkg.applicationInfo.uid; 10047 bp.sourcePackage = p.info.packageName; 10048 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 10049 } else if (!currentOwnerIsSystem) { 10050 String msg = "New decl " + p.owner + " of permission " 10051 + p.info.name + " is system; overriding " + bp.sourcePackage; 10052 reportSettingsProblem(Log.WARN, msg); 10053 bp = null; 10054 } 10055 } 10056 } 10057 10058 if (bp == null) { 10059 bp = new BasePermission(p.info.name, p.info.packageName, 10060 BasePermission.TYPE_NORMAL); 10061 permissionMap.put(p.info.name, bp); 10062 } 10063 10064 if (bp.perm == null) { 10065 if (bp.sourcePackage == null 10066 || bp.sourcePackage.equals(p.info.packageName)) { 10067 BasePermission tree = findPermissionTreeLP(p.info.name); 10068 if (tree == null 10069 || tree.sourcePackage.equals(p.info.packageName)) { 10070 bp.packageSetting = pkgSetting; 10071 bp.perm = p; 10072 bp.uid = pkg.applicationInfo.uid; 10073 bp.sourcePackage = p.info.packageName; 10074 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 10075 if (chatty) { 10076 if (r == null) { 10077 r = new StringBuilder(256); 10078 } else { 10079 r.append(' '); 10080 } 10081 r.append(p.info.name); 10082 } 10083 } else { 10084 Slog.w(TAG, "Permission " + p.info.name + " from package " 10085 + p.info.packageName + " ignored: base tree " 10086 + tree.name + " is from package " 10087 + tree.sourcePackage); 10088 } 10089 } else { 10090 Slog.w(TAG, "Permission " + p.info.name + " from package " 10091 + p.info.packageName + " ignored: original from " 10092 + bp.sourcePackage); 10093 } 10094 } else if (chatty) { 10095 if (r == null) { 10096 r = new StringBuilder(256); 10097 } else { 10098 r.append(' '); 10099 } 10100 r.append("DUP:"); 10101 r.append(p.info.name); 10102 } 10103 if (bp.perm == p) { 10104 bp.protectionLevel = p.info.protectionLevel; 10105 } 10106 } 10107 10108 if (r != null) { 10109 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 10110 } 10111 10112 N = pkg.instrumentation.size(); 10113 r = null; 10114 for (i=0; i<N; i++) { 10115 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 10116 a.info.packageName = pkg.applicationInfo.packageName; 10117 a.info.sourceDir = pkg.applicationInfo.sourceDir; 10118 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 10119 a.info.splitNames = pkg.splitNames; 10120 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 10121 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 10122 a.info.splitDependencies = pkg.applicationInfo.splitDependencies; 10123 a.info.dataDir = pkg.applicationInfo.dataDir; 10124 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 10125 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 10126 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 10127 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 10128 mInstrumentation.put(a.getComponentName(), a); 10129 if (chatty) { 10130 if (r == null) { 10131 r = new StringBuilder(256); 10132 } else { 10133 r.append(' '); 10134 } 10135 r.append(a.info.name); 10136 } 10137 } 10138 if (r != null) { 10139 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 10140 } 10141 10142 if (pkg.protectedBroadcasts != null) { 10143 N = pkg.protectedBroadcasts.size(); 10144 for (i=0; i<N; i++) { 10145 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 10146 } 10147 } 10148 10149 // Create idmap files for pairs of (packages, overlay packages). 10150 // Note: "android", ie framework-res.apk, is handled by native layers. 10151 if (pkg.mOverlayTarget != null) { 10152 // This is an overlay package. 10153 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 10154 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 10155 mOverlays.put(pkg.mOverlayTarget, 10156 new ArrayMap<String, PackageParser.Package>()); 10157 } 10158 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 10159 map.put(pkg.packageName, pkg); 10160 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 10161 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 10162 createIdmapFailed = true; 10163 } 10164 } 10165 } else if (mOverlays.containsKey(pkg.packageName) && 10166 !pkg.packageName.equals("android")) { 10167 // This is a regular package, with one or more known overlay packages. 10168 createIdmapsForPackageLI(pkg); 10169 } 10170 } 10171 10172 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10173 10174 if (createIdmapFailed) { 10175 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 10176 "scanPackageLI failed to createIdmap"); 10177 } 10178 } 10179 10180 private static void maybeRenameForeignDexMarkers(PackageParser.Package existing, 10181 PackageParser.Package update, int[] userIds) { 10182 if (existing.applicationInfo == null || update.applicationInfo == null) { 10183 // This isn't due to an app installation. 10184 return; 10185 } 10186 10187 final File oldCodePath = new File(existing.applicationInfo.getCodePath()); 10188 final File newCodePath = new File(update.applicationInfo.getCodePath()); 10189 10190 // The codePath hasn't changed, so there's nothing for us to do. 10191 if (Objects.equals(oldCodePath, newCodePath)) { 10192 return; 10193 } 10194 10195 File canonicalNewCodePath; 10196 try { 10197 canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath)); 10198 } catch (IOException e) { 10199 Slog.w(TAG, "Failed to get canonical path.", e); 10200 return; 10201 } 10202 10203 // This is a bit of a hack. The oldCodePath doesn't exist at this point (because 10204 // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume 10205 // that the last component of the path (i.e, the name) doesn't need canonicalization 10206 // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now 10207 // but may change in the future. Hopefully this function won't exist at that point. 10208 final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(), 10209 oldCodePath.getName()); 10210 10211 // Calculate the prefixes of the markers. These are just the paths with "/" replaced 10212 // with "@". 10213 String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@'); 10214 if (!oldMarkerPrefix.endsWith("@")) { 10215 oldMarkerPrefix += "@"; 10216 } 10217 String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@'); 10218 if (!newMarkerPrefix.endsWith("@")) { 10219 newMarkerPrefix += "@"; 10220 } 10221 10222 List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly(); 10223 List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size()); 10224 for (String updatedPath : updatedPaths) { 10225 String updatedPathName = new File(updatedPath).getName(); 10226 markerSuffixes.add(updatedPathName.replace('/', '@')); 10227 } 10228 10229 for (int userId : userIds) { 10230 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId); 10231 10232 for (String markerSuffix : markerSuffixes) { 10233 File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix); 10234 File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix); 10235 if (oldForeignUseMark.exists()) { 10236 try { 10237 Os.rename(oldForeignUseMark.getAbsolutePath(), 10238 newForeignUseMark.getAbsolutePath()); 10239 } catch (ErrnoException e) { 10240 Slog.w(TAG, "Failed to rename foreign use marker", e); 10241 oldForeignUseMark.delete(); 10242 } 10243 } 10244 } 10245 } 10246 } 10247 10248 /** 10249 * Derive the ABI of a non-system package located at {@code scanFile}. This information 10250 * is derived purely on the basis of the contents of {@code scanFile} and 10251 * {@code cpuAbiOverride}. 10252 * 10253 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 10254 */ 10255 private static void derivePackageAbi(PackageParser.Package pkg, File scanFile, 10256 String cpuAbiOverride, boolean extractLibs, 10257 File appLib32InstallDir) 10258 throws PackageManagerException { 10259 // Give ourselves some initial paths; we'll come back for another 10260 // pass once we've determined ABI below. 10261 setNativeLibraryPaths(pkg, appLib32InstallDir); 10262 10263 // We would never need to extract libs for forward-locked and external packages, 10264 // since the container service will do it for us. We shouldn't attempt to 10265 // extract libs from system app when it was not updated. 10266 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 10267 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 10268 extractLibs = false; 10269 } 10270 10271 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 10272 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 10273 10274 NativeLibraryHelper.Handle handle = null; 10275 try { 10276 handle = NativeLibraryHelper.Handle.create(pkg); 10277 // TODO(multiArch): This can be null for apps that didn't go through the 10278 // usual installation process. We can calculate it again, like we 10279 // do during install time. 10280 // 10281 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 10282 // unnecessary. 10283 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 10284 10285 // Null out the abis so that they can be recalculated. 10286 pkg.applicationInfo.primaryCpuAbi = null; 10287 pkg.applicationInfo.secondaryCpuAbi = null; 10288 if (isMultiArch(pkg.applicationInfo)) { 10289 // Warn if we've set an abiOverride for multi-lib packages.. 10290 // By definition, we need to copy both 32 and 64 bit libraries for 10291 // such packages. 10292 if (pkg.cpuAbiOverride != null 10293 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 10294 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 10295 } 10296 10297 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 10298 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 10299 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 10300 if (extractLibs) { 10301 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 10302 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 10303 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 10304 useIsaSpecificSubdirs); 10305 } else { 10306 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 10307 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 10308 } 10309 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10310 } 10311 10312 maybeThrowExceptionForMultiArchCopy( 10313 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 10314 10315 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 10316 if (extractLibs) { 10317 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 10318 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 10319 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 10320 useIsaSpecificSubdirs); 10321 } else { 10322 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 10323 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 10324 } 10325 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10326 } 10327 10328 maybeThrowExceptionForMultiArchCopy( 10329 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 10330 10331 if (abi64 >= 0) { 10332 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 10333 } 10334 10335 if (abi32 >= 0) { 10336 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 10337 if (abi64 >= 0) { 10338 if (pkg.use32bitAbi) { 10339 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 10340 pkg.applicationInfo.primaryCpuAbi = abi; 10341 } else { 10342 pkg.applicationInfo.secondaryCpuAbi = abi; 10343 } 10344 } else { 10345 pkg.applicationInfo.primaryCpuAbi = abi; 10346 } 10347 } 10348 10349 } else { 10350 String[] abiList = (cpuAbiOverride != null) ? 10351 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 10352 10353 // Enable gross and lame hacks for apps that are built with old 10354 // SDK tools. We must scan their APKs for renderscript bitcode and 10355 // not launch them if it's present. Don't bother checking on devices 10356 // that don't have 64 bit support. 10357 boolean needsRenderScriptOverride = false; 10358 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 10359 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 10360 abiList = Build.SUPPORTED_32_BIT_ABIS; 10361 needsRenderScriptOverride = true; 10362 } 10363 10364 final int copyRet; 10365 if (extractLibs) { 10366 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 10367 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 10368 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 10369 } else { 10370 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 10371 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 10372 } 10373 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10374 10375 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 10376 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 10377 "Error unpackaging native libs for app, errorCode=" + copyRet); 10378 } 10379 10380 if (copyRet >= 0) { 10381 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 10382 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 10383 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 10384 } else if (needsRenderScriptOverride) { 10385 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 10386 } 10387 } 10388 } catch (IOException ioe) { 10389 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 10390 } finally { 10391 IoUtils.closeQuietly(handle); 10392 } 10393 10394 // Now that we've calculated the ABIs and determined if it's an internal app, 10395 // we will go ahead and populate the nativeLibraryPath. 10396 setNativeLibraryPaths(pkg, appLib32InstallDir); 10397 } 10398 10399 /** 10400 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 10401 * i.e, so that all packages can be run inside a single process if required. 10402 * 10403 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 10404 * this function will either try and make the ABI for all packages in {@code packagesForUser} 10405 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 10406 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 10407 * updating a package that belongs to a shared user. 10408 * 10409 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 10410 * adds unnecessary complexity. 10411 */ 10412 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 10413 PackageParser.Package scannedPackage) { 10414 String requiredInstructionSet = null; 10415 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 10416 requiredInstructionSet = VMRuntime.getInstructionSet( 10417 scannedPackage.applicationInfo.primaryCpuAbi); 10418 } 10419 10420 PackageSetting requirer = null; 10421 for (PackageSetting ps : packagesForUser) { 10422 // If packagesForUser contains scannedPackage, we skip it. This will happen 10423 // when scannedPackage is an update of an existing package. Without this check, 10424 // we will never be able to change the ABI of any package belonging to a shared 10425 // user, even if it's compatible with other packages. 10426 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 10427 if (ps.primaryCpuAbiString == null) { 10428 continue; 10429 } 10430 10431 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 10432 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 10433 // We have a mismatch between instruction sets (say arm vs arm64) warn about 10434 // this but there's not much we can do. 10435 String errorMessage = "Instruction set mismatch, " 10436 + ((requirer == null) ? "[caller]" : requirer) 10437 + " requires " + requiredInstructionSet + " whereas " + ps 10438 + " requires " + instructionSet; 10439 Slog.w(TAG, errorMessage); 10440 } 10441 10442 if (requiredInstructionSet == null) { 10443 requiredInstructionSet = instructionSet; 10444 requirer = ps; 10445 } 10446 } 10447 } 10448 10449 if (requiredInstructionSet != null) { 10450 String adjustedAbi; 10451 if (requirer != null) { 10452 // requirer != null implies that either scannedPackage was null or that scannedPackage 10453 // did not require an ABI, in which case we have to adjust scannedPackage to match 10454 // the ABI of the set (which is the same as requirer's ABI) 10455 adjustedAbi = requirer.primaryCpuAbiString; 10456 if (scannedPackage != null) { 10457 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 10458 } 10459 } else { 10460 // requirer == null implies that we're updating all ABIs in the set to 10461 // match scannedPackage. 10462 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 10463 } 10464 10465 for (PackageSetting ps : packagesForUser) { 10466 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 10467 if (ps.primaryCpuAbiString != null) { 10468 continue; 10469 } 10470 10471 ps.primaryCpuAbiString = adjustedAbi; 10472 if (ps.pkg != null && ps.pkg.applicationInfo != null && 10473 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 10474 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 10475 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 10476 + " (requirer=" 10477 + (requirer == null ? "null" : requirer.pkg.packageName) 10478 + ", scannedPackage=" 10479 + (scannedPackage != null ? scannedPackage.packageName : "null") 10480 + ")"); 10481 try { 10482 mInstaller.rmdex(ps.codePathString, 10483 getDexCodeInstructionSet(getPreferredInstructionSet())); 10484 } catch (InstallerException ignored) { 10485 } 10486 } 10487 } 10488 } 10489 } 10490 } 10491 10492 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 10493 synchronized (mPackages) { 10494 mResolverReplaced = true; 10495 // Set up information for custom user intent resolution activity. 10496 mResolveActivity.applicationInfo = pkg.applicationInfo; 10497 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 10498 mResolveActivity.packageName = pkg.applicationInfo.packageName; 10499 mResolveActivity.processName = pkg.applicationInfo.packageName; 10500 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 10501 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 10502 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 10503 mResolveActivity.theme = 0; 10504 mResolveActivity.exported = true; 10505 mResolveActivity.enabled = true; 10506 mResolveInfo.activityInfo = mResolveActivity; 10507 mResolveInfo.priority = 0; 10508 mResolveInfo.preferredOrder = 0; 10509 mResolveInfo.match = 0; 10510 mResolveComponentName = mCustomResolverComponentName; 10511 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 10512 mResolveComponentName); 10513 } 10514 } 10515 10516 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 10517 if (installerComponent == null) { 10518 if (DEBUG_EPHEMERAL) { 10519 Slog.d(TAG, "Clear ephemeral installer activity"); 10520 } 10521 mEphemeralInstallerActivity.applicationInfo = null; 10522 return; 10523 } 10524 10525 if (DEBUG_EPHEMERAL) { 10526 Slog.d(TAG, "Set ephemeral installer activity: " + installerComponent); 10527 } 10528 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 10529 // Set up information for ephemeral installer activity 10530 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 10531 mEphemeralInstallerActivity.name = installerComponent.getClassName(); 10532 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 10533 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 10534 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 10535 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS 10536 | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 10537 mEphemeralInstallerActivity.theme = 0; 10538 mEphemeralInstallerActivity.exported = true; 10539 mEphemeralInstallerActivity.enabled = true; 10540 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 10541 mEphemeralInstallerInfo.priority = 0; 10542 mEphemeralInstallerInfo.preferredOrder = 1; 10543 mEphemeralInstallerInfo.isDefault = true; 10544 mEphemeralInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 10545 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 10546 } 10547 10548 private static String calculateBundledApkRoot(final String codePathString) { 10549 final File codePath = new File(codePathString); 10550 final File codeRoot; 10551 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 10552 codeRoot = Environment.getRootDirectory(); 10553 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 10554 codeRoot = Environment.getOemDirectory(); 10555 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 10556 codeRoot = Environment.getVendorDirectory(); 10557 } else { 10558 // Unrecognized code path; take its top real segment as the apk root: 10559 // e.g. /something/app/blah.apk => /something 10560 try { 10561 File f = codePath.getCanonicalFile(); 10562 File parent = f.getParentFile(); // non-null because codePath is a file 10563 File tmp; 10564 while ((tmp = parent.getParentFile()) != null) { 10565 f = parent; 10566 parent = tmp; 10567 } 10568 codeRoot = f; 10569 Slog.w(TAG, "Unrecognized code path " 10570 + codePath + " - using " + codeRoot); 10571 } catch (IOException e) { 10572 // Can't canonicalize the code path -- shenanigans? 10573 Slog.w(TAG, "Can't canonicalize code path " + codePath); 10574 return Environment.getRootDirectory().getPath(); 10575 } 10576 } 10577 return codeRoot.getPath(); 10578 } 10579 10580 /** 10581 * Derive and set the location of native libraries for the given package, 10582 * which varies depending on where and how the package was installed. 10583 */ 10584 private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) { 10585 final ApplicationInfo info = pkg.applicationInfo; 10586 final String codePath = pkg.codePath; 10587 final File codeFile = new File(codePath); 10588 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 10589 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 10590 10591 info.nativeLibraryRootDir = null; 10592 info.nativeLibraryRootRequiresIsa = false; 10593 info.nativeLibraryDir = null; 10594 info.secondaryNativeLibraryDir = null; 10595 10596 if (isApkFile(codeFile)) { 10597 // Monolithic install 10598 if (bundledApp) { 10599 // If "/system/lib64/apkname" exists, assume that is the per-package 10600 // native library directory to use; otherwise use "/system/lib/apkname". 10601 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 10602 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 10603 getPrimaryInstructionSet(info)); 10604 10605 // This is a bundled system app so choose the path based on the ABI. 10606 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 10607 // is just the default path. 10608 final String apkName = deriveCodePathName(codePath); 10609 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 10610 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 10611 apkName).getAbsolutePath(); 10612 10613 if (info.secondaryCpuAbi != null) { 10614 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 10615 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 10616 secondaryLibDir, apkName).getAbsolutePath(); 10617 } 10618 } else if (asecApp) { 10619 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 10620 .getAbsolutePath(); 10621 } else { 10622 final String apkName = deriveCodePathName(codePath); 10623 info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName) 10624 .getAbsolutePath(); 10625 } 10626 10627 info.nativeLibraryRootRequiresIsa = false; 10628 info.nativeLibraryDir = info.nativeLibraryRootDir; 10629 } else { 10630 // Cluster install 10631 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 10632 info.nativeLibraryRootRequiresIsa = true; 10633 10634 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 10635 getPrimaryInstructionSet(info)).getAbsolutePath(); 10636 10637 if (info.secondaryCpuAbi != null) { 10638 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 10639 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 10640 } 10641 } 10642 } 10643 10644 /** 10645 * Calculate the abis and roots for a bundled app. These can uniquely 10646 * be determined from the contents of the system partition, i.e whether 10647 * it contains 64 or 32 bit shared libraries etc. We do not validate any 10648 * of this information, and instead assume that the system was built 10649 * sensibly. 10650 */ 10651 private static void setBundledAppAbisAndRoots(PackageParser.Package pkg, 10652 PackageSetting pkgSetting) { 10653 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 10654 10655 // If "/system/lib64/apkname" exists, assume that is the per-package 10656 // native library directory to use; otherwise use "/system/lib/apkname". 10657 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 10658 setBundledAppAbi(pkg, apkRoot, apkName); 10659 // pkgSetting might be null during rescan following uninstall of updates 10660 // to a bundled app, so accommodate that possibility. The settings in 10661 // that case will be established later from the parsed package. 10662 // 10663 // If the settings aren't null, sync them up with what we've just derived. 10664 // note that apkRoot isn't stored in the package settings. 10665 if (pkgSetting != null) { 10666 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 10667 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 10668 } 10669 } 10670 10671 /** 10672 * Deduces the ABI of a bundled app and sets the relevant fields on the 10673 * parsed pkg object. 10674 * 10675 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 10676 * under which system libraries are installed. 10677 * @param apkName the name of the installed package. 10678 */ 10679 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 10680 final File codeFile = new File(pkg.codePath); 10681 10682 final boolean has64BitLibs; 10683 final boolean has32BitLibs; 10684 if (isApkFile(codeFile)) { 10685 // Monolithic install 10686 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 10687 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 10688 } else { 10689 // Cluster install 10690 final File rootDir = new File(codeFile, LIB_DIR_NAME); 10691 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 10692 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 10693 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 10694 has64BitLibs = (new File(rootDir, isa)).exists(); 10695 } else { 10696 has64BitLibs = false; 10697 } 10698 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 10699 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 10700 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 10701 has32BitLibs = (new File(rootDir, isa)).exists(); 10702 } else { 10703 has32BitLibs = false; 10704 } 10705 } 10706 10707 if (has64BitLibs && !has32BitLibs) { 10708 // The package has 64 bit libs, but not 32 bit libs. Its primary 10709 // ABI should be 64 bit. We can safely assume here that the bundled 10710 // native libraries correspond to the most preferred ABI in the list. 10711 10712 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 10713 pkg.applicationInfo.secondaryCpuAbi = null; 10714 } else if (has32BitLibs && !has64BitLibs) { 10715 // The package has 32 bit libs but not 64 bit libs. Its primary 10716 // ABI should be 32 bit. 10717 10718 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 10719 pkg.applicationInfo.secondaryCpuAbi = null; 10720 } else if (has32BitLibs && has64BitLibs) { 10721 // The application has both 64 and 32 bit bundled libraries. We check 10722 // here that the app declares multiArch support, and warn if it doesn't. 10723 // 10724 // We will be lenient here and record both ABIs. The primary will be the 10725 // ABI that's higher on the list, i.e, a device that's configured to prefer 10726 // 64 bit apps will see a 64 bit primary ABI, 10727 10728 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 10729 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 10730 } 10731 10732 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 10733 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 10734 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 10735 } else { 10736 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 10737 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 10738 } 10739 } else { 10740 pkg.applicationInfo.primaryCpuAbi = null; 10741 pkg.applicationInfo.secondaryCpuAbi = null; 10742 } 10743 } 10744 10745 private void killApplication(String pkgName, int appId, String reason) { 10746 killApplication(pkgName, appId, UserHandle.USER_ALL, reason); 10747 } 10748 10749 private void killApplication(String pkgName, int appId, int userId, String reason) { 10750 // Request the ActivityManager to kill the process(only for existing packages) 10751 // so that we do not end up in a confused state while the user is still using the older 10752 // version of the application while the new one gets installed. 10753 final long token = Binder.clearCallingIdentity(); 10754 try { 10755 IActivityManager am = ActivityManager.getService(); 10756 if (am != null) { 10757 try { 10758 am.killApplication(pkgName, appId, userId, reason); 10759 } catch (RemoteException e) { 10760 } 10761 } 10762 } finally { 10763 Binder.restoreCallingIdentity(token); 10764 } 10765 } 10766 10767 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 10768 // Remove the parent package setting 10769 PackageSetting ps = (PackageSetting) pkg.mExtras; 10770 if (ps != null) { 10771 removePackageLI(ps, chatty); 10772 } 10773 // Remove the child package setting 10774 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 10775 for (int i = 0; i < childCount; i++) { 10776 PackageParser.Package childPkg = pkg.childPackages.get(i); 10777 ps = (PackageSetting) childPkg.mExtras; 10778 if (ps != null) { 10779 removePackageLI(ps, chatty); 10780 } 10781 } 10782 } 10783 10784 void removePackageLI(PackageSetting ps, boolean chatty) { 10785 if (DEBUG_INSTALL) { 10786 if (chatty) 10787 Log.d(TAG, "Removing package " + ps.name); 10788 } 10789 10790 // writer 10791 synchronized (mPackages) { 10792 mPackages.remove(ps.name); 10793 final PackageParser.Package pkg = ps.pkg; 10794 if (pkg != null) { 10795 cleanPackageDataStructuresLILPw(pkg, chatty); 10796 } 10797 } 10798 } 10799 10800 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 10801 if (DEBUG_INSTALL) { 10802 if (chatty) 10803 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 10804 } 10805 10806 // writer 10807 synchronized (mPackages) { 10808 // Remove the parent package 10809 mPackages.remove(pkg.applicationInfo.packageName); 10810 cleanPackageDataStructuresLILPw(pkg, chatty); 10811 10812 // Remove the child packages 10813 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 10814 for (int i = 0; i < childCount; i++) { 10815 PackageParser.Package childPkg = pkg.childPackages.get(i); 10816 mPackages.remove(childPkg.applicationInfo.packageName); 10817 cleanPackageDataStructuresLILPw(childPkg, chatty); 10818 } 10819 } 10820 } 10821 10822 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 10823 int N = pkg.providers.size(); 10824 StringBuilder r = null; 10825 int i; 10826 for (i=0; i<N; i++) { 10827 PackageParser.Provider p = pkg.providers.get(i); 10828 mProviders.removeProvider(p); 10829 if (p.info.authority == null) { 10830 10831 /* There was another ContentProvider with this authority when 10832 * this app was installed so this authority is null, 10833 * Ignore it as we don't have to unregister the provider. 10834 */ 10835 continue; 10836 } 10837 String names[] = p.info.authority.split(";"); 10838 for (int j = 0; j < names.length; j++) { 10839 if (mProvidersByAuthority.get(names[j]) == p) { 10840 mProvidersByAuthority.remove(names[j]); 10841 if (DEBUG_REMOVE) { 10842 if (chatty) 10843 Log.d(TAG, "Unregistered content provider: " + names[j] 10844 + ", className = " + p.info.name + ", isSyncable = " 10845 + p.info.isSyncable); 10846 } 10847 } 10848 } 10849 if (DEBUG_REMOVE && chatty) { 10850 if (r == null) { 10851 r = new StringBuilder(256); 10852 } else { 10853 r.append(' '); 10854 } 10855 r.append(p.info.name); 10856 } 10857 } 10858 if (r != null) { 10859 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 10860 } 10861 10862 N = pkg.services.size(); 10863 r = null; 10864 for (i=0; i<N; i++) { 10865 PackageParser.Service s = pkg.services.get(i); 10866 mServices.removeService(s); 10867 if (chatty) { 10868 if (r == null) { 10869 r = new StringBuilder(256); 10870 } else { 10871 r.append(' '); 10872 } 10873 r.append(s.info.name); 10874 } 10875 } 10876 if (r != null) { 10877 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 10878 } 10879 10880 N = pkg.receivers.size(); 10881 r = null; 10882 for (i=0; i<N; i++) { 10883 PackageParser.Activity a = pkg.receivers.get(i); 10884 mReceivers.removeActivity(a, "receiver"); 10885 if (DEBUG_REMOVE && chatty) { 10886 if (r == null) { 10887 r = new StringBuilder(256); 10888 } else { 10889 r.append(' '); 10890 } 10891 r.append(a.info.name); 10892 } 10893 } 10894 if (r != null) { 10895 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 10896 } 10897 10898 N = pkg.activities.size(); 10899 r = null; 10900 for (i=0; i<N; i++) { 10901 PackageParser.Activity a = pkg.activities.get(i); 10902 mActivities.removeActivity(a, "activity"); 10903 if (DEBUG_REMOVE && chatty) { 10904 if (r == null) { 10905 r = new StringBuilder(256); 10906 } else { 10907 r.append(' '); 10908 } 10909 r.append(a.info.name); 10910 } 10911 } 10912 if (r != null) { 10913 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 10914 } 10915 10916 N = pkg.permissions.size(); 10917 r = null; 10918 for (i=0; i<N; i++) { 10919 PackageParser.Permission p = pkg.permissions.get(i); 10920 BasePermission bp = mSettings.mPermissions.get(p.info.name); 10921 if (bp == null) { 10922 bp = mSettings.mPermissionTrees.get(p.info.name); 10923 } 10924 if (bp != null && bp.perm == p) { 10925 bp.perm = null; 10926 if (DEBUG_REMOVE && chatty) { 10927 if (r == null) { 10928 r = new StringBuilder(256); 10929 } else { 10930 r.append(' '); 10931 } 10932 r.append(p.info.name); 10933 } 10934 } 10935 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 10936 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 10937 if (appOpPkgs != null) { 10938 appOpPkgs.remove(pkg.packageName); 10939 } 10940 } 10941 } 10942 if (r != null) { 10943 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 10944 } 10945 10946 N = pkg.requestedPermissions.size(); 10947 r = null; 10948 for (i=0; i<N; i++) { 10949 String perm = pkg.requestedPermissions.get(i); 10950 BasePermission bp = mSettings.mPermissions.get(perm); 10951 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 10952 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 10953 if (appOpPkgs != null) { 10954 appOpPkgs.remove(pkg.packageName); 10955 if (appOpPkgs.isEmpty()) { 10956 mAppOpPermissionPackages.remove(perm); 10957 } 10958 } 10959 } 10960 } 10961 if (r != null) { 10962 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 10963 } 10964 10965 N = pkg.instrumentation.size(); 10966 r = null; 10967 for (i=0; i<N; i++) { 10968 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 10969 mInstrumentation.remove(a.getComponentName()); 10970 if (DEBUG_REMOVE && chatty) { 10971 if (r == null) { 10972 r = new StringBuilder(256); 10973 } else { 10974 r.append(' '); 10975 } 10976 r.append(a.info.name); 10977 } 10978 } 10979 if (r != null) { 10980 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 10981 } 10982 10983 r = null; 10984 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 10985 // Only system apps can hold shared libraries. 10986 if (pkg.libraryNames != null) { 10987 for (i = 0; i < pkg.libraryNames.size(); i++) { 10988 String name = pkg.libraryNames.get(i); 10989 if (removeSharedLibraryLPw(name, 0)) { 10990 if (DEBUG_REMOVE && chatty) { 10991 if (r == null) { 10992 r = new StringBuilder(256); 10993 } else { 10994 r.append(' '); 10995 } 10996 r.append(name); 10997 } 10998 } 10999 } 11000 } 11001 } 11002 11003 r = null; 11004 11005 // Any package can hold static shared libraries. 11006 if (pkg.staticSharedLibName != null) { 11007 if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) { 11008 if (DEBUG_REMOVE && chatty) { 11009 if (r == null) { 11010 r = new StringBuilder(256); 11011 } else { 11012 r.append(' '); 11013 } 11014 r.append(pkg.staticSharedLibName); 11015 } 11016 } 11017 } 11018 11019 if (r != null) { 11020 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 11021 } 11022 } 11023 11024 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 11025 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 11026 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 11027 return true; 11028 } 11029 } 11030 return false; 11031 } 11032 11033 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 11034 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 11035 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 11036 11037 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 11038 // Update the parent permissions 11039 updatePermissionsLPw(pkg.packageName, pkg, flags); 11040 // Update the child permissions 11041 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 11042 for (int i = 0; i < childCount; i++) { 11043 PackageParser.Package childPkg = pkg.childPackages.get(i); 11044 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 11045 } 11046 } 11047 11048 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 11049 int flags) { 11050 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 11051 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 11052 } 11053 11054 private void updatePermissionsLPw(String changingPkg, 11055 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 11056 // Make sure there are no dangling permission trees. 11057 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 11058 while (it.hasNext()) { 11059 final BasePermission bp = it.next(); 11060 if (bp.packageSetting == null) { 11061 // We may not yet have parsed the package, so just see if 11062 // we still know about its settings. 11063 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 11064 } 11065 if (bp.packageSetting == null) { 11066 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 11067 + " from package " + bp.sourcePackage); 11068 it.remove(); 11069 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 11070 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 11071 Slog.i(TAG, "Removing old permission tree: " + bp.name 11072 + " from package " + bp.sourcePackage); 11073 flags |= UPDATE_PERMISSIONS_ALL; 11074 it.remove(); 11075 } 11076 } 11077 } 11078 11079 // Make sure all dynamic permissions have been assigned to a package, 11080 // and make sure there are no dangling permissions. 11081 it = mSettings.mPermissions.values().iterator(); 11082 while (it.hasNext()) { 11083 final BasePermission bp = it.next(); 11084 if (bp.type == BasePermission.TYPE_DYNAMIC) { 11085 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 11086 + bp.name + " pkg=" + bp.sourcePackage 11087 + " info=" + bp.pendingInfo); 11088 if (bp.packageSetting == null && bp.pendingInfo != null) { 11089 final BasePermission tree = findPermissionTreeLP(bp.name); 11090 if (tree != null && tree.perm != null) { 11091 bp.packageSetting = tree.packageSetting; 11092 bp.perm = new PackageParser.Permission(tree.perm.owner, 11093 new PermissionInfo(bp.pendingInfo)); 11094 bp.perm.info.packageName = tree.perm.info.packageName; 11095 bp.perm.info.name = bp.name; 11096 bp.uid = tree.uid; 11097 } 11098 } 11099 } 11100 if (bp.packageSetting == null) { 11101 // We may not yet have parsed the package, so just see if 11102 // we still know about its settings. 11103 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 11104 } 11105 if (bp.packageSetting == null) { 11106 Slog.w(TAG, "Removing dangling permission: " + bp.name 11107 + " from package " + bp.sourcePackage); 11108 it.remove(); 11109 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 11110 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 11111 Slog.i(TAG, "Removing old permission: " + bp.name 11112 + " from package " + bp.sourcePackage); 11113 flags |= UPDATE_PERMISSIONS_ALL; 11114 it.remove(); 11115 } 11116 } 11117 } 11118 11119 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 11120 // Now update the permissions for all packages, in particular 11121 // replace the granted permissions of the system packages. 11122 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 11123 for (PackageParser.Package pkg : mPackages.values()) { 11124 if (pkg != pkgInfo) { 11125 // Only replace for packages on requested volume 11126 final String volumeUuid = getVolumeUuidForPackage(pkg); 11127 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 11128 && Objects.equals(replaceVolumeUuid, volumeUuid); 11129 grantPermissionsLPw(pkg, replace, changingPkg); 11130 } 11131 } 11132 } 11133 11134 if (pkgInfo != null) { 11135 // Only replace for packages on requested volume 11136 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 11137 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 11138 && Objects.equals(replaceVolumeUuid, volumeUuid); 11139 grantPermissionsLPw(pkgInfo, replace, changingPkg); 11140 } 11141 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11142 } 11143 11144 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 11145 String packageOfInterest) { 11146 // IMPORTANT: There are two types of permissions: install and runtime. 11147 // Install time permissions are granted when the app is installed to 11148 // all device users and users added in the future. Runtime permissions 11149 // are granted at runtime explicitly to specific users. Normal and signature 11150 // protected permissions are install time permissions. Dangerous permissions 11151 // are install permissions if the app's target SDK is Lollipop MR1 or older, 11152 // otherwise they are runtime permissions. This function does not manage 11153 // runtime permissions except for the case an app targeting Lollipop MR1 11154 // being upgraded to target a newer SDK, in which case dangerous permissions 11155 // are transformed from install time to runtime ones. 11156 11157 final PackageSetting ps = (PackageSetting) pkg.mExtras; 11158 if (ps == null) { 11159 return; 11160 } 11161 11162 PermissionsState permissionsState = ps.getPermissionsState(); 11163 PermissionsState origPermissions = permissionsState; 11164 11165 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 11166 11167 boolean runtimePermissionsRevoked = false; 11168 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 11169 11170 boolean changedInstallPermission = false; 11171 11172 if (replace) { 11173 ps.installPermissionsFixed = false; 11174 if (!ps.isSharedUser()) { 11175 origPermissions = new PermissionsState(permissionsState); 11176 permissionsState.reset(); 11177 } else { 11178 // We need to know only about runtime permission changes since the 11179 // calling code always writes the install permissions state but 11180 // the runtime ones are written only if changed. The only cases of 11181 // changed runtime permissions here are promotion of an install to 11182 // runtime and revocation of a runtime from a shared user. 11183 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 11184 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 11185 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 11186 runtimePermissionsRevoked = true; 11187 } 11188 } 11189 } 11190 11191 permissionsState.setGlobalGids(mGlobalGids); 11192 11193 final int N = pkg.requestedPermissions.size(); 11194 for (int i=0; i<N; i++) { 11195 final String name = pkg.requestedPermissions.get(i); 11196 final BasePermission bp = mSettings.mPermissions.get(name); 11197 11198 if (DEBUG_INSTALL) { 11199 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 11200 } 11201 11202 if (bp == null || bp.packageSetting == null) { 11203 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 11204 Slog.w(TAG, "Unknown permission " + name 11205 + " in package " + pkg.packageName); 11206 } 11207 continue; 11208 } 11209 11210 11211 // Limit ephemeral apps to ephemeral allowed permissions. 11212 if (pkg.applicationInfo.isEphemeralApp() && !bp.isEphemeral()) { 11213 Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package " 11214 + pkg.packageName); 11215 continue; 11216 } 11217 11218 final String perm = bp.name; 11219 boolean allowedSig = false; 11220 int grant = GRANT_DENIED; 11221 11222 // Keep track of app op permissions. 11223 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 11224 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 11225 if (pkgs == null) { 11226 pkgs = new ArraySet<>(); 11227 mAppOpPermissionPackages.put(bp.name, pkgs); 11228 } 11229 pkgs.add(pkg.packageName); 11230 } 11231 11232 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 11233 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 11234 >= Build.VERSION_CODES.M; 11235 switch (level) { 11236 case PermissionInfo.PROTECTION_NORMAL: { 11237 // For all apps normal permissions are install time ones. 11238 grant = GRANT_INSTALL; 11239 } break; 11240 11241 case PermissionInfo.PROTECTION_DANGEROUS: { 11242 // If a permission review is required for legacy apps we represent 11243 // their permissions as always granted runtime ones since we need 11244 // to keep the review required permission flag per user while an 11245 // install permission's state is shared across all users. 11246 if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) { 11247 // For legacy apps dangerous permissions are install time ones. 11248 grant = GRANT_INSTALL; 11249 } else if (origPermissions.hasInstallPermission(bp.name)) { 11250 // For legacy apps that became modern, install becomes runtime. 11251 grant = GRANT_UPGRADE; 11252 } else if (mPromoteSystemApps 11253 && isSystemApp(ps) 11254 && mExistingSystemPackages.contains(ps.name)) { 11255 // For legacy system apps, install becomes runtime. 11256 // We cannot check hasInstallPermission() for system apps since those 11257 // permissions were granted implicitly and not persisted pre-M. 11258 grant = GRANT_UPGRADE; 11259 } else { 11260 // For modern apps keep runtime permissions unchanged. 11261 grant = GRANT_RUNTIME; 11262 } 11263 } break; 11264 11265 case PermissionInfo.PROTECTION_SIGNATURE: { 11266 // For all apps signature permissions are install time ones. 11267 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 11268 if (allowedSig) { 11269 grant = GRANT_INSTALL; 11270 } 11271 } break; 11272 } 11273 11274 if (DEBUG_INSTALL) { 11275 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 11276 } 11277 11278 if (grant != GRANT_DENIED) { 11279 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 11280 // If this is an existing, non-system package, then 11281 // we can't add any new permissions to it. 11282 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 11283 // Except... if this is a permission that was added 11284 // to the platform (note: need to only do this when 11285 // updating the platform). 11286 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 11287 grant = GRANT_DENIED; 11288 } 11289 } 11290 } 11291 11292 switch (grant) { 11293 case GRANT_INSTALL: { 11294 // Revoke this as runtime permission to handle the case of 11295 // a runtime permission being downgraded to an install one. 11296 // Also in permission review mode we keep dangerous permissions 11297 // for legacy apps 11298 for (int userId : UserManagerService.getInstance().getUserIds()) { 11299 if (origPermissions.getRuntimePermissionState( 11300 bp.name, userId) != null) { 11301 // Revoke the runtime permission and clear the flags. 11302 origPermissions.revokeRuntimePermission(bp, userId); 11303 origPermissions.updatePermissionFlags(bp, userId, 11304 PackageManager.MASK_PERMISSION_FLAGS, 0); 11305 // If we revoked a permission permission, we have to write. 11306 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11307 changedRuntimePermissionUserIds, userId); 11308 } 11309 } 11310 // Grant an install permission. 11311 if (permissionsState.grantInstallPermission(bp) != 11312 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11313 changedInstallPermission = true; 11314 } 11315 } break; 11316 11317 case GRANT_RUNTIME: { 11318 // Grant previously granted runtime permissions. 11319 for (int userId : UserManagerService.getInstance().getUserIds()) { 11320 PermissionState permissionState = origPermissions 11321 .getRuntimePermissionState(bp.name, userId); 11322 int flags = permissionState != null 11323 ? permissionState.getFlags() : 0; 11324 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 11325 // Don't propagate the permission in a permission review mode if 11326 // the former was revoked, i.e. marked to not propagate on upgrade. 11327 // Note that in a permission review mode install permissions are 11328 // represented as constantly granted runtime ones since we need to 11329 // keep a per user state associated with the permission. Also the 11330 // revoke on upgrade flag is no longer applicable and is reset. 11331 final boolean revokeOnUpgrade = (flags & PackageManager 11332 .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 11333 if (revokeOnUpgrade) { 11334 flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 11335 // Since we changed the flags, we have to write. 11336 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11337 changedRuntimePermissionUserIds, userId); 11338 } 11339 if (!mPermissionReviewRequired || !revokeOnUpgrade) { 11340 if (permissionsState.grantRuntimePermission(bp, userId) == 11341 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11342 // If we cannot put the permission as it was, 11343 // we have to write. 11344 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11345 changedRuntimePermissionUserIds, userId); 11346 } 11347 } 11348 11349 // If the app supports runtime permissions no need for a review. 11350 if (mPermissionReviewRequired 11351 && appSupportsRuntimePermissions 11352 && (flags & PackageManager 11353 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 11354 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 11355 // Since we changed the flags, we have to write. 11356 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11357 changedRuntimePermissionUserIds, userId); 11358 } 11359 } else if (mPermissionReviewRequired 11360 && !appSupportsRuntimePermissions) { 11361 // For legacy apps that need a permission review, every new 11362 // runtime permission is granted but it is pending a review. 11363 // We also need to review only platform defined runtime 11364 // permissions as these are the only ones the platform knows 11365 // how to disable the API to simulate revocation as legacy 11366 // apps don't expect to run with revoked permissions. 11367 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 11368 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 11369 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 11370 // We changed the flags, hence have to write. 11371 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11372 changedRuntimePermissionUserIds, userId); 11373 } 11374 } 11375 if (permissionsState.grantRuntimePermission(bp, userId) 11376 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 11377 // We changed the permission, hence have to write. 11378 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11379 changedRuntimePermissionUserIds, userId); 11380 } 11381 } 11382 // Propagate the permission flags. 11383 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 11384 } 11385 } break; 11386 11387 case GRANT_UPGRADE: { 11388 // Grant runtime permissions for a previously held install permission. 11389 PermissionState permissionState = origPermissions 11390 .getInstallPermissionState(bp.name); 11391 final int flags = permissionState != null ? permissionState.getFlags() : 0; 11392 11393 if (origPermissions.revokeInstallPermission(bp) 11394 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 11395 // We will be transferring the permission flags, so clear them. 11396 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 11397 PackageManager.MASK_PERMISSION_FLAGS, 0); 11398 changedInstallPermission = true; 11399 } 11400 11401 // If the permission is not to be promoted to runtime we ignore it and 11402 // also its other flags as they are not applicable to install permissions. 11403 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 11404 for (int userId : currentUserIds) { 11405 if (permissionsState.grantRuntimePermission(bp, userId) != 11406 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11407 // Transfer the permission flags. 11408 permissionsState.updatePermissionFlags(bp, userId, 11409 flags, flags); 11410 // If we granted the permission, we have to write. 11411 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11412 changedRuntimePermissionUserIds, userId); 11413 } 11414 } 11415 } 11416 } break; 11417 11418 default: { 11419 if (packageOfInterest == null 11420 || packageOfInterest.equals(pkg.packageName)) { 11421 Slog.w(TAG, "Not granting permission " + perm 11422 + " to package " + pkg.packageName 11423 + " because it was previously installed without"); 11424 } 11425 } break; 11426 } 11427 } else { 11428 if (permissionsState.revokeInstallPermission(bp) != 11429 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11430 // Also drop the permission flags. 11431 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 11432 PackageManager.MASK_PERMISSION_FLAGS, 0); 11433 changedInstallPermission = true; 11434 Slog.i(TAG, "Un-granting permission " + perm 11435 + " from package " + pkg.packageName 11436 + " (protectionLevel=" + bp.protectionLevel 11437 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 11438 + ")"); 11439 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 11440 // Don't print warning for app op permissions, since it is fine for them 11441 // not to be granted, there is a UI for the user to decide. 11442 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 11443 Slog.w(TAG, "Not granting permission " + perm 11444 + " to package " + pkg.packageName 11445 + " (protectionLevel=" + bp.protectionLevel 11446 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 11447 + ")"); 11448 } 11449 } 11450 } 11451 } 11452 11453 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 11454 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 11455 // This is the first that we have heard about this package, so the 11456 // permissions we have now selected are fixed until explicitly 11457 // changed. 11458 ps.installPermissionsFixed = true; 11459 } 11460 11461 // Persist the runtime permissions state for users with changes. If permissions 11462 // were revoked because no app in the shared user declares them we have to 11463 // write synchronously to avoid losing runtime permissions state. 11464 for (int userId : changedRuntimePermissionUserIds) { 11465 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 11466 } 11467 } 11468 11469 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 11470 boolean allowed = false; 11471 final int NP = PackageParser.NEW_PERMISSIONS.length; 11472 for (int ip=0; ip<NP; ip++) { 11473 final PackageParser.NewPermissionInfo npi 11474 = PackageParser.NEW_PERMISSIONS[ip]; 11475 if (npi.name.equals(perm) 11476 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 11477 allowed = true; 11478 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 11479 + pkg.packageName); 11480 break; 11481 } 11482 } 11483 return allowed; 11484 } 11485 11486 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 11487 BasePermission bp, PermissionsState origPermissions) { 11488 boolean privilegedPermission = (bp.protectionLevel 11489 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0; 11490 boolean privappPermissionsDisable = 11491 RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE; 11492 boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage); 11493 boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName); 11494 if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp() 11495 && !platformPackage && platformPermission) { 11496 ArraySet<String> wlPermissions = SystemConfig.getInstance() 11497 .getPrivAppPermissions(pkg.packageName); 11498 boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm); 11499 if (!whitelisted) { 11500 Slog.w(TAG, "Privileged permission " + perm + " for package " 11501 + pkg.packageName + " - not in privapp-permissions whitelist"); 11502 if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) { 11503 return false; 11504 } 11505 } 11506 } 11507 boolean allowed = (compareSignatures( 11508 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 11509 == PackageManager.SIGNATURE_MATCH) 11510 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 11511 == PackageManager.SIGNATURE_MATCH); 11512 if (!allowed && privilegedPermission) { 11513 if (isSystemApp(pkg)) { 11514 // For updated system applications, a system permission 11515 // is granted only if it had been defined by the original application. 11516 if (pkg.isUpdatedSystemApp()) { 11517 final PackageSetting sysPs = mSettings 11518 .getDisabledSystemPkgLPr(pkg.packageName); 11519 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 11520 // If the original was granted this permission, we take 11521 // that grant decision as read and propagate it to the 11522 // update. 11523 if (sysPs.isPrivileged()) { 11524 allowed = true; 11525 } 11526 } else { 11527 // The system apk may have been updated with an older 11528 // version of the one on the data partition, but which 11529 // granted a new system permission that it didn't have 11530 // before. In this case we do want to allow the app to 11531 // now get the new permission if the ancestral apk is 11532 // privileged to get it. 11533 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 11534 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 11535 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 11536 allowed = true; 11537 break; 11538 } 11539 } 11540 } 11541 // Also if a privileged parent package on the system image or any of 11542 // its children requested a privileged permission, the updated child 11543 // packages can also get the permission. 11544 if (pkg.parentPackage != null) { 11545 final PackageSetting disabledSysParentPs = mSettings 11546 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 11547 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 11548 && disabledSysParentPs.isPrivileged()) { 11549 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 11550 allowed = true; 11551 } else if (disabledSysParentPs.pkg.childPackages != null) { 11552 final int count = disabledSysParentPs.pkg.childPackages.size(); 11553 for (int i = 0; i < count; i++) { 11554 PackageParser.Package disabledSysChildPkg = 11555 disabledSysParentPs.pkg.childPackages.get(i); 11556 if (isPackageRequestingPermission(disabledSysChildPkg, 11557 perm)) { 11558 allowed = true; 11559 break; 11560 } 11561 } 11562 } 11563 } 11564 } 11565 } 11566 } else { 11567 allowed = isPrivilegedApp(pkg); 11568 } 11569 } 11570 } 11571 if (!allowed) { 11572 if (!allowed && (bp.protectionLevel 11573 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 11574 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 11575 // If this was a previously normal/dangerous permission that got moved 11576 // to a system permission as part of the runtime permission redesign, then 11577 // we still want to blindly grant it to old apps. 11578 allowed = true; 11579 } 11580 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 11581 && pkg.packageName.equals(mRequiredInstallerPackage)) { 11582 // If this permission is to be granted to the system installer and 11583 // this app is an installer, then it gets the permission. 11584 allowed = true; 11585 } 11586 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 11587 && pkg.packageName.equals(mRequiredVerifierPackage)) { 11588 // If this permission is to be granted to the system verifier and 11589 // this app is a verifier, then it gets the permission. 11590 allowed = true; 11591 } 11592 if (!allowed && (bp.protectionLevel 11593 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 11594 && isSystemApp(pkg)) { 11595 // Any pre-installed system app is allowed to get this permission. 11596 allowed = true; 11597 } 11598 if (!allowed && (bp.protectionLevel 11599 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 11600 // For development permissions, a development permission 11601 // is granted only if it was already granted. 11602 allowed = origPermissions.hasInstallPermission(perm); 11603 } 11604 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 11605 && pkg.packageName.equals(mSetupWizardPackage)) { 11606 // If this permission is to be granted to the system setup wizard and 11607 // this app is a setup wizard, then it gets the permission. 11608 allowed = true; 11609 } 11610 } 11611 return allowed; 11612 } 11613 11614 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 11615 final int permCount = pkg.requestedPermissions.size(); 11616 for (int j = 0; j < permCount; j++) { 11617 String requestedPermission = pkg.requestedPermissions.get(j); 11618 if (permission.equals(requestedPermission)) { 11619 return true; 11620 } 11621 } 11622 return false; 11623 } 11624 11625 final class ActivityIntentResolver 11626 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 11627 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 11628 boolean defaultOnly, boolean visibleToEphemeral, boolean isEphemeral, int userId) { 11629 if (!sUserManager.exists(userId)) return null; 11630 mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0) 11631 | (visibleToEphemeral ? PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY : 0) 11632 | (isEphemeral ? PackageManager.MATCH_EPHEMERAL : 0); 11633 return super.queryIntent(intent, resolvedType, defaultOnly, visibleToEphemeral, 11634 isEphemeral, userId); 11635 } 11636 11637 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 11638 int userId) { 11639 if (!sUserManager.exists(userId)) return null; 11640 mFlags = flags; 11641 return super.queryIntent(intent, resolvedType, 11642 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 11643 (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0, 11644 (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId); 11645 } 11646 11647 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 11648 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 11649 if (!sUserManager.exists(userId)) return null; 11650 if (packageActivities == null) { 11651 return null; 11652 } 11653 mFlags = flags; 11654 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 11655 final boolean vislbleToEphemeral = 11656 (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0; 11657 final boolean isEphemeral = (flags & PackageManager.MATCH_EPHEMERAL) != 0; 11658 final int N = packageActivities.size(); 11659 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 11660 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 11661 11662 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 11663 for (int i = 0; i < N; ++i) { 11664 intentFilters = packageActivities.get(i).intents; 11665 if (intentFilters != null && intentFilters.size() > 0) { 11666 PackageParser.ActivityIntentInfo[] array = 11667 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 11668 intentFilters.toArray(array); 11669 listCut.add(array); 11670 } 11671 } 11672 return super.queryIntentFromList(intent, resolvedType, defaultOnly, 11673 vislbleToEphemeral, isEphemeral, listCut, userId); 11674 } 11675 11676 /** 11677 * Finds a privileged activity that matches the specified activity names. 11678 */ 11679 private PackageParser.Activity findMatchingActivity( 11680 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 11681 for (PackageParser.Activity sysActivity : activityList) { 11682 if (sysActivity.info.name.equals(activityInfo.name)) { 11683 return sysActivity; 11684 } 11685 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 11686 return sysActivity; 11687 } 11688 if (sysActivity.info.targetActivity != null) { 11689 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 11690 return sysActivity; 11691 } 11692 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 11693 return sysActivity; 11694 } 11695 } 11696 } 11697 return null; 11698 } 11699 11700 public class IterGenerator<E> { 11701 public Iterator<E> generate(ActivityIntentInfo info) { 11702 return null; 11703 } 11704 } 11705 11706 public class ActionIterGenerator extends IterGenerator<String> { 11707 @Override 11708 public Iterator<String> generate(ActivityIntentInfo info) { 11709 return info.actionsIterator(); 11710 } 11711 } 11712 11713 public class CategoriesIterGenerator extends IterGenerator<String> { 11714 @Override 11715 public Iterator<String> generate(ActivityIntentInfo info) { 11716 return info.categoriesIterator(); 11717 } 11718 } 11719 11720 public class SchemesIterGenerator extends IterGenerator<String> { 11721 @Override 11722 public Iterator<String> generate(ActivityIntentInfo info) { 11723 return info.schemesIterator(); 11724 } 11725 } 11726 11727 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 11728 @Override 11729 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 11730 return info.authoritiesIterator(); 11731 } 11732 } 11733 11734 /** 11735 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 11736 * MODIFIED. Do not pass in a list that should not be changed. 11737 */ 11738 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 11739 IterGenerator<T> generator, Iterator<T> searchIterator) { 11740 // loop through the set of actions; every one must be found in the intent filter 11741 while (searchIterator.hasNext()) { 11742 // we must have at least one filter in the list to consider a match 11743 if (intentList.size() == 0) { 11744 break; 11745 } 11746 11747 final T searchAction = searchIterator.next(); 11748 11749 // loop through the set of intent filters 11750 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 11751 while (intentIter.hasNext()) { 11752 final ActivityIntentInfo intentInfo = intentIter.next(); 11753 boolean selectionFound = false; 11754 11755 // loop through the intent filter's selection criteria; at least one 11756 // of them must match the searched criteria 11757 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 11758 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 11759 final T intentSelection = intentSelectionIter.next(); 11760 if (intentSelection != null && intentSelection.equals(searchAction)) { 11761 selectionFound = true; 11762 break; 11763 } 11764 } 11765 11766 // the selection criteria wasn't found in this filter's set; this filter 11767 // is not a potential match 11768 if (!selectionFound) { 11769 intentIter.remove(); 11770 } 11771 } 11772 } 11773 } 11774 11775 private boolean isProtectedAction(ActivityIntentInfo filter) { 11776 final Iterator<String> actionsIter = filter.actionsIterator(); 11777 while (actionsIter != null && actionsIter.hasNext()) { 11778 final String filterAction = actionsIter.next(); 11779 if (PROTECTED_ACTIONS.contains(filterAction)) { 11780 return true; 11781 } 11782 } 11783 return false; 11784 } 11785 11786 /** 11787 * Adjusts the priority of the given intent filter according to policy. 11788 * <p> 11789 * <ul> 11790 * <li>The priority for non privileged applications is capped to '0'</li> 11791 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 11792 * <li>The priority for unbundled updates to privileged applications is capped to the 11793 * priority defined on the system partition</li> 11794 * </ul> 11795 * <p> 11796 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 11797 * allowed to obtain any priority on any action. 11798 */ 11799 private void adjustPriority( 11800 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 11801 // nothing to do; priority is fine as-is 11802 if (intent.getPriority() <= 0) { 11803 return; 11804 } 11805 11806 final ActivityInfo activityInfo = intent.activity.info; 11807 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 11808 11809 final boolean privilegedApp = 11810 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 11811 if (!privilegedApp) { 11812 // non-privileged applications can never define a priority >0 11813 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 11814 + " package: " + applicationInfo.packageName 11815 + " activity: " + intent.activity.className 11816 + " origPrio: " + intent.getPriority()); 11817 intent.setPriority(0); 11818 return; 11819 } 11820 11821 if (systemActivities == null) { 11822 // the system package is not disabled; we're parsing the system partition 11823 if (isProtectedAction(intent)) { 11824 if (mDeferProtectedFilters) { 11825 // We can't deal with these just yet. No component should ever obtain a 11826 // >0 priority for a protected actions, with ONE exception -- the setup 11827 // wizard. The setup wizard, however, cannot be known until we're able to 11828 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 11829 // until all intent filters have been processed. Chicken, meet egg. 11830 // Let the filter temporarily have a high priority and rectify the 11831 // priorities after all system packages have been scanned. 11832 mProtectedFilters.add(intent); 11833 if (DEBUG_FILTERS) { 11834 Slog.i(TAG, "Protected action; save for later;" 11835 + " package: " + applicationInfo.packageName 11836 + " activity: " + intent.activity.className 11837 + " origPrio: " + intent.getPriority()); 11838 } 11839 return; 11840 } else { 11841 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 11842 Slog.i(TAG, "No setup wizard;" 11843 + " All protected intents capped to priority 0"); 11844 } 11845 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 11846 if (DEBUG_FILTERS) { 11847 Slog.i(TAG, "Found setup wizard;" 11848 + " allow priority " + intent.getPriority() + ";" 11849 + " package: " + intent.activity.info.packageName 11850 + " activity: " + intent.activity.className 11851 + " priority: " + intent.getPriority()); 11852 } 11853 // setup wizard gets whatever it wants 11854 return; 11855 } 11856 Slog.w(TAG, "Protected action; cap priority to 0;" 11857 + " package: " + intent.activity.info.packageName 11858 + " activity: " + intent.activity.className 11859 + " origPrio: " + intent.getPriority()); 11860 intent.setPriority(0); 11861 return; 11862 } 11863 } 11864 // privileged apps on the system image get whatever priority they request 11865 return; 11866 } 11867 11868 // privileged app unbundled update ... try to find the same activity 11869 final PackageParser.Activity foundActivity = 11870 findMatchingActivity(systemActivities, activityInfo); 11871 if (foundActivity == null) { 11872 // this is a new activity; it cannot obtain >0 priority 11873 if (DEBUG_FILTERS) { 11874 Slog.i(TAG, "New activity; cap priority to 0;" 11875 + " package: " + applicationInfo.packageName 11876 + " activity: " + intent.activity.className 11877 + " origPrio: " + intent.getPriority()); 11878 } 11879 intent.setPriority(0); 11880 return; 11881 } 11882 11883 // found activity, now check for filter equivalence 11884 11885 // a shallow copy is enough; we modify the list, not its contents 11886 final List<ActivityIntentInfo> intentListCopy = 11887 new ArrayList<>(foundActivity.intents); 11888 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 11889 11890 // find matching action subsets 11891 final Iterator<String> actionsIterator = intent.actionsIterator(); 11892 if (actionsIterator != null) { 11893 getIntentListSubset( 11894 intentListCopy, new ActionIterGenerator(), actionsIterator); 11895 if (intentListCopy.size() == 0) { 11896 // no more intents to match; we're not equivalent 11897 if (DEBUG_FILTERS) { 11898 Slog.i(TAG, "Mismatched action; cap priority to 0;" 11899 + " package: " + applicationInfo.packageName 11900 + " activity: " + intent.activity.className 11901 + " origPrio: " + intent.getPriority()); 11902 } 11903 intent.setPriority(0); 11904 return; 11905 } 11906 } 11907 11908 // find matching category subsets 11909 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 11910 if (categoriesIterator != null) { 11911 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 11912 categoriesIterator); 11913 if (intentListCopy.size() == 0) { 11914 // no more intents to match; we're not equivalent 11915 if (DEBUG_FILTERS) { 11916 Slog.i(TAG, "Mismatched category; cap priority to 0;" 11917 + " package: " + applicationInfo.packageName 11918 + " activity: " + intent.activity.className 11919 + " origPrio: " + intent.getPriority()); 11920 } 11921 intent.setPriority(0); 11922 return; 11923 } 11924 } 11925 11926 // find matching schemes subsets 11927 final Iterator<String> schemesIterator = intent.schemesIterator(); 11928 if (schemesIterator != null) { 11929 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 11930 schemesIterator); 11931 if (intentListCopy.size() == 0) { 11932 // no more intents to match; we're not equivalent 11933 if (DEBUG_FILTERS) { 11934 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 11935 + " package: " + applicationInfo.packageName 11936 + " activity: " + intent.activity.className 11937 + " origPrio: " + intent.getPriority()); 11938 } 11939 intent.setPriority(0); 11940 return; 11941 } 11942 } 11943 11944 // find matching authorities subsets 11945 final Iterator<IntentFilter.AuthorityEntry> 11946 authoritiesIterator = intent.authoritiesIterator(); 11947 if (authoritiesIterator != null) { 11948 getIntentListSubset(intentListCopy, 11949 new AuthoritiesIterGenerator(), 11950 authoritiesIterator); 11951 if (intentListCopy.size() == 0) { 11952 // no more intents to match; we're not equivalent 11953 if (DEBUG_FILTERS) { 11954 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 11955 + " package: " + applicationInfo.packageName 11956 + " activity: " + intent.activity.className 11957 + " origPrio: " + intent.getPriority()); 11958 } 11959 intent.setPriority(0); 11960 return; 11961 } 11962 } 11963 11964 // we found matching filter(s); app gets the max priority of all intents 11965 int cappedPriority = 0; 11966 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 11967 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 11968 } 11969 if (intent.getPriority() > cappedPriority) { 11970 if (DEBUG_FILTERS) { 11971 Slog.i(TAG, "Found matching filter(s);" 11972 + " cap priority to " + cappedPriority + ";" 11973 + " package: " + applicationInfo.packageName 11974 + " activity: " + intent.activity.className 11975 + " origPrio: " + intent.getPriority()); 11976 } 11977 intent.setPriority(cappedPriority); 11978 return; 11979 } 11980 // all this for nothing; the requested priority was <= what was on the system 11981 } 11982 11983 public final void addActivity(PackageParser.Activity a, String type) { 11984 mActivities.put(a.getComponentName(), a); 11985 if (DEBUG_SHOW_INFO) 11986 Log.v( 11987 TAG, " " + type + " " + 11988 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 11989 if (DEBUG_SHOW_INFO) 11990 Log.v(TAG, " Class=" + a.info.name); 11991 final int NI = a.intents.size(); 11992 for (int j=0; j<NI; j++) { 11993 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 11994 if ("activity".equals(type)) { 11995 final PackageSetting ps = 11996 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 11997 final List<PackageParser.Activity> systemActivities = 11998 ps != null && ps.pkg != null ? ps.pkg.activities : null; 11999 adjustPriority(systemActivities, intent); 12000 } 12001 if (DEBUG_SHOW_INFO) { 12002 Log.v(TAG, " IntentFilter:"); 12003 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12004 } 12005 if (!intent.debugCheck()) { 12006 Log.w(TAG, "==> For Activity " + a.info.name); 12007 } 12008 addFilter(intent); 12009 } 12010 } 12011 12012 public final void removeActivity(PackageParser.Activity a, String type) { 12013 mActivities.remove(a.getComponentName()); 12014 if (DEBUG_SHOW_INFO) { 12015 Log.v(TAG, " " + type + " " 12016 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 12017 : a.info.name) + ":"); 12018 Log.v(TAG, " Class=" + a.info.name); 12019 } 12020 final int NI = a.intents.size(); 12021 for (int j=0; j<NI; j++) { 12022 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 12023 if (DEBUG_SHOW_INFO) { 12024 Log.v(TAG, " IntentFilter:"); 12025 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12026 } 12027 removeFilter(intent); 12028 } 12029 } 12030 12031 @Override 12032 protected boolean allowFilterResult( 12033 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 12034 ActivityInfo filterAi = filter.activity.info; 12035 for (int i=dest.size()-1; i>=0; i--) { 12036 ActivityInfo destAi = dest.get(i).activityInfo; 12037 if (destAi.name == filterAi.name 12038 && destAi.packageName == filterAi.packageName) { 12039 return false; 12040 } 12041 } 12042 return true; 12043 } 12044 12045 @Override 12046 protected ActivityIntentInfo[] newArray(int size) { 12047 return new ActivityIntentInfo[size]; 12048 } 12049 12050 @Override 12051 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 12052 if (!sUserManager.exists(userId)) return true; 12053 PackageParser.Package p = filter.activity.owner; 12054 if (p != null) { 12055 PackageSetting ps = (PackageSetting)p.mExtras; 12056 if (ps != null) { 12057 // System apps are never considered stopped for purposes of 12058 // filtering, because there may be no way for the user to 12059 // actually re-launch them. 12060 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 12061 && ps.getStopped(userId); 12062 } 12063 } 12064 return false; 12065 } 12066 12067 @Override 12068 protected boolean isPackageForFilter(String packageName, 12069 PackageParser.ActivityIntentInfo info) { 12070 return packageName.equals(info.activity.owner.packageName); 12071 } 12072 12073 @Override 12074 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 12075 int match, int userId) { 12076 if (!sUserManager.exists(userId)) return null; 12077 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 12078 return null; 12079 } 12080 final PackageParser.Activity activity = info.activity; 12081 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 12082 if (ps == null) { 12083 return null; 12084 } 12085 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 12086 ps.readUserState(userId), userId); 12087 if (ai == null) { 12088 return null; 12089 } 12090 final ResolveInfo res = new ResolveInfo(); 12091 res.activityInfo = ai; 12092 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 12093 res.filter = info; 12094 } 12095 if (info != null) { 12096 res.handleAllWebDataURI = info.handleAllWebDataURI(); 12097 } 12098 res.priority = info.getPriority(); 12099 res.preferredOrder = activity.owner.mPreferredOrder; 12100 //System.out.println("Result: " + res.activityInfo.className + 12101 // " = " + res.priority); 12102 res.match = match; 12103 res.isDefault = info.hasDefault; 12104 res.labelRes = info.labelRes; 12105 res.nonLocalizedLabel = info.nonLocalizedLabel; 12106 if (userNeedsBadging(userId)) { 12107 res.noResourceId = true; 12108 } else { 12109 res.icon = info.icon; 12110 } 12111 res.iconResourceId = info.icon; 12112 res.system = res.activityInfo.applicationInfo.isSystemApp(); 12113 return res; 12114 } 12115 12116 @Override 12117 protected void sortResults(List<ResolveInfo> results) { 12118 Collections.sort(results, mResolvePrioritySorter); 12119 } 12120 12121 @Override 12122 protected void dumpFilter(PrintWriter out, String prefix, 12123 PackageParser.ActivityIntentInfo filter) { 12124 out.print(prefix); out.print( 12125 Integer.toHexString(System.identityHashCode(filter.activity))); 12126 out.print(' '); 12127 filter.activity.printComponentShortName(out); 12128 out.print(" filter "); 12129 out.println(Integer.toHexString(System.identityHashCode(filter))); 12130 } 12131 12132 @Override 12133 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 12134 return filter.activity; 12135 } 12136 12137 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12138 PackageParser.Activity activity = (PackageParser.Activity)label; 12139 out.print(prefix); out.print( 12140 Integer.toHexString(System.identityHashCode(activity))); 12141 out.print(' '); 12142 activity.printComponentShortName(out); 12143 if (count > 1) { 12144 out.print(" ("); out.print(count); out.print(" filters)"); 12145 } 12146 out.println(); 12147 } 12148 12149 // Keys are String (activity class name), values are Activity. 12150 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 12151 = new ArrayMap<ComponentName, PackageParser.Activity>(); 12152 private int mFlags; 12153 } 12154 12155 private final class ServiceIntentResolver 12156 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 12157 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12158 boolean defaultOnly, boolean visibleToEphemeral, boolean isEphemeral, int userId) { 12159 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 12160 return super.queryIntent(intent, resolvedType, defaultOnly, visibleToEphemeral, 12161 isEphemeral, userId); 12162 } 12163 12164 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12165 int userId) { 12166 if (!sUserManager.exists(userId)) return null; 12167 mFlags = flags; 12168 return super.queryIntent(intent, resolvedType, 12169 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12170 (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0, 12171 (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId); 12172 } 12173 12174 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12175 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 12176 if (!sUserManager.exists(userId)) return null; 12177 if (packageServices == null) { 12178 return null; 12179 } 12180 mFlags = flags; 12181 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 12182 final boolean vislbleToEphemeral = 12183 (flags&PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0; 12184 final boolean isEphemeral = (flags&PackageManager.MATCH_EPHEMERAL) != 0; 12185 final int N = packageServices.size(); 12186 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 12187 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 12188 12189 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 12190 for (int i = 0; i < N; ++i) { 12191 intentFilters = packageServices.get(i).intents; 12192 if (intentFilters != null && intentFilters.size() > 0) { 12193 PackageParser.ServiceIntentInfo[] array = 12194 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 12195 intentFilters.toArray(array); 12196 listCut.add(array); 12197 } 12198 } 12199 return super.queryIntentFromList(intent, resolvedType, defaultOnly, 12200 vislbleToEphemeral, isEphemeral, listCut, userId); 12201 } 12202 12203 public final void addService(PackageParser.Service s) { 12204 mServices.put(s.getComponentName(), s); 12205 if (DEBUG_SHOW_INFO) { 12206 Log.v(TAG, " " 12207 + (s.info.nonLocalizedLabel != null 12208 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 12209 Log.v(TAG, " Class=" + s.info.name); 12210 } 12211 final int NI = s.intents.size(); 12212 int j; 12213 for (j=0; j<NI; j++) { 12214 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 12215 if (DEBUG_SHOW_INFO) { 12216 Log.v(TAG, " IntentFilter:"); 12217 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12218 } 12219 if (!intent.debugCheck()) { 12220 Log.w(TAG, "==> For Service " + s.info.name); 12221 } 12222 addFilter(intent); 12223 } 12224 } 12225 12226 public final void removeService(PackageParser.Service s) { 12227 mServices.remove(s.getComponentName()); 12228 if (DEBUG_SHOW_INFO) { 12229 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 12230 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 12231 Log.v(TAG, " Class=" + s.info.name); 12232 } 12233 final int NI = s.intents.size(); 12234 int j; 12235 for (j=0; j<NI; j++) { 12236 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 12237 if (DEBUG_SHOW_INFO) { 12238 Log.v(TAG, " IntentFilter:"); 12239 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12240 } 12241 removeFilter(intent); 12242 } 12243 } 12244 12245 @Override 12246 protected boolean allowFilterResult( 12247 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 12248 ServiceInfo filterSi = filter.service.info; 12249 for (int i=dest.size()-1; i>=0; i--) { 12250 ServiceInfo destAi = dest.get(i).serviceInfo; 12251 if (destAi.name == filterSi.name 12252 && destAi.packageName == filterSi.packageName) { 12253 return false; 12254 } 12255 } 12256 return true; 12257 } 12258 12259 @Override 12260 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 12261 return new PackageParser.ServiceIntentInfo[size]; 12262 } 12263 12264 @Override 12265 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 12266 if (!sUserManager.exists(userId)) return true; 12267 PackageParser.Package p = filter.service.owner; 12268 if (p != null) { 12269 PackageSetting ps = (PackageSetting)p.mExtras; 12270 if (ps != null) { 12271 // System apps are never considered stopped for purposes of 12272 // filtering, because there may be no way for the user to 12273 // actually re-launch them. 12274 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 12275 && ps.getStopped(userId); 12276 } 12277 } 12278 return false; 12279 } 12280 12281 @Override 12282 protected boolean isPackageForFilter(String packageName, 12283 PackageParser.ServiceIntentInfo info) { 12284 return packageName.equals(info.service.owner.packageName); 12285 } 12286 12287 @Override 12288 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 12289 int match, int userId) { 12290 if (!sUserManager.exists(userId)) return null; 12291 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 12292 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 12293 return null; 12294 } 12295 final PackageParser.Service service = info.service; 12296 PackageSetting ps = (PackageSetting) service.owner.mExtras; 12297 if (ps == null) { 12298 return null; 12299 } 12300 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 12301 ps.readUserState(userId), userId); 12302 if (si == null) { 12303 return null; 12304 } 12305 final ResolveInfo res = new ResolveInfo(); 12306 res.serviceInfo = si; 12307 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 12308 res.filter = filter; 12309 } 12310 res.priority = info.getPriority(); 12311 res.preferredOrder = service.owner.mPreferredOrder; 12312 res.match = match; 12313 res.isDefault = info.hasDefault; 12314 res.labelRes = info.labelRes; 12315 res.nonLocalizedLabel = info.nonLocalizedLabel; 12316 res.icon = info.icon; 12317 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 12318 return res; 12319 } 12320 12321 @Override 12322 protected void sortResults(List<ResolveInfo> results) { 12323 Collections.sort(results, mResolvePrioritySorter); 12324 } 12325 12326 @Override 12327 protected void dumpFilter(PrintWriter out, String prefix, 12328 PackageParser.ServiceIntentInfo filter) { 12329 out.print(prefix); out.print( 12330 Integer.toHexString(System.identityHashCode(filter.service))); 12331 out.print(' '); 12332 filter.service.printComponentShortName(out); 12333 out.print(" filter "); 12334 out.println(Integer.toHexString(System.identityHashCode(filter))); 12335 } 12336 12337 @Override 12338 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 12339 return filter.service; 12340 } 12341 12342 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12343 PackageParser.Service service = (PackageParser.Service)label; 12344 out.print(prefix); out.print( 12345 Integer.toHexString(System.identityHashCode(service))); 12346 out.print(' '); 12347 service.printComponentShortName(out); 12348 if (count > 1) { 12349 out.print(" ("); out.print(count); out.print(" filters)"); 12350 } 12351 out.println(); 12352 } 12353 12354// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 12355// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 12356// final List<ResolveInfo> retList = Lists.newArrayList(); 12357// while (i.hasNext()) { 12358// final ResolveInfo resolveInfo = (ResolveInfo) i; 12359// if (isEnabledLP(resolveInfo.serviceInfo)) { 12360// retList.add(resolveInfo); 12361// } 12362// } 12363// return retList; 12364// } 12365 12366 // Keys are String (activity class name), values are Activity. 12367 private final ArrayMap<ComponentName, PackageParser.Service> mServices 12368 = new ArrayMap<ComponentName, PackageParser.Service>(); 12369 private int mFlags; 12370 } 12371 12372 private final class ProviderIntentResolver 12373 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 12374 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12375 boolean defaultOnly, boolean visibleToEphemeral, boolean isEphemeral, int userId) { 12376 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 12377 return super.queryIntent(intent, resolvedType, defaultOnly, visibleToEphemeral, 12378 isEphemeral, userId); 12379 } 12380 12381 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12382 int userId) { 12383 if (!sUserManager.exists(userId)) 12384 return null; 12385 mFlags = flags; 12386 return super.queryIntent(intent, resolvedType, 12387 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12388 (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0, 12389 (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId); 12390 } 12391 12392 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12393 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 12394 if (!sUserManager.exists(userId)) 12395 return null; 12396 if (packageProviders == null) { 12397 return null; 12398 } 12399 mFlags = flags; 12400 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 12401 final boolean isEphemeral = (flags&PackageManager.MATCH_EPHEMERAL) != 0; 12402 final boolean vislbleToEphemeral = 12403 (flags&PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0; 12404 final int N = packageProviders.size(); 12405 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 12406 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 12407 12408 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 12409 for (int i = 0; i < N; ++i) { 12410 intentFilters = packageProviders.get(i).intents; 12411 if (intentFilters != null && intentFilters.size() > 0) { 12412 PackageParser.ProviderIntentInfo[] array = 12413 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 12414 intentFilters.toArray(array); 12415 listCut.add(array); 12416 } 12417 } 12418 return super.queryIntentFromList(intent, resolvedType, defaultOnly, 12419 vislbleToEphemeral, isEphemeral, listCut, userId); 12420 } 12421 12422 public final void addProvider(PackageParser.Provider p) { 12423 if (mProviders.containsKey(p.getComponentName())) { 12424 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 12425 return; 12426 } 12427 12428 mProviders.put(p.getComponentName(), p); 12429 if (DEBUG_SHOW_INFO) { 12430 Log.v(TAG, " " 12431 + (p.info.nonLocalizedLabel != null 12432 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 12433 Log.v(TAG, " Class=" + p.info.name); 12434 } 12435 final int NI = p.intents.size(); 12436 int j; 12437 for (j = 0; j < NI; j++) { 12438 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 12439 if (DEBUG_SHOW_INFO) { 12440 Log.v(TAG, " IntentFilter:"); 12441 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12442 } 12443 if (!intent.debugCheck()) { 12444 Log.w(TAG, "==> For Provider " + p.info.name); 12445 } 12446 addFilter(intent); 12447 } 12448 } 12449 12450 public final void removeProvider(PackageParser.Provider p) { 12451 mProviders.remove(p.getComponentName()); 12452 if (DEBUG_SHOW_INFO) { 12453 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 12454 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 12455 Log.v(TAG, " Class=" + p.info.name); 12456 } 12457 final int NI = p.intents.size(); 12458 int j; 12459 for (j = 0; j < NI; j++) { 12460 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 12461 if (DEBUG_SHOW_INFO) { 12462 Log.v(TAG, " IntentFilter:"); 12463 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12464 } 12465 removeFilter(intent); 12466 } 12467 } 12468 12469 @Override 12470 protected boolean allowFilterResult( 12471 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 12472 ProviderInfo filterPi = filter.provider.info; 12473 for (int i = dest.size() - 1; i >= 0; i--) { 12474 ProviderInfo destPi = dest.get(i).providerInfo; 12475 if (destPi.name == filterPi.name 12476 && destPi.packageName == filterPi.packageName) { 12477 return false; 12478 } 12479 } 12480 return true; 12481 } 12482 12483 @Override 12484 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 12485 return new PackageParser.ProviderIntentInfo[size]; 12486 } 12487 12488 @Override 12489 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 12490 if (!sUserManager.exists(userId)) 12491 return true; 12492 PackageParser.Package p = filter.provider.owner; 12493 if (p != null) { 12494 PackageSetting ps = (PackageSetting) p.mExtras; 12495 if (ps != null) { 12496 // System apps are never considered stopped for purposes of 12497 // filtering, because there may be no way for the user to 12498 // actually re-launch them. 12499 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 12500 && ps.getStopped(userId); 12501 } 12502 } 12503 return false; 12504 } 12505 12506 @Override 12507 protected boolean isPackageForFilter(String packageName, 12508 PackageParser.ProviderIntentInfo info) { 12509 return packageName.equals(info.provider.owner.packageName); 12510 } 12511 12512 @Override 12513 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 12514 int match, int userId) { 12515 if (!sUserManager.exists(userId)) 12516 return null; 12517 final PackageParser.ProviderIntentInfo info = filter; 12518 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 12519 return null; 12520 } 12521 final PackageParser.Provider provider = info.provider; 12522 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 12523 if (ps == null) { 12524 return null; 12525 } 12526 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 12527 ps.readUserState(userId), userId); 12528 if (pi == null) { 12529 return null; 12530 } 12531 final ResolveInfo res = new ResolveInfo(); 12532 res.providerInfo = pi; 12533 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 12534 res.filter = filter; 12535 } 12536 res.priority = info.getPriority(); 12537 res.preferredOrder = provider.owner.mPreferredOrder; 12538 res.match = match; 12539 res.isDefault = info.hasDefault; 12540 res.labelRes = info.labelRes; 12541 res.nonLocalizedLabel = info.nonLocalizedLabel; 12542 res.icon = info.icon; 12543 res.system = res.providerInfo.applicationInfo.isSystemApp(); 12544 return res; 12545 } 12546 12547 @Override 12548 protected void sortResults(List<ResolveInfo> results) { 12549 Collections.sort(results, mResolvePrioritySorter); 12550 } 12551 12552 @Override 12553 protected void dumpFilter(PrintWriter out, String prefix, 12554 PackageParser.ProviderIntentInfo filter) { 12555 out.print(prefix); 12556 out.print( 12557 Integer.toHexString(System.identityHashCode(filter.provider))); 12558 out.print(' '); 12559 filter.provider.printComponentShortName(out); 12560 out.print(" filter "); 12561 out.println(Integer.toHexString(System.identityHashCode(filter))); 12562 } 12563 12564 @Override 12565 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 12566 return filter.provider; 12567 } 12568 12569 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12570 PackageParser.Provider provider = (PackageParser.Provider)label; 12571 out.print(prefix); out.print( 12572 Integer.toHexString(System.identityHashCode(provider))); 12573 out.print(' '); 12574 provider.printComponentShortName(out); 12575 if (count > 1) { 12576 out.print(" ("); out.print(count); out.print(" filters)"); 12577 } 12578 out.println(); 12579 } 12580 12581 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 12582 = new ArrayMap<ComponentName, PackageParser.Provider>(); 12583 private int mFlags; 12584 } 12585 12586 static final class EphemeralIntentResolver 12587 extends IntentResolver<EphemeralResponse, EphemeralResponse> { 12588 /** 12589 * The result that has the highest defined order. Ordering applies on a 12590 * per-package basis. Mapping is from package name to Pair of order and 12591 * EphemeralResolveInfo. 12592 * <p> 12593 * NOTE: This is implemented as a field variable for convenience and efficiency. 12594 * By having a field variable, we're able to track filter ordering as soon as 12595 * a non-zero order is defined. Otherwise, multiple loops across the result set 12596 * would be needed to apply ordering. If the intent resolver becomes re-entrant, 12597 * this needs to be contained entirely within {@link #filterResults()}. 12598 */ 12599 final ArrayMap<String, Pair<Integer, EphemeralResolveInfo>> mOrderResult = new ArrayMap<>(); 12600 12601 @Override 12602 protected EphemeralResponse[] newArray(int size) { 12603 return new EphemeralResponse[size]; 12604 } 12605 12606 @Override 12607 protected boolean isPackageForFilter(String packageName, EphemeralResponse responseObj) { 12608 return true; 12609 } 12610 12611 @Override 12612 protected EphemeralResponse newResult(EphemeralResponse responseObj, int match, 12613 int userId) { 12614 if (!sUserManager.exists(userId)) { 12615 return null; 12616 } 12617 final String packageName = responseObj.resolveInfo.getPackageName(); 12618 final Integer order = responseObj.getOrder(); 12619 final Pair<Integer, EphemeralResolveInfo> lastOrderResult = 12620 mOrderResult.get(packageName); 12621 // ordering is enabled and this item's order isn't high enough 12622 if (lastOrderResult != null && lastOrderResult.first >= order) { 12623 return null; 12624 } 12625 final EphemeralResolveInfo res = responseObj.resolveInfo; 12626 if (order > 0) { 12627 // non-zero order, enable ordering 12628 mOrderResult.put(packageName, new Pair<>(order, res)); 12629 } 12630 return responseObj; 12631 } 12632 12633 @Override 12634 protected void filterResults(List<EphemeralResponse> results) { 12635 // only do work if ordering is enabled [most of the time it won't be] 12636 if (mOrderResult.size() == 0) { 12637 return; 12638 } 12639 int resultSize = results.size(); 12640 for (int i = 0; i < resultSize; i++) { 12641 final EphemeralResolveInfo info = results.get(i).resolveInfo; 12642 final String packageName = info.getPackageName(); 12643 final Pair<Integer, EphemeralResolveInfo> savedInfo = mOrderResult.get(packageName); 12644 if (savedInfo == null) { 12645 // package doesn't having ordering 12646 continue; 12647 } 12648 if (savedInfo.second == info) { 12649 // circled back to the highest ordered item; remove from order list 12650 mOrderResult.remove(savedInfo); 12651 if (mOrderResult.size() == 0) { 12652 // no more ordered items 12653 break; 12654 } 12655 continue; 12656 } 12657 // item has a worse order, remove it from the result list 12658 results.remove(i); 12659 resultSize--; 12660 i--; 12661 } 12662 } 12663 } 12664 12665 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 12666 new Comparator<ResolveInfo>() { 12667 public int compare(ResolveInfo r1, ResolveInfo r2) { 12668 int v1 = r1.priority; 12669 int v2 = r2.priority; 12670 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 12671 if (v1 != v2) { 12672 return (v1 > v2) ? -1 : 1; 12673 } 12674 v1 = r1.preferredOrder; 12675 v2 = r2.preferredOrder; 12676 if (v1 != v2) { 12677 return (v1 > v2) ? -1 : 1; 12678 } 12679 if (r1.isDefault != r2.isDefault) { 12680 return r1.isDefault ? -1 : 1; 12681 } 12682 v1 = r1.match; 12683 v2 = r2.match; 12684 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 12685 if (v1 != v2) { 12686 return (v1 > v2) ? -1 : 1; 12687 } 12688 if (r1.system != r2.system) { 12689 return r1.system ? -1 : 1; 12690 } 12691 if (r1.activityInfo != null) { 12692 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 12693 } 12694 if (r1.serviceInfo != null) { 12695 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 12696 } 12697 if (r1.providerInfo != null) { 12698 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 12699 } 12700 return 0; 12701 } 12702 }; 12703 12704 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 12705 new Comparator<ProviderInfo>() { 12706 public int compare(ProviderInfo p1, ProviderInfo p2) { 12707 final int v1 = p1.initOrder; 12708 final int v2 = p2.initOrder; 12709 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 12710 } 12711 }; 12712 12713 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 12714 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 12715 final int[] userIds) { 12716 mHandler.post(new Runnable() { 12717 @Override 12718 public void run() { 12719 try { 12720 final IActivityManager am = ActivityManager.getService(); 12721 if (am == null) return; 12722 final int[] resolvedUserIds; 12723 if (userIds == null) { 12724 resolvedUserIds = am.getRunningUserIds(); 12725 } else { 12726 resolvedUserIds = userIds; 12727 } 12728 for (int id : resolvedUserIds) { 12729 final Intent intent = new Intent(action, 12730 pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null); 12731 if (extras != null) { 12732 intent.putExtras(extras); 12733 } 12734 if (targetPkg != null) { 12735 intent.setPackage(targetPkg); 12736 } 12737 // Modify the UID when posting to other users 12738 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 12739 if (uid > 0 && UserHandle.getUserId(uid) != id) { 12740 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 12741 intent.putExtra(Intent.EXTRA_UID, uid); 12742 } 12743 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 12744 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 12745 if (DEBUG_BROADCASTS) { 12746 RuntimeException here = new RuntimeException("here"); 12747 here.fillInStackTrace(); 12748 Slog.d(TAG, "Sending to user " + id + ": " 12749 + intent.toShortString(false, true, false, false) 12750 + " " + intent.getExtras(), here); 12751 } 12752 am.broadcastIntent(null, intent, null, finishedReceiver, 12753 0, null, null, null, android.app.AppOpsManager.OP_NONE, 12754 null, finishedReceiver != null, false, id); 12755 } 12756 } catch (RemoteException ex) { 12757 } 12758 } 12759 }); 12760 } 12761 12762 /** 12763 * Check if the external storage media is available. This is true if there 12764 * is a mounted external storage medium or if the external storage is 12765 * emulated. 12766 */ 12767 private boolean isExternalMediaAvailable() { 12768 return mMediaMounted || Environment.isExternalStorageEmulated(); 12769 } 12770 12771 @Override 12772 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 12773 // writer 12774 synchronized (mPackages) { 12775 if (!isExternalMediaAvailable()) { 12776 // If the external storage is no longer mounted at this point, 12777 // the caller may not have been able to delete all of this 12778 // packages files and can not delete any more. Bail. 12779 return null; 12780 } 12781 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 12782 if (lastPackage != null) { 12783 pkgs.remove(lastPackage); 12784 } 12785 if (pkgs.size() > 0) { 12786 return pkgs.get(0); 12787 } 12788 } 12789 return null; 12790 } 12791 12792 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 12793 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 12794 userId, andCode ? 1 : 0, packageName); 12795 if (mSystemReady) { 12796 msg.sendToTarget(); 12797 } else { 12798 if (mPostSystemReadyMessages == null) { 12799 mPostSystemReadyMessages = new ArrayList<>(); 12800 } 12801 mPostSystemReadyMessages.add(msg); 12802 } 12803 } 12804 12805 void startCleaningPackages() { 12806 // reader 12807 if (!isExternalMediaAvailable()) { 12808 return; 12809 } 12810 synchronized (mPackages) { 12811 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 12812 return; 12813 } 12814 } 12815 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 12816 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 12817 IActivityManager am = ActivityManager.getService(); 12818 if (am != null) { 12819 try { 12820 am.startService(null, intent, null, -1, null, mContext.getOpPackageName(), 12821 UserHandle.USER_SYSTEM); 12822 } catch (RemoteException e) { 12823 } 12824 } 12825 } 12826 12827 @Override 12828 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 12829 int installFlags, String installerPackageName, int userId) { 12830 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 12831 12832 final int callingUid = Binder.getCallingUid(); 12833 enforceCrossUserPermission(callingUid, userId, 12834 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 12835 12836 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 12837 try { 12838 if (observer != null) { 12839 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 12840 } 12841 } catch (RemoteException re) { 12842 } 12843 return; 12844 } 12845 12846 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 12847 installFlags |= PackageManager.INSTALL_FROM_ADB; 12848 12849 } else { 12850 // Caller holds INSTALL_PACKAGES permission, so we're less strict 12851 // about installerPackageName. 12852 12853 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 12854 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 12855 } 12856 12857 UserHandle user; 12858 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 12859 user = UserHandle.ALL; 12860 } else { 12861 user = new UserHandle(userId); 12862 } 12863 12864 // Only system components can circumvent runtime permissions when installing. 12865 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 12866 && mContext.checkCallingOrSelfPermission(Manifest.permission 12867 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 12868 throw new SecurityException("You need the " 12869 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 12870 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 12871 } 12872 12873 final File originFile = new File(originPath); 12874 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 12875 12876 final Message msg = mHandler.obtainMessage(INIT_COPY); 12877 final VerificationInfo verificationInfo = new VerificationInfo( 12878 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 12879 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 12880 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 12881 null /*packageAbiOverride*/, null /*grantedPermissions*/, 12882 null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN); 12883 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 12884 msg.obj = params; 12885 12886 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 12887 System.identityHashCode(msg.obj)); 12888 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 12889 System.identityHashCode(msg.obj)); 12890 12891 mHandler.sendMessage(msg); 12892 } 12893 12894 12895 /** 12896 * Ensure that the install reason matches what we know about the package installer (e.g. whether 12897 * it is acting on behalf on an enterprise or the user). 12898 * 12899 * Note that the ordering of the conditionals in this method is important. The checks we perform 12900 * are as follows, in this order: 12901 * 12902 * 1) If the install is being performed by a system app, we can trust the app to have set the 12903 * install reason correctly. Thus, we pass through the install reason unchanged, no matter 12904 * what it is. 12905 * 2) If the install is being performed by a device or profile owner app, the install reason 12906 * should be enterprise policy. However, we cannot be sure that the device or profile owner 12907 * set the install reason correctly. If the app targets an older SDK version where install 12908 * reasons did not exist yet, or if the app author simply forgot, the install reason may be 12909 * unset or wrong. Thus, we force the install reason to be enterprise policy. 12910 * 3) In all other cases, the install is being performed by a regular app that is neither part 12911 * of the system nor a device or profile owner. We have no reason to believe that this app is 12912 * acting on behalf of the enterprise admin. Thus, we check whether the install reason was 12913 * set to enterprise policy and if so, change it to unknown instead. 12914 */ 12915 private int fixUpInstallReason(String installerPackageName, int installerUid, 12916 int installReason) { 12917 if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid) 12918 == PERMISSION_GRANTED) { 12919 // If the install is being performed by a system app, we trust that app to have set the 12920 // install reason correctly. 12921 return installReason; 12922 } 12923 12924 final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 12925 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 12926 if (dpm != null) { 12927 ComponentName owner = null; 12928 try { 12929 owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */); 12930 if (owner == null) { 12931 owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid)); 12932 } 12933 } catch (RemoteException e) { 12934 } 12935 if (owner != null && owner.getPackageName().equals(installerPackageName)) { 12936 // If the install is being performed by a device or profile owner, the install 12937 // reason should be enterprise policy. 12938 return PackageManager.INSTALL_REASON_POLICY; 12939 } 12940 } 12941 12942 if (installReason == PackageManager.INSTALL_REASON_POLICY) { 12943 // If the install is being performed by a regular app (i.e. neither system app nor 12944 // device or profile owner), we have no reason to believe that the app is acting on 12945 // behalf of an enterprise. If the app set the install reason to enterprise policy, 12946 // change it to unknown instead. 12947 return PackageManager.INSTALL_REASON_UNKNOWN; 12948 } 12949 12950 // If the install is being performed by a regular app and the install reason was set to any 12951 // value but enterprise policy, leave the install reason unchanged. 12952 return installReason; 12953 } 12954 12955 void installStage(String packageName, File stagedDir, String stagedCid, 12956 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 12957 String installerPackageName, int installerUid, UserHandle user, 12958 Certificate[][] certificates) { 12959 if (DEBUG_EPHEMERAL) { 12960 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 12961 Slog.d(TAG, "Ephemeral install of " + packageName); 12962 } 12963 } 12964 final VerificationInfo verificationInfo = new VerificationInfo( 12965 sessionParams.originatingUri, sessionParams.referrerUri, 12966 sessionParams.originatingUid, installerUid); 12967 12968 final OriginInfo origin; 12969 if (stagedDir != null) { 12970 origin = OriginInfo.fromStagedFile(stagedDir); 12971 } else { 12972 origin = OriginInfo.fromStagedContainer(stagedCid); 12973 } 12974 12975 final Message msg = mHandler.obtainMessage(INIT_COPY); 12976 final int installReason = fixUpInstallReason(installerPackageName, installerUid, 12977 sessionParams.installReason); 12978 final InstallParams params = new InstallParams(origin, null, observer, 12979 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 12980 verificationInfo, user, sessionParams.abiOverride, 12981 sessionParams.grantedRuntimePermissions, certificates, installReason); 12982 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 12983 msg.obj = params; 12984 12985 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 12986 System.identityHashCode(msg.obj)); 12987 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 12988 System.identityHashCode(msg.obj)); 12989 12990 mHandler.sendMessage(msg); 12991 } 12992 12993 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 12994 int userId) { 12995 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 12996 sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId); 12997 } 12998 12999 private void sendPackageAddedForNewUsers(String packageName, boolean isSystem, 13000 int appId, int... userIds) { 13001 if (ArrayUtils.isEmpty(userIds)) { 13002 return; 13003 } 13004 Bundle extras = new Bundle(1); 13005 // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast 13006 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId)); 13007 13008 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 13009 packageName, extras, 0, null, null, userIds); 13010 if (isSystem) { 13011 mHandler.post(() -> { 13012 for (int userId : userIds) { 13013 sendBootCompletedBroadcastToSystemApp(packageName, userId); 13014 } 13015 } 13016 ); 13017 } 13018 } 13019 13020 /** 13021 * The just-installed/enabled app is bundled on the system, so presumed to be able to run 13022 * automatically without needing an explicit launch. 13023 * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones. 13024 */ 13025 private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) { 13026 // If user is not running, the app didn't miss any broadcast 13027 if (!mUserManagerInternal.isUserRunning(userId)) { 13028 return; 13029 } 13030 final IActivityManager am = ActivityManager.getService(); 13031 try { 13032 // Deliver LOCKED_BOOT_COMPLETED first 13033 Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED) 13034 .setPackage(packageName); 13035 final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED}; 13036 am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions, 13037 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 13038 13039 // Deliver BOOT_COMPLETED only if user is unlocked 13040 if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) { 13041 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName); 13042 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions, 13043 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 13044 } 13045 } catch (RemoteException e) { 13046 throw e.rethrowFromSystemServer(); 13047 } 13048 } 13049 13050 @Override 13051 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 13052 int userId) { 13053 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13054 PackageSetting pkgSetting; 13055 final int uid = Binder.getCallingUid(); 13056 enforceCrossUserPermission(uid, userId, 13057 true /* requireFullPermission */, true /* checkShell */, 13058 "setApplicationHiddenSetting for user " + userId); 13059 13060 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 13061 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 13062 return false; 13063 } 13064 13065 long callingId = Binder.clearCallingIdentity(); 13066 try { 13067 boolean sendAdded = false; 13068 boolean sendRemoved = false; 13069 // writer 13070 synchronized (mPackages) { 13071 pkgSetting = mSettings.mPackages.get(packageName); 13072 if (pkgSetting == null) { 13073 return false; 13074 } 13075 // Do not allow "android" is being disabled 13076 if ("android".equals(packageName)) { 13077 Slog.w(TAG, "Cannot hide package: android"); 13078 return false; 13079 } 13080 // Cannot hide static shared libs as they are considered 13081 // a part of the using app (emulating static linking). Also 13082 // static libs are installed always on internal storage. 13083 PackageParser.Package pkg = mPackages.get(packageName); 13084 if (pkg != null && pkg.staticSharedLibName != null) { 13085 Slog.w(TAG, "Cannot hide package: " + packageName 13086 + " providing static shared library: " 13087 + pkg.staticSharedLibName); 13088 return false; 13089 } 13090 // Only allow protected packages to hide themselves. 13091 if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId) 13092 && mProtectedPackages.isPackageStateProtected(userId, packageName)) { 13093 Slog.w(TAG, "Not hiding protected package: " + packageName); 13094 return false; 13095 } 13096 13097 if (pkgSetting.getHidden(userId) != hidden) { 13098 pkgSetting.setHidden(hidden, userId); 13099 mSettings.writePackageRestrictionsLPr(userId); 13100 if (hidden) { 13101 sendRemoved = true; 13102 } else { 13103 sendAdded = true; 13104 } 13105 } 13106 } 13107 if (sendAdded) { 13108 sendPackageAddedForUser(packageName, pkgSetting, userId); 13109 return true; 13110 } 13111 if (sendRemoved) { 13112 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 13113 "hiding pkg"); 13114 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 13115 return true; 13116 } 13117 } finally { 13118 Binder.restoreCallingIdentity(callingId); 13119 } 13120 return false; 13121 } 13122 13123 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 13124 int userId) { 13125 final PackageRemovedInfo info = new PackageRemovedInfo(); 13126 info.removedPackage = packageName; 13127 info.removedUsers = new int[] {userId}; 13128 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 13129 info.sendPackageRemovedBroadcasts(true /*killApp*/); 13130 } 13131 13132 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 13133 if (pkgList.length > 0) { 13134 Bundle extras = new Bundle(1); 13135 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 13136 13137 sendPackageBroadcast( 13138 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 13139 : Intent.ACTION_PACKAGES_UNSUSPENDED, 13140 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 13141 new int[] {userId}); 13142 } 13143 } 13144 13145 /** 13146 * Returns true if application is not found or there was an error. Otherwise it returns 13147 * the hidden state of the package for the given user. 13148 */ 13149 @Override 13150 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 13151 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13152 enforceCrossUserPermission(Binder.getCallingUid(), userId, 13153 true /* requireFullPermission */, false /* checkShell */, 13154 "getApplicationHidden for user " + userId); 13155 PackageSetting pkgSetting; 13156 long callingId = Binder.clearCallingIdentity(); 13157 try { 13158 // writer 13159 synchronized (mPackages) { 13160 pkgSetting = mSettings.mPackages.get(packageName); 13161 if (pkgSetting == null) { 13162 return true; 13163 } 13164 return pkgSetting.getHidden(userId); 13165 } 13166 } finally { 13167 Binder.restoreCallingIdentity(callingId); 13168 } 13169 } 13170 13171 /** 13172 * @hide 13173 */ 13174 @Override 13175 public int installExistingPackageAsUser(String packageName, int userId, int installReason) { 13176 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 13177 null); 13178 PackageSetting pkgSetting; 13179 final int uid = Binder.getCallingUid(); 13180 enforceCrossUserPermission(uid, userId, 13181 true /* requireFullPermission */, true /* checkShell */, 13182 "installExistingPackage for user " + userId); 13183 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 13184 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 13185 } 13186 13187 long callingId = Binder.clearCallingIdentity(); 13188 try { 13189 boolean installed = false; 13190 13191 // writer 13192 synchronized (mPackages) { 13193 pkgSetting = mSettings.mPackages.get(packageName); 13194 if (pkgSetting == null) { 13195 return PackageManager.INSTALL_FAILED_INVALID_URI; 13196 } 13197 if (!pkgSetting.getInstalled(userId)) { 13198 pkgSetting.setInstalled(true, userId); 13199 pkgSetting.setHidden(false, userId); 13200 pkgSetting.setInstallReason(installReason, userId); 13201 mSettings.writePackageRestrictionsLPr(userId); 13202 installed = true; 13203 } 13204 } 13205 13206 if (installed) { 13207 if (pkgSetting.pkg != null) { 13208 synchronized (mInstallLock) { 13209 // We don't need to freeze for a brand new install 13210 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 13211 } 13212 } 13213 sendPackageAddedForUser(packageName, pkgSetting, userId); 13214 } 13215 } finally { 13216 Binder.restoreCallingIdentity(callingId); 13217 } 13218 13219 return PackageManager.INSTALL_SUCCEEDED; 13220 } 13221 13222 boolean isUserRestricted(int userId, String restrictionKey) { 13223 Bundle restrictions = sUserManager.getUserRestrictions(userId); 13224 if (restrictions.getBoolean(restrictionKey, false)) { 13225 Log.w(TAG, "User is restricted: " + restrictionKey); 13226 return true; 13227 } 13228 return false; 13229 } 13230 13231 @Override 13232 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 13233 int userId) { 13234 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13235 enforceCrossUserPermission(Binder.getCallingUid(), userId, 13236 true /* requireFullPermission */, true /* checkShell */, 13237 "setPackagesSuspended for user " + userId); 13238 13239 if (ArrayUtils.isEmpty(packageNames)) { 13240 return packageNames; 13241 } 13242 13243 // List of package names for whom the suspended state has changed. 13244 List<String> changedPackages = new ArrayList<>(packageNames.length); 13245 // List of package names for whom the suspended state is not set as requested in this 13246 // method. 13247 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 13248 long callingId = Binder.clearCallingIdentity(); 13249 try { 13250 for (int i = 0; i < packageNames.length; i++) { 13251 String packageName = packageNames[i]; 13252 boolean changed = false; 13253 final int appId; 13254 synchronized (mPackages) { 13255 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 13256 if (pkgSetting == null) { 13257 Slog.w(TAG, "Could not find package setting for package \"" + packageName 13258 + "\". Skipping suspending/un-suspending."); 13259 unactionedPackages.add(packageName); 13260 continue; 13261 } 13262 appId = pkgSetting.appId; 13263 if (pkgSetting.getSuspended(userId) != suspended) { 13264 if (!canSuspendPackageForUserLocked(packageName, userId)) { 13265 unactionedPackages.add(packageName); 13266 continue; 13267 } 13268 pkgSetting.setSuspended(suspended, userId); 13269 mSettings.writePackageRestrictionsLPr(userId); 13270 changed = true; 13271 changedPackages.add(packageName); 13272 } 13273 } 13274 13275 if (changed && suspended) { 13276 killApplication(packageName, UserHandle.getUid(userId, appId), 13277 "suspending package"); 13278 } 13279 } 13280 } finally { 13281 Binder.restoreCallingIdentity(callingId); 13282 } 13283 13284 if (!changedPackages.isEmpty()) { 13285 sendPackagesSuspendedForUser(changedPackages.toArray( 13286 new String[changedPackages.size()]), userId, suspended); 13287 } 13288 13289 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 13290 } 13291 13292 @Override 13293 public boolean isPackageSuspendedForUser(String packageName, int userId) { 13294 enforceCrossUserPermission(Binder.getCallingUid(), userId, 13295 true /* requireFullPermission */, false /* checkShell */, 13296 "isPackageSuspendedForUser for user " + userId); 13297 synchronized (mPackages) { 13298 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 13299 if (pkgSetting == null) { 13300 throw new IllegalArgumentException("Unknown target package: " + packageName); 13301 } 13302 return pkgSetting.getSuspended(userId); 13303 } 13304 } 13305 13306 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 13307 if (isPackageDeviceAdmin(packageName, userId)) { 13308 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13309 + "\": has an active device admin"); 13310 return false; 13311 } 13312 13313 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 13314 if (packageName.equals(activeLauncherPackageName)) { 13315 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13316 + "\": contains the active launcher"); 13317 return false; 13318 } 13319 13320 if (packageName.equals(mRequiredInstallerPackage)) { 13321 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13322 + "\": required for package installation"); 13323 return false; 13324 } 13325 13326 if (packageName.equals(mRequiredUninstallerPackage)) { 13327 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13328 + "\": required for package uninstallation"); 13329 return false; 13330 } 13331 13332 if (packageName.equals(mRequiredVerifierPackage)) { 13333 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13334 + "\": required for package verification"); 13335 return false; 13336 } 13337 13338 if (packageName.equals(getDefaultDialerPackageName(userId))) { 13339 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13340 + "\": is the default dialer"); 13341 return false; 13342 } 13343 13344 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 13345 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13346 + "\": protected package"); 13347 return false; 13348 } 13349 13350 // Cannot suspend static shared libs as they are considered 13351 // a part of the using app (emulating static linking). Also 13352 // static libs are installed always on internal storage. 13353 PackageParser.Package pkg = mPackages.get(packageName); 13354 if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) { 13355 Slog.w(TAG, "Cannot suspend package: " + packageName 13356 + " providing static shared library: " 13357 + pkg.staticSharedLibName); 13358 return false; 13359 } 13360 13361 return true; 13362 } 13363 13364 private String getActiveLauncherPackageName(int userId) { 13365 Intent intent = new Intent(Intent.ACTION_MAIN); 13366 intent.addCategory(Intent.CATEGORY_HOME); 13367 ResolveInfo resolveInfo = resolveIntent( 13368 intent, 13369 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 13370 PackageManager.MATCH_DEFAULT_ONLY, 13371 userId); 13372 13373 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 13374 } 13375 13376 private String getDefaultDialerPackageName(int userId) { 13377 synchronized (mPackages) { 13378 return mSettings.getDefaultDialerPackageNameLPw(userId); 13379 } 13380 } 13381 13382 @Override 13383 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 13384 mContext.enforceCallingOrSelfPermission( 13385 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13386 "Only package verification agents can verify applications"); 13387 13388 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 13389 final PackageVerificationResponse response = new PackageVerificationResponse( 13390 verificationCode, Binder.getCallingUid()); 13391 msg.arg1 = id; 13392 msg.obj = response; 13393 mHandler.sendMessage(msg); 13394 } 13395 13396 @Override 13397 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 13398 long millisecondsToDelay) { 13399 mContext.enforceCallingOrSelfPermission( 13400 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13401 "Only package verification agents can extend verification timeouts"); 13402 13403 final PackageVerificationState state = mPendingVerification.get(id); 13404 final PackageVerificationResponse response = new PackageVerificationResponse( 13405 verificationCodeAtTimeout, Binder.getCallingUid()); 13406 13407 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 13408 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 13409 } 13410 if (millisecondsToDelay < 0) { 13411 millisecondsToDelay = 0; 13412 } 13413 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 13414 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 13415 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 13416 } 13417 13418 if ((state != null) && !state.timeoutExtended()) { 13419 state.extendTimeout(); 13420 13421 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 13422 msg.arg1 = id; 13423 msg.obj = response; 13424 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 13425 } 13426 } 13427 13428 private void broadcastPackageVerified(int verificationId, Uri packageUri, 13429 int verificationCode, UserHandle user) { 13430 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 13431 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 13432 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 13433 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 13434 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 13435 13436 mContext.sendBroadcastAsUser(intent, user, 13437 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 13438 } 13439 13440 private ComponentName matchComponentForVerifier(String packageName, 13441 List<ResolveInfo> receivers) { 13442 ActivityInfo targetReceiver = null; 13443 13444 final int NR = receivers.size(); 13445 for (int i = 0; i < NR; i++) { 13446 final ResolveInfo info = receivers.get(i); 13447 if (info.activityInfo == null) { 13448 continue; 13449 } 13450 13451 if (packageName.equals(info.activityInfo.packageName)) { 13452 targetReceiver = info.activityInfo; 13453 break; 13454 } 13455 } 13456 13457 if (targetReceiver == null) { 13458 return null; 13459 } 13460 13461 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 13462 } 13463 13464 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 13465 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 13466 if (pkgInfo.verifiers.length == 0) { 13467 return null; 13468 } 13469 13470 final int N = pkgInfo.verifiers.length; 13471 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 13472 for (int i = 0; i < N; i++) { 13473 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 13474 13475 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 13476 receivers); 13477 if (comp == null) { 13478 continue; 13479 } 13480 13481 final int verifierUid = getUidForVerifier(verifierInfo); 13482 if (verifierUid == -1) { 13483 continue; 13484 } 13485 13486 if (DEBUG_VERIFY) { 13487 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 13488 + " with the correct signature"); 13489 } 13490 sufficientVerifiers.add(comp); 13491 verificationState.addSufficientVerifier(verifierUid); 13492 } 13493 13494 return sufficientVerifiers; 13495 } 13496 13497 private int getUidForVerifier(VerifierInfo verifierInfo) { 13498 synchronized (mPackages) { 13499 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 13500 if (pkg == null) { 13501 return -1; 13502 } else if (pkg.mSignatures.length != 1) { 13503 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 13504 + " has more than one signature; ignoring"); 13505 return -1; 13506 } 13507 13508 /* 13509 * If the public key of the package's signature does not match 13510 * our expected public key, then this is a different package and 13511 * we should skip. 13512 */ 13513 13514 final byte[] expectedPublicKey; 13515 try { 13516 final Signature verifierSig = pkg.mSignatures[0]; 13517 final PublicKey publicKey = verifierSig.getPublicKey(); 13518 expectedPublicKey = publicKey.getEncoded(); 13519 } catch (CertificateException e) { 13520 return -1; 13521 } 13522 13523 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 13524 13525 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 13526 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 13527 + " does not have the expected public key; ignoring"); 13528 return -1; 13529 } 13530 13531 return pkg.applicationInfo.uid; 13532 } 13533 } 13534 13535 @Override 13536 public void finishPackageInstall(int token, boolean didLaunch) { 13537 enforceSystemOrRoot("Only the system is allowed to finish installs"); 13538 13539 if (DEBUG_INSTALL) { 13540 Slog.v(TAG, "BM finishing package install for " + token); 13541 } 13542 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 13543 13544 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 13545 mHandler.sendMessage(msg); 13546 } 13547 13548 /** 13549 * Get the verification agent timeout. 13550 * 13551 * @return verification timeout in milliseconds 13552 */ 13553 private long getVerificationTimeout() { 13554 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 13555 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 13556 DEFAULT_VERIFICATION_TIMEOUT); 13557 } 13558 13559 /** 13560 * Get the default verification agent response code. 13561 * 13562 * @return default verification response code 13563 */ 13564 private int getDefaultVerificationResponse() { 13565 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13566 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 13567 DEFAULT_VERIFICATION_RESPONSE); 13568 } 13569 13570 /** 13571 * Check whether or not package verification has been enabled. 13572 * 13573 * @return true if verification should be performed 13574 */ 13575 private boolean isVerificationEnabled(int userId, int installFlags) { 13576 if (!DEFAULT_VERIFY_ENABLE) { 13577 return false; 13578 } 13579 // Ephemeral apps don't get the full verification treatment 13580 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 13581 if (DEBUG_EPHEMERAL) { 13582 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 13583 } 13584 return false; 13585 } 13586 13587 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 13588 13589 // Check if installing from ADB 13590 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 13591 // Do not run verification in a test harness environment 13592 if (ActivityManager.isRunningInTestHarness()) { 13593 return false; 13594 } 13595 if (ensureVerifyAppsEnabled) { 13596 return true; 13597 } 13598 // Check if the developer does not want package verification for ADB installs 13599 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13600 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 13601 return false; 13602 } 13603 } 13604 13605 if (ensureVerifyAppsEnabled) { 13606 return true; 13607 } 13608 13609 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13610 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 13611 } 13612 13613 @Override 13614 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 13615 throws RemoteException { 13616 mContext.enforceCallingOrSelfPermission( 13617 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 13618 "Only intentfilter verification agents can verify applications"); 13619 13620 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 13621 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 13622 Binder.getCallingUid(), verificationCode, failedDomains); 13623 msg.arg1 = id; 13624 msg.obj = response; 13625 mHandler.sendMessage(msg); 13626 } 13627 13628 @Override 13629 public int getIntentVerificationStatus(String packageName, int userId) { 13630 synchronized (mPackages) { 13631 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 13632 } 13633 } 13634 13635 @Override 13636 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 13637 mContext.enforceCallingOrSelfPermission( 13638 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13639 13640 boolean result = false; 13641 synchronized (mPackages) { 13642 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 13643 } 13644 if (result) { 13645 scheduleWritePackageRestrictionsLocked(userId); 13646 } 13647 return result; 13648 } 13649 13650 @Override 13651 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 13652 String packageName) { 13653 synchronized (mPackages) { 13654 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 13655 } 13656 } 13657 13658 @Override 13659 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 13660 if (TextUtils.isEmpty(packageName)) { 13661 return ParceledListSlice.emptyList(); 13662 } 13663 synchronized (mPackages) { 13664 PackageParser.Package pkg = mPackages.get(packageName); 13665 if (pkg == null || pkg.activities == null) { 13666 return ParceledListSlice.emptyList(); 13667 } 13668 final int count = pkg.activities.size(); 13669 ArrayList<IntentFilter> result = new ArrayList<>(); 13670 for (int n=0; n<count; n++) { 13671 PackageParser.Activity activity = pkg.activities.get(n); 13672 if (activity.intents != null && activity.intents.size() > 0) { 13673 result.addAll(activity.intents); 13674 } 13675 } 13676 return new ParceledListSlice<>(result); 13677 } 13678 } 13679 13680 @Override 13681 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 13682 mContext.enforceCallingOrSelfPermission( 13683 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13684 13685 synchronized (mPackages) { 13686 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 13687 if (packageName != null) { 13688 result |= updateIntentVerificationStatus(packageName, 13689 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 13690 userId); 13691 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 13692 packageName, userId); 13693 } 13694 return result; 13695 } 13696 } 13697 13698 @Override 13699 public String getDefaultBrowserPackageName(int userId) { 13700 synchronized (mPackages) { 13701 return mSettings.getDefaultBrowserPackageNameLPw(userId); 13702 } 13703 } 13704 13705 /** 13706 * Get the "allow unknown sources" setting. 13707 * 13708 * @return the current "allow unknown sources" setting 13709 */ 13710 private int getUnknownSourcesSettings() { 13711 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 13712 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 13713 -1); 13714 } 13715 13716 @Override 13717 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 13718 final int uid = Binder.getCallingUid(); 13719 // writer 13720 synchronized (mPackages) { 13721 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 13722 if (targetPackageSetting == null) { 13723 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 13724 } 13725 13726 PackageSetting installerPackageSetting; 13727 if (installerPackageName != null) { 13728 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 13729 if (installerPackageSetting == null) { 13730 throw new IllegalArgumentException("Unknown installer package: " 13731 + installerPackageName); 13732 } 13733 } else { 13734 installerPackageSetting = null; 13735 } 13736 13737 Signature[] callerSignature; 13738 Object obj = mSettings.getUserIdLPr(uid); 13739 if (obj != null) { 13740 if (obj instanceof SharedUserSetting) { 13741 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 13742 } else if (obj instanceof PackageSetting) { 13743 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 13744 } else { 13745 throw new SecurityException("Bad object " + obj + " for uid " + uid); 13746 } 13747 } else { 13748 throw new SecurityException("Unknown calling UID: " + uid); 13749 } 13750 13751 // Verify: can't set installerPackageName to a package that is 13752 // not signed with the same cert as the caller. 13753 if (installerPackageSetting != null) { 13754 if (compareSignatures(callerSignature, 13755 installerPackageSetting.signatures.mSignatures) 13756 != PackageManager.SIGNATURE_MATCH) { 13757 throw new SecurityException( 13758 "Caller does not have same cert as new installer package " 13759 + installerPackageName); 13760 } 13761 } 13762 13763 // Verify: if target already has an installer package, it must 13764 // be signed with the same cert as the caller. 13765 if (targetPackageSetting.installerPackageName != null) { 13766 PackageSetting setting = mSettings.mPackages.get( 13767 targetPackageSetting.installerPackageName); 13768 // If the currently set package isn't valid, then it's always 13769 // okay to change it. 13770 if (setting != null) { 13771 if (compareSignatures(callerSignature, 13772 setting.signatures.mSignatures) 13773 != PackageManager.SIGNATURE_MATCH) { 13774 throw new SecurityException( 13775 "Caller does not have same cert as old installer package " 13776 + targetPackageSetting.installerPackageName); 13777 } 13778 } 13779 } 13780 13781 // Okay! 13782 targetPackageSetting.installerPackageName = installerPackageName; 13783 if (installerPackageName != null) { 13784 mSettings.mInstallerPackages.add(installerPackageName); 13785 } 13786 scheduleWriteSettingsLocked(); 13787 } 13788 } 13789 13790 @Override 13791 public void setApplicationCategoryHint(String packageName, int categoryHint, 13792 String callerPackageName) { 13793 mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(), 13794 callerPackageName); 13795 synchronized (mPackages) { 13796 PackageSetting ps = mSettings.mPackages.get(packageName); 13797 if (ps == null) { 13798 throw new IllegalArgumentException("Unknown target package " + packageName); 13799 } 13800 13801 if (!Objects.equals(callerPackageName, ps.installerPackageName)) { 13802 throw new IllegalArgumentException("Calling package " + callerPackageName 13803 + " is not installer for " + packageName); 13804 } 13805 13806 if (ps.categoryHint != categoryHint) { 13807 ps.categoryHint = categoryHint; 13808 scheduleWriteSettingsLocked(); 13809 } 13810 } 13811 } 13812 13813 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 13814 // Queue up an async operation since the package installation may take a little while. 13815 mHandler.post(new Runnable() { 13816 public void run() { 13817 mHandler.removeCallbacks(this); 13818 // Result object to be returned 13819 PackageInstalledInfo res = new PackageInstalledInfo(); 13820 res.setReturnCode(currentStatus); 13821 res.uid = -1; 13822 res.pkg = null; 13823 res.removedInfo = null; 13824 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13825 args.doPreInstall(res.returnCode); 13826 synchronized (mInstallLock) { 13827 installPackageTracedLI(args, res); 13828 } 13829 args.doPostInstall(res.returnCode, res.uid); 13830 } 13831 13832 // A restore should be performed at this point if (a) the install 13833 // succeeded, (b) the operation is not an update, and (c) the new 13834 // package has not opted out of backup participation. 13835 final boolean update = res.removedInfo != null 13836 && res.removedInfo.removedPackage != null; 13837 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 13838 boolean doRestore = !update 13839 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 13840 13841 // Set up the post-install work request bookkeeping. This will be used 13842 // and cleaned up by the post-install event handling regardless of whether 13843 // there's a restore pass performed. Token values are >= 1. 13844 int token; 13845 if (mNextInstallToken < 0) mNextInstallToken = 1; 13846 token = mNextInstallToken++; 13847 13848 PostInstallData data = new PostInstallData(args, res); 13849 mRunningInstalls.put(token, data); 13850 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 13851 13852 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 13853 // Pass responsibility to the Backup Manager. It will perform a 13854 // restore if appropriate, then pass responsibility back to the 13855 // Package Manager to run the post-install observer callbacks 13856 // and broadcasts. 13857 IBackupManager bm = IBackupManager.Stub.asInterface( 13858 ServiceManager.getService(Context.BACKUP_SERVICE)); 13859 if (bm != null) { 13860 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 13861 + " to BM for possible restore"); 13862 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 13863 try { 13864 // TODO: http://b/22388012 13865 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 13866 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 13867 } else { 13868 doRestore = false; 13869 } 13870 } catch (RemoteException e) { 13871 // can't happen; the backup manager is local 13872 } catch (Exception e) { 13873 Slog.e(TAG, "Exception trying to enqueue restore", e); 13874 doRestore = false; 13875 } 13876 } else { 13877 Slog.e(TAG, "Backup Manager not found!"); 13878 doRestore = false; 13879 } 13880 } 13881 13882 if (!doRestore) { 13883 // No restore possible, or the Backup Manager was mysteriously not 13884 // available -- just fire the post-install work request directly. 13885 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 13886 13887 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 13888 13889 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 13890 mHandler.sendMessage(msg); 13891 } 13892 } 13893 }); 13894 } 13895 13896 /** 13897 * Callback from PackageSettings whenever an app is first transitioned out of the 13898 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 13899 * the app was "launched" for a restoreAtInstall operation. Therefore we check 13900 * here whether the app is the target of an ongoing install, and only send the 13901 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 13902 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 13903 * handling. 13904 */ 13905 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 13906 // Serialize this with the rest of the install-process message chain. In the 13907 // restore-at-install case, this Runnable will necessarily run before the 13908 // POST_INSTALL message is processed, so the contents of mRunningInstalls 13909 // are coherent. In the non-restore case, the app has already completed install 13910 // and been launched through some other means, so it is not in a problematic 13911 // state for observers to see the FIRST_LAUNCH signal. 13912 mHandler.post(new Runnable() { 13913 @Override 13914 public void run() { 13915 for (int i = 0; i < mRunningInstalls.size(); i++) { 13916 final PostInstallData data = mRunningInstalls.valueAt(i); 13917 if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 13918 continue; 13919 } 13920 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 13921 // right package; but is it for the right user? 13922 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 13923 if (userId == data.res.newUsers[uIndex]) { 13924 if (DEBUG_BACKUP) { 13925 Slog.i(TAG, "Package " + pkgName 13926 + " being restored so deferring FIRST_LAUNCH"); 13927 } 13928 return; 13929 } 13930 } 13931 } 13932 } 13933 // didn't find it, so not being restored 13934 if (DEBUG_BACKUP) { 13935 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 13936 } 13937 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 13938 } 13939 }); 13940 } 13941 13942 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 13943 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 13944 installerPkg, null, userIds); 13945 } 13946 13947 private abstract class HandlerParams { 13948 private static final int MAX_RETRIES = 4; 13949 13950 /** 13951 * Number of times startCopy() has been attempted and had a non-fatal 13952 * error. 13953 */ 13954 private int mRetries = 0; 13955 13956 /** User handle for the user requesting the information or installation. */ 13957 private final UserHandle mUser; 13958 String traceMethod; 13959 int traceCookie; 13960 13961 HandlerParams(UserHandle user) { 13962 mUser = user; 13963 } 13964 13965 UserHandle getUser() { 13966 return mUser; 13967 } 13968 13969 HandlerParams setTraceMethod(String traceMethod) { 13970 this.traceMethod = traceMethod; 13971 return this; 13972 } 13973 13974 HandlerParams setTraceCookie(int traceCookie) { 13975 this.traceCookie = traceCookie; 13976 return this; 13977 } 13978 13979 final boolean startCopy() { 13980 boolean res; 13981 try { 13982 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 13983 13984 if (++mRetries > MAX_RETRIES) { 13985 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 13986 mHandler.sendEmptyMessage(MCS_GIVE_UP); 13987 handleServiceError(); 13988 return false; 13989 } else { 13990 handleStartCopy(); 13991 res = true; 13992 } 13993 } catch (RemoteException e) { 13994 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 13995 mHandler.sendEmptyMessage(MCS_RECONNECT); 13996 res = false; 13997 } 13998 handleReturnCode(); 13999 return res; 14000 } 14001 14002 final void serviceError() { 14003 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 14004 handleServiceError(); 14005 handleReturnCode(); 14006 } 14007 14008 abstract void handleStartCopy() throws RemoteException; 14009 abstract void handleServiceError(); 14010 abstract void handleReturnCode(); 14011 } 14012 14013 class MeasureParams extends HandlerParams { 14014 private final PackageStats mStats; 14015 private boolean mSuccess; 14016 14017 private final IPackageStatsObserver mObserver; 14018 14019 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 14020 super(new UserHandle(stats.userHandle)); 14021 mObserver = observer; 14022 mStats = stats; 14023 } 14024 14025 @Override 14026 public String toString() { 14027 return "MeasureParams{" 14028 + Integer.toHexString(System.identityHashCode(this)) 14029 + " " + mStats.packageName + "}"; 14030 } 14031 14032 @Override 14033 void handleStartCopy() throws RemoteException { 14034 synchronized (mInstallLock) { 14035 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 14036 } 14037 14038 if (mSuccess) { 14039 boolean mounted = false; 14040 try { 14041 final String status = Environment.getExternalStorageState(); 14042 mounted = (Environment.MEDIA_MOUNTED.equals(status) 14043 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 14044 } catch (Exception e) { 14045 } 14046 14047 if (mounted) { 14048 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 14049 14050 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 14051 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 14052 14053 mStats.externalDataSize = calculateDirectorySize(mContainerService, 14054 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 14055 14056 // Always subtract cache size, since it's a subdirectory 14057 mStats.externalDataSize -= mStats.externalCacheSize; 14058 14059 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 14060 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 14061 14062 mStats.externalObbSize = calculateDirectorySize(mContainerService, 14063 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 14064 } 14065 } 14066 } 14067 14068 @Override 14069 void handleReturnCode() { 14070 if (mObserver != null) { 14071 try { 14072 mObserver.onGetStatsCompleted(mStats, mSuccess); 14073 } catch (RemoteException e) { 14074 Slog.i(TAG, "Observer no longer exists."); 14075 } 14076 } 14077 } 14078 14079 @Override 14080 void handleServiceError() { 14081 Slog.e(TAG, "Could not measure application " + mStats.packageName 14082 + " external storage"); 14083 } 14084 } 14085 14086 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 14087 throws RemoteException { 14088 long result = 0; 14089 for (File path : paths) { 14090 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 14091 } 14092 return result; 14093 } 14094 14095 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 14096 for (File path : paths) { 14097 try { 14098 mcs.clearDirectory(path.getAbsolutePath()); 14099 } catch (RemoteException e) { 14100 } 14101 } 14102 } 14103 14104 static class OriginInfo { 14105 /** 14106 * Location where install is coming from, before it has been 14107 * copied/renamed into place. This could be a single monolithic APK 14108 * file, or a cluster directory. This location may be untrusted. 14109 */ 14110 final File file; 14111 final String cid; 14112 14113 /** 14114 * Flag indicating that {@link #file} or {@link #cid} has already been 14115 * staged, meaning downstream users don't need to defensively copy the 14116 * contents. 14117 */ 14118 final boolean staged; 14119 14120 /** 14121 * Flag indicating that {@link #file} or {@link #cid} is an already 14122 * installed app that is being moved. 14123 */ 14124 final boolean existing; 14125 14126 final String resolvedPath; 14127 final File resolvedFile; 14128 14129 static OriginInfo fromNothing() { 14130 return new OriginInfo(null, null, false, false); 14131 } 14132 14133 static OriginInfo fromUntrustedFile(File file) { 14134 return new OriginInfo(file, null, false, false); 14135 } 14136 14137 static OriginInfo fromExistingFile(File file) { 14138 return new OriginInfo(file, null, false, true); 14139 } 14140 14141 static OriginInfo fromStagedFile(File file) { 14142 return new OriginInfo(file, null, true, false); 14143 } 14144 14145 static OriginInfo fromStagedContainer(String cid) { 14146 return new OriginInfo(null, cid, true, false); 14147 } 14148 14149 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 14150 this.file = file; 14151 this.cid = cid; 14152 this.staged = staged; 14153 this.existing = existing; 14154 14155 if (cid != null) { 14156 resolvedPath = PackageHelper.getSdDir(cid); 14157 resolvedFile = new File(resolvedPath); 14158 } else if (file != null) { 14159 resolvedPath = file.getAbsolutePath(); 14160 resolvedFile = file; 14161 } else { 14162 resolvedPath = null; 14163 resolvedFile = null; 14164 } 14165 } 14166 } 14167 14168 static class MoveInfo { 14169 final int moveId; 14170 final String fromUuid; 14171 final String toUuid; 14172 final String packageName; 14173 final String dataAppName; 14174 final int appId; 14175 final String seinfo; 14176 final int targetSdkVersion; 14177 14178 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 14179 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 14180 this.moveId = moveId; 14181 this.fromUuid = fromUuid; 14182 this.toUuid = toUuid; 14183 this.packageName = packageName; 14184 this.dataAppName = dataAppName; 14185 this.appId = appId; 14186 this.seinfo = seinfo; 14187 this.targetSdkVersion = targetSdkVersion; 14188 } 14189 } 14190 14191 static class VerificationInfo { 14192 /** A constant used to indicate that a uid value is not present. */ 14193 public static final int NO_UID = -1; 14194 14195 /** URI referencing where the package was downloaded from. */ 14196 final Uri originatingUri; 14197 14198 /** HTTP referrer URI associated with the originatingURI. */ 14199 final Uri referrer; 14200 14201 /** UID of the application that the install request originated from. */ 14202 final int originatingUid; 14203 14204 /** UID of application requesting the install */ 14205 final int installerUid; 14206 14207 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 14208 this.originatingUri = originatingUri; 14209 this.referrer = referrer; 14210 this.originatingUid = originatingUid; 14211 this.installerUid = installerUid; 14212 } 14213 } 14214 14215 class InstallParams extends HandlerParams { 14216 final OriginInfo origin; 14217 final MoveInfo move; 14218 final IPackageInstallObserver2 observer; 14219 int installFlags; 14220 final String installerPackageName; 14221 final String volumeUuid; 14222 private InstallArgs mArgs; 14223 private int mRet; 14224 final String packageAbiOverride; 14225 final String[] grantedRuntimePermissions; 14226 final VerificationInfo verificationInfo; 14227 final Certificate[][] certificates; 14228 final int installReason; 14229 14230 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 14231 int installFlags, String installerPackageName, String volumeUuid, 14232 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 14233 String[] grantedPermissions, Certificate[][] certificates, int installReason) { 14234 super(user); 14235 this.origin = origin; 14236 this.move = move; 14237 this.observer = observer; 14238 this.installFlags = installFlags; 14239 this.installerPackageName = installerPackageName; 14240 this.volumeUuid = volumeUuid; 14241 this.verificationInfo = verificationInfo; 14242 this.packageAbiOverride = packageAbiOverride; 14243 this.grantedRuntimePermissions = grantedPermissions; 14244 this.certificates = certificates; 14245 this.installReason = installReason; 14246 } 14247 14248 @Override 14249 public String toString() { 14250 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 14251 + " file=" + origin.file + " cid=" + origin.cid + "}"; 14252 } 14253 14254 private int installLocationPolicy(PackageInfoLite pkgLite) { 14255 String packageName = pkgLite.packageName; 14256 int installLocation = pkgLite.installLocation; 14257 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14258 // reader 14259 synchronized (mPackages) { 14260 // Currently installed package which the new package is attempting to replace or 14261 // null if no such package is installed. 14262 PackageParser.Package installedPkg = mPackages.get(packageName); 14263 // Package which currently owns the data which the new package will own if installed. 14264 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 14265 // will be null whereas dataOwnerPkg will contain information about the package 14266 // which was uninstalled while keeping its data. 14267 PackageParser.Package dataOwnerPkg = installedPkg; 14268 if (dataOwnerPkg == null) { 14269 PackageSetting ps = mSettings.mPackages.get(packageName); 14270 if (ps != null) { 14271 dataOwnerPkg = ps.pkg; 14272 } 14273 } 14274 14275 if (dataOwnerPkg != null) { 14276 // If installed, the package will get access to data left on the device by its 14277 // predecessor. As a security measure, this is permited only if this is not a 14278 // version downgrade or if the predecessor package is marked as debuggable and 14279 // a downgrade is explicitly requested. 14280 // 14281 // On debuggable platform builds, downgrades are permitted even for 14282 // non-debuggable packages to make testing easier. Debuggable platform builds do 14283 // not offer security guarantees and thus it's OK to disable some security 14284 // mechanisms to make debugging/testing easier on those builds. However, even on 14285 // debuggable builds downgrades of packages are permitted only if requested via 14286 // installFlags. This is because we aim to keep the behavior of debuggable 14287 // platform builds as close as possible to the behavior of non-debuggable 14288 // platform builds. 14289 final boolean downgradeRequested = 14290 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 14291 final boolean packageDebuggable = 14292 (dataOwnerPkg.applicationInfo.flags 14293 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 14294 final boolean downgradePermitted = 14295 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 14296 if (!downgradePermitted) { 14297 try { 14298 checkDowngrade(dataOwnerPkg, pkgLite); 14299 } catch (PackageManagerException e) { 14300 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 14301 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 14302 } 14303 } 14304 } 14305 14306 if (installedPkg != null) { 14307 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14308 // Check for updated system application. 14309 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 14310 if (onSd) { 14311 Slog.w(TAG, "Cannot install update to system app on sdcard"); 14312 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 14313 } 14314 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14315 } else { 14316 if (onSd) { 14317 // Install flag overrides everything. 14318 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14319 } 14320 // If current upgrade specifies particular preference 14321 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 14322 // Application explicitly specified internal. 14323 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14324 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 14325 // App explictly prefers external. Let policy decide 14326 } else { 14327 // Prefer previous location 14328 if (isExternal(installedPkg)) { 14329 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14330 } 14331 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14332 } 14333 } 14334 } else { 14335 // Invalid install. Return error code 14336 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 14337 } 14338 } 14339 } 14340 // All the special cases have been taken care of. 14341 // Return result based on recommended install location. 14342 if (onSd) { 14343 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14344 } 14345 return pkgLite.recommendedInstallLocation; 14346 } 14347 14348 /* 14349 * Invoke remote method to get package information and install 14350 * location values. Override install location based on default 14351 * policy if needed and then create install arguments based 14352 * on the install location. 14353 */ 14354 public void handleStartCopy() throws RemoteException { 14355 int ret = PackageManager.INSTALL_SUCCEEDED; 14356 14357 // If we're already staged, we've firmly committed to an install location 14358 if (origin.staged) { 14359 if (origin.file != null) { 14360 installFlags |= PackageManager.INSTALL_INTERNAL; 14361 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 14362 } else if (origin.cid != null) { 14363 installFlags |= PackageManager.INSTALL_EXTERNAL; 14364 installFlags &= ~PackageManager.INSTALL_INTERNAL; 14365 } else { 14366 throw new IllegalStateException("Invalid stage location"); 14367 } 14368 } 14369 14370 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14371 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 14372 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 14373 PackageInfoLite pkgLite = null; 14374 14375 if (onInt && onSd) { 14376 // Check if both bits are set. 14377 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 14378 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14379 } else if (onSd && ephemeral) { 14380 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 14381 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14382 } else { 14383 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 14384 packageAbiOverride); 14385 14386 if (DEBUG_EPHEMERAL && ephemeral) { 14387 Slog.v(TAG, "pkgLite for install: " + pkgLite); 14388 } 14389 14390 /* 14391 * If we have too little free space, try to free cache 14392 * before giving up. 14393 */ 14394 if (!origin.staged && pkgLite.recommendedInstallLocation 14395 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 14396 // TODO: focus freeing disk space on the target device 14397 final StorageManager storage = StorageManager.from(mContext); 14398 final long lowThreshold = storage.getStorageLowBytes( 14399 Environment.getDataDirectory()); 14400 14401 final long sizeBytes = mContainerService.calculateInstalledSize( 14402 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 14403 14404 try { 14405 mInstaller.freeCache(null, sizeBytes + lowThreshold, 0); 14406 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 14407 installFlags, packageAbiOverride); 14408 } catch (InstallerException e) { 14409 Slog.w(TAG, "Failed to free cache", e); 14410 } 14411 14412 /* 14413 * The cache free must have deleted the file we 14414 * downloaded to install. 14415 * 14416 * TODO: fix the "freeCache" call to not delete 14417 * the file we care about. 14418 */ 14419 if (pkgLite.recommendedInstallLocation 14420 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 14421 pkgLite.recommendedInstallLocation 14422 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 14423 } 14424 } 14425 } 14426 14427 if (ret == PackageManager.INSTALL_SUCCEEDED) { 14428 int loc = pkgLite.recommendedInstallLocation; 14429 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 14430 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14431 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 14432 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 14433 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 14434 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 14435 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 14436 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 14437 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 14438 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 14439 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 14440 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 14441 } else { 14442 // Override with defaults if needed. 14443 loc = installLocationPolicy(pkgLite); 14444 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 14445 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 14446 } else if (!onSd && !onInt) { 14447 // Override install location with flags 14448 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 14449 // Set the flag to install on external media. 14450 installFlags |= PackageManager.INSTALL_EXTERNAL; 14451 installFlags &= ~PackageManager.INSTALL_INTERNAL; 14452 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 14453 if (DEBUG_EPHEMERAL) { 14454 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 14455 } 14456 installFlags |= PackageManager.INSTALL_EPHEMERAL; 14457 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 14458 |PackageManager.INSTALL_INTERNAL); 14459 } else { 14460 // Make sure the flag for installing on external 14461 // media is unset 14462 installFlags |= PackageManager.INSTALL_INTERNAL; 14463 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 14464 } 14465 } 14466 } 14467 } 14468 14469 final InstallArgs args = createInstallArgs(this); 14470 mArgs = args; 14471 14472 if (ret == PackageManager.INSTALL_SUCCEEDED) { 14473 // TODO: http://b/22976637 14474 // Apps installed for "all" users use the device owner to verify the app 14475 UserHandle verifierUser = getUser(); 14476 if (verifierUser == UserHandle.ALL) { 14477 verifierUser = UserHandle.SYSTEM; 14478 } 14479 14480 /* 14481 * Determine if we have any installed package verifiers. If we 14482 * do, then we'll defer to them to verify the packages. 14483 */ 14484 final int requiredUid = mRequiredVerifierPackage == null ? -1 14485 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 14486 verifierUser.getIdentifier()); 14487 if (!origin.existing && requiredUid != -1 14488 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 14489 final Intent verification = new Intent( 14490 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 14491 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 14492 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 14493 PACKAGE_MIME_TYPE); 14494 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 14495 14496 // Query all live verifiers based on current user state 14497 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 14498 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 14499 14500 if (DEBUG_VERIFY) { 14501 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 14502 + verification.toString() + " with " + pkgLite.verifiers.length 14503 + " optional verifiers"); 14504 } 14505 14506 final int verificationId = mPendingVerificationToken++; 14507 14508 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 14509 14510 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 14511 installerPackageName); 14512 14513 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 14514 installFlags); 14515 14516 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 14517 pkgLite.packageName); 14518 14519 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 14520 pkgLite.versionCode); 14521 14522 if (verificationInfo != null) { 14523 if (verificationInfo.originatingUri != null) { 14524 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 14525 verificationInfo.originatingUri); 14526 } 14527 if (verificationInfo.referrer != null) { 14528 verification.putExtra(Intent.EXTRA_REFERRER, 14529 verificationInfo.referrer); 14530 } 14531 if (verificationInfo.originatingUid >= 0) { 14532 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 14533 verificationInfo.originatingUid); 14534 } 14535 if (verificationInfo.installerUid >= 0) { 14536 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 14537 verificationInfo.installerUid); 14538 } 14539 } 14540 14541 final PackageVerificationState verificationState = new PackageVerificationState( 14542 requiredUid, args); 14543 14544 mPendingVerification.append(verificationId, verificationState); 14545 14546 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 14547 receivers, verificationState); 14548 14549 /* 14550 * If any sufficient verifiers were listed in the package 14551 * manifest, attempt to ask them. 14552 */ 14553 if (sufficientVerifiers != null) { 14554 final int N = sufficientVerifiers.size(); 14555 if (N == 0) { 14556 Slog.i(TAG, "Additional verifiers required, but none installed."); 14557 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 14558 } else { 14559 for (int i = 0; i < N; i++) { 14560 final ComponentName verifierComponent = sufficientVerifiers.get(i); 14561 14562 final Intent sufficientIntent = new Intent(verification); 14563 sufficientIntent.setComponent(verifierComponent); 14564 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 14565 } 14566 } 14567 } 14568 14569 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 14570 mRequiredVerifierPackage, receivers); 14571 if (ret == PackageManager.INSTALL_SUCCEEDED 14572 && mRequiredVerifierPackage != null) { 14573 Trace.asyncTraceBegin( 14574 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 14575 /* 14576 * Send the intent to the required verification agent, 14577 * but only start the verification timeout after the 14578 * target BroadcastReceivers have run. 14579 */ 14580 verification.setComponent(requiredVerifierComponent); 14581 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 14582 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 14583 new BroadcastReceiver() { 14584 @Override 14585 public void onReceive(Context context, Intent intent) { 14586 final Message msg = mHandler 14587 .obtainMessage(CHECK_PENDING_VERIFICATION); 14588 msg.arg1 = verificationId; 14589 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 14590 } 14591 }, null, 0, null, null); 14592 14593 /* 14594 * We don't want the copy to proceed until verification 14595 * succeeds, so null out this field. 14596 */ 14597 mArgs = null; 14598 } 14599 } else { 14600 /* 14601 * No package verification is enabled, so immediately start 14602 * the remote call to initiate copy using temporary file. 14603 */ 14604 ret = args.copyApk(mContainerService, true); 14605 } 14606 } 14607 14608 mRet = ret; 14609 } 14610 14611 @Override 14612 void handleReturnCode() { 14613 // If mArgs is null, then MCS couldn't be reached. When it 14614 // reconnects, it will try again to install. At that point, this 14615 // will succeed. 14616 if (mArgs != null) { 14617 processPendingInstall(mArgs, mRet); 14618 } 14619 } 14620 14621 @Override 14622 void handleServiceError() { 14623 mArgs = createInstallArgs(this); 14624 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 14625 } 14626 14627 public boolean isForwardLocked() { 14628 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 14629 } 14630 } 14631 14632 /** 14633 * Used during creation of InstallArgs 14634 * 14635 * @param installFlags package installation flags 14636 * @return true if should be installed on external storage 14637 */ 14638 private static boolean installOnExternalAsec(int installFlags) { 14639 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 14640 return false; 14641 } 14642 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 14643 return true; 14644 } 14645 return false; 14646 } 14647 14648 /** 14649 * Used during creation of InstallArgs 14650 * 14651 * @param installFlags package installation flags 14652 * @return true if should be installed as forward locked 14653 */ 14654 private static boolean installForwardLocked(int installFlags) { 14655 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 14656 } 14657 14658 private InstallArgs createInstallArgs(InstallParams params) { 14659 if (params.move != null) { 14660 return new MoveInstallArgs(params); 14661 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 14662 return new AsecInstallArgs(params); 14663 } else { 14664 return new FileInstallArgs(params); 14665 } 14666 } 14667 14668 /** 14669 * Create args that describe an existing installed package. Typically used 14670 * when cleaning up old installs, or used as a move source. 14671 */ 14672 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 14673 String resourcePath, String[] instructionSets) { 14674 final boolean isInAsec; 14675 if (installOnExternalAsec(installFlags)) { 14676 /* Apps on SD card are always in ASEC containers. */ 14677 isInAsec = true; 14678 } else if (installForwardLocked(installFlags) 14679 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 14680 /* 14681 * Forward-locked apps are only in ASEC containers if they're the 14682 * new style 14683 */ 14684 isInAsec = true; 14685 } else { 14686 isInAsec = false; 14687 } 14688 14689 if (isInAsec) { 14690 return new AsecInstallArgs(codePath, instructionSets, 14691 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 14692 } else { 14693 return new FileInstallArgs(codePath, resourcePath, instructionSets); 14694 } 14695 } 14696 14697 static abstract class InstallArgs { 14698 /** @see InstallParams#origin */ 14699 final OriginInfo origin; 14700 /** @see InstallParams#move */ 14701 final MoveInfo move; 14702 14703 final IPackageInstallObserver2 observer; 14704 // Always refers to PackageManager flags only 14705 final int installFlags; 14706 final String installerPackageName; 14707 final String volumeUuid; 14708 final UserHandle user; 14709 final String abiOverride; 14710 final String[] installGrantPermissions; 14711 /** If non-null, drop an async trace when the install completes */ 14712 final String traceMethod; 14713 final int traceCookie; 14714 final Certificate[][] certificates; 14715 final int installReason; 14716 14717 // The list of instruction sets supported by this app. This is currently 14718 // only used during the rmdex() phase to clean up resources. We can get rid of this 14719 // if we move dex files under the common app path. 14720 /* nullable */ String[] instructionSets; 14721 14722 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 14723 int installFlags, String installerPackageName, String volumeUuid, 14724 UserHandle user, String[] instructionSets, 14725 String abiOverride, String[] installGrantPermissions, 14726 String traceMethod, int traceCookie, Certificate[][] certificates, 14727 int installReason) { 14728 this.origin = origin; 14729 this.move = move; 14730 this.installFlags = installFlags; 14731 this.observer = observer; 14732 this.installerPackageName = installerPackageName; 14733 this.volumeUuid = volumeUuid; 14734 this.user = user; 14735 this.instructionSets = instructionSets; 14736 this.abiOverride = abiOverride; 14737 this.installGrantPermissions = installGrantPermissions; 14738 this.traceMethod = traceMethod; 14739 this.traceCookie = traceCookie; 14740 this.certificates = certificates; 14741 this.installReason = installReason; 14742 } 14743 14744 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 14745 abstract int doPreInstall(int status); 14746 14747 /** 14748 * Rename package into final resting place. All paths on the given 14749 * scanned package should be updated to reflect the rename. 14750 */ 14751 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 14752 abstract int doPostInstall(int status, int uid); 14753 14754 /** @see PackageSettingBase#codePathString */ 14755 abstract String getCodePath(); 14756 /** @see PackageSettingBase#resourcePathString */ 14757 abstract String getResourcePath(); 14758 14759 // Need installer lock especially for dex file removal. 14760 abstract void cleanUpResourcesLI(); 14761 abstract boolean doPostDeleteLI(boolean delete); 14762 14763 /** 14764 * Called before the source arguments are copied. This is used mostly 14765 * for MoveParams when it needs to read the source file to put it in the 14766 * destination. 14767 */ 14768 int doPreCopy() { 14769 return PackageManager.INSTALL_SUCCEEDED; 14770 } 14771 14772 /** 14773 * Called after the source arguments are copied. This is used mostly for 14774 * MoveParams when it needs to read the source file to put it in the 14775 * destination. 14776 */ 14777 int doPostCopy(int uid) { 14778 return PackageManager.INSTALL_SUCCEEDED; 14779 } 14780 14781 protected boolean isFwdLocked() { 14782 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 14783 } 14784 14785 protected boolean isExternalAsec() { 14786 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14787 } 14788 14789 protected boolean isEphemeral() { 14790 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 14791 } 14792 14793 UserHandle getUser() { 14794 return user; 14795 } 14796 } 14797 14798 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 14799 if (!allCodePaths.isEmpty()) { 14800 if (instructionSets == null) { 14801 throw new IllegalStateException("instructionSet == null"); 14802 } 14803 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 14804 for (String codePath : allCodePaths) { 14805 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 14806 try { 14807 mInstaller.rmdex(codePath, dexCodeInstructionSet); 14808 } catch (InstallerException ignored) { 14809 } 14810 } 14811 } 14812 } 14813 } 14814 14815 /** 14816 * Logic to handle installation of non-ASEC applications, including copying 14817 * and renaming logic. 14818 */ 14819 class FileInstallArgs extends InstallArgs { 14820 private File codeFile; 14821 private File resourceFile; 14822 14823 // Example topology: 14824 // /data/app/com.example/base.apk 14825 // /data/app/com.example/split_foo.apk 14826 // /data/app/com.example/lib/arm/libfoo.so 14827 // /data/app/com.example/lib/arm64/libfoo.so 14828 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 14829 14830 /** New install */ 14831 FileInstallArgs(InstallParams params) { 14832 super(params.origin, params.move, params.observer, params.installFlags, 14833 params.installerPackageName, params.volumeUuid, 14834 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 14835 params.grantedRuntimePermissions, 14836 params.traceMethod, params.traceCookie, params.certificates, 14837 params.installReason); 14838 if (isFwdLocked()) { 14839 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 14840 } 14841 } 14842 14843 /** Existing install */ 14844 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 14845 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 14846 null, null, null, 0, null /*certificates*/, 14847 PackageManager.INSTALL_REASON_UNKNOWN); 14848 this.codeFile = (codePath != null) ? new File(codePath) : null; 14849 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 14850 } 14851 14852 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 14853 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 14854 try { 14855 return doCopyApk(imcs, temp); 14856 } finally { 14857 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14858 } 14859 } 14860 14861 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 14862 if (origin.staged) { 14863 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 14864 codeFile = origin.file; 14865 resourceFile = origin.file; 14866 return PackageManager.INSTALL_SUCCEEDED; 14867 } 14868 14869 try { 14870 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 14871 final File tempDir = 14872 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 14873 codeFile = tempDir; 14874 resourceFile = tempDir; 14875 } catch (IOException e) { 14876 Slog.w(TAG, "Failed to create copy file: " + e); 14877 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 14878 } 14879 14880 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 14881 @Override 14882 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 14883 if (!FileUtils.isValidExtFilename(name)) { 14884 throw new IllegalArgumentException("Invalid filename: " + name); 14885 } 14886 try { 14887 final File file = new File(codeFile, name); 14888 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 14889 O_RDWR | O_CREAT, 0644); 14890 Os.chmod(file.getAbsolutePath(), 0644); 14891 return new ParcelFileDescriptor(fd); 14892 } catch (ErrnoException e) { 14893 throw new RemoteException("Failed to open: " + e.getMessage()); 14894 } 14895 } 14896 }; 14897 14898 int ret = PackageManager.INSTALL_SUCCEEDED; 14899 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 14900 if (ret != PackageManager.INSTALL_SUCCEEDED) { 14901 Slog.e(TAG, "Failed to copy package"); 14902 return ret; 14903 } 14904 14905 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 14906 NativeLibraryHelper.Handle handle = null; 14907 try { 14908 handle = NativeLibraryHelper.Handle.create(codeFile); 14909 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 14910 abiOverride); 14911 } catch (IOException e) { 14912 Slog.e(TAG, "Copying native libraries failed", e); 14913 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 14914 } finally { 14915 IoUtils.closeQuietly(handle); 14916 } 14917 14918 return ret; 14919 } 14920 14921 int doPreInstall(int status) { 14922 if (status != PackageManager.INSTALL_SUCCEEDED) { 14923 cleanUp(); 14924 } 14925 return status; 14926 } 14927 14928 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 14929 if (status != PackageManager.INSTALL_SUCCEEDED) { 14930 cleanUp(); 14931 return false; 14932 } 14933 14934 final File targetDir = codeFile.getParentFile(); 14935 final File beforeCodeFile = codeFile; 14936 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 14937 14938 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 14939 try { 14940 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 14941 } catch (ErrnoException e) { 14942 Slog.w(TAG, "Failed to rename", e); 14943 return false; 14944 } 14945 14946 if (!SELinux.restoreconRecursive(afterCodeFile)) { 14947 Slog.w(TAG, "Failed to restorecon"); 14948 return false; 14949 } 14950 14951 // Reflect the rename internally 14952 codeFile = afterCodeFile; 14953 resourceFile = afterCodeFile; 14954 14955 // Reflect the rename in scanned details 14956 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 14957 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 14958 afterCodeFile, pkg.baseCodePath)); 14959 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 14960 afterCodeFile, pkg.splitCodePaths)); 14961 14962 // Reflect the rename in app info 14963 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 14964 pkg.setApplicationInfoCodePath(pkg.codePath); 14965 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 14966 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 14967 pkg.setApplicationInfoResourcePath(pkg.codePath); 14968 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 14969 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 14970 14971 return true; 14972 } 14973 14974 int doPostInstall(int status, int uid) { 14975 if (status != PackageManager.INSTALL_SUCCEEDED) { 14976 cleanUp(); 14977 } 14978 return status; 14979 } 14980 14981 @Override 14982 String getCodePath() { 14983 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 14984 } 14985 14986 @Override 14987 String getResourcePath() { 14988 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 14989 } 14990 14991 private boolean cleanUp() { 14992 if (codeFile == null || !codeFile.exists()) { 14993 return false; 14994 } 14995 14996 removeCodePathLI(codeFile); 14997 14998 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 14999 resourceFile.delete(); 15000 } 15001 15002 return true; 15003 } 15004 15005 void cleanUpResourcesLI() { 15006 // Try enumerating all code paths before deleting 15007 List<String> allCodePaths = Collections.EMPTY_LIST; 15008 if (codeFile != null && codeFile.exists()) { 15009 try { 15010 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 15011 allCodePaths = pkg.getAllCodePaths(); 15012 } catch (PackageParserException e) { 15013 // Ignored; we tried our best 15014 } 15015 } 15016 15017 cleanUp(); 15018 removeDexFiles(allCodePaths, instructionSets); 15019 } 15020 15021 boolean doPostDeleteLI(boolean delete) { 15022 // XXX err, shouldn't we respect the delete flag? 15023 cleanUpResourcesLI(); 15024 return true; 15025 } 15026 } 15027 15028 private boolean isAsecExternal(String cid) { 15029 final String asecPath = PackageHelper.getSdFilesystem(cid); 15030 return !asecPath.startsWith(mAsecInternalPath); 15031 } 15032 15033 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 15034 PackageManagerException { 15035 if (copyRet < 0) { 15036 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 15037 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 15038 throw new PackageManagerException(copyRet, message); 15039 } 15040 } 15041 } 15042 15043 /** 15044 * Extract the StorageManagerService "container ID" from the full code path of an 15045 * .apk. 15046 */ 15047 static String cidFromCodePath(String fullCodePath) { 15048 int eidx = fullCodePath.lastIndexOf("/"); 15049 String subStr1 = fullCodePath.substring(0, eidx); 15050 int sidx = subStr1.lastIndexOf("/"); 15051 return subStr1.substring(sidx+1, eidx); 15052 } 15053 15054 /** 15055 * Logic to handle installation of ASEC applications, including copying and 15056 * renaming logic. 15057 */ 15058 class AsecInstallArgs extends InstallArgs { 15059 static final String RES_FILE_NAME = "pkg.apk"; 15060 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 15061 15062 String cid; 15063 String packagePath; 15064 String resourcePath; 15065 15066 /** New install */ 15067 AsecInstallArgs(InstallParams params) { 15068 super(params.origin, params.move, params.observer, params.installFlags, 15069 params.installerPackageName, params.volumeUuid, 15070 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 15071 params.grantedRuntimePermissions, 15072 params.traceMethod, params.traceCookie, params.certificates, 15073 params.installReason); 15074 } 15075 15076 /** Existing install */ 15077 AsecInstallArgs(String fullCodePath, String[] instructionSets, 15078 boolean isExternal, boolean isForwardLocked) { 15079 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 15080 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 15081 instructionSets, null, null, null, 0, null /*certificates*/, 15082 PackageManager.INSTALL_REASON_UNKNOWN); 15083 // Hackily pretend we're still looking at a full code path 15084 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 15085 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 15086 } 15087 15088 // Extract cid from fullCodePath 15089 int eidx = fullCodePath.lastIndexOf("/"); 15090 String subStr1 = fullCodePath.substring(0, eidx); 15091 int sidx = subStr1.lastIndexOf("/"); 15092 cid = subStr1.substring(sidx+1, eidx); 15093 setMountPath(subStr1); 15094 } 15095 15096 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 15097 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 15098 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 15099 instructionSets, null, null, null, 0, null /*certificates*/, 15100 PackageManager.INSTALL_REASON_UNKNOWN); 15101 this.cid = cid; 15102 setMountPath(PackageHelper.getSdDir(cid)); 15103 } 15104 15105 void createCopyFile() { 15106 cid = mInstallerService.allocateExternalStageCidLegacy(); 15107 } 15108 15109 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 15110 if (origin.staged && origin.cid != null) { 15111 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 15112 cid = origin.cid; 15113 setMountPath(PackageHelper.getSdDir(cid)); 15114 return PackageManager.INSTALL_SUCCEEDED; 15115 } 15116 15117 if (temp) { 15118 createCopyFile(); 15119 } else { 15120 /* 15121 * Pre-emptively destroy the container since it's destroyed if 15122 * copying fails due to it existing anyway. 15123 */ 15124 PackageHelper.destroySdDir(cid); 15125 } 15126 15127 final String newMountPath = imcs.copyPackageToContainer( 15128 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 15129 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 15130 15131 if (newMountPath != null) { 15132 setMountPath(newMountPath); 15133 return PackageManager.INSTALL_SUCCEEDED; 15134 } else { 15135 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15136 } 15137 } 15138 15139 @Override 15140 String getCodePath() { 15141 return packagePath; 15142 } 15143 15144 @Override 15145 String getResourcePath() { 15146 return resourcePath; 15147 } 15148 15149 int doPreInstall(int status) { 15150 if (status != PackageManager.INSTALL_SUCCEEDED) { 15151 // Destroy container 15152 PackageHelper.destroySdDir(cid); 15153 } else { 15154 boolean mounted = PackageHelper.isContainerMounted(cid); 15155 if (!mounted) { 15156 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 15157 Process.SYSTEM_UID); 15158 if (newMountPath != null) { 15159 setMountPath(newMountPath); 15160 } else { 15161 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15162 } 15163 } 15164 } 15165 return status; 15166 } 15167 15168 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15169 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 15170 String newMountPath = null; 15171 if (PackageHelper.isContainerMounted(cid)) { 15172 // Unmount the container 15173 if (!PackageHelper.unMountSdDir(cid)) { 15174 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 15175 return false; 15176 } 15177 } 15178 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 15179 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 15180 " which might be stale. Will try to clean up."); 15181 // Clean up the stale container and proceed to recreate. 15182 if (!PackageHelper.destroySdDir(newCacheId)) { 15183 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 15184 return false; 15185 } 15186 // Successfully cleaned up stale container. Try to rename again. 15187 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 15188 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 15189 + " inspite of cleaning it up."); 15190 return false; 15191 } 15192 } 15193 if (!PackageHelper.isContainerMounted(newCacheId)) { 15194 Slog.w(TAG, "Mounting container " + newCacheId); 15195 newMountPath = PackageHelper.mountSdDir(newCacheId, 15196 getEncryptKey(), Process.SYSTEM_UID); 15197 } else { 15198 newMountPath = PackageHelper.getSdDir(newCacheId); 15199 } 15200 if (newMountPath == null) { 15201 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 15202 return false; 15203 } 15204 Log.i(TAG, "Succesfully renamed " + cid + 15205 " to " + newCacheId + 15206 " at new path: " + newMountPath); 15207 cid = newCacheId; 15208 15209 final File beforeCodeFile = new File(packagePath); 15210 setMountPath(newMountPath); 15211 final File afterCodeFile = new File(packagePath); 15212 15213 // Reflect the rename in scanned details 15214 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 15215 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 15216 afterCodeFile, pkg.baseCodePath)); 15217 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 15218 afterCodeFile, pkg.splitCodePaths)); 15219 15220 // Reflect the rename in app info 15221 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15222 pkg.setApplicationInfoCodePath(pkg.codePath); 15223 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15224 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15225 pkg.setApplicationInfoResourcePath(pkg.codePath); 15226 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15227 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15228 15229 return true; 15230 } 15231 15232 private void setMountPath(String mountPath) { 15233 final File mountFile = new File(mountPath); 15234 15235 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 15236 if (monolithicFile.exists()) { 15237 packagePath = monolithicFile.getAbsolutePath(); 15238 if (isFwdLocked()) { 15239 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 15240 } else { 15241 resourcePath = packagePath; 15242 } 15243 } else { 15244 packagePath = mountFile.getAbsolutePath(); 15245 resourcePath = packagePath; 15246 } 15247 } 15248 15249 int doPostInstall(int status, int uid) { 15250 if (status != PackageManager.INSTALL_SUCCEEDED) { 15251 cleanUp(); 15252 } else { 15253 final int groupOwner; 15254 final String protectedFile; 15255 if (isFwdLocked()) { 15256 groupOwner = UserHandle.getSharedAppGid(uid); 15257 protectedFile = RES_FILE_NAME; 15258 } else { 15259 groupOwner = -1; 15260 protectedFile = null; 15261 } 15262 15263 if (uid < Process.FIRST_APPLICATION_UID 15264 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 15265 Slog.e(TAG, "Failed to finalize " + cid); 15266 PackageHelper.destroySdDir(cid); 15267 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15268 } 15269 15270 boolean mounted = PackageHelper.isContainerMounted(cid); 15271 if (!mounted) { 15272 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 15273 } 15274 } 15275 return status; 15276 } 15277 15278 private void cleanUp() { 15279 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 15280 15281 // Destroy secure container 15282 PackageHelper.destroySdDir(cid); 15283 } 15284 15285 private List<String> getAllCodePaths() { 15286 final File codeFile = new File(getCodePath()); 15287 if (codeFile != null && codeFile.exists()) { 15288 try { 15289 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 15290 return pkg.getAllCodePaths(); 15291 } catch (PackageParserException e) { 15292 // Ignored; we tried our best 15293 } 15294 } 15295 return Collections.EMPTY_LIST; 15296 } 15297 15298 void cleanUpResourcesLI() { 15299 // Enumerate all code paths before deleting 15300 cleanUpResourcesLI(getAllCodePaths()); 15301 } 15302 15303 private void cleanUpResourcesLI(List<String> allCodePaths) { 15304 cleanUp(); 15305 removeDexFiles(allCodePaths, instructionSets); 15306 } 15307 15308 String getPackageName() { 15309 return getAsecPackageName(cid); 15310 } 15311 15312 boolean doPostDeleteLI(boolean delete) { 15313 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 15314 final List<String> allCodePaths = getAllCodePaths(); 15315 boolean mounted = PackageHelper.isContainerMounted(cid); 15316 if (mounted) { 15317 // Unmount first 15318 if (PackageHelper.unMountSdDir(cid)) { 15319 mounted = false; 15320 } 15321 } 15322 if (!mounted && delete) { 15323 cleanUpResourcesLI(allCodePaths); 15324 } 15325 return !mounted; 15326 } 15327 15328 @Override 15329 int doPreCopy() { 15330 if (isFwdLocked()) { 15331 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 15332 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 15333 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15334 } 15335 } 15336 15337 return PackageManager.INSTALL_SUCCEEDED; 15338 } 15339 15340 @Override 15341 int doPostCopy(int uid) { 15342 if (isFwdLocked()) { 15343 if (uid < Process.FIRST_APPLICATION_UID 15344 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 15345 RES_FILE_NAME)) { 15346 Slog.e(TAG, "Failed to finalize " + cid); 15347 PackageHelper.destroySdDir(cid); 15348 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15349 } 15350 } 15351 15352 return PackageManager.INSTALL_SUCCEEDED; 15353 } 15354 } 15355 15356 /** 15357 * Logic to handle movement of existing installed applications. 15358 */ 15359 class MoveInstallArgs extends InstallArgs { 15360 private File codeFile; 15361 private File resourceFile; 15362 15363 /** New install */ 15364 MoveInstallArgs(InstallParams params) { 15365 super(params.origin, params.move, params.observer, params.installFlags, 15366 params.installerPackageName, params.volumeUuid, 15367 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 15368 params.grantedRuntimePermissions, 15369 params.traceMethod, params.traceCookie, params.certificates, 15370 params.installReason); 15371 } 15372 15373 int copyApk(IMediaContainerService imcs, boolean temp) { 15374 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 15375 + move.fromUuid + " to " + move.toUuid); 15376 synchronized (mInstaller) { 15377 try { 15378 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 15379 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 15380 } catch (InstallerException e) { 15381 Slog.w(TAG, "Failed to move app", e); 15382 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15383 } 15384 } 15385 15386 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 15387 resourceFile = codeFile; 15388 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 15389 15390 return PackageManager.INSTALL_SUCCEEDED; 15391 } 15392 15393 int doPreInstall(int status) { 15394 if (status != PackageManager.INSTALL_SUCCEEDED) { 15395 cleanUp(move.toUuid); 15396 } 15397 return status; 15398 } 15399 15400 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15401 if (status != PackageManager.INSTALL_SUCCEEDED) { 15402 cleanUp(move.toUuid); 15403 return false; 15404 } 15405 15406 // Reflect the move in app info 15407 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15408 pkg.setApplicationInfoCodePath(pkg.codePath); 15409 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15410 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15411 pkg.setApplicationInfoResourcePath(pkg.codePath); 15412 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15413 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15414 15415 return true; 15416 } 15417 15418 int doPostInstall(int status, int uid) { 15419 if (status == PackageManager.INSTALL_SUCCEEDED) { 15420 cleanUp(move.fromUuid); 15421 } else { 15422 cleanUp(move.toUuid); 15423 } 15424 return status; 15425 } 15426 15427 @Override 15428 String getCodePath() { 15429 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 15430 } 15431 15432 @Override 15433 String getResourcePath() { 15434 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 15435 } 15436 15437 private boolean cleanUp(String volumeUuid) { 15438 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 15439 move.dataAppName); 15440 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 15441 final int[] userIds = sUserManager.getUserIds(); 15442 synchronized (mInstallLock) { 15443 // Clean up both app data and code 15444 // All package moves are frozen until finished 15445 for (int userId : userIds) { 15446 try { 15447 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 15448 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 15449 } catch (InstallerException e) { 15450 Slog.w(TAG, String.valueOf(e)); 15451 } 15452 } 15453 removeCodePathLI(codeFile); 15454 } 15455 return true; 15456 } 15457 15458 void cleanUpResourcesLI() { 15459 throw new UnsupportedOperationException(); 15460 } 15461 15462 boolean doPostDeleteLI(boolean delete) { 15463 throw new UnsupportedOperationException(); 15464 } 15465 } 15466 15467 static String getAsecPackageName(String packageCid) { 15468 int idx = packageCid.lastIndexOf("-"); 15469 if (idx == -1) { 15470 return packageCid; 15471 } 15472 return packageCid.substring(0, idx); 15473 } 15474 15475 // Utility method used to create code paths based on package name and available index. 15476 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 15477 String idxStr = ""; 15478 int idx = 1; 15479 // Fall back to default value of idx=1 if prefix is not 15480 // part of oldCodePath 15481 if (oldCodePath != null) { 15482 String subStr = oldCodePath; 15483 // Drop the suffix right away 15484 if (suffix != null && subStr.endsWith(suffix)) { 15485 subStr = subStr.substring(0, subStr.length() - suffix.length()); 15486 } 15487 // If oldCodePath already contains prefix find out the 15488 // ending index to either increment or decrement. 15489 int sidx = subStr.lastIndexOf(prefix); 15490 if (sidx != -1) { 15491 subStr = subStr.substring(sidx + prefix.length()); 15492 if (subStr != null) { 15493 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 15494 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 15495 } 15496 try { 15497 idx = Integer.parseInt(subStr); 15498 if (idx <= 1) { 15499 idx++; 15500 } else { 15501 idx--; 15502 } 15503 } catch(NumberFormatException e) { 15504 } 15505 } 15506 } 15507 } 15508 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 15509 return prefix + idxStr; 15510 } 15511 15512 private File getNextCodePath(File targetDir, String packageName) { 15513 File result; 15514 SecureRandom random = new SecureRandom(); 15515 byte[] bytes = new byte[16]; 15516 do { 15517 random.nextBytes(bytes); 15518 String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP); 15519 result = new File(targetDir, packageName + "-" + suffix); 15520 } while (result.exists()); 15521 return result; 15522 } 15523 15524 // Utility method that returns the relative package path with respect 15525 // to the installation directory. Like say for /data/data/com.test-1.apk 15526 // string com.test-1 is returned. 15527 static String deriveCodePathName(String codePath) { 15528 if (codePath == null) { 15529 return null; 15530 } 15531 final File codeFile = new File(codePath); 15532 final String name = codeFile.getName(); 15533 if (codeFile.isDirectory()) { 15534 return name; 15535 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 15536 final int lastDot = name.lastIndexOf('.'); 15537 return name.substring(0, lastDot); 15538 } else { 15539 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 15540 return null; 15541 } 15542 } 15543 15544 static class PackageInstalledInfo { 15545 String name; 15546 int uid; 15547 // The set of users that originally had this package installed. 15548 int[] origUsers; 15549 // The set of users that now have this package installed. 15550 int[] newUsers; 15551 PackageParser.Package pkg; 15552 int returnCode; 15553 String returnMsg; 15554 PackageRemovedInfo removedInfo; 15555 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 15556 15557 public void setError(int code, String msg) { 15558 setReturnCode(code); 15559 setReturnMessage(msg); 15560 Slog.w(TAG, msg); 15561 } 15562 15563 public void setError(String msg, PackageParserException e) { 15564 setReturnCode(e.error); 15565 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 15566 Slog.w(TAG, msg, e); 15567 } 15568 15569 public void setError(String msg, PackageManagerException e) { 15570 returnCode = e.error; 15571 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 15572 Slog.w(TAG, msg, e); 15573 } 15574 15575 public void setReturnCode(int returnCode) { 15576 this.returnCode = returnCode; 15577 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15578 for (int i = 0; i < childCount; i++) { 15579 addedChildPackages.valueAt(i).returnCode = returnCode; 15580 } 15581 } 15582 15583 private void setReturnMessage(String returnMsg) { 15584 this.returnMsg = returnMsg; 15585 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15586 for (int i = 0; i < childCount; i++) { 15587 addedChildPackages.valueAt(i).returnMsg = returnMsg; 15588 } 15589 } 15590 15591 // In some error cases we want to convey more info back to the observer 15592 String origPackage; 15593 String origPermission; 15594 } 15595 15596 /* 15597 * Install a non-existing package. 15598 */ 15599 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 15600 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 15601 PackageInstalledInfo res, int installReason) { 15602 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 15603 15604 // Remember this for later, in case we need to rollback this install 15605 String pkgName = pkg.packageName; 15606 15607 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 15608 15609 synchronized(mPackages) { 15610 final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName); 15611 if (renamedPackage != null) { 15612 // A package with the same name is already installed, though 15613 // it has been renamed to an older name. The package we 15614 // are trying to install should be installed as an update to 15615 // the existing one, but that has not been requested, so bail. 15616 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 15617 + " without first uninstalling package running as " 15618 + renamedPackage); 15619 return; 15620 } 15621 if (mPackages.containsKey(pkgName)) { 15622 // Don't allow installation over an existing package with the same name. 15623 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 15624 + " without first uninstalling."); 15625 return; 15626 } 15627 } 15628 15629 try { 15630 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 15631 System.currentTimeMillis(), user); 15632 15633 updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason); 15634 15635 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 15636 prepareAppDataAfterInstallLIF(newPackage); 15637 15638 } else { 15639 // Remove package from internal structures, but keep around any 15640 // data that might have already existed 15641 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 15642 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 15643 } 15644 } catch (PackageManagerException e) { 15645 res.setError("Package couldn't be installed in " + pkg.codePath, e); 15646 } 15647 15648 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15649 } 15650 15651 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 15652 // Can't rotate keys during boot or if sharedUser. 15653 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 15654 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 15655 return false; 15656 } 15657 // app is using upgradeKeySets; make sure all are valid 15658 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15659 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 15660 for (int i = 0; i < upgradeKeySets.length; i++) { 15661 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 15662 Slog.wtf(TAG, "Package " 15663 + (oldPs.name != null ? oldPs.name : "<null>") 15664 + " contains upgrade-key-set reference to unknown key-set: " 15665 + upgradeKeySets[i] 15666 + " reverting to signatures check."); 15667 return false; 15668 } 15669 } 15670 return true; 15671 } 15672 15673 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 15674 // Upgrade keysets are being used. Determine if new package has a superset of the 15675 // required keys. 15676 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 15677 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15678 for (int i = 0; i < upgradeKeySets.length; i++) { 15679 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 15680 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 15681 return true; 15682 } 15683 } 15684 return false; 15685 } 15686 15687 private static void updateDigest(MessageDigest digest, File file) throws IOException { 15688 try (DigestInputStream digestStream = 15689 new DigestInputStream(new FileInputStream(file), digest)) { 15690 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 15691 } 15692 } 15693 15694 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 15695 UserHandle user, String installerPackageName, PackageInstalledInfo res, 15696 int installReason) { 15697 final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 15698 15699 final PackageParser.Package oldPackage; 15700 final String pkgName = pkg.packageName; 15701 final int[] allUsers; 15702 final int[] installedUsers; 15703 15704 synchronized(mPackages) { 15705 oldPackage = mPackages.get(pkgName); 15706 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 15707 15708 // don't allow upgrade to target a release SDK from a pre-release SDK 15709 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 15710 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 15711 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 15712 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 15713 if (oldTargetsPreRelease 15714 && !newTargetsPreRelease 15715 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 15716 Slog.w(TAG, "Can't install package targeting released sdk"); 15717 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 15718 return; 15719 } 15720 15721 // don't allow an upgrade from full to ephemeral 15722 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 15723 if (isEphemeral && !oldIsEphemeral) { 15724 // can't downgrade from full to ephemeral 15725 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 15726 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 15727 return; 15728 } 15729 15730 // verify signatures are valid 15731 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15732 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 15733 if (!checkUpgradeKeySetLP(ps, pkg)) { 15734 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 15735 "New package not signed by keys specified by upgrade-keysets: " 15736 + pkgName); 15737 return; 15738 } 15739 } else { 15740 // default to original signature matching 15741 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 15742 != PackageManager.SIGNATURE_MATCH) { 15743 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 15744 "New package has a different signature: " + pkgName); 15745 return; 15746 } 15747 } 15748 15749 // don't allow a system upgrade unless the upgrade hash matches 15750 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 15751 byte[] digestBytes = null; 15752 try { 15753 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 15754 updateDigest(digest, new File(pkg.baseCodePath)); 15755 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 15756 for (String path : pkg.splitCodePaths) { 15757 updateDigest(digest, new File(path)); 15758 } 15759 } 15760 digestBytes = digest.digest(); 15761 } catch (NoSuchAlgorithmException | IOException e) { 15762 res.setError(INSTALL_FAILED_INVALID_APK, 15763 "Could not compute hash: " + pkgName); 15764 return; 15765 } 15766 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 15767 res.setError(INSTALL_FAILED_INVALID_APK, 15768 "New package fails restrict-update check: " + pkgName); 15769 return; 15770 } 15771 // retain upgrade restriction 15772 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 15773 } 15774 15775 // Check for shared user id changes 15776 String invalidPackageName = 15777 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 15778 if (invalidPackageName != null) { 15779 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 15780 "Package " + invalidPackageName + " tried to change user " 15781 + oldPackage.mSharedUserId); 15782 return; 15783 } 15784 15785 // In case of rollback, remember per-user/profile install state 15786 allUsers = sUserManager.getUserIds(); 15787 installedUsers = ps.queryInstalledUsers(allUsers, true); 15788 } 15789 15790 // Update what is removed 15791 res.removedInfo = new PackageRemovedInfo(); 15792 res.removedInfo.uid = oldPackage.applicationInfo.uid; 15793 res.removedInfo.removedPackage = oldPackage.packageName; 15794 res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null; 15795 res.removedInfo.isUpdate = true; 15796 res.removedInfo.origUsers = installedUsers; 15797 final PackageSetting ps = mSettings.getPackageLPr(pkgName); 15798 res.removedInfo.installReasons = new SparseArray<>(installedUsers.length); 15799 for (int i = 0; i < installedUsers.length; i++) { 15800 final int userId = installedUsers[i]; 15801 res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId)); 15802 } 15803 15804 final int childCount = (oldPackage.childPackages != null) 15805 ? oldPackage.childPackages.size() : 0; 15806 for (int i = 0; i < childCount; i++) { 15807 boolean childPackageUpdated = false; 15808 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 15809 final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 15810 if (res.addedChildPackages != null) { 15811 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 15812 if (childRes != null) { 15813 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 15814 childRes.removedInfo.removedPackage = childPkg.packageName; 15815 childRes.removedInfo.isUpdate = true; 15816 childRes.removedInfo.installReasons = res.removedInfo.installReasons; 15817 childPackageUpdated = true; 15818 } 15819 } 15820 if (!childPackageUpdated) { 15821 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 15822 childRemovedRes.removedPackage = childPkg.packageName; 15823 childRemovedRes.isUpdate = false; 15824 childRemovedRes.dataRemoved = true; 15825 synchronized (mPackages) { 15826 if (childPs != null) { 15827 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 15828 } 15829 } 15830 if (res.removedInfo.removedChildPackages == null) { 15831 res.removedInfo.removedChildPackages = new ArrayMap<>(); 15832 } 15833 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 15834 } 15835 } 15836 15837 boolean sysPkg = (isSystemApp(oldPackage)); 15838 if (sysPkg) { 15839 // Set the system/privileged flags as needed 15840 final boolean privileged = 15841 (oldPackage.applicationInfo.privateFlags 15842 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 15843 final int systemPolicyFlags = policyFlags 15844 | PackageParser.PARSE_IS_SYSTEM 15845 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 15846 15847 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 15848 user, allUsers, installerPackageName, res, installReason); 15849 } else { 15850 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 15851 user, allUsers, installerPackageName, res, installReason); 15852 } 15853 } 15854 15855 public List<String> getPreviousCodePaths(String packageName) { 15856 final PackageSetting ps = mSettings.mPackages.get(packageName); 15857 final List<String> result = new ArrayList<String>(); 15858 if (ps != null && ps.oldCodePaths != null) { 15859 result.addAll(ps.oldCodePaths); 15860 } 15861 return result; 15862 } 15863 15864 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 15865 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 15866 int[] allUsers, String installerPackageName, PackageInstalledInfo res, 15867 int installReason) { 15868 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 15869 + deletedPackage); 15870 15871 String pkgName = deletedPackage.packageName; 15872 boolean deletedPkg = true; 15873 boolean addedPkg = false; 15874 boolean updatedSettings = false; 15875 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 15876 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 15877 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 15878 15879 final long origUpdateTime = (pkg.mExtras != null) 15880 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 15881 15882 // First delete the existing package while retaining the data directory 15883 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 15884 res.removedInfo, true, pkg)) { 15885 // If the existing package wasn't successfully deleted 15886 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 15887 deletedPkg = false; 15888 } else { 15889 // Successfully deleted the old package; proceed with replace. 15890 15891 // If deleted package lived in a container, give users a chance to 15892 // relinquish resources before killing. 15893 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 15894 if (DEBUG_INSTALL) { 15895 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 15896 } 15897 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 15898 final ArrayList<String> pkgList = new ArrayList<String>(1); 15899 pkgList.add(deletedPackage.applicationInfo.packageName); 15900 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 15901 } 15902 15903 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 15904 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 15905 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 15906 15907 try { 15908 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 15909 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 15910 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 15911 installReason); 15912 15913 // Update the in-memory copy of the previous code paths. 15914 PackageSetting ps = mSettings.mPackages.get(pkgName); 15915 if (!killApp) { 15916 if (ps.oldCodePaths == null) { 15917 ps.oldCodePaths = new ArraySet<>(); 15918 } 15919 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 15920 if (deletedPackage.splitCodePaths != null) { 15921 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 15922 } 15923 } else { 15924 ps.oldCodePaths = null; 15925 } 15926 if (ps.childPackageNames != null) { 15927 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 15928 final String childPkgName = ps.childPackageNames.get(i); 15929 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 15930 childPs.oldCodePaths = ps.oldCodePaths; 15931 } 15932 } 15933 prepareAppDataAfterInstallLIF(newPackage); 15934 addedPkg = true; 15935 } catch (PackageManagerException e) { 15936 res.setError("Package couldn't be installed in " + pkg.codePath, e); 15937 } 15938 } 15939 15940 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 15941 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 15942 15943 // Revert all internal state mutations and added folders for the failed install 15944 if (addedPkg) { 15945 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 15946 res.removedInfo, true, null); 15947 } 15948 15949 // Restore the old package 15950 if (deletedPkg) { 15951 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 15952 File restoreFile = new File(deletedPackage.codePath); 15953 // Parse old package 15954 boolean oldExternal = isExternal(deletedPackage); 15955 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 15956 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 15957 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 15958 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 15959 try { 15960 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 15961 null); 15962 } catch (PackageManagerException e) { 15963 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 15964 + e.getMessage()); 15965 return; 15966 } 15967 15968 synchronized (mPackages) { 15969 // Ensure the installer package name up to date 15970 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 15971 15972 // Update permissions for restored package 15973 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 15974 15975 mSettings.writeLPr(); 15976 } 15977 15978 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 15979 } 15980 } else { 15981 synchronized (mPackages) { 15982 PackageSetting ps = mSettings.getPackageLPr(pkg.packageName); 15983 if (ps != null) { 15984 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 15985 if (res.removedInfo.removedChildPackages != null) { 15986 final int childCount = res.removedInfo.removedChildPackages.size(); 15987 // Iterate in reverse as we may modify the collection 15988 for (int i = childCount - 1; i >= 0; i--) { 15989 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 15990 if (res.addedChildPackages.containsKey(childPackageName)) { 15991 res.removedInfo.removedChildPackages.removeAt(i); 15992 } else { 15993 PackageRemovedInfo childInfo = res.removedInfo 15994 .removedChildPackages.valueAt(i); 15995 childInfo.removedForAllUsers = mPackages.get( 15996 childInfo.removedPackage) == null; 15997 } 15998 } 15999 } 16000 } 16001 } 16002 } 16003 } 16004 16005 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 16006 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 16007 int[] allUsers, String installerPackageName, PackageInstalledInfo res, 16008 int installReason) { 16009 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 16010 + ", old=" + deletedPackage); 16011 16012 final boolean disabledSystem; 16013 16014 // Remove existing system package 16015 removePackageLI(deletedPackage, true); 16016 16017 synchronized (mPackages) { 16018 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 16019 } 16020 if (!disabledSystem) { 16021 // We didn't need to disable the .apk as a current system package, 16022 // which means we are replacing another update that is already 16023 // installed. We need to make sure to delete the older one's .apk. 16024 res.removedInfo.args = createInstallArgsForExisting(0, 16025 deletedPackage.applicationInfo.getCodePath(), 16026 deletedPackage.applicationInfo.getResourcePath(), 16027 getAppDexInstructionSets(deletedPackage.applicationInfo)); 16028 } else { 16029 res.removedInfo.args = null; 16030 } 16031 16032 // Successfully disabled the old package. Now proceed with re-installation 16033 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 16034 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16035 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 16036 16037 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16038 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 16039 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 16040 16041 PackageParser.Package newPackage = null; 16042 try { 16043 // Add the package to the internal data structures 16044 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 16045 16046 // Set the update and install times 16047 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 16048 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 16049 System.currentTimeMillis()); 16050 16051 // Update the package dynamic state if succeeded 16052 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 16053 // Now that the install succeeded make sure we remove data 16054 // directories for any child package the update removed. 16055 final int deletedChildCount = (deletedPackage.childPackages != null) 16056 ? deletedPackage.childPackages.size() : 0; 16057 final int newChildCount = (newPackage.childPackages != null) 16058 ? newPackage.childPackages.size() : 0; 16059 for (int i = 0; i < deletedChildCount; i++) { 16060 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 16061 boolean childPackageDeleted = true; 16062 for (int j = 0; j < newChildCount; j++) { 16063 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 16064 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 16065 childPackageDeleted = false; 16066 break; 16067 } 16068 } 16069 if (childPackageDeleted) { 16070 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 16071 deletedChildPkg.packageName); 16072 if (ps != null && res.removedInfo.removedChildPackages != null) { 16073 PackageRemovedInfo removedChildRes = res.removedInfo 16074 .removedChildPackages.get(deletedChildPkg.packageName); 16075 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 16076 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 16077 } 16078 } 16079 } 16080 16081 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 16082 installReason); 16083 prepareAppDataAfterInstallLIF(newPackage); 16084 } 16085 } catch (PackageManagerException e) { 16086 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 16087 res.setError("Package couldn't be installed in " + pkg.codePath, e); 16088 } 16089 16090 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 16091 // Re installation failed. Restore old information 16092 // Remove new pkg information 16093 if (newPackage != null) { 16094 removeInstalledPackageLI(newPackage, true); 16095 } 16096 // Add back the old system package 16097 try { 16098 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 16099 } catch (PackageManagerException e) { 16100 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 16101 } 16102 16103 synchronized (mPackages) { 16104 if (disabledSystem) { 16105 enableSystemPackageLPw(deletedPackage); 16106 } 16107 16108 // Ensure the installer package name up to date 16109 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 16110 16111 // Update permissions for restored package 16112 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 16113 16114 mSettings.writeLPr(); 16115 } 16116 16117 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 16118 + " after failed upgrade"); 16119 } 16120 } 16121 16122 /** 16123 * Checks whether the parent or any of the child packages have a change shared 16124 * user. For a package to be a valid update the shred users of the parent and 16125 * the children should match. We may later support changing child shared users. 16126 * @param oldPkg The updated package. 16127 * @param newPkg The update package. 16128 * @return The shared user that change between the versions. 16129 */ 16130 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 16131 PackageParser.Package newPkg) { 16132 // Check parent shared user 16133 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 16134 return newPkg.packageName; 16135 } 16136 // Check child shared users 16137 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 16138 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 16139 for (int i = 0; i < newChildCount; i++) { 16140 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 16141 // If this child was present, did it have the same shared user? 16142 for (int j = 0; j < oldChildCount; j++) { 16143 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 16144 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 16145 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 16146 return newChildPkg.packageName; 16147 } 16148 } 16149 } 16150 return null; 16151 } 16152 16153 private void removeNativeBinariesLI(PackageSetting ps) { 16154 // Remove the lib path for the parent package 16155 if (ps != null) { 16156 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 16157 // Remove the lib path for the child packages 16158 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 16159 for (int i = 0; i < childCount; i++) { 16160 PackageSetting childPs = null; 16161 synchronized (mPackages) { 16162 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 16163 } 16164 if (childPs != null) { 16165 NativeLibraryHelper.removeNativeBinariesLI(childPs 16166 .legacyNativeLibraryPathString); 16167 } 16168 } 16169 } 16170 } 16171 16172 private void enableSystemPackageLPw(PackageParser.Package pkg) { 16173 // Enable the parent package 16174 mSettings.enableSystemPackageLPw(pkg.packageName); 16175 // Enable the child packages 16176 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16177 for (int i = 0; i < childCount; i++) { 16178 PackageParser.Package childPkg = pkg.childPackages.get(i); 16179 mSettings.enableSystemPackageLPw(childPkg.packageName); 16180 } 16181 } 16182 16183 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 16184 PackageParser.Package newPkg) { 16185 // Disable the parent package (parent always replaced) 16186 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 16187 // Disable the child packages 16188 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 16189 for (int i = 0; i < childCount; i++) { 16190 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 16191 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 16192 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 16193 } 16194 return disabled; 16195 } 16196 16197 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 16198 String installerPackageName) { 16199 // Enable the parent package 16200 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 16201 // Enable the child packages 16202 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16203 for (int i = 0; i < childCount; i++) { 16204 PackageParser.Package childPkg = pkg.childPackages.get(i); 16205 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 16206 } 16207 } 16208 16209 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 16210 // Collect all used permissions in the UID 16211 ArraySet<String> usedPermissions = new ArraySet<>(); 16212 final int packageCount = su.packages.size(); 16213 for (int i = 0; i < packageCount; i++) { 16214 PackageSetting ps = su.packages.valueAt(i); 16215 if (ps.pkg == null) { 16216 continue; 16217 } 16218 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 16219 for (int j = 0; j < requestedPermCount; j++) { 16220 String permission = ps.pkg.requestedPermissions.get(j); 16221 BasePermission bp = mSettings.mPermissions.get(permission); 16222 if (bp != null) { 16223 usedPermissions.add(permission); 16224 } 16225 } 16226 } 16227 16228 PermissionsState permissionsState = su.getPermissionsState(); 16229 // Prune install permissions 16230 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 16231 final int installPermCount = installPermStates.size(); 16232 for (int i = installPermCount - 1; i >= 0; i--) { 16233 PermissionState permissionState = installPermStates.get(i); 16234 if (!usedPermissions.contains(permissionState.getName())) { 16235 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 16236 if (bp != null) { 16237 permissionsState.revokeInstallPermission(bp); 16238 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 16239 PackageManager.MASK_PERMISSION_FLAGS, 0); 16240 } 16241 } 16242 } 16243 16244 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 16245 16246 // Prune runtime permissions 16247 for (int userId : allUserIds) { 16248 List<PermissionState> runtimePermStates = permissionsState 16249 .getRuntimePermissionStates(userId); 16250 final int runtimePermCount = runtimePermStates.size(); 16251 for (int i = runtimePermCount - 1; i >= 0; i--) { 16252 PermissionState permissionState = runtimePermStates.get(i); 16253 if (!usedPermissions.contains(permissionState.getName())) { 16254 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 16255 if (bp != null) { 16256 permissionsState.revokeRuntimePermission(bp, userId); 16257 permissionsState.updatePermissionFlags(bp, userId, 16258 PackageManager.MASK_PERMISSION_FLAGS, 0); 16259 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 16260 runtimePermissionChangedUserIds, userId); 16261 } 16262 } 16263 } 16264 } 16265 16266 return runtimePermissionChangedUserIds; 16267 } 16268 16269 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 16270 int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) { 16271 // Update the parent package setting 16272 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 16273 res, user, installReason); 16274 // Update the child packages setting 16275 final int childCount = (newPackage.childPackages != null) 16276 ? newPackage.childPackages.size() : 0; 16277 for (int i = 0; i < childCount; i++) { 16278 PackageParser.Package childPackage = newPackage.childPackages.get(i); 16279 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 16280 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 16281 childRes.origUsers, childRes, user, installReason); 16282 } 16283 } 16284 16285 private void updateSettingsInternalLI(PackageParser.Package newPackage, 16286 String installerPackageName, int[] allUsers, int[] installedForUsers, 16287 PackageInstalledInfo res, UserHandle user, int installReason) { 16288 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 16289 16290 String pkgName = newPackage.packageName; 16291 synchronized (mPackages) { 16292 //write settings. the installStatus will be incomplete at this stage. 16293 //note that the new package setting would have already been 16294 //added to mPackages. It hasn't been persisted yet. 16295 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 16296 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 16297 mSettings.writeLPr(); 16298 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16299 } 16300 16301 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 16302 synchronized (mPackages) { 16303 updatePermissionsLPw(newPackage.packageName, newPackage, 16304 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 16305 ? UPDATE_PERMISSIONS_ALL : 0)); 16306 // For system-bundled packages, we assume that installing an upgraded version 16307 // of the package implies that the user actually wants to run that new code, 16308 // so we enable the package. 16309 PackageSetting ps = mSettings.mPackages.get(pkgName); 16310 final int userId = user.getIdentifier(); 16311 if (ps != null) { 16312 if (isSystemApp(newPackage)) { 16313 if (DEBUG_INSTALL) { 16314 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 16315 } 16316 // Enable system package for requested users 16317 if (res.origUsers != null) { 16318 for (int origUserId : res.origUsers) { 16319 if (userId == UserHandle.USER_ALL || userId == origUserId) { 16320 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 16321 origUserId, installerPackageName); 16322 } 16323 } 16324 } 16325 // Also convey the prior install/uninstall state 16326 if (allUsers != null && installedForUsers != null) { 16327 for (int currentUserId : allUsers) { 16328 final boolean installed = ArrayUtils.contains( 16329 installedForUsers, currentUserId); 16330 if (DEBUG_INSTALL) { 16331 Slog.d(TAG, " user " + currentUserId + " => " + installed); 16332 } 16333 ps.setInstalled(installed, currentUserId); 16334 } 16335 // these install state changes will be persisted in the 16336 // upcoming call to mSettings.writeLPr(). 16337 } 16338 } 16339 // It's implied that when a user requests installation, they want the app to be 16340 // installed and enabled. 16341 if (userId != UserHandle.USER_ALL) { 16342 ps.setInstalled(true, userId); 16343 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 16344 } 16345 16346 // When replacing an existing package, preserve the original install reason for all 16347 // users that had the package installed before. 16348 final Set<Integer> previousUserIds = new ArraySet<>(); 16349 if (res.removedInfo != null && res.removedInfo.installReasons != null) { 16350 final int installReasonCount = res.removedInfo.installReasons.size(); 16351 for (int i = 0; i < installReasonCount; i++) { 16352 final int previousUserId = res.removedInfo.installReasons.keyAt(i); 16353 final int previousInstallReason = res.removedInfo.installReasons.valueAt(i); 16354 ps.setInstallReason(previousInstallReason, previousUserId); 16355 previousUserIds.add(previousUserId); 16356 } 16357 } 16358 16359 // Set install reason for users that are having the package newly installed. 16360 if (userId == UserHandle.USER_ALL) { 16361 for (int currentUserId : sUserManager.getUserIds()) { 16362 if (!previousUserIds.contains(currentUserId)) { 16363 ps.setInstallReason(installReason, currentUserId); 16364 } 16365 } 16366 } else if (!previousUserIds.contains(userId)) { 16367 ps.setInstallReason(installReason, userId); 16368 } 16369 } 16370 res.name = pkgName; 16371 res.uid = newPackage.applicationInfo.uid; 16372 res.pkg = newPackage; 16373 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 16374 mSettings.setInstallerPackageName(pkgName, installerPackageName); 16375 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16376 //to update install status 16377 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 16378 mSettings.writeLPr(); 16379 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16380 } 16381 16382 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16383 } 16384 16385 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 16386 try { 16387 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 16388 installPackageLI(args, res); 16389 } finally { 16390 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16391 } 16392 } 16393 16394 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 16395 final int installFlags = args.installFlags; 16396 final String installerPackageName = args.installerPackageName; 16397 final String volumeUuid = args.volumeUuid; 16398 final File tmpPackageFile = new File(args.getCodePath()); 16399 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 16400 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 16401 || (args.volumeUuid != null)); 16402 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 16403 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 16404 boolean replace = false; 16405 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 16406 if (args.move != null) { 16407 // moving a complete application; perform an initial scan on the new install location 16408 scanFlags |= SCAN_INITIAL; 16409 } 16410 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 16411 scanFlags |= SCAN_DONT_KILL_APP; 16412 } 16413 16414 // Result object to be returned 16415 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16416 16417 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 16418 16419 // Sanity check 16420 if (ephemeral && (forwardLocked || onExternal)) { 16421 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 16422 + " external=" + onExternal); 16423 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 16424 return; 16425 } 16426 16427 // Retrieve PackageSettings and parse package 16428 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 16429 | PackageParser.PARSE_ENFORCE_CODE 16430 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 16431 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 16432 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0) 16433 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 16434 PackageParser pp = new PackageParser(); 16435 pp.setSeparateProcesses(mSeparateProcesses); 16436 pp.setDisplayMetrics(mMetrics); 16437 16438 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 16439 final PackageParser.Package pkg; 16440 try { 16441 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 16442 } catch (PackageParserException e) { 16443 res.setError("Failed parse during installPackageLI", e); 16444 return; 16445 } finally { 16446 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16447 } 16448 16449 // Ephemeral apps must have target SDK >= O. 16450 // TODO: Update conditional and error message when O gets locked down 16451 if (ephemeral && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) { 16452 res.setError(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID, 16453 "Ephemeral apps must have target SDK version of at least O"); 16454 return; 16455 } 16456 16457 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16458 // Static shared libraries have synthetic package names 16459 renameStaticSharedLibraryPackage(pkg); 16460 16461 // No static shared libs on external storage 16462 if (onExternal) { 16463 Slog.i(TAG, "Static shared libs can only be installed on internal storage."); 16464 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 16465 "Packages declaring static-shared libs cannot be updated"); 16466 return; 16467 } 16468 } 16469 16470 // If we are installing a clustered package add results for the children 16471 if (pkg.childPackages != null) { 16472 synchronized (mPackages) { 16473 final int childCount = pkg.childPackages.size(); 16474 for (int i = 0; i < childCount; i++) { 16475 PackageParser.Package childPkg = pkg.childPackages.get(i); 16476 PackageInstalledInfo childRes = new PackageInstalledInfo(); 16477 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16478 childRes.pkg = childPkg; 16479 childRes.name = childPkg.packageName; 16480 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 16481 if (childPs != null) { 16482 childRes.origUsers = childPs.queryInstalledUsers( 16483 sUserManager.getUserIds(), true); 16484 } 16485 if ((mPackages.containsKey(childPkg.packageName))) { 16486 childRes.removedInfo = new PackageRemovedInfo(); 16487 childRes.removedInfo.removedPackage = childPkg.packageName; 16488 } 16489 if (res.addedChildPackages == null) { 16490 res.addedChildPackages = new ArrayMap<>(); 16491 } 16492 res.addedChildPackages.put(childPkg.packageName, childRes); 16493 } 16494 } 16495 } 16496 16497 // If package doesn't declare API override, mark that we have an install 16498 // time CPU ABI override. 16499 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 16500 pkg.cpuAbiOverride = args.abiOverride; 16501 } 16502 16503 String pkgName = res.name = pkg.packageName; 16504 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 16505 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 16506 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 16507 return; 16508 } 16509 } 16510 16511 try { 16512 // either use what we've been given or parse directly from the APK 16513 if (args.certificates != null) { 16514 try { 16515 PackageParser.populateCertificates(pkg, args.certificates); 16516 } catch (PackageParserException e) { 16517 // there was something wrong with the certificates we were given; 16518 // try to pull them from the APK 16519 PackageParser.collectCertificates(pkg, parseFlags); 16520 } 16521 } else { 16522 PackageParser.collectCertificates(pkg, parseFlags); 16523 } 16524 } catch (PackageParserException e) { 16525 res.setError("Failed collect during installPackageLI", e); 16526 return; 16527 } 16528 16529 // Get rid of all references to package scan path via parser. 16530 pp = null; 16531 String oldCodePath = null; 16532 boolean systemApp = false; 16533 synchronized (mPackages) { 16534 // Check if installing already existing package 16535 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 16536 String oldName = mSettings.getRenamedPackageLPr(pkgName); 16537 if (pkg.mOriginalPackages != null 16538 && pkg.mOriginalPackages.contains(oldName) 16539 && mPackages.containsKey(oldName)) { 16540 // This package is derived from an original package, 16541 // and this device has been updating from that original 16542 // name. We must continue using the original name, so 16543 // rename the new package here. 16544 pkg.setPackageName(oldName); 16545 pkgName = pkg.packageName; 16546 replace = true; 16547 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 16548 + oldName + " pkgName=" + pkgName); 16549 } else if (mPackages.containsKey(pkgName)) { 16550 // This package, under its official name, already exists 16551 // on the device; we should replace it. 16552 replace = true; 16553 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 16554 } 16555 16556 // Child packages are installed through the parent package 16557 if (pkg.parentPackage != null) { 16558 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 16559 "Package " + pkg.packageName + " is child of package " 16560 + pkg.parentPackage.parentPackage + ". Child packages " 16561 + "can be updated only through the parent package."); 16562 return; 16563 } 16564 16565 if (replace) { 16566 // Prevent apps opting out from runtime permissions 16567 PackageParser.Package oldPackage = mPackages.get(pkgName); 16568 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 16569 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 16570 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 16571 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 16572 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 16573 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 16574 + " doesn't support runtime permissions but the old" 16575 + " target SDK " + oldTargetSdk + " does."); 16576 return; 16577 } 16578 16579 // Prevent installing of child packages 16580 if (oldPackage.parentPackage != null) { 16581 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 16582 "Package " + pkg.packageName + " is child of package " 16583 + oldPackage.parentPackage + ". Child packages " 16584 + "can be updated only through the parent package."); 16585 return; 16586 } 16587 } 16588 } 16589 16590 PackageSetting ps = mSettings.mPackages.get(pkgName); 16591 if (ps != null) { 16592 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 16593 16594 // Static shared libs have same package with different versions where 16595 // we internally use a synthetic package name to allow multiple versions 16596 // of the same package, therefore we need to compare signatures against 16597 // the package setting for the latest library version. 16598 PackageSetting signatureCheckPs = ps; 16599 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16600 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg); 16601 if (libraryEntry != null) { 16602 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk); 16603 } 16604 } 16605 16606 // Quick sanity check that we're signed correctly if updating; 16607 // we'll check this again later when scanning, but we want to 16608 // bail early here before tripping over redefined permissions. 16609 if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) { 16610 if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) { 16611 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 16612 + pkg.packageName + " upgrade keys do not match the " 16613 + "previously installed version"); 16614 return; 16615 } 16616 } else { 16617 try { 16618 verifySignaturesLP(signatureCheckPs, pkg); 16619 } catch (PackageManagerException e) { 16620 res.setError(e.error, e.getMessage()); 16621 return; 16622 } 16623 } 16624 16625 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 16626 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 16627 systemApp = (ps.pkg.applicationInfo.flags & 16628 ApplicationInfo.FLAG_SYSTEM) != 0; 16629 } 16630 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 16631 } 16632 16633 // Check whether the newly-scanned package wants to define an already-defined perm 16634 int N = pkg.permissions.size(); 16635 for (int i = N-1; i >= 0; i--) { 16636 PackageParser.Permission perm = pkg.permissions.get(i); 16637 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 16638 if (bp != null) { 16639 // If the defining package is signed with our cert, it's okay. This 16640 // also includes the "updating the same package" case, of course. 16641 // "updating same package" could also involve key-rotation. 16642 final boolean sigsOk; 16643 if (bp.sourcePackage.equals(pkg.packageName) 16644 && (bp.packageSetting instanceof PackageSetting) 16645 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 16646 scanFlags))) { 16647 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 16648 } else { 16649 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 16650 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 16651 } 16652 if (!sigsOk) { 16653 // If the owning package is the system itself, we log but allow 16654 // install to proceed; we fail the install on all other permission 16655 // redefinitions. 16656 if (!bp.sourcePackage.equals("android")) { 16657 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 16658 + pkg.packageName + " attempting to redeclare permission " 16659 + perm.info.name + " already owned by " + bp.sourcePackage); 16660 res.origPermission = perm.info.name; 16661 res.origPackage = bp.sourcePackage; 16662 return; 16663 } else { 16664 Slog.w(TAG, "Package " + pkg.packageName 16665 + " attempting to redeclare system permission " 16666 + perm.info.name + "; ignoring new declaration"); 16667 pkg.permissions.remove(i); 16668 } 16669 } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) { 16670 // Prevent apps to change protection level to dangerous from any other 16671 // type as this would allow a privilege escalation where an app adds a 16672 // normal/signature permission in other app's group and later redefines 16673 // it as dangerous leading to the group auto-grant. 16674 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE) 16675 == PermissionInfo.PROTECTION_DANGEROUS) { 16676 if (bp != null && !bp.isRuntime()) { 16677 Slog.w(TAG, "Package " + pkg.packageName + " trying to change a " 16678 + "non-runtime permission " + perm.info.name 16679 + " to runtime; keeping old protection level"); 16680 perm.info.protectionLevel = bp.protectionLevel; 16681 } 16682 } 16683 } 16684 } 16685 } 16686 } 16687 16688 if (systemApp) { 16689 if (onExternal) { 16690 // Abort update; system app can't be replaced with app on sdcard 16691 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 16692 "Cannot install updates to system apps on sdcard"); 16693 return; 16694 } else if (ephemeral) { 16695 // Abort update; system app can't be replaced with an ephemeral app 16696 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 16697 "Cannot update a system app with an ephemeral app"); 16698 return; 16699 } 16700 } 16701 16702 if (args.move != null) { 16703 // We did an in-place move, so dex is ready to roll 16704 scanFlags |= SCAN_NO_DEX; 16705 scanFlags |= SCAN_MOVE; 16706 16707 synchronized (mPackages) { 16708 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16709 if (ps == null) { 16710 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 16711 "Missing settings for moved package " + pkgName); 16712 } 16713 16714 // We moved the entire application as-is, so bring over the 16715 // previously derived ABI information. 16716 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 16717 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 16718 } 16719 16720 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 16721 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 16722 scanFlags |= SCAN_NO_DEX; 16723 16724 try { 16725 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 16726 args.abiOverride : pkg.cpuAbiOverride); 16727 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 16728 true /*extractLibs*/, mAppLib32InstallDir); 16729 } catch (PackageManagerException pme) { 16730 Slog.e(TAG, "Error deriving application ABI", pme); 16731 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 16732 return; 16733 } 16734 16735 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 16736 // Do not run PackageDexOptimizer through the local performDexOpt 16737 // method because `pkg` may not be in `mPackages` yet. 16738 // 16739 // Also, don't fail application installs if the dexopt step fails. 16740 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 16741 null /* instructionSets */, false /* checkProfiles */, 16742 getCompilerFilterForReason(REASON_INSTALL), 16743 getOrCreateCompilerPackageStats(pkg)); 16744 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16745 16746 // Notify BackgroundDexOptService that the package has been changed. 16747 // If this is an update of a package which used to fail to compile, 16748 // BDOS will remove it from its blacklist. 16749 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 16750 } 16751 16752 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 16753 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 16754 return; 16755 } 16756 16757 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 16758 16759 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 16760 "installPackageLI")) { 16761 if (replace) { 16762 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16763 // Static libs have a synthetic package name containing the version 16764 // and cannot be updated as an update would get a new package name, 16765 // unless this is the exact same version code which is useful for 16766 // development. 16767 PackageParser.Package existingPkg = mPackages.get(pkg.packageName); 16768 if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) { 16769 res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring " 16770 + "static-shared libs cannot be updated"); 16771 return; 16772 } 16773 } 16774 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 16775 installerPackageName, res, args.installReason); 16776 } else { 16777 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 16778 args.user, installerPackageName, volumeUuid, res, args.installReason); 16779 } 16780 } 16781 synchronized (mPackages) { 16782 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16783 if (ps != null) { 16784 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 16785 } 16786 16787 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16788 for (int i = 0; i < childCount; i++) { 16789 PackageParser.Package childPkg = pkg.childPackages.get(i); 16790 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 16791 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 16792 if (childPs != null) { 16793 childRes.newUsers = childPs.queryInstalledUsers( 16794 sUserManager.getUserIds(), true); 16795 } 16796 } 16797 } 16798 } 16799 16800 private void startIntentFilterVerifications(int userId, boolean replacing, 16801 PackageParser.Package pkg) { 16802 if (mIntentFilterVerifierComponent == null) { 16803 Slog.w(TAG, "No IntentFilter verification will not be done as " 16804 + "there is no IntentFilterVerifier available!"); 16805 return; 16806 } 16807 16808 final int verifierUid = getPackageUid( 16809 mIntentFilterVerifierComponent.getPackageName(), 16810 MATCH_DEBUG_TRIAGED_MISSING, 16811 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 16812 16813 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 16814 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 16815 mHandler.sendMessage(msg); 16816 16817 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16818 for (int i = 0; i < childCount; i++) { 16819 PackageParser.Package childPkg = pkg.childPackages.get(i); 16820 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 16821 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 16822 mHandler.sendMessage(msg); 16823 } 16824 } 16825 16826 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 16827 PackageParser.Package pkg) { 16828 int size = pkg.activities.size(); 16829 if (size == 0) { 16830 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 16831 "No activity, so no need to verify any IntentFilter!"); 16832 return; 16833 } 16834 16835 final boolean hasDomainURLs = hasDomainURLs(pkg); 16836 if (!hasDomainURLs) { 16837 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 16838 "No domain URLs, so no need to verify any IntentFilter!"); 16839 return; 16840 } 16841 16842 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 16843 + " if any IntentFilter from the " + size 16844 + " Activities needs verification ..."); 16845 16846 int count = 0; 16847 final String packageName = pkg.packageName; 16848 16849 synchronized (mPackages) { 16850 // If this is a new install and we see that we've already run verification for this 16851 // package, we have nothing to do: it means the state was restored from backup. 16852 if (!replacing) { 16853 IntentFilterVerificationInfo ivi = 16854 mSettings.getIntentFilterVerificationLPr(packageName); 16855 if (ivi != null) { 16856 if (DEBUG_DOMAIN_VERIFICATION) { 16857 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 16858 + ivi.getStatusString()); 16859 } 16860 return; 16861 } 16862 } 16863 16864 // If any filters need to be verified, then all need to be. 16865 boolean needToVerify = false; 16866 for (PackageParser.Activity a : pkg.activities) { 16867 for (ActivityIntentInfo filter : a.intents) { 16868 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 16869 if (DEBUG_DOMAIN_VERIFICATION) { 16870 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 16871 } 16872 needToVerify = true; 16873 break; 16874 } 16875 } 16876 } 16877 16878 if (needToVerify) { 16879 final int verificationId = mIntentFilterVerificationToken++; 16880 for (PackageParser.Activity a : pkg.activities) { 16881 for (ActivityIntentInfo filter : a.intents) { 16882 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 16883 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 16884 "Verification needed for IntentFilter:" + filter.toString()); 16885 mIntentFilterVerifier.addOneIntentFilterVerification( 16886 verifierUid, userId, verificationId, filter, packageName); 16887 count++; 16888 } 16889 } 16890 } 16891 } 16892 } 16893 16894 if (count > 0) { 16895 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 16896 + " IntentFilter verification" + (count > 1 ? "s" : "") 16897 + " for userId:" + userId); 16898 mIntentFilterVerifier.startVerifications(userId); 16899 } else { 16900 if (DEBUG_DOMAIN_VERIFICATION) { 16901 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 16902 } 16903 } 16904 } 16905 16906 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 16907 final ComponentName cn = filter.activity.getComponentName(); 16908 final String packageName = cn.getPackageName(); 16909 16910 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 16911 packageName); 16912 if (ivi == null) { 16913 return true; 16914 } 16915 int status = ivi.getStatus(); 16916 switch (status) { 16917 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 16918 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 16919 return true; 16920 16921 default: 16922 // Nothing to do 16923 return false; 16924 } 16925 } 16926 16927 private static boolean isMultiArch(ApplicationInfo info) { 16928 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 16929 } 16930 16931 private static boolean isExternal(PackageParser.Package pkg) { 16932 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 16933 } 16934 16935 private static boolean isExternal(PackageSetting ps) { 16936 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 16937 } 16938 16939 private static boolean isEphemeral(PackageParser.Package pkg) { 16940 return pkg.applicationInfo.isEphemeralApp(); 16941 } 16942 16943 private static boolean isEphemeral(PackageSetting ps) { 16944 return ps.pkg != null && isEphemeral(ps.pkg); 16945 } 16946 16947 private static boolean isSystemApp(PackageParser.Package pkg) { 16948 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 16949 } 16950 16951 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 16952 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 16953 } 16954 16955 private static boolean hasDomainURLs(PackageParser.Package pkg) { 16956 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 16957 } 16958 16959 private static boolean isSystemApp(PackageSetting ps) { 16960 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 16961 } 16962 16963 private static boolean isUpdatedSystemApp(PackageSetting ps) { 16964 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 16965 } 16966 16967 private int packageFlagsToInstallFlags(PackageSetting ps) { 16968 int installFlags = 0; 16969 if (isEphemeral(ps)) { 16970 installFlags |= PackageManager.INSTALL_EPHEMERAL; 16971 } 16972 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 16973 // This existing package was an external ASEC install when we have 16974 // the external flag without a UUID 16975 installFlags |= PackageManager.INSTALL_EXTERNAL; 16976 } 16977 if (ps.isForwardLocked()) { 16978 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 16979 } 16980 return installFlags; 16981 } 16982 16983 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 16984 if (isExternal(pkg)) { 16985 if (TextUtils.isEmpty(pkg.volumeUuid)) { 16986 return StorageManager.UUID_PRIMARY_PHYSICAL; 16987 } else { 16988 return pkg.volumeUuid; 16989 } 16990 } else { 16991 return StorageManager.UUID_PRIVATE_INTERNAL; 16992 } 16993 } 16994 16995 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 16996 if (isExternal(pkg)) { 16997 if (TextUtils.isEmpty(pkg.volumeUuid)) { 16998 return mSettings.getExternalVersion(); 16999 } else { 17000 return mSettings.findOrCreateVersion(pkg.volumeUuid); 17001 } 17002 } else { 17003 return mSettings.getInternalVersion(); 17004 } 17005 } 17006 17007 private void deleteTempPackageFiles() { 17008 final FilenameFilter filter = new FilenameFilter() { 17009 public boolean accept(File dir, String name) { 17010 return name.startsWith("vmdl") && name.endsWith(".tmp"); 17011 } 17012 }; 17013 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 17014 file.delete(); 17015 } 17016 } 17017 17018 @Override 17019 public void deletePackageAsUser(String packageName, int versionCode, 17020 IPackageDeleteObserver observer, int userId, int flags) { 17021 deletePackageVersioned(new VersionedPackage(packageName, versionCode), 17022 new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags); 17023 } 17024 17025 @Override 17026 public void deletePackageVersioned(VersionedPackage versionedPackage, 17027 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 17028 mContext.enforceCallingOrSelfPermission( 17029 android.Manifest.permission.DELETE_PACKAGES, null); 17030 Preconditions.checkNotNull(versionedPackage); 17031 Preconditions.checkNotNull(observer); 17032 Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(), 17033 PackageManager.VERSION_CODE_HIGHEST, 17034 Integer.MAX_VALUE, "versionCode must be >= -1"); 17035 17036 final String packageName = versionedPackage.getPackageName(); 17037 // TODO: We will change version code to long, so in the new API it is long 17038 final int versionCode = (int) versionedPackage.getVersionCode(); 17039 final String internalPackageName; 17040 synchronized (mPackages) { 17041 // Normalize package name to handle renamed packages and static libs 17042 internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(), 17043 // TODO: We will change version code to long, so in the new API it is long 17044 (int) versionedPackage.getVersionCode()); 17045 } 17046 17047 final int uid = Binder.getCallingUid(); 17048 if (!isOrphaned(internalPackageName) 17049 && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) { 17050 try { 17051 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 17052 intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null)); 17053 intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder()); 17054 observer.onUserActionRequired(intent); 17055 } catch (RemoteException re) { 17056 } 17057 return; 17058 } 17059 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 17060 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 17061 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 17062 mContext.enforceCallingOrSelfPermission( 17063 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 17064 "deletePackage for user " + userId); 17065 } 17066 17067 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 17068 try { 17069 observer.onPackageDeleted(packageName, 17070 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 17071 } catch (RemoteException re) { 17072 } 17073 return; 17074 } 17075 17076 if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) { 17077 try { 17078 observer.onPackageDeleted(packageName, 17079 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 17080 } catch (RemoteException re) { 17081 } 17082 return; 17083 } 17084 17085 if (DEBUG_REMOVE) { 17086 Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId 17087 + " deleteAllUsers: " + deleteAllUsers + " version=" 17088 + (versionCode == PackageManager.VERSION_CODE_HIGHEST 17089 ? "VERSION_CODE_HIGHEST" : versionCode)); 17090 } 17091 // Queue up an async operation since the package deletion may take a little while. 17092 mHandler.post(new Runnable() { 17093 public void run() { 17094 mHandler.removeCallbacks(this); 17095 int returnCode; 17096 if (!deleteAllUsers) { 17097 returnCode = deletePackageX(internalPackageName, versionCode, 17098 userId, deleteFlags); 17099 } else { 17100 int[] blockUninstallUserIds = getBlockUninstallForUsers( 17101 internalPackageName, users); 17102 // If nobody is blocking uninstall, proceed with delete for all users 17103 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 17104 returnCode = deletePackageX(internalPackageName, versionCode, 17105 userId, deleteFlags); 17106 } else { 17107 // Otherwise uninstall individually for users with blockUninstalls=false 17108 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 17109 for (int userId : users) { 17110 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 17111 returnCode = deletePackageX(internalPackageName, versionCode, 17112 userId, userFlags); 17113 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 17114 Slog.w(TAG, "Package delete failed for user " + userId 17115 + ", returnCode " + returnCode); 17116 } 17117 } 17118 } 17119 // The app has only been marked uninstalled for certain users. 17120 // We still need to report that delete was blocked 17121 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 17122 } 17123 } 17124 try { 17125 observer.onPackageDeleted(packageName, returnCode, null); 17126 } catch (RemoteException e) { 17127 Log.i(TAG, "Observer no longer exists."); 17128 } //end catch 17129 } //end run 17130 }); 17131 } 17132 17133 private String resolveExternalPackageNameLPr(PackageParser.Package pkg) { 17134 if (pkg.staticSharedLibName != null) { 17135 return pkg.manifestPackageName; 17136 } 17137 return pkg.packageName; 17138 } 17139 17140 private String resolveInternalPackageNameLPr(String packageName, int versionCode) { 17141 // Handle renamed packages 17142 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 17143 packageName = normalizedPackageName != null ? normalizedPackageName : packageName; 17144 17145 // Is this a static library? 17146 SparseArray<SharedLibraryEntry> versionedLib = 17147 mStaticLibsByDeclaringPackage.get(packageName); 17148 if (versionedLib == null || versionedLib.size() <= 0) { 17149 return packageName; 17150 } 17151 17152 // Figure out which lib versions the caller can see 17153 SparseIntArray versionsCallerCanSee = null; 17154 final int callingAppId = UserHandle.getAppId(Binder.getCallingUid()); 17155 if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID 17156 && callingAppId != Process.ROOT_UID) { 17157 versionsCallerCanSee = new SparseIntArray(); 17158 String libName = versionedLib.valueAt(0).info.getName(); 17159 String[] uidPackages = getPackagesForUid(Binder.getCallingUid()); 17160 if (uidPackages != null) { 17161 for (String uidPackage : uidPackages) { 17162 PackageSetting ps = mSettings.getPackageLPr(uidPackage); 17163 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 17164 if (libIdx >= 0) { 17165 final int libVersion = ps.usesStaticLibrariesVersions[libIdx]; 17166 versionsCallerCanSee.append(libVersion, libVersion); 17167 } 17168 } 17169 } 17170 } 17171 17172 // Caller can see nothing - done 17173 if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) { 17174 return packageName; 17175 } 17176 17177 // Find the version the caller can see and the app version code 17178 SharedLibraryEntry highestVersion = null; 17179 final int versionCount = versionedLib.size(); 17180 for (int i = 0; i < versionCount; i++) { 17181 SharedLibraryEntry libEntry = versionedLib.valueAt(i); 17182 if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey( 17183 libEntry.info.getVersion()) < 0) { 17184 continue; 17185 } 17186 // TODO: We will change version code to long, so in the new API it is long 17187 final int libVersionCode = (int) libEntry.info.getDeclaringPackage().getVersionCode(); 17188 if (versionCode != PackageManager.VERSION_CODE_HIGHEST) { 17189 if (libVersionCode == versionCode) { 17190 return libEntry.apk; 17191 } 17192 } else if (highestVersion == null) { 17193 highestVersion = libEntry; 17194 } else if (libVersionCode > highestVersion.info 17195 .getDeclaringPackage().getVersionCode()) { 17196 highestVersion = libEntry; 17197 } 17198 } 17199 17200 if (highestVersion != null) { 17201 return highestVersion.apk; 17202 } 17203 17204 return packageName; 17205 } 17206 17207 private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) { 17208 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID 17209 || callingUid == Process.SYSTEM_UID) { 17210 return true; 17211 } 17212 final int callingUserId = UserHandle.getUserId(callingUid); 17213 // If the caller installed the pkgName, then allow it to silently uninstall. 17214 if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) { 17215 return true; 17216 } 17217 17218 // Allow package verifier to silently uninstall. 17219 if (mRequiredVerifierPackage != null && 17220 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) { 17221 return true; 17222 } 17223 17224 // Allow package uninstaller to silently uninstall. 17225 if (mRequiredUninstallerPackage != null && 17226 callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) { 17227 return true; 17228 } 17229 17230 // Allow storage manager to silently uninstall. 17231 if (mStorageManagerPackage != null && 17232 callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) { 17233 return true; 17234 } 17235 return false; 17236 } 17237 17238 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 17239 int[] result = EMPTY_INT_ARRAY; 17240 for (int userId : userIds) { 17241 if (getBlockUninstallForUser(packageName, userId)) { 17242 result = ArrayUtils.appendInt(result, userId); 17243 } 17244 } 17245 return result; 17246 } 17247 17248 @Override 17249 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 17250 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 17251 } 17252 17253 private boolean isPackageDeviceAdmin(String packageName, int userId) { 17254 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 17255 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 17256 try { 17257 if (dpm != null) { 17258 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 17259 /* callingUserOnly =*/ false); 17260 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 17261 : deviceOwnerComponentName.getPackageName(); 17262 // Does the package contains the device owner? 17263 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 17264 // this check is probably not needed, since DO should be registered as a device 17265 // admin on some user too. (Original bug for this: b/17657954) 17266 if (packageName.equals(deviceOwnerPackageName)) { 17267 return true; 17268 } 17269 // Does it contain a device admin for any user? 17270 int[] users; 17271 if (userId == UserHandle.USER_ALL) { 17272 users = sUserManager.getUserIds(); 17273 } else { 17274 users = new int[]{userId}; 17275 } 17276 for (int i = 0; i < users.length; ++i) { 17277 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 17278 return true; 17279 } 17280 } 17281 } 17282 } catch (RemoteException e) { 17283 } 17284 return false; 17285 } 17286 17287 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 17288 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 17289 } 17290 17291 /** 17292 * This method is an internal method that could be get invoked either 17293 * to delete an installed package or to clean up a failed installation. 17294 * After deleting an installed package, a broadcast is sent to notify any 17295 * listeners that the package has been removed. For cleaning up a failed 17296 * installation, the broadcast is not necessary since the package's 17297 * installation wouldn't have sent the initial broadcast either 17298 * The key steps in deleting a package are 17299 * deleting the package information in internal structures like mPackages, 17300 * deleting the packages base directories through installd 17301 * updating mSettings to reflect current status 17302 * persisting settings for later use 17303 * sending a broadcast if necessary 17304 */ 17305 private int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) { 17306 final PackageRemovedInfo info = new PackageRemovedInfo(); 17307 final boolean res; 17308 17309 final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 17310 ? UserHandle.USER_ALL : userId; 17311 17312 if (isPackageDeviceAdmin(packageName, removeUser)) { 17313 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 17314 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 17315 } 17316 17317 PackageSetting uninstalledPs = null; 17318 17319 // for the uninstall-updates case and restricted profiles, remember the per- 17320 // user handle installed state 17321 int[] allUsers; 17322 synchronized (mPackages) { 17323 uninstalledPs = mSettings.mPackages.get(packageName); 17324 if (uninstalledPs == null) { 17325 Slog.w(TAG, "Not removing non-existent package " + packageName); 17326 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17327 } 17328 17329 if (versionCode != PackageManager.VERSION_CODE_HIGHEST 17330 && uninstalledPs.versionCode != versionCode) { 17331 Slog.w(TAG, "Not removing package " + packageName + " with versionCode " 17332 + uninstalledPs.versionCode + " != " + versionCode); 17333 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17334 } 17335 17336 // Static shared libs can be declared by any package, so let us not 17337 // allow removing a package if it provides a lib others depend on. 17338 PackageParser.Package pkg = mPackages.get(packageName); 17339 if (pkg != null && pkg.staticSharedLibName != null) { 17340 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName, 17341 pkg.staticSharedLibVersion); 17342 if (libEntry != null) { 17343 List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr( 17344 libEntry.info, 0, userId); 17345 if (!ArrayUtils.isEmpty(libClientPackages)) { 17346 Slog.w(TAG, "Not removing package " + pkg.manifestPackageName 17347 + " hosting lib " + libEntry.info.getName() + " version " 17348 + libEntry.info.getVersion() + " used by " + libClientPackages); 17349 return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY; 17350 } 17351 } 17352 } 17353 17354 allUsers = sUserManager.getUserIds(); 17355 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 17356 } 17357 17358 final int freezeUser; 17359 if (isUpdatedSystemApp(uninstalledPs) 17360 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) { 17361 // We're downgrading a system app, which will apply to all users, so 17362 // freeze them all during the downgrade 17363 freezeUser = UserHandle.USER_ALL; 17364 } else { 17365 freezeUser = removeUser; 17366 } 17367 17368 synchronized (mInstallLock) { 17369 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 17370 try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser, 17371 deleteFlags, "deletePackageX")) { 17372 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers, 17373 deleteFlags | REMOVE_CHATTY, info, true, null); 17374 } 17375 synchronized (mPackages) { 17376 if (res) { 17377 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 17378 } 17379 } 17380 } 17381 17382 if (res) { 17383 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 17384 info.sendPackageRemovedBroadcasts(killApp); 17385 info.sendSystemPackageUpdatedBroadcasts(); 17386 info.sendSystemPackageAppearedBroadcasts(); 17387 } 17388 // Force a gc here. 17389 Runtime.getRuntime().gc(); 17390 // Delete the resources here after sending the broadcast to let 17391 // other processes clean up before deleting resources. 17392 if (info.args != null) { 17393 synchronized (mInstallLock) { 17394 info.args.doPostDeleteLI(true); 17395 } 17396 } 17397 17398 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17399 } 17400 17401 class PackageRemovedInfo { 17402 String removedPackage; 17403 int uid = -1; 17404 int removedAppId = -1; 17405 int[] origUsers; 17406 int[] removedUsers = null; 17407 SparseArray<Integer> installReasons; 17408 boolean isRemovedPackageSystemUpdate = false; 17409 boolean isUpdate; 17410 boolean dataRemoved; 17411 boolean removedForAllUsers; 17412 boolean isStaticSharedLib; 17413 // Clean up resources deleted packages. 17414 InstallArgs args = null; 17415 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 17416 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 17417 17418 void sendPackageRemovedBroadcasts(boolean killApp) { 17419 sendPackageRemovedBroadcastInternal(killApp); 17420 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 17421 for (int i = 0; i < childCount; i++) { 17422 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 17423 childInfo.sendPackageRemovedBroadcastInternal(killApp); 17424 } 17425 } 17426 17427 void sendSystemPackageUpdatedBroadcasts() { 17428 if (isRemovedPackageSystemUpdate) { 17429 sendSystemPackageUpdatedBroadcastsInternal(); 17430 final int childCount = (removedChildPackages != null) 17431 ? removedChildPackages.size() : 0; 17432 for (int i = 0; i < childCount; i++) { 17433 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 17434 if (childInfo.isRemovedPackageSystemUpdate) { 17435 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 17436 } 17437 } 17438 } 17439 } 17440 17441 void sendSystemPackageAppearedBroadcasts() { 17442 final int packageCount = (appearedChildPackages != null) 17443 ? appearedChildPackages.size() : 0; 17444 for (int i = 0; i < packageCount; i++) { 17445 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 17446 sendPackageAddedForNewUsers(installedInfo.name, true, 17447 UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers); 17448 } 17449 } 17450 17451 private void sendSystemPackageUpdatedBroadcastsInternal() { 17452 Bundle extras = new Bundle(2); 17453 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 17454 extras.putBoolean(Intent.EXTRA_REPLACING, true); 17455 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 17456 extras, 0, null, null, null); 17457 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 17458 extras, 0, null, null, null); 17459 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 17460 null, 0, removedPackage, null, null); 17461 } 17462 17463 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 17464 // Don't send static shared library removal broadcasts as these 17465 // libs are visible only the the apps that depend on them an one 17466 // cannot remove the library if it has a dependency. 17467 if (isStaticSharedLib) { 17468 return; 17469 } 17470 Bundle extras = new Bundle(2); 17471 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 17472 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 17473 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 17474 if (isUpdate || isRemovedPackageSystemUpdate) { 17475 extras.putBoolean(Intent.EXTRA_REPLACING, true); 17476 } 17477 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 17478 if (removedPackage != null) { 17479 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 17480 extras, 0, null, null, removedUsers); 17481 if (dataRemoved && !isRemovedPackageSystemUpdate) { 17482 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 17483 removedPackage, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, 17484 null, null, removedUsers); 17485 } 17486 } 17487 if (removedAppId >= 0) { 17488 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 17489 removedUsers); 17490 } 17491 } 17492 } 17493 17494 /* 17495 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 17496 * flag is not set, the data directory is removed as well. 17497 * make sure this flag is set for partially installed apps. If not its meaningless to 17498 * delete a partially installed application. 17499 */ 17500 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 17501 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 17502 String packageName = ps.name; 17503 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 17504 // Retrieve object to delete permissions for shared user later on 17505 final PackageParser.Package deletedPkg; 17506 final PackageSetting deletedPs; 17507 // reader 17508 synchronized (mPackages) { 17509 deletedPkg = mPackages.get(packageName); 17510 deletedPs = mSettings.mPackages.get(packageName); 17511 if (outInfo != null) { 17512 outInfo.removedPackage = packageName; 17513 outInfo.isStaticSharedLib = deletedPkg != null 17514 && deletedPkg.staticSharedLibName != null; 17515 outInfo.removedUsers = deletedPs != null 17516 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 17517 : null; 17518 } 17519 } 17520 17521 removePackageLI(ps, (flags & REMOVE_CHATTY) != 0); 17522 17523 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 17524 final PackageParser.Package resolvedPkg; 17525 if (deletedPkg != null) { 17526 resolvedPkg = deletedPkg; 17527 } else { 17528 // We don't have a parsed package when it lives on an ejected 17529 // adopted storage device, so fake something together 17530 resolvedPkg = new PackageParser.Package(ps.name); 17531 resolvedPkg.setVolumeUuid(ps.volumeUuid); 17532 } 17533 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 17534 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 17535 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 17536 if (outInfo != null) { 17537 outInfo.dataRemoved = true; 17538 } 17539 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 17540 } 17541 17542 int removedAppId = -1; 17543 17544 // writer 17545 synchronized (mPackages) { 17546 if (deletedPs != null) { 17547 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 17548 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 17549 clearDefaultBrowserIfNeeded(packageName); 17550 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 17551 removedAppId = mSettings.removePackageLPw(packageName); 17552 if (outInfo != null) { 17553 outInfo.removedAppId = removedAppId; 17554 } 17555 updatePermissionsLPw(deletedPs.name, null, 0); 17556 if (deletedPs.sharedUser != null) { 17557 // Remove permissions associated with package. Since runtime 17558 // permissions are per user we have to kill the removed package 17559 // or packages running under the shared user of the removed 17560 // package if revoking the permissions requested only by the removed 17561 // package is successful and this causes a change in gids. 17562 for (int userId : UserManagerService.getInstance().getUserIds()) { 17563 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 17564 userId); 17565 if (userIdToKill == UserHandle.USER_ALL 17566 || userIdToKill >= UserHandle.USER_SYSTEM) { 17567 // If gids changed for this user, kill all affected packages. 17568 mHandler.post(new Runnable() { 17569 @Override 17570 public void run() { 17571 // This has to happen with no lock held. 17572 killApplication(deletedPs.name, deletedPs.appId, 17573 KILL_APP_REASON_GIDS_CHANGED); 17574 } 17575 }); 17576 break; 17577 } 17578 } 17579 } 17580 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 17581 } 17582 // make sure to preserve per-user disabled state if this removal was just 17583 // a downgrade of a system app to the factory package 17584 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 17585 if (DEBUG_REMOVE) { 17586 Slog.d(TAG, "Propagating install state across downgrade"); 17587 } 17588 for (int userId : allUserHandles) { 17589 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 17590 if (DEBUG_REMOVE) { 17591 Slog.d(TAG, " user " + userId + " => " + installed); 17592 } 17593 ps.setInstalled(installed, userId); 17594 } 17595 } 17596 } 17597 // can downgrade to reader 17598 if (writeSettings) { 17599 // Save settings now 17600 mSettings.writeLPr(); 17601 } 17602 } 17603 if (removedAppId != -1) { 17604 // A user ID was deleted here. Go through all users and remove it 17605 // from KeyStore. 17606 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId); 17607 } 17608 } 17609 17610 static boolean locationIsPrivileged(File path) { 17611 try { 17612 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 17613 .getCanonicalPath(); 17614 return path.getCanonicalPath().startsWith(privilegedAppDir); 17615 } catch (IOException e) { 17616 Slog.e(TAG, "Unable to access code path " + path); 17617 } 17618 return false; 17619 } 17620 17621 /* 17622 * Tries to delete system package. 17623 */ 17624 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 17625 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 17626 boolean writeSettings) { 17627 if (deletedPs.parentPackageName != null) { 17628 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 17629 return false; 17630 } 17631 17632 final boolean applyUserRestrictions 17633 = (allUserHandles != null) && (outInfo.origUsers != null); 17634 final PackageSetting disabledPs; 17635 // Confirm if the system package has been updated 17636 // An updated system app can be deleted. This will also have to restore 17637 // the system pkg from system partition 17638 // reader 17639 synchronized (mPackages) { 17640 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 17641 } 17642 17643 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 17644 + " disabledPs=" + disabledPs); 17645 17646 if (disabledPs == null) { 17647 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 17648 return false; 17649 } else if (DEBUG_REMOVE) { 17650 Slog.d(TAG, "Deleting system pkg from data partition"); 17651 } 17652 17653 if (DEBUG_REMOVE) { 17654 if (applyUserRestrictions) { 17655 Slog.d(TAG, "Remembering install states:"); 17656 for (int userId : allUserHandles) { 17657 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 17658 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 17659 } 17660 } 17661 } 17662 17663 // Delete the updated package 17664 outInfo.isRemovedPackageSystemUpdate = true; 17665 if (outInfo.removedChildPackages != null) { 17666 final int childCount = (deletedPs.childPackageNames != null) 17667 ? deletedPs.childPackageNames.size() : 0; 17668 for (int i = 0; i < childCount; i++) { 17669 String childPackageName = deletedPs.childPackageNames.get(i); 17670 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 17671 .contains(childPackageName)) { 17672 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 17673 childPackageName); 17674 if (childInfo != null) { 17675 childInfo.isRemovedPackageSystemUpdate = true; 17676 } 17677 } 17678 } 17679 } 17680 17681 if (disabledPs.versionCode < deletedPs.versionCode) { 17682 // Delete data for downgrades 17683 flags &= ~PackageManager.DELETE_KEEP_DATA; 17684 } else { 17685 // Preserve data by setting flag 17686 flags |= PackageManager.DELETE_KEEP_DATA; 17687 } 17688 17689 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 17690 outInfo, writeSettings, disabledPs.pkg); 17691 if (!ret) { 17692 return false; 17693 } 17694 17695 // writer 17696 synchronized (mPackages) { 17697 // Reinstate the old system package 17698 enableSystemPackageLPw(disabledPs.pkg); 17699 // Remove any native libraries from the upgraded package. 17700 removeNativeBinariesLI(deletedPs); 17701 } 17702 17703 // Install the system package 17704 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 17705 int parseFlags = mDefParseFlags 17706 | PackageParser.PARSE_MUST_BE_APK 17707 | PackageParser.PARSE_IS_SYSTEM 17708 | PackageParser.PARSE_IS_SYSTEM_DIR; 17709 if (locationIsPrivileged(disabledPs.codePath)) { 17710 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 17711 } 17712 17713 final PackageParser.Package newPkg; 17714 try { 17715 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */, 17716 0 /* currentTime */, null); 17717 } catch (PackageManagerException e) { 17718 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 17719 + e.getMessage()); 17720 return false; 17721 } 17722 17723 try { 17724 // update shared libraries for the newly re-installed system package 17725 updateSharedLibrariesLPr(newPkg, null); 17726 } catch (PackageManagerException e) { 17727 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 17728 } 17729 17730 prepareAppDataAfterInstallLIF(newPkg); 17731 17732 // writer 17733 synchronized (mPackages) { 17734 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 17735 17736 // Propagate the permissions state as we do not want to drop on the floor 17737 // runtime permissions. The update permissions method below will take 17738 // care of removing obsolete permissions and grant install permissions. 17739 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 17740 updatePermissionsLPw(newPkg.packageName, newPkg, 17741 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 17742 17743 if (applyUserRestrictions) { 17744 if (DEBUG_REMOVE) { 17745 Slog.d(TAG, "Propagating install state across reinstall"); 17746 } 17747 for (int userId : allUserHandles) { 17748 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 17749 if (DEBUG_REMOVE) { 17750 Slog.d(TAG, " user " + userId + " => " + installed); 17751 } 17752 ps.setInstalled(installed, userId); 17753 17754 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 17755 } 17756 // Regardless of writeSettings we need to ensure that this restriction 17757 // state propagation is persisted 17758 mSettings.writeAllUsersPackageRestrictionsLPr(); 17759 } 17760 // can downgrade to reader here 17761 if (writeSettings) { 17762 mSettings.writeLPr(); 17763 } 17764 } 17765 return true; 17766 } 17767 17768 private boolean deleteInstalledPackageLIF(PackageSetting ps, 17769 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 17770 PackageRemovedInfo outInfo, boolean writeSettings, 17771 PackageParser.Package replacingPackage) { 17772 synchronized (mPackages) { 17773 if (outInfo != null) { 17774 outInfo.uid = ps.appId; 17775 } 17776 17777 if (outInfo != null && outInfo.removedChildPackages != null) { 17778 final int childCount = (ps.childPackageNames != null) 17779 ? ps.childPackageNames.size() : 0; 17780 for (int i = 0; i < childCount; i++) { 17781 String childPackageName = ps.childPackageNames.get(i); 17782 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 17783 if (childPs == null) { 17784 return false; 17785 } 17786 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 17787 childPackageName); 17788 if (childInfo != null) { 17789 childInfo.uid = childPs.appId; 17790 } 17791 } 17792 } 17793 } 17794 17795 // Delete package data from internal structures and also remove data if flag is set 17796 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 17797 17798 // Delete the child packages data 17799 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 17800 for (int i = 0; i < childCount; i++) { 17801 PackageSetting childPs; 17802 synchronized (mPackages) { 17803 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 17804 } 17805 if (childPs != null) { 17806 PackageRemovedInfo childOutInfo = (outInfo != null 17807 && outInfo.removedChildPackages != null) 17808 ? outInfo.removedChildPackages.get(childPs.name) : null; 17809 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 17810 && (replacingPackage != null 17811 && !replacingPackage.hasChildPackage(childPs.name)) 17812 ? flags & ~DELETE_KEEP_DATA : flags; 17813 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 17814 deleteFlags, writeSettings); 17815 } 17816 } 17817 17818 // Delete application code and resources only for parent packages 17819 if (ps.parentPackageName == null) { 17820 if (deleteCodeAndResources && (outInfo != null)) { 17821 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 17822 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 17823 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 17824 } 17825 } 17826 17827 return true; 17828 } 17829 17830 @Override 17831 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 17832 int userId) { 17833 mContext.enforceCallingOrSelfPermission( 17834 android.Manifest.permission.DELETE_PACKAGES, null); 17835 synchronized (mPackages) { 17836 PackageSetting ps = mSettings.mPackages.get(packageName); 17837 if (ps == null) { 17838 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 17839 return false; 17840 } 17841 // Cannot block uninstall of static shared libs as they are 17842 // considered a part of the using app (emulating static linking). 17843 // Also static libs are installed always on internal storage. 17844 PackageParser.Package pkg = mPackages.get(packageName); 17845 if (pkg != null && pkg.staticSharedLibName != null) { 17846 Slog.w(TAG, "Cannot block uninstall of package: " + packageName 17847 + " providing static shared library: " + pkg.staticSharedLibName); 17848 return false; 17849 } 17850 if (!ps.getInstalled(userId)) { 17851 // Can't block uninstall for an app that is not installed or enabled. 17852 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 17853 return false; 17854 } 17855 ps.setBlockUninstall(blockUninstall, userId); 17856 mSettings.writePackageRestrictionsLPr(userId); 17857 } 17858 return true; 17859 } 17860 17861 @Override 17862 public boolean getBlockUninstallForUser(String packageName, int userId) { 17863 synchronized (mPackages) { 17864 PackageSetting ps = mSettings.mPackages.get(packageName); 17865 if (ps == null) { 17866 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 17867 return false; 17868 } 17869 return ps.getBlockUninstall(userId); 17870 } 17871 } 17872 17873 @Override 17874 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 17875 int callingUid = Binder.getCallingUid(); 17876 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 17877 throw new SecurityException( 17878 "setRequiredForSystemUser can only be run by the system or root"); 17879 } 17880 synchronized (mPackages) { 17881 PackageSetting ps = mSettings.mPackages.get(packageName); 17882 if (ps == null) { 17883 Log.w(TAG, "Package doesn't exist: " + packageName); 17884 return false; 17885 } 17886 if (systemUserApp) { 17887 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 17888 } else { 17889 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 17890 } 17891 mSettings.writeLPr(); 17892 } 17893 return true; 17894 } 17895 17896 /* 17897 * This method handles package deletion in general 17898 */ 17899 private boolean deletePackageLIF(String packageName, UserHandle user, 17900 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 17901 PackageRemovedInfo outInfo, boolean writeSettings, 17902 PackageParser.Package replacingPackage) { 17903 if (packageName == null) { 17904 Slog.w(TAG, "Attempt to delete null packageName."); 17905 return false; 17906 } 17907 17908 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 17909 17910 PackageSetting ps; 17911 synchronized (mPackages) { 17912 ps = mSettings.mPackages.get(packageName); 17913 if (ps == null) { 17914 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 17915 return false; 17916 } 17917 17918 if (ps.parentPackageName != null && (!isSystemApp(ps) 17919 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 17920 if (DEBUG_REMOVE) { 17921 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 17922 + ((user == null) ? UserHandle.USER_ALL : user)); 17923 } 17924 final int removedUserId = (user != null) ? user.getIdentifier() 17925 : UserHandle.USER_ALL; 17926 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 17927 return false; 17928 } 17929 markPackageUninstalledForUserLPw(ps, user); 17930 scheduleWritePackageRestrictionsLocked(user); 17931 return true; 17932 } 17933 } 17934 17935 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 17936 && user.getIdentifier() != UserHandle.USER_ALL)) { 17937 // The caller is asking that the package only be deleted for a single 17938 // user. To do this, we just mark its uninstalled state and delete 17939 // its data. If this is a system app, we only allow this to happen if 17940 // they have set the special DELETE_SYSTEM_APP which requests different 17941 // semantics than normal for uninstalling system apps. 17942 markPackageUninstalledForUserLPw(ps, user); 17943 17944 if (!isSystemApp(ps)) { 17945 // Do not uninstall the APK if an app should be cached 17946 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 17947 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 17948 // Other user still have this package installed, so all 17949 // we need to do is clear this user's data and save that 17950 // it is uninstalled. 17951 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 17952 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 17953 return false; 17954 } 17955 scheduleWritePackageRestrictionsLocked(user); 17956 return true; 17957 } else { 17958 // We need to set it back to 'installed' so the uninstall 17959 // broadcasts will be sent correctly. 17960 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 17961 ps.setInstalled(true, user.getIdentifier()); 17962 } 17963 } else { 17964 // This is a system app, so we assume that the 17965 // other users still have this package installed, so all 17966 // we need to do is clear this user's data and save that 17967 // it is uninstalled. 17968 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 17969 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 17970 return false; 17971 } 17972 scheduleWritePackageRestrictionsLocked(user); 17973 return true; 17974 } 17975 } 17976 17977 // If we are deleting a composite package for all users, keep track 17978 // of result for each child. 17979 if (ps.childPackageNames != null && outInfo != null) { 17980 synchronized (mPackages) { 17981 final int childCount = ps.childPackageNames.size(); 17982 outInfo.removedChildPackages = new ArrayMap<>(childCount); 17983 for (int i = 0; i < childCount; i++) { 17984 String childPackageName = ps.childPackageNames.get(i); 17985 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 17986 childInfo.removedPackage = childPackageName; 17987 outInfo.removedChildPackages.put(childPackageName, childInfo); 17988 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 17989 if (childPs != null) { 17990 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 17991 } 17992 } 17993 } 17994 } 17995 17996 boolean ret = false; 17997 if (isSystemApp(ps)) { 17998 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 17999 // When an updated system application is deleted we delete the existing resources 18000 // as well and fall back to existing code in system partition 18001 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 18002 } else { 18003 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 18004 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 18005 outInfo, writeSettings, replacingPackage); 18006 } 18007 18008 // Take a note whether we deleted the package for all users 18009 if (outInfo != null) { 18010 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 18011 if (outInfo.removedChildPackages != null) { 18012 synchronized (mPackages) { 18013 final int childCount = outInfo.removedChildPackages.size(); 18014 for (int i = 0; i < childCount; i++) { 18015 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 18016 if (childInfo != null) { 18017 childInfo.removedForAllUsers = mPackages.get( 18018 childInfo.removedPackage) == null; 18019 } 18020 } 18021 } 18022 } 18023 // If we uninstalled an update to a system app there may be some 18024 // child packages that appeared as they are declared in the system 18025 // app but were not declared in the update. 18026 if (isSystemApp(ps)) { 18027 synchronized (mPackages) { 18028 PackageSetting updatedPs = mSettings.getPackageLPr(ps.name); 18029 final int childCount = (updatedPs.childPackageNames != null) 18030 ? updatedPs.childPackageNames.size() : 0; 18031 for (int i = 0; i < childCount; i++) { 18032 String childPackageName = updatedPs.childPackageNames.get(i); 18033 if (outInfo.removedChildPackages == null 18034 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 18035 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 18036 if (childPs == null) { 18037 continue; 18038 } 18039 PackageInstalledInfo installRes = new PackageInstalledInfo(); 18040 installRes.name = childPackageName; 18041 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 18042 installRes.pkg = mPackages.get(childPackageName); 18043 installRes.uid = childPs.pkg.applicationInfo.uid; 18044 if (outInfo.appearedChildPackages == null) { 18045 outInfo.appearedChildPackages = new ArrayMap<>(); 18046 } 18047 outInfo.appearedChildPackages.put(childPackageName, installRes); 18048 } 18049 } 18050 } 18051 } 18052 } 18053 18054 return ret; 18055 } 18056 18057 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 18058 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 18059 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 18060 for (int nextUserId : userIds) { 18061 if (DEBUG_REMOVE) { 18062 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 18063 } 18064 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 18065 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 18066 false /*hidden*/, false /*suspended*/, null, null, null, 18067 false /*blockUninstall*/, 18068 ps.readUserState(nextUserId).domainVerificationStatus, 0, 18069 PackageManager.INSTALL_REASON_UNKNOWN); 18070 } 18071 } 18072 18073 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 18074 PackageRemovedInfo outInfo) { 18075 final PackageParser.Package pkg; 18076 synchronized (mPackages) { 18077 pkg = mPackages.get(ps.name); 18078 } 18079 18080 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 18081 : new int[] {userId}; 18082 for (int nextUserId : userIds) { 18083 if (DEBUG_REMOVE) { 18084 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 18085 + nextUserId); 18086 } 18087 18088 destroyAppDataLIF(pkg, userId, 18089 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18090 destroyAppProfilesLIF(pkg, userId); 18091 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 18092 schedulePackageCleaning(ps.name, nextUserId, false); 18093 synchronized (mPackages) { 18094 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 18095 scheduleWritePackageRestrictionsLocked(nextUserId); 18096 } 18097 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 18098 } 18099 } 18100 18101 if (outInfo != null) { 18102 outInfo.removedPackage = ps.name; 18103 outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null; 18104 outInfo.removedAppId = ps.appId; 18105 outInfo.removedUsers = userIds; 18106 } 18107 18108 return true; 18109 } 18110 18111 private final class ClearStorageConnection implements ServiceConnection { 18112 IMediaContainerService mContainerService; 18113 18114 @Override 18115 public void onServiceConnected(ComponentName name, IBinder service) { 18116 synchronized (this) { 18117 mContainerService = IMediaContainerService.Stub 18118 .asInterface(Binder.allowBlocking(service)); 18119 notifyAll(); 18120 } 18121 } 18122 18123 @Override 18124 public void onServiceDisconnected(ComponentName name) { 18125 } 18126 } 18127 18128 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 18129 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 18130 18131 final boolean mounted; 18132 if (Environment.isExternalStorageEmulated()) { 18133 mounted = true; 18134 } else { 18135 final String status = Environment.getExternalStorageState(); 18136 18137 mounted = status.equals(Environment.MEDIA_MOUNTED) 18138 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 18139 } 18140 18141 if (!mounted) { 18142 return; 18143 } 18144 18145 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 18146 int[] users; 18147 if (userId == UserHandle.USER_ALL) { 18148 users = sUserManager.getUserIds(); 18149 } else { 18150 users = new int[] { userId }; 18151 } 18152 final ClearStorageConnection conn = new ClearStorageConnection(); 18153 if (mContext.bindServiceAsUser( 18154 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 18155 try { 18156 for (int curUser : users) { 18157 long timeout = SystemClock.uptimeMillis() + 5000; 18158 synchronized (conn) { 18159 long now; 18160 while (conn.mContainerService == null && 18161 (now = SystemClock.uptimeMillis()) < timeout) { 18162 try { 18163 conn.wait(timeout - now); 18164 } catch (InterruptedException e) { 18165 } 18166 } 18167 } 18168 if (conn.mContainerService == null) { 18169 return; 18170 } 18171 18172 final UserEnvironment userEnv = new UserEnvironment(curUser); 18173 clearDirectory(conn.mContainerService, 18174 userEnv.buildExternalStorageAppCacheDirs(packageName)); 18175 if (allData) { 18176 clearDirectory(conn.mContainerService, 18177 userEnv.buildExternalStorageAppDataDirs(packageName)); 18178 clearDirectory(conn.mContainerService, 18179 userEnv.buildExternalStorageAppMediaDirs(packageName)); 18180 } 18181 } 18182 } finally { 18183 mContext.unbindService(conn); 18184 } 18185 } 18186 } 18187 18188 @Override 18189 public void clearApplicationProfileData(String packageName) { 18190 enforceSystemOrRoot("Only the system can clear all profile data"); 18191 18192 final PackageParser.Package pkg; 18193 synchronized (mPackages) { 18194 pkg = mPackages.get(packageName); 18195 } 18196 18197 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 18198 synchronized (mInstallLock) { 18199 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 18200 destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL, 18201 true /* removeBaseMarker */); 18202 } 18203 } 18204 } 18205 18206 @Override 18207 public void clearApplicationUserData(final String packageName, 18208 final IPackageDataObserver observer, final int userId) { 18209 mContext.enforceCallingOrSelfPermission( 18210 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 18211 18212 enforceCrossUserPermission(Binder.getCallingUid(), userId, 18213 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 18214 18215 if (mProtectedPackages.isPackageDataProtected(userId, packageName)) { 18216 throw new SecurityException("Cannot clear data for a protected package: " 18217 + packageName); 18218 } 18219 // Queue up an async operation since the package deletion may take a little while. 18220 mHandler.post(new Runnable() { 18221 public void run() { 18222 mHandler.removeCallbacks(this); 18223 final boolean succeeded; 18224 try (PackageFreezer freezer = freezePackage(packageName, 18225 "clearApplicationUserData")) { 18226 synchronized (mInstallLock) { 18227 succeeded = clearApplicationUserDataLIF(packageName, userId); 18228 } 18229 clearExternalStorageDataSync(packageName, userId, true); 18230 } 18231 if (succeeded) { 18232 // invoke DeviceStorageMonitor's update method to clear any notifications 18233 DeviceStorageMonitorInternal dsm = LocalServices 18234 .getService(DeviceStorageMonitorInternal.class); 18235 if (dsm != null) { 18236 dsm.checkMemory(); 18237 } 18238 } 18239 if(observer != null) { 18240 try { 18241 observer.onRemoveCompleted(packageName, succeeded); 18242 } catch (RemoteException e) { 18243 Log.i(TAG, "Observer no longer exists."); 18244 } 18245 } //end if observer 18246 } //end run 18247 }); 18248 } 18249 18250 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 18251 if (packageName == null) { 18252 Slog.w(TAG, "Attempt to delete null packageName."); 18253 return false; 18254 } 18255 18256 // Try finding details about the requested package 18257 PackageParser.Package pkg; 18258 synchronized (mPackages) { 18259 pkg = mPackages.get(packageName); 18260 if (pkg == null) { 18261 final PackageSetting ps = mSettings.mPackages.get(packageName); 18262 if (ps != null) { 18263 pkg = ps.pkg; 18264 } 18265 } 18266 18267 if (pkg == null) { 18268 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 18269 return false; 18270 } 18271 18272 PackageSetting ps = (PackageSetting) pkg.mExtras; 18273 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 18274 } 18275 18276 clearAppDataLIF(pkg, userId, 18277 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18278 18279 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 18280 removeKeystoreDataIfNeeded(userId, appId); 18281 18282 UserManagerInternal umInternal = getUserManagerInternal(); 18283 final int flags; 18284 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 18285 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18286 } else if (umInternal.isUserRunning(userId)) { 18287 flags = StorageManager.FLAG_STORAGE_DE; 18288 } else { 18289 flags = 0; 18290 } 18291 prepareAppDataContentsLIF(pkg, userId, flags); 18292 18293 return true; 18294 } 18295 18296 /** 18297 * Reverts user permission state changes (permissions and flags) in 18298 * all packages for a given user. 18299 * 18300 * @param userId The device user for which to do a reset. 18301 */ 18302 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 18303 final int packageCount = mPackages.size(); 18304 for (int i = 0; i < packageCount; i++) { 18305 PackageParser.Package pkg = mPackages.valueAt(i); 18306 PackageSetting ps = (PackageSetting) pkg.mExtras; 18307 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 18308 } 18309 } 18310 18311 private void resetNetworkPolicies(int userId) { 18312 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 18313 } 18314 18315 /** 18316 * Reverts user permission state changes (permissions and flags). 18317 * 18318 * @param ps The package for which to reset. 18319 * @param userId The device user for which to do a reset. 18320 */ 18321 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 18322 final PackageSetting ps, final int userId) { 18323 if (ps.pkg == null) { 18324 return; 18325 } 18326 18327 // These are flags that can change base on user actions. 18328 final int userSettableMask = FLAG_PERMISSION_USER_SET 18329 | FLAG_PERMISSION_USER_FIXED 18330 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 18331 | FLAG_PERMISSION_REVIEW_REQUIRED; 18332 18333 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 18334 | FLAG_PERMISSION_POLICY_FIXED; 18335 18336 boolean writeInstallPermissions = false; 18337 boolean writeRuntimePermissions = false; 18338 18339 final int permissionCount = ps.pkg.requestedPermissions.size(); 18340 for (int i = 0; i < permissionCount; i++) { 18341 String permission = ps.pkg.requestedPermissions.get(i); 18342 18343 BasePermission bp = mSettings.mPermissions.get(permission); 18344 if (bp == null) { 18345 continue; 18346 } 18347 18348 // If shared user we just reset the state to which only this app contributed. 18349 if (ps.sharedUser != null) { 18350 boolean used = false; 18351 final int packageCount = ps.sharedUser.packages.size(); 18352 for (int j = 0; j < packageCount; j++) { 18353 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 18354 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 18355 && pkg.pkg.requestedPermissions.contains(permission)) { 18356 used = true; 18357 break; 18358 } 18359 } 18360 if (used) { 18361 continue; 18362 } 18363 } 18364 18365 PermissionsState permissionsState = ps.getPermissionsState(); 18366 18367 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 18368 18369 // Always clear the user settable flags. 18370 final boolean hasInstallState = permissionsState.getInstallPermissionState( 18371 bp.name) != null; 18372 // If permission review is enabled and this is a legacy app, mark the 18373 // permission as requiring a review as this is the initial state. 18374 int flags = 0; 18375 if (mPermissionReviewRequired 18376 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 18377 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 18378 } 18379 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 18380 if (hasInstallState) { 18381 writeInstallPermissions = true; 18382 } else { 18383 writeRuntimePermissions = true; 18384 } 18385 } 18386 18387 // Below is only runtime permission handling. 18388 if (!bp.isRuntime()) { 18389 continue; 18390 } 18391 18392 // Never clobber system or policy. 18393 if ((oldFlags & policyOrSystemFlags) != 0) { 18394 continue; 18395 } 18396 18397 // If this permission was granted by default, make sure it is. 18398 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 18399 if (permissionsState.grantRuntimePermission(bp, userId) 18400 != PERMISSION_OPERATION_FAILURE) { 18401 writeRuntimePermissions = true; 18402 } 18403 // If permission review is enabled the permissions for a legacy apps 18404 // are represented as constantly granted runtime ones, so don't revoke. 18405 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 18406 // Otherwise, reset the permission. 18407 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 18408 switch (revokeResult) { 18409 case PERMISSION_OPERATION_SUCCESS: 18410 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 18411 writeRuntimePermissions = true; 18412 final int appId = ps.appId; 18413 mHandler.post(new Runnable() { 18414 @Override 18415 public void run() { 18416 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 18417 } 18418 }); 18419 } break; 18420 } 18421 } 18422 } 18423 18424 // Synchronously write as we are taking permissions away. 18425 if (writeRuntimePermissions) { 18426 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 18427 } 18428 18429 // Synchronously write as we are taking permissions away. 18430 if (writeInstallPermissions) { 18431 mSettings.writeLPr(); 18432 } 18433 } 18434 18435 /** 18436 * Remove entries from the keystore daemon. Will only remove it if the 18437 * {@code appId} is valid. 18438 */ 18439 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 18440 if (appId < 0) { 18441 return; 18442 } 18443 18444 final KeyStore keyStore = KeyStore.getInstance(); 18445 if (keyStore != null) { 18446 if (userId == UserHandle.USER_ALL) { 18447 for (final int individual : sUserManager.getUserIds()) { 18448 keyStore.clearUid(UserHandle.getUid(individual, appId)); 18449 } 18450 } else { 18451 keyStore.clearUid(UserHandle.getUid(userId, appId)); 18452 } 18453 } else { 18454 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 18455 } 18456 } 18457 18458 @Override 18459 public void deleteApplicationCacheFiles(final String packageName, 18460 final IPackageDataObserver observer) { 18461 final int userId = UserHandle.getCallingUserId(); 18462 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 18463 } 18464 18465 @Override 18466 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 18467 final IPackageDataObserver observer) { 18468 mContext.enforceCallingOrSelfPermission( 18469 android.Manifest.permission.DELETE_CACHE_FILES, null); 18470 enforceCrossUserPermission(Binder.getCallingUid(), userId, 18471 /* requireFullPermission= */ true, /* checkShell= */ false, 18472 "delete application cache files"); 18473 18474 final PackageParser.Package pkg; 18475 synchronized (mPackages) { 18476 pkg = mPackages.get(packageName); 18477 } 18478 18479 // Queue up an async operation since the package deletion may take a little while. 18480 mHandler.post(new Runnable() { 18481 public void run() { 18482 synchronized (mInstallLock) { 18483 final int flags = StorageManager.FLAG_STORAGE_DE 18484 | StorageManager.FLAG_STORAGE_CE; 18485 // We're only clearing cache files, so we don't care if the 18486 // app is unfrozen and still able to run 18487 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 18488 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 18489 } 18490 clearExternalStorageDataSync(packageName, userId, false); 18491 if (observer != null) { 18492 try { 18493 observer.onRemoveCompleted(packageName, true); 18494 } catch (RemoteException e) { 18495 Log.i(TAG, "Observer no longer exists."); 18496 } 18497 } 18498 } 18499 }); 18500 } 18501 18502 @Override 18503 public void getPackageSizeInfo(final String packageName, int userHandle, 18504 final IPackageStatsObserver observer) { 18505 mContext.enforceCallingOrSelfPermission( 18506 android.Manifest.permission.GET_PACKAGE_SIZE, null); 18507 if (packageName == null) { 18508 throw new IllegalArgumentException("Attempt to get size of null packageName"); 18509 } 18510 18511 PackageStats stats = new PackageStats(packageName, userHandle); 18512 18513 /* 18514 * Queue up an async operation since the package measurement may take a 18515 * little while. 18516 */ 18517 Message msg = mHandler.obtainMessage(INIT_COPY); 18518 msg.obj = new MeasureParams(stats, observer); 18519 mHandler.sendMessage(msg); 18520 } 18521 18522 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 18523 final PackageSetting ps; 18524 synchronized (mPackages) { 18525 ps = mSettings.mPackages.get(packageName); 18526 if (ps == null) { 18527 Slog.w(TAG, "Failed to find settings for " + packageName); 18528 return false; 18529 } 18530 } 18531 18532 final String[] packageNames = { packageName }; 18533 final long[] ceDataInodes = { ps.getCeDataInode(userId) }; 18534 final String[] codePaths = { ps.codePathString }; 18535 18536 try { 18537 mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0, 18538 ps.appId, ceDataInodes, codePaths, stats); 18539 18540 // For now, ignore code size of packages on system partition 18541 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 18542 stats.codeSize = 0; 18543 } 18544 18545 // External clients expect these to be tracked separately 18546 stats.dataSize -= stats.cacheSize; 18547 18548 } catch (InstallerException e) { 18549 Slog.w(TAG, String.valueOf(e)); 18550 return false; 18551 } 18552 18553 return true; 18554 } 18555 18556 private int getUidTargetSdkVersionLockedLPr(int uid) { 18557 Object obj = mSettings.getUserIdLPr(uid); 18558 if (obj instanceof SharedUserSetting) { 18559 final SharedUserSetting sus = (SharedUserSetting) obj; 18560 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 18561 final Iterator<PackageSetting> it = sus.packages.iterator(); 18562 while (it.hasNext()) { 18563 final PackageSetting ps = it.next(); 18564 if (ps.pkg != null) { 18565 int v = ps.pkg.applicationInfo.targetSdkVersion; 18566 if (v < vers) vers = v; 18567 } 18568 } 18569 return vers; 18570 } else if (obj instanceof PackageSetting) { 18571 final PackageSetting ps = (PackageSetting) obj; 18572 if (ps.pkg != null) { 18573 return ps.pkg.applicationInfo.targetSdkVersion; 18574 } 18575 } 18576 return Build.VERSION_CODES.CUR_DEVELOPMENT; 18577 } 18578 18579 @Override 18580 public void addPreferredActivity(IntentFilter filter, int match, 18581 ComponentName[] set, ComponentName activity, int userId) { 18582 addPreferredActivityInternal(filter, match, set, activity, true, userId, 18583 "Adding preferred"); 18584 } 18585 18586 private void addPreferredActivityInternal(IntentFilter filter, int match, 18587 ComponentName[] set, ComponentName activity, boolean always, int userId, 18588 String opname) { 18589 // writer 18590 int callingUid = Binder.getCallingUid(); 18591 enforceCrossUserPermission(callingUid, userId, 18592 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 18593 if (filter.countActions() == 0) { 18594 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 18595 return; 18596 } 18597 synchronized (mPackages) { 18598 if (mContext.checkCallingOrSelfPermission( 18599 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 18600 != PackageManager.PERMISSION_GRANTED) { 18601 if (getUidTargetSdkVersionLockedLPr(callingUid) 18602 < Build.VERSION_CODES.FROYO) { 18603 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 18604 + callingUid); 18605 return; 18606 } 18607 mContext.enforceCallingOrSelfPermission( 18608 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 18609 } 18610 18611 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 18612 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 18613 + userId + ":"); 18614 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18615 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 18616 scheduleWritePackageRestrictionsLocked(userId); 18617 postPreferredActivityChangedBroadcast(userId); 18618 } 18619 } 18620 18621 private void postPreferredActivityChangedBroadcast(int userId) { 18622 mHandler.post(() -> { 18623 final IActivityManager am = ActivityManager.getService(); 18624 if (am == null) { 18625 return; 18626 } 18627 18628 final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED); 18629 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 18630 try { 18631 am.broadcastIntent(null, intent, null, null, 18632 0, null, null, null, android.app.AppOpsManager.OP_NONE, 18633 null, false, false, userId); 18634 } catch (RemoteException e) { 18635 } 18636 }); 18637 } 18638 18639 @Override 18640 public void replacePreferredActivity(IntentFilter filter, int match, 18641 ComponentName[] set, ComponentName activity, int userId) { 18642 if (filter.countActions() != 1) { 18643 throw new IllegalArgumentException( 18644 "replacePreferredActivity expects filter to have only 1 action."); 18645 } 18646 if (filter.countDataAuthorities() != 0 18647 || filter.countDataPaths() != 0 18648 || filter.countDataSchemes() > 1 18649 || filter.countDataTypes() != 0) { 18650 throw new IllegalArgumentException( 18651 "replacePreferredActivity expects filter to have no data authorities, " + 18652 "paths, or types; and at most one scheme."); 18653 } 18654 18655 final int callingUid = Binder.getCallingUid(); 18656 enforceCrossUserPermission(callingUid, userId, 18657 true /* requireFullPermission */, false /* checkShell */, 18658 "replace preferred activity"); 18659 synchronized (mPackages) { 18660 if (mContext.checkCallingOrSelfPermission( 18661 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 18662 != PackageManager.PERMISSION_GRANTED) { 18663 if (getUidTargetSdkVersionLockedLPr(callingUid) 18664 < Build.VERSION_CODES.FROYO) { 18665 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 18666 + Binder.getCallingUid()); 18667 return; 18668 } 18669 mContext.enforceCallingOrSelfPermission( 18670 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 18671 } 18672 18673 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 18674 if (pir != null) { 18675 // Get all of the existing entries that exactly match this filter. 18676 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 18677 if (existing != null && existing.size() == 1) { 18678 PreferredActivity cur = existing.get(0); 18679 if (DEBUG_PREFERRED) { 18680 Slog.i(TAG, "Checking replace of preferred:"); 18681 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18682 if (!cur.mPref.mAlways) { 18683 Slog.i(TAG, " -- CUR; not mAlways!"); 18684 } else { 18685 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 18686 Slog.i(TAG, " -- CUR: mSet=" 18687 + Arrays.toString(cur.mPref.mSetComponents)); 18688 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 18689 Slog.i(TAG, " -- NEW: mMatch=" 18690 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 18691 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 18692 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 18693 } 18694 } 18695 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 18696 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 18697 && cur.mPref.sameSet(set)) { 18698 // Setting the preferred activity to what it happens to be already 18699 if (DEBUG_PREFERRED) { 18700 Slog.i(TAG, "Replacing with same preferred activity " 18701 + cur.mPref.mShortComponent + " for user " 18702 + userId + ":"); 18703 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18704 } 18705 return; 18706 } 18707 } 18708 18709 if (existing != null) { 18710 if (DEBUG_PREFERRED) { 18711 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 18712 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18713 } 18714 for (int i = 0; i < existing.size(); i++) { 18715 PreferredActivity pa = existing.get(i); 18716 if (DEBUG_PREFERRED) { 18717 Slog.i(TAG, "Removing existing preferred activity " 18718 + pa.mPref.mComponent + ":"); 18719 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 18720 } 18721 pir.removeFilter(pa); 18722 } 18723 } 18724 } 18725 addPreferredActivityInternal(filter, match, set, activity, true, userId, 18726 "Replacing preferred"); 18727 } 18728 } 18729 18730 @Override 18731 public void clearPackagePreferredActivities(String packageName) { 18732 final int uid = Binder.getCallingUid(); 18733 // writer 18734 synchronized (mPackages) { 18735 PackageParser.Package pkg = mPackages.get(packageName); 18736 if (pkg == null || pkg.applicationInfo.uid != uid) { 18737 if (mContext.checkCallingOrSelfPermission( 18738 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 18739 != PackageManager.PERMISSION_GRANTED) { 18740 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 18741 < Build.VERSION_CODES.FROYO) { 18742 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 18743 + Binder.getCallingUid()); 18744 return; 18745 } 18746 mContext.enforceCallingOrSelfPermission( 18747 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 18748 } 18749 } 18750 18751 int user = UserHandle.getCallingUserId(); 18752 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 18753 scheduleWritePackageRestrictionsLocked(user); 18754 } 18755 } 18756 } 18757 18758 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 18759 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 18760 ArrayList<PreferredActivity> removed = null; 18761 boolean changed = false; 18762 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18763 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 18764 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18765 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 18766 continue; 18767 } 18768 Iterator<PreferredActivity> it = pir.filterIterator(); 18769 while (it.hasNext()) { 18770 PreferredActivity pa = it.next(); 18771 // Mark entry for removal only if it matches the package name 18772 // and the entry is of type "always". 18773 if (packageName == null || 18774 (pa.mPref.mComponent.getPackageName().equals(packageName) 18775 && pa.mPref.mAlways)) { 18776 if (removed == null) { 18777 removed = new ArrayList<PreferredActivity>(); 18778 } 18779 removed.add(pa); 18780 } 18781 } 18782 if (removed != null) { 18783 for (int j=0; j<removed.size(); j++) { 18784 PreferredActivity pa = removed.get(j); 18785 pir.removeFilter(pa); 18786 } 18787 changed = true; 18788 } 18789 } 18790 if (changed) { 18791 postPreferredActivityChangedBroadcast(userId); 18792 } 18793 return changed; 18794 } 18795 18796 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 18797 private void clearIntentFilterVerificationsLPw(int userId) { 18798 final int packageCount = mPackages.size(); 18799 for (int i = 0; i < packageCount; i++) { 18800 PackageParser.Package pkg = mPackages.valueAt(i); 18801 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 18802 } 18803 } 18804 18805 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 18806 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 18807 if (userId == UserHandle.USER_ALL) { 18808 if (mSettings.removeIntentFilterVerificationLPw(packageName, 18809 sUserManager.getUserIds())) { 18810 for (int oneUserId : sUserManager.getUserIds()) { 18811 scheduleWritePackageRestrictionsLocked(oneUserId); 18812 } 18813 } 18814 } else { 18815 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 18816 scheduleWritePackageRestrictionsLocked(userId); 18817 } 18818 } 18819 } 18820 18821 void clearDefaultBrowserIfNeeded(String packageName) { 18822 for (int oneUserId : sUserManager.getUserIds()) { 18823 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 18824 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 18825 if (packageName.equals(defaultBrowserPackageName)) { 18826 setDefaultBrowserPackageName(null, oneUserId); 18827 } 18828 } 18829 } 18830 18831 @Override 18832 public void resetApplicationPreferences(int userId) { 18833 mContext.enforceCallingOrSelfPermission( 18834 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 18835 final long identity = Binder.clearCallingIdentity(); 18836 // writer 18837 try { 18838 synchronized (mPackages) { 18839 clearPackagePreferredActivitiesLPw(null, userId); 18840 mSettings.applyDefaultPreferredAppsLPw(this, userId); 18841 // TODO: We have to reset the default SMS and Phone. This requires 18842 // significant refactoring to keep all default apps in the package 18843 // manager (cleaner but more work) or have the services provide 18844 // callbacks to the package manager to request a default app reset. 18845 applyFactoryDefaultBrowserLPw(userId); 18846 clearIntentFilterVerificationsLPw(userId); 18847 primeDomainVerificationsLPw(userId); 18848 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 18849 scheduleWritePackageRestrictionsLocked(userId); 18850 } 18851 resetNetworkPolicies(userId); 18852 } finally { 18853 Binder.restoreCallingIdentity(identity); 18854 } 18855 } 18856 18857 @Override 18858 public int getPreferredActivities(List<IntentFilter> outFilters, 18859 List<ComponentName> outActivities, String packageName) { 18860 18861 int num = 0; 18862 final int userId = UserHandle.getCallingUserId(); 18863 // reader 18864 synchronized (mPackages) { 18865 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 18866 if (pir != null) { 18867 final Iterator<PreferredActivity> it = pir.filterIterator(); 18868 while (it.hasNext()) { 18869 final PreferredActivity pa = it.next(); 18870 if (packageName == null 18871 || (pa.mPref.mComponent.getPackageName().equals(packageName) 18872 && pa.mPref.mAlways)) { 18873 if (outFilters != null) { 18874 outFilters.add(new IntentFilter(pa)); 18875 } 18876 if (outActivities != null) { 18877 outActivities.add(pa.mPref.mComponent); 18878 } 18879 } 18880 } 18881 } 18882 } 18883 18884 return num; 18885 } 18886 18887 @Override 18888 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 18889 int userId) { 18890 int callingUid = Binder.getCallingUid(); 18891 if (callingUid != Process.SYSTEM_UID) { 18892 throw new SecurityException( 18893 "addPersistentPreferredActivity can only be run by the system"); 18894 } 18895 if (filter.countActions() == 0) { 18896 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 18897 return; 18898 } 18899 synchronized (mPackages) { 18900 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 18901 ":"); 18902 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18903 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 18904 new PersistentPreferredActivity(filter, activity)); 18905 scheduleWritePackageRestrictionsLocked(userId); 18906 postPreferredActivityChangedBroadcast(userId); 18907 } 18908 } 18909 18910 @Override 18911 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 18912 int callingUid = Binder.getCallingUid(); 18913 if (callingUid != Process.SYSTEM_UID) { 18914 throw new SecurityException( 18915 "clearPackagePersistentPreferredActivities can only be run by the system"); 18916 } 18917 ArrayList<PersistentPreferredActivity> removed = null; 18918 boolean changed = false; 18919 synchronized (mPackages) { 18920 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 18921 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 18922 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 18923 .valueAt(i); 18924 if (userId != thisUserId) { 18925 continue; 18926 } 18927 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 18928 while (it.hasNext()) { 18929 PersistentPreferredActivity ppa = it.next(); 18930 // Mark entry for removal only if it matches the package name. 18931 if (ppa.mComponent.getPackageName().equals(packageName)) { 18932 if (removed == null) { 18933 removed = new ArrayList<PersistentPreferredActivity>(); 18934 } 18935 removed.add(ppa); 18936 } 18937 } 18938 if (removed != null) { 18939 for (int j=0; j<removed.size(); j++) { 18940 PersistentPreferredActivity ppa = removed.get(j); 18941 ppir.removeFilter(ppa); 18942 } 18943 changed = true; 18944 } 18945 } 18946 18947 if (changed) { 18948 scheduleWritePackageRestrictionsLocked(userId); 18949 postPreferredActivityChangedBroadcast(userId); 18950 } 18951 } 18952 } 18953 18954 /** 18955 * Common machinery for picking apart a restored XML blob and passing 18956 * it to a caller-supplied functor to be applied to the running system. 18957 */ 18958 private void restoreFromXml(XmlPullParser parser, int userId, 18959 String expectedStartTag, BlobXmlRestorer functor) 18960 throws IOException, XmlPullParserException { 18961 int type; 18962 while ((type = parser.next()) != XmlPullParser.START_TAG 18963 && type != XmlPullParser.END_DOCUMENT) { 18964 } 18965 if (type != XmlPullParser.START_TAG) { 18966 // oops didn't find a start tag?! 18967 if (DEBUG_BACKUP) { 18968 Slog.e(TAG, "Didn't find start tag during restore"); 18969 } 18970 return; 18971 } 18972Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 18973 // this is supposed to be TAG_PREFERRED_BACKUP 18974 if (!expectedStartTag.equals(parser.getName())) { 18975 if (DEBUG_BACKUP) { 18976 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 18977 } 18978 return; 18979 } 18980 18981 // skip interfering stuff, then we're aligned with the backing implementation 18982 while ((type = parser.next()) == XmlPullParser.TEXT) { } 18983Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 18984 functor.apply(parser, userId); 18985 } 18986 18987 private interface BlobXmlRestorer { 18988 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 18989 } 18990 18991 /** 18992 * Non-Binder method, support for the backup/restore mechanism: write the 18993 * full set of preferred activities in its canonical XML format. Returns the 18994 * XML output as a byte array, or null if there is none. 18995 */ 18996 @Override 18997 public byte[] getPreferredActivityBackup(int userId) { 18998 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 18999 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 19000 } 19001 19002 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19003 try { 19004 final XmlSerializer serializer = new FastXmlSerializer(); 19005 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19006 serializer.startDocument(null, true); 19007 serializer.startTag(null, TAG_PREFERRED_BACKUP); 19008 19009 synchronized (mPackages) { 19010 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 19011 } 19012 19013 serializer.endTag(null, TAG_PREFERRED_BACKUP); 19014 serializer.endDocument(); 19015 serializer.flush(); 19016 } catch (Exception e) { 19017 if (DEBUG_BACKUP) { 19018 Slog.e(TAG, "Unable to write preferred activities for backup", e); 19019 } 19020 return null; 19021 } 19022 19023 return dataStream.toByteArray(); 19024 } 19025 19026 @Override 19027 public void restorePreferredActivities(byte[] backup, int userId) { 19028 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19029 throw new SecurityException("Only the system may call restorePreferredActivities()"); 19030 } 19031 19032 try { 19033 final XmlPullParser parser = Xml.newPullParser(); 19034 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19035 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 19036 new BlobXmlRestorer() { 19037 @Override 19038 public void apply(XmlPullParser parser, int userId) 19039 throws XmlPullParserException, IOException { 19040 synchronized (mPackages) { 19041 mSettings.readPreferredActivitiesLPw(parser, userId); 19042 } 19043 } 19044 } ); 19045 } catch (Exception e) { 19046 if (DEBUG_BACKUP) { 19047 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19048 } 19049 } 19050 } 19051 19052 /** 19053 * Non-Binder method, support for the backup/restore mechanism: write the 19054 * default browser (etc) settings in its canonical XML format. Returns the default 19055 * browser XML representation as a byte array, or null if there is none. 19056 */ 19057 @Override 19058 public byte[] getDefaultAppsBackup(int userId) { 19059 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19060 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 19061 } 19062 19063 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19064 try { 19065 final XmlSerializer serializer = new FastXmlSerializer(); 19066 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19067 serializer.startDocument(null, true); 19068 serializer.startTag(null, TAG_DEFAULT_APPS); 19069 19070 synchronized (mPackages) { 19071 mSettings.writeDefaultAppsLPr(serializer, userId); 19072 } 19073 19074 serializer.endTag(null, TAG_DEFAULT_APPS); 19075 serializer.endDocument(); 19076 serializer.flush(); 19077 } catch (Exception e) { 19078 if (DEBUG_BACKUP) { 19079 Slog.e(TAG, "Unable to write default apps for backup", e); 19080 } 19081 return null; 19082 } 19083 19084 return dataStream.toByteArray(); 19085 } 19086 19087 @Override 19088 public void restoreDefaultApps(byte[] backup, int userId) { 19089 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19090 throw new SecurityException("Only the system may call restoreDefaultApps()"); 19091 } 19092 19093 try { 19094 final XmlPullParser parser = Xml.newPullParser(); 19095 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19096 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 19097 new BlobXmlRestorer() { 19098 @Override 19099 public void apply(XmlPullParser parser, int userId) 19100 throws XmlPullParserException, IOException { 19101 synchronized (mPackages) { 19102 mSettings.readDefaultAppsLPw(parser, userId); 19103 } 19104 } 19105 } ); 19106 } catch (Exception e) { 19107 if (DEBUG_BACKUP) { 19108 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 19109 } 19110 } 19111 } 19112 19113 @Override 19114 public byte[] getIntentFilterVerificationBackup(int userId) { 19115 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19116 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 19117 } 19118 19119 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19120 try { 19121 final XmlSerializer serializer = new FastXmlSerializer(); 19122 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19123 serializer.startDocument(null, true); 19124 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 19125 19126 synchronized (mPackages) { 19127 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 19128 } 19129 19130 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 19131 serializer.endDocument(); 19132 serializer.flush(); 19133 } catch (Exception e) { 19134 if (DEBUG_BACKUP) { 19135 Slog.e(TAG, "Unable to write default apps for backup", e); 19136 } 19137 return null; 19138 } 19139 19140 return dataStream.toByteArray(); 19141 } 19142 19143 @Override 19144 public void restoreIntentFilterVerification(byte[] backup, int userId) { 19145 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19146 throw new SecurityException("Only the system may call restorePreferredActivities()"); 19147 } 19148 19149 try { 19150 final XmlPullParser parser = Xml.newPullParser(); 19151 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19152 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 19153 new BlobXmlRestorer() { 19154 @Override 19155 public void apply(XmlPullParser parser, int userId) 19156 throws XmlPullParserException, IOException { 19157 synchronized (mPackages) { 19158 mSettings.readAllDomainVerificationsLPr(parser, userId); 19159 mSettings.writeLPr(); 19160 } 19161 } 19162 } ); 19163 } catch (Exception e) { 19164 if (DEBUG_BACKUP) { 19165 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19166 } 19167 } 19168 } 19169 19170 @Override 19171 public byte[] getPermissionGrantBackup(int userId) { 19172 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19173 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 19174 } 19175 19176 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19177 try { 19178 final XmlSerializer serializer = new FastXmlSerializer(); 19179 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19180 serializer.startDocument(null, true); 19181 serializer.startTag(null, TAG_PERMISSION_BACKUP); 19182 19183 synchronized (mPackages) { 19184 serializeRuntimePermissionGrantsLPr(serializer, userId); 19185 } 19186 19187 serializer.endTag(null, TAG_PERMISSION_BACKUP); 19188 serializer.endDocument(); 19189 serializer.flush(); 19190 } catch (Exception e) { 19191 if (DEBUG_BACKUP) { 19192 Slog.e(TAG, "Unable to write default apps for backup", e); 19193 } 19194 return null; 19195 } 19196 19197 return dataStream.toByteArray(); 19198 } 19199 19200 @Override 19201 public void restorePermissionGrants(byte[] backup, int userId) { 19202 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19203 throw new SecurityException("Only the system may call restorePermissionGrants()"); 19204 } 19205 19206 try { 19207 final XmlPullParser parser = Xml.newPullParser(); 19208 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19209 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 19210 new BlobXmlRestorer() { 19211 @Override 19212 public void apply(XmlPullParser parser, int userId) 19213 throws XmlPullParserException, IOException { 19214 synchronized (mPackages) { 19215 processRestoredPermissionGrantsLPr(parser, userId); 19216 } 19217 } 19218 } ); 19219 } catch (Exception e) { 19220 if (DEBUG_BACKUP) { 19221 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19222 } 19223 } 19224 } 19225 19226 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 19227 throws IOException { 19228 serializer.startTag(null, TAG_ALL_GRANTS); 19229 19230 final int N = mSettings.mPackages.size(); 19231 for (int i = 0; i < N; i++) { 19232 final PackageSetting ps = mSettings.mPackages.valueAt(i); 19233 boolean pkgGrantsKnown = false; 19234 19235 PermissionsState packagePerms = ps.getPermissionsState(); 19236 19237 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 19238 final int grantFlags = state.getFlags(); 19239 // only look at grants that are not system/policy fixed 19240 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 19241 final boolean isGranted = state.isGranted(); 19242 // And only back up the user-twiddled state bits 19243 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 19244 final String packageName = mSettings.mPackages.keyAt(i); 19245 if (!pkgGrantsKnown) { 19246 serializer.startTag(null, TAG_GRANT); 19247 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 19248 pkgGrantsKnown = true; 19249 } 19250 19251 final boolean userSet = 19252 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 19253 final boolean userFixed = 19254 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 19255 final boolean revoke = 19256 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 19257 19258 serializer.startTag(null, TAG_PERMISSION); 19259 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 19260 if (isGranted) { 19261 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 19262 } 19263 if (userSet) { 19264 serializer.attribute(null, ATTR_USER_SET, "true"); 19265 } 19266 if (userFixed) { 19267 serializer.attribute(null, ATTR_USER_FIXED, "true"); 19268 } 19269 if (revoke) { 19270 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 19271 } 19272 serializer.endTag(null, TAG_PERMISSION); 19273 } 19274 } 19275 } 19276 19277 if (pkgGrantsKnown) { 19278 serializer.endTag(null, TAG_GRANT); 19279 } 19280 } 19281 19282 serializer.endTag(null, TAG_ALL_GRANTS); 19283 } 19284 19285 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 19286 throws XmlPullParserException, IOException { 19287 String pkgName = null; 19288 int outerDepth = parser.getDepth(); 19289 int type; 19290 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 19291 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 19292 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 19293 continue; 19294 } 19295 19296 final String tagName = parser.getName(); 19297 if (tagName.equals(TAG_GRANT)) { 19298 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 19299 if (DEBUG_BACKUP) { 19300 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 19301 } 19302 } else if (tagName.equals(TAG_PERMISSION)) { 19303 19304 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 19305 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 19306 19307 int newFlagSet = 0; 19308 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 19309 newFlagSet |= FLAG_PERMISSION_USER_SET; 19310 } 19311 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 19312 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 19313 } 19314 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 19315 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 19316 } 19317 if (DEBUG_BACKUP) { 19318 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 19319 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 19320 } 19321 final PackageSetting ps = mSettings.mPackages.get(pkgName); 19322 if (ps != null) { 19323 // Already installed so we apply the grant immediately 19324 if (DEBUG_BACKUP) { 19325 Slog.v(TAG, " + already installed; applying"); 19326 } 19327 PermissionsState perms = ps.getPermissionsState(); 19328 BasePermission bp = mSettings.mPermissions.get(permName); 19329 if (bp != null) { 19330 if (isGranted) { 19331 perms.grantRuntimePermission(bp, userId); 19332 } 19333 if (newFlagSet != 0) { 19334 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 19335 } 19336 } 19337 } else { 19338 // Need to wait for post-restore install to apply the grant 19339 if (DEBUG_BACKUP) { 19340 Slog.v(TAG, " - not yet installed; saving for later"); 19341 } 19342 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 19343 isGranted, newFlagSet, userId); 19344 } 19345 } else { 19346 PackageManagerService.reportSettingsProblem(Log.WARN, 19347 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 19348 XmlUtils.skipCurrentTag(parser); 19349 } 19350 } 19351 19352 scheduleWriteSettingsLocked(); 19353 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 19354 } 19355 19356 @Override 19357 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 19358 int sourceUserId, int targetUserId, int flags) { 19359 mContext.enforceCallingOrSelfPermission( 19360 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 19361 int callingUid = Binder.getCallingUid(); 19362 enforceOwnerRights(ownerPackage, callingUid); 19363 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 19364 if (intentFilter.countActions() == 0) { 19365 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 19366 return; 19367 } 19368 synchronized (mPackages) { 19369 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 19370 ownerPackage, targetUserId, flags); 19371 CrossProfileIntentResolver resolver = 19372 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 19373 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 19374 // We have all those whose filter is equal. Now checking if the rest is equal as well. 19375 if (existing != null) { 19376 int size = existing.size(); 19377 for (int i = 0; i < size; i++) { 19378 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 19379 return; 19380 } 19381 } 19382 } 19383 resolver.addFilter(newFilter); 19384 scheduleWritePackageRestrictionsLocked(sourceUserId); 19385 } 19386 } 19387 19388 @Override 19389 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 19390 mContext.enforceCallingOrSelfPermission( 19391 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 19392 int callingUid = Binder.getCallingUid(); 19393 enforceOwnerRights(ownerPackage, callingUid); 19394 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 19395 synchronized (mPackages) { 19396 CrossProfileIntentResolver resolver = 19397 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 19398 ArraySet<CrossProfileIntentFilter> set = 19399 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 19400 for (CrossProfileIntentFilter filter : set) { 19401 if (filter.getOwnerPackage().equals(ownerPackage)) { 19402 resolver.removeFilter(filter); 19403 } 19404 } 19405 scheduleWritePackageRestrictionsLocked(sourceUserId); 19406 } 19407 } 19408 19409 // Enforcing that callingUid is owning pkg on userId 19410 private void enforceOwnerRights(String pkg, int callingUid) { 19411 // The system owns everything. 19412 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 19413 return; 19414 } 19415 int callingUserId = UserHandle.getUserId(callingUid); 19416 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 19417 if (pi == null) { 19418 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 19419 + callingUserId); 19420 } 19421 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 19422 throw new SecurityException("Calling uid " + callingUid 19423 + " does not own package " + pkg); 19424 } 19425 } 19426 19427 @Override 19428 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 19429 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 19430 } 19431 19432 private Intent getHomeIntent() { 19433 Intent intent = new Intent(Intent.ACTION_MAIN); 19434 intent.addCategory(Intent.CATEGORY_HOME); 19435 intent.addCategory(Intent.CATEGORY_DEFAULT); 19436 return intent; 19437 } 19438 19439 private IntentFilter getHomeFilter() { 19440 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 19441 filter.addCategory(Intent.CATEGORY_HOME); 19442 filter.addCategory(Intent.CATEGORY_DEFAULT); 19443 return filter; 19444 } 19445 19446 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 19447 int userId) { 19448 Intent intent = getHomeIntent(); 19449 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 19450 PackageManager.GET_META_DATA, userId); 19451 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 19452 true, false, false, userId); 19453 19454 allHomeCandidates.clear(); 19455 if (list != null) { 19456 for (ResolveInfo ri : list) { 19457 allHomeCandidates.add(ri); 19458 } 19459 } 19460 return (preferred == null || preferred.activityInfo == null) 19461 ? null 19462 : new ComponentName(preferred.activityInfo.packageName, 19463 preferred.activityInfo.name); 19464 } 19465 19466 @Override 19467 public void setHomeActivity(ComponentName comp, int userId) { 19468 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 19469 getHomeActivitiesAsUser(homeActivities, userId); 19470 19471 boolean found = false; 19472 19473 final int size = homeActivities.size(); 19474 final ComponentName[] set = new ComponentName[size]; 19475 for (int i = 0; i < size; i++) { 19476 final ResolveInfo candidate = homeActivities.get(i); 19477 final ActivityInfo info = candidate.activityInfo; 19478 final ComponentName activityName = new ComponentName(info.packageName, info.name); 19479 set[i] = activityName; 19480 if (!found && activityName.equals(comp)) { 19481 found = true; 19482 } 19483 } 19484 if (!found) { 19485 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 19486 + userId); 19487 } 19488 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 19489 set, comp, userId); 19490 } 19491 19492 private @Nullable String getSetupWizardPackageName() { 19493 final Intent intent = new Intent(Intent.ACTION_MAIN); 19494 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 19495 19496 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 19497 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 19498 | MATCH_DISABLED_COMPONENTS, 19499 UserHandle.myUserId()); 19500 if (matches.size() == 1) { 19501 return matches.get(0).getComponentInfo().packageName; 19502 } else { 19503 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 19504 + ": matches=" + matches); 19505 return null; 19506 } 19507 } 19508 19509 private @Nullable String getStorageManagerPackageName() { 19510 final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE); 19511 19512 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 19513 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 19514 | MATCH_DISABLED_COMPONENTS, 19515 UserHandle.myUserId()); 19516 if (matches.size() == 1) { 19517 return matches.get(0).getComponentInfo().packageName; 19518 } else { 19519 Slog.e(TAG, "There should probably be exactly one storage manager; found " 19520 + matches.size() + ": matches=" + matches); 19521 return null; 19522 } 19523 } 19524 19525 @Override 19526 public void setApplicationEnabledSetting(String appPackageName, 19527 int newState, int flags, int userId, String callingPackage) { 19528 if (!sUserManager.exists(userId)) return; 19529 if (callingPackage == null) { 19530 callingPackage = Integer.toString(Binder.getCallingUid()); 19531 } 19532 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 19533 } 19534 19535 @Override 19536 public void setComponentEnabledSetting(ComponentName componentName, 19537 int newState, int flags, int userId) { 19538 if (!sUserManager.exists(userId)) return; 19539 setEnabledSetting(componentName.getPackageName(), 19540 componentName.getClassName(), newState, flags, userId, null); 19541 } 19542 19543 private void setEnabledSetting(final String packageName, String className, int newState, 19544 final int flags, int userId, String callingPackage) { 19545 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 19546 || newState == COMPONENT_ENABLED_STATE_ENABLED 19547 || newState == COMPONENT_ENABLED_STATE_DISABLED 19548 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 19549 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 19550 throw new IllegalArgumentException("Invalid new component state: " 19551 + newState); 19552 } 19553 PackageSetting pkgSetting; 19554 final int uid = Binder.getCallingUid(); 19555 final int permission; 19556 if (uid == Process.SYSTEM_UID) { 19557 permission = PackageManager.PERMISSION_GRANTED; 19558 } else { 19559 permission = mContext.checkCallingOrSelfPermission( 19560 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 19561 } 19562 enforceCrossUserPermission(uid, userId, 19563 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 19564 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 19565 boolean sendNow = false; 19566 boolean isApp = (className == null); 19567 String componentName = isApp ? packageName : className; 19568 int packageUid = -1; 19569 ArrayList<String> components; 19570 19571 // writer 19572 synchronized (mPackages) { 19573 pkgSetting = mSettings.mPackages.get(packageName); 19574 if (pkgSetting == null) { 19575 if (className == null) { 19576 throw new IllegalArgumentException("Unknown package: " + packageName); 19577 } 19578 throw new IllegalArgumentException( 19579 "Unknown component: " + packageName + "/" + className); 19580 } 19581 } 19582 19583 // Limit who can change which apps 19584 if (!UserHandle.isSameApp(uid, pkgSetting.appId)) { 19585 // Don't allow apps that don't have permission to modify other apps 19586 if (!allowedByPermission) { 19587 throw new SecurityException( 19588 "Permission Denial: attempt to change component state from pid=" 19589 + Binder.getCallingPid() 19590 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 19591 } 19592 // Don't allow changing protected packages. 19593 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 19594 throw new SecurityException("Cannot disable a protected package: " + packageName); 19595 } 19596 } 19597 19598 synchronized (mPackages) { 19599 if (uid == Process.SHELL_UID 19600 && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) { 19601 // Shell can only change whole packages between ENABLED and DISABLED_USER states 19602 // unless it is a test package. 19603 int oldState = pkgSetting.getEnabled(userId); 19604 if (className == null 19605 && 19606 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 19607 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 19608 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 19609 && 19610 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 19611 || newState == COMPONENT_ENABLED_STATE_DEFAULT 19612 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 19613 // ok 19614 } else { 19615 throw new SecurityException( 19616 "Shell cannot change component state for " + packageName + "/" 19617 + className + " to " + newState); 19618 } 19619 } 19620 if (className == null) { 19621 // We're dealing with an application/package level state change 19622 if (pkgSetting.getEnabled(userId) == newState) { 19623 // Nothing to do 19624 return; 19625 } 19626 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 19627 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 19628 // Don't care about who enables an app. 19629 callingPackage = null; 19630 } 19631 pkgSetting.setEnabled(newState, userId, callingPackage); 19632 // pkgSetting.pkg.mSetEnabled = newState; 19633 } else { 19634 // We're dealing with a component level state change 19635 // First, verify that this is a valid class name. 19636 PackageParser.Package pkg = pkgSetting.pkg; 19637 if (pkg == null || !pkg.hasComponentClassName(className)) { 19638 if (pkg != null && 19639 pkg.applicationInfo.targetSdkVersion >= 19640 Build.VERSION_CODES.JELLY_BEAN) { 19641 throw new IllegalArgumentException("Component class " + className 19642 + " does not exist in " + packageName); 19643 } else { 19644 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 19645 + className + " does not exist in " + packageName); 19646 } 19647 } 19648 switch (newState) { 19649 case COMPONENT_ENABLED_STATE_ENABLED: 19650 if (!pkgSetting.enableComponentLPw(className, userId)) { 19651 return; 19652 } 19653 break; 19654 case COMPONENT_ENABLED_STATE_DISABLED: 19655 if (!pkgSetting.disableComponentLPw(className, userId)) { 19656 return; 19657 } 19658 break; 19659 case COMPONENT_ENABLED_STATE_DEFAULT: 19660 if (!pkgSetting.restoreComponentLPw(className, userId)) { 19661 return; 19662 } 19663 break; 19664 default: 19665 Slog.e(TAG, "Invalid new component state: " + newState); 19666 return; 19667 } 19668 } 19669 scheduleWritePackageRestrictionsLocked(userId); 19670 components = mPendingBroadcasts.get(userId, packageName); 19671 final boolean newPackage = components == null; 19672 if (newPackage) { 19673 components = new ArrayList<String>(); 19674 } 19675 if (!components.contains(componentName)) { 19676 components.add(componentName); 19677 } 19678 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 19679 sendNow = true; 19680 // Purge entry from pending broadcast list if another one exists already 19681 // since we are sending one right away. 19682 mPendingBroadcasts.remove(userId, packageName); 19683 } else { 19684 if (newPackage) { 19685 mPendingBroadcasts.put(userId, packageName, components); 19686 } 19687 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 19688 // Schedule a message 19689 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 19690 } 19691 } 19692 } 19693 19694 long callingId = Binder.clearCallingIdentity(); 19695 try { 19696 if (sendNow) { 19697 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 19698 sendPackageChangedBroadcast(packageName, 19699 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 19700 } 19701 } finally { 19702 Binder.restoreCallingIdentity(callingId); 19703 } 19704 } 19705 19706 @Override 19707 public void flushPackageRestrictionsAsUser(int userId) { 19708 if (!sUserManager.exists(userId)) { 19709 return; 19710 } 19711 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 19712 false /* checkShell */, "flushPackageRestrictions"); 19713 synchronized (mPackages) { 19714 mSettings.writePackageRestrictionsLPr(userId); 19715 mDirtyUsers.remove(userId); 19716 if (mDirtyUsers.isEmpty()) { 19717 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 19718 } 19719 } 19720 } 19721 19722 private void sendPackageChangedBroadcast(String packageName, 19723 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 19724 if (DEBUG_INSTALL) 19725 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 19726 + componentNames); 19727 Bundle extras = new Bundle(4); 19728 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 19729 String nameList[] = new String[componentNames.size()]; 19730 componentNames.toArray(nameList); 19731 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 19732 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 19733 extras.putInt(Intent.EXTRA_UID, packageUid); 19734 // If this is not reporting a change of the overall package, then only send it 19735 // to registered receivers. We don't want to launch a swath of apps for every 19736 // little component state change. 19737 final int flags = !componentNames.contains(packageName) 19738 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 19739 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 19740 new int[] {UserHandle.getUserId(packageUid)}); 19741 } 19742 19743 @Override 19744 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 19745 if (!sUserManager.exists(userId)) return; 19746 final int uid = Binder.getCallingUid(); 19747 final int permission = mContext.checkCallingOrSelfPermission( 19748 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 19749 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 19750 enforceCrossUserPermission(uid, userId, 19751 true /* requireFullPermission */, true /* checkShell */, "stop package"); 19752 // writer 19753 synchronized (mPackages) { 19754 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 19755 allowedByPermission, uid, userId)) { 19756 scheduleWritePackageRestrictionsLocked(userId); 19757 } 19758 } 19759 } 19760 19761 @Override 19762 public String getInstallerPackageName(String packageName) { 19763 // reader 19764 synchronized (mPackages) { 19765 return mSettings.getInstallerPackageNameLPr(packageName); 19766 } 19767 } 19768 19769 public boolean isOrphaned(String packageName) { 19770 // reader 19771 synchronized (mPackages) { 19772 return mSettings.isOrphaned(packageName); 19773 } 19774 } 19775 19776 @Override 19777 public int getApplicationEnabledSetting(String packageName, int userId) { 19778 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 19779 int uid = Binder.getCallingUid(); 19780 enforceCrossUserPermission(uid, userId, 19781 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 19782 // reader 19783 synchronized (mPackages) { 19784 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 19785 } 19786 } 19787 19788 @Override 19789 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 19790 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 19791 int uid = Binder.getCallingUid(); 19792 enforceCrossUserPermission(uid, userId, 19793 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 19794 // reader 19795 synchronized (mPackages) { 19796 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 19797 } 19798 } 19799 19800 @Override 19801 public void enterSafeMode() { 19802 enforceSystemOrRoot("Only the system can request entering safe mode"); 19803 19804 if (!mSystemReady) { 19805 mSafeMode = true; 19806 } 19807 } 19808 19809 @Override 19810 public void systemReady() { 19811 mSystemReady = true; 19812 19813 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 19814 // disabled after already being started. 19815 CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this, 19816 mContext.getContentResolver(), UserHandle.USER_SYSTEM); 19817 19818 // Read the compatibilty setting when the system is ready. 19819 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 19820 mContext.getContentResolver(), 19821 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 19822 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 19823 if (DEBUG_SETTINGS) { 19824 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 19825 } 19826 19827 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 19828 19829 synchronized (mPackages) { 19830 // Verify that all of the preferred activity components actually 19831 // exist. It is possible for applications to be updated and at 19832 // that point remove a previously declared activity component that 19833 // had been set as a preferred activity. We try to clean this up 19834 // the next time we encounter that preferred activity, but it is 19835 // possible for the user flow to never be able to return to that 19836 // situation so here we do a sanity check to make sure we haven't 19837 // left any junk around. 19838 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 19839 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 19840 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 19841 removed.clear(); 19842 for (PreferredActivity pa : pir.filterSet()) { 19843 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 19844 removed.add(pa); 19845 } 19846 } 19847 if (removed.size() > 0) { 19848 for (int r=0; r<removed.size(); r++) { 19849 PreferredActivity pa = removed.get(r); 19850 Slog.w(TAG, "Removing dangling preferred activity: " 19851 + pa.mPref.mComponent); 19852 pir.removeFilter(pa); 19853 } 19854 mSettings.writePackageRestrictionsLPr( 19855 mSettings.mPreferredActivities.keyAt(i)); 19856 } 19857 } 19858 19859 for (int userId : UserManagerService.getInstance().getUserIds()) { 19860 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 19861 grantPermissionsUserIds = ArrayUtils.appendInt( 19862 grantPermissionsUserIds, userId); 19863 } 19864 } 19865 } 19866 sUserManager.systemReady(); 19867 19868 // If we upgraded grant all default permissions before kicking off. 19869 for (int userId : grantPermissionsUserIds) { 19870 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 19871 } 19872 19873 // If we did not grant default permissions, we preload from this the 19874 // default permission exceptions lazily to ensure we don't hit the 19875 // disk on a new user creation. 19876 if (grantPermissionsUserIds == EMPTY_INT_ARRAY) { 19877 mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions(); 19878 } 19879 19880 // Kick off any messages waiting for system ready 19881 if (mPostSystemReadyMessages != null) { 19882 for (Message msg : mPostSystemReadyMessages) { 19883 msg.sendToTarget(); 19884 } 19885 mPostSystemReadyMessages = null; 19886 } 19887 19888 // Watch for external volumes that come and go over time 19889 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19890 storage.registerListener(mStorageListener); 19891 19892 mInstallerService.systemReady(); 19893 mPackageDexOptimizer.systemReady(); 19894 19895 StorageManagerInternal StorageManagerInternal = LocalServices.getService( 19896 StorageManagerInternal.class); 19897 StorageManagerInternal.addExternalStoragePolicy( 19898 new StorageManagerInternal.ExternalStorageMountPolicy() { 19899 @Override 19900 public int getMountMode(int uid, String packageName) { 19901 if (Process.isIsolated(uid)) { 19902 return Zygote.MOUNT_EXTERNAL_NONE; 19903 } 19904 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 19905 return Zygote.MOUNT_EXTERNAL_DEFAULT; 19906 } 19907 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 19908 return Zygote.MOUNT_EXTERNAL_DEFAULT; 19909 } 19910 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 19911 return Zygote.MOUNT_EXTERNAL_READ; 19912 } 19913 return Zygote.MOUNT_EXTERNAL_WRITE; 19914 } 19915 19916 @Override 19917 public boolean hasExternalStorage(int uid, String packageName) { 19918 return true; 19919 } 19920 }); 19921 19922 // Now that we're mostly running, clean up stale users and apps 19923 reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 19924 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 19925 } 19926 19927 @Override 19928 public boolean isSafeMode() { 19929 return mSafeMode; 19930 } 19931 19932 @Override 19933 public boolean hasSystemUidErrors() { 19934 return mHasSystemUidErrors; 19935 } 19936 19937 static String arrayToString(int[] array) { 19938 StringBuffer buf = new StringBuffer(128); 19939 buf.append('['); 19940 if (array != null) { 19941 for (int i=0; i<array.length; i++) { 19942 if (i > 0) buf.append(", "); 19943 buf.append(array[i]); 19944 } 19945 } 19946 buf.append(']'); 19947 return buf.toString(); 19948 } 19949 19950 static class DumpState { 19951 public static final int DUMP_LIBS = 1 << 0; 19952 public static final int DUMP_FEATURES = 1 << 1; 19953 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 19954 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 19955 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 19956 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 19957 public static final int DUMP_PERMISSIONS = 1 << 6; 19958 public static final int DUMP_PACKAGES = 1 << 7; 19959 public static final int DUMP_SHARED_USERS = 1 << 8; 19960 public static final int DUMP_MESSAGES = 1 << 9; 19961 public static final int DUMP_PROVIDERS = 1 << 10; 19962 public static final int DUMP_VERIFIERS = 1 << 11; 19963 public static final int DUMP_PREFERRED = 1 << 12; 19964 public static final int DUMP_PREFERRED_XML = 1 << 13; 19965 public static final int DUMP_KEYSETS = 1 << 14; 19966 public static final int DUMP_VERSION = 1 << 15; 19967 public static final int DUMP_INSTALLS = 1 << 16; 19968 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 19969 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 19970 public static final int DUMP_FROZEN = 1 << 19; 19971 public static final int DUMP_DEXOPT = 1 << 20; 19972 public static final int DUMP_COMPILER_STATS = 1 << 21; 19973 19974 public static final int OPTION_SHOW_FILTERS = 1 << 0; 19975 19976 private int mTypes; 19977 19978 private int mOptions; 19979 19980 private boolean mTitlePrinted; 19981 19982 private SharedUserSetting mSharedUser; 19983 19984 public boolean isDumping(int type) { 19985 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 19986 return true; 19987 } 19988 19989 return (mTypes & type) != 0; 19990 } 19991 19992 public void setDump(int type) { 19993 mTypes |= type; 19994 } 19995 19996 public boolean isOptionEnabled(int option) { 19997 return (mOptions & option) != 0; 19998 } 19999 20000 public void setOptionEnabled(int option) { 20001 mOptions |= option; 20002 } 20003 20004 public boolean onTitlePrinted() { 20005 final boolean printed = mTitlePrinted; 20006 mTitlePrinted = true; 20007 return printed; 20008 } 20009 20010 public boolean getTitlePrinted() { 20011 return mTitlePrinted; 20012 } 20013 20014 public void setTitlePrinted(boolean enabled) { 20015 mTitlePrinted = enabled; 20016 } 20017 20018 public SharedUserSetting getSharedUser() { 20019 return mSharedUser; 20020 } 20021 20022 public void setSharedUser(SharedUserSetting user) { 20023 mSharedUser = user; 20024 } 20025 } 20026 20027 @Override 20028 public void onShellCommand(FileDescriptor in, FileDescriptor out, 20029 FileDescriptor err, String[] args, ShellCallback callback, 20030 ResultReceiver resultReceiver) { 20031 (new PackageManagerShellCommand(this)).exec( 20032 this, in, out, err, args, callback, resultReceiver); 20033 } 20034 20035 @Override 20036 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 20037 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 20038 != PackageManager.PERMISSION_GRANTED) { 20039 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 20040 + Binder.getCallingPid() 20041 + ", uid=" + Binder.getCallingUid() 20042 + " without permission " 20043 + android.Manifest.permission.DUMP); 20044 return; 20045 } 20046 20047 DumpState dumpState = new DumpState(); 20048 boolean fullPreferred = false; 20049 boolean checkin = false; 20050 20051 String packageName = null; 20052 ArraySet<String> permissionNames = null; 20053 20054 int opti = 0; 20055 while (opti < args.length) { 20056 String opt = args[opti]; 20057 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 20058 break; 20059 } 20060 opti++; 20061 20062 if ("-a".equals(opt)) { 20063 // Right now we only know how to print all. 20064 } else if ("-h".equals(opt)) { 20065 pw.println("Package manager dump options:"); 20066 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 20067 pw.println(" --checkin: dump for a checkin"); 20068 pw.println(" -f: print details of intent filters"); 20069 pw.println(" -h: print this help"); 20070 pw.println(" cmd may be one of:"); 20071 pw.println(" l[ibraries]: list known shared libraries"); 20072 pw.println(" f[eatures]: list device features"); 20073 pw.println(" k[eysets]: print known keysets"); 20074 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 20075 pw.println(" perm[issions]: dump permissions"); 20076 pw.println(" permission [name ...]: dump declaration and use of given permission"); 20077 pw.println(" pref[erred]: print preferred package settings"); 20078 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 20079 pw.println(" prov[iders]: dump content providers"); 20080 pw.println(" p[ackages]: dump installed packages"); 20081 pw.println(" s[hared-users]: dump shared user IDs"); 20082 pw.println(" m[essages]: print collected runtime messages"); 20083 pw.println(" v[erifiers]: print package verifier info"); 20084 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 20085 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 20086 pw.println(" version: print database version info"); 20087 pw.println(" write: write current settings now"); 20088 pw.println(" installs: details about install sessions"); 20089 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 20090 pw.println(" dexopt: dump dexopt state"); 20091 pw.println(" compiler-stats: dump compiler statistics"); 20092 pw.println(" <package.name>: info about given package"); 20093 return; 20094 } else if ("--checkin".equals(opt)) { 20095 checkin = true; 20096 } else if ("-f".equals(opt)) { 20097 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 20098 } else { 20099 pw.println("Unknown argument: " + opt + "; use -h for help"); 20100 } 20101 } 20102 20103 // Is the caller requesting to dump a particular piece of data? 20104 if (opti < args.length) { 20105 String cmd = args[opti]; 20106 opti++; 20107 // Is this a package name? 20108 if ("android".equals(cmd) || cmd.contains(".")) { 20109 packageName = cmd; 20110 // When dumping a single package, we always dump all of its 20111 // filter information since the amount of data will be reasonable. 20112 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 20113 } else if ("check-permission".equals(cmd)) { 20114 if (opti >= args.length) { 20115 pw.println("Error: check-permission missing permission argument"); 20116 return; 20117 } 20118 String perm = args[opti]; 20119 opti++; 20120 if (opti >= args.length) { 20121 pw.println("Error: check-permission missing package argument"); 20122 return; 20123 } 20124 20125 String pkg = args[opti]; 20126 opti++; 20127 int user = UserHandle.getUserId(Binder.getCallingUid()); 20128 if (opti < args.length) { 20129 try { 20130 user = Integer.parseInt(args[opti]); 20131 } catch (NumberFormatException e) { 20132 pw.println("Error: check-permission user argument is not a number: " 20133 + args[opti]); 20134 return; 20135 } 20136 } 20137 20138 // Normalize package name to handle renamed packages and static libs 20139 pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST); 20140 20141 pw.println(checkPermission(perm, pkg, user)); 20142 return; 20143 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 20144 dumpState.setDump(DumpState.DUMP_LIBS); 20145 } else if ("f".equals(cmd) || "features".equals(cmd)) { 20146 dumpState.setDump(DumpState.DUMP_FEATURES); 20147 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 20148 if (opti >= args.length) { 20149 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 20150 | DumpState.DUMP_SERVICE_RESOLVERS 20151 | DumpState.DUMP_RECEIVER_RESOLVERS 20152 | DumpState.DUMP_CONTENT_RESOLVERS); 20153 } else { 20154 while (opti < args.length) { 20155 String name = args[opti]; 20156 if ("a".equals(name) || "activity".equals(name)) { 20157 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 20158 } else if ("s".equals(name) || "service".equals(name)) { 20159 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 20160 } else if ("r".equals(name) || "receiver".equals(name)) { 20161 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 20162 } else if ("c".equals(name) || "content".equals(name)) { 20163 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 20164 } else { 20165 pw.println("Error: unknown resolver table type: " + name); 20166 return; 20167 } 20168 opti++; 20169 } 20170 } 20171 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 20172 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 20173 } else if ("permission".equals(cmd)) { 20174 if (opti >= args.length) { 20175 pw.println("Error: permission requires permission name"); 20176 return; 20177 } 20178 permissionNames = new ArraySet<>(); 20179 while (opti < args.length) { 20180 permissionNames.add(args[opti]); 20181 opti++; 20182 } 20183 dumpState.setDump(DumpState.DUMP_PERMISSIONS 20184 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 20185 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 20186 dumpState.setDump(DumpState.DUMP_PREFERRED); 20187 } else if ("preferred-xml".equals(cmd)) { 20188 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 20189 if (opti < args.length && "--full".equals(args[opti])) { 20190 fullPreferred = true; 20191 opti++; 20192 } 20193 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 20194 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 20195 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 20196 dumpState.setDump(DumpState.DUMP_PACKAGES); 20197 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 20198 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 20199 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 20200 dumpState.setDump(DumpState.DUMP_PROVIDERS); 20201 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 20202 dumpState.setDump(DumpState.DUMP_MESSAGES); 20203 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 20204 dumpState.setDump(DumpState.DUMP_VERIFIERS); 20205 } else if ("i".equals(cmd) || "ifv".equals(cmd) 20206 || "intent-filter-verifiers".equals(cmd)) { 20207 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 20208 } else if ("version".equals(cmd)) { 20209 dumpState.setDump(DumpState.DUMP_VERSION); 20210 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 20211 dumpState.setDump(DumpState.DUMP_KEYSETS); 20212 } else if ("installs".equals(cmd)) { 20213 dumpState.setDump(DumpState.DUMP_INSTALLS); 20214 } else if ("frozen".equals(cmd)) { 20215 dumpState.setDump(DumpState.DUMP_FROZEN); 20216 } else if ("dexopt".equals(cmd)) { 20217 dumpState.setDump(DumpState.DUMP_DEXOPT); 20218 } else if ("compiler-stats".equals(cmd)) { 20219 dumpState.setDump(DumpState.DUMP_COMPILER_STATS); 20220 } else if ("write".equals(cmd)) { 20221 synchronized (mPackages) { 20222 mSettings.writeLPr(); 20223 pw.println("Settings written."); 20224 return; 20225 } 20226 } 20227 } 20228 20229 if (checkin) { 20230 pw.println("vers,1"); 20231 } 20232 20233 // reader 20234 synchronized (mPackages) { 20235 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 20236 if (!checkin) { 20237 if (dumpState.onTitlePrinted()) 20238 pw.println(); 20239 pw.println("Database versions:"); 20240 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 20241 } 20242 } 20243 20244 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 20245 if (!checkin) { 20246 if (dumpState.onTitlePrinted()) 20247 pw.println(); 20248 pw.println("Verifiers:"); 20249 pw.print(" Required: "); 20250 pw.print(mRequiredVerifierPackage); 20251 pw.print(" (uid="); 20252 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 20253 UserHandle.USER_SYSTEM)); 20254 pw.println(")"); 20255 } else if (mRequiredVerifierPackage != null) { 20256 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 20257 pw.print(","); 20258 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 20259 UserHandle.USER_SYSTEM)); 20260 } 20261 } 20262 20263 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 20264 packageName == null) { 20265 if (mIntentFilterVerifierComponent != null) { 20266 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 20267 if (!checkin) { 20268 if (dumpState.onTitlePrinted()) 20269 pw.println(); 20270 pw.println("Intent Filter Verifier:"); 20271 pw.print(" Using: "); 20272 pw.print(verifierPackageName); 20273 pw.print(" (uid="); 20274 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 20275 UserHandle.USER_SYSTEM)); 20276 pw.println(")"); 20277 } else if (verifierPackageName != null) { 20278 pw.print("ifv,"); pw.print(verifierPackageName); 20279 pw.print(","); 20280 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 20281 UserHandle.USER_SYSTEM)); 20282 } 20283 } else { 20284 pw.println(); 20285 pw.println("No Intent Filter Verifier available!"); 20286 } 20287 } 20288 20289 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 20290 boolean printedHeader = false; 20291 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 20292 while (it.hasNext()) { 20293 String libName = it.next(); 20294 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName); 20295 if (versionedLib == null) { 20296 continue; 20297 } 20298 final int versionCount = versionedLib.size(); 20299 for (int i = 0; i < versionCount; i++) { 20300 SharedLibraryEntry libEntry = versionedLib.valueAt(i); 20301 if (!checkin) { 20302 if (!printedHeader) { 20303 if (dumpState.onTitlePrinted()) 20304 pw.println(); 20305 pw.println("Libraries:"); 20306 printedHeader = true; 20307 } 20308 pw.print(" "); 20309 } else { 20310 pw.print("lib,"); 20311 } 20312 pw.print(libEntry.info.getName()); 20313 if (libEntry.info.isStatic()) { 20314 pw.print(" version=" + libEntry.info.getVersion()); 20315 } 20316 if (!checkin) { 20317 pw.print(" -> "); 20318 } 20319 if (libEntry.path != null) { 20320 pw.print(" (jar) "); 20321 pw.print(libEntry.path); 20322 } else { 20323 pw.print(" (apk) "); 20324 pw.print(libEntry.apk); 20325 } 20326 pw.println(); 20327 } 20328 } 20329 } 20330 20331 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 20332 if (dumpState.onTitlePrinted()) 20333 pw.println(); 20334 if (!checkin) { 20335 pw.println("Features:"); 20336 } 20337 20338 for (FeatureInfo feat : mAvailableFeatures.values()) { 20339 if (checkin) { 20340 pw.print("feat,"); 20341 pw.print(feat.name); 20342 pw.print(","); 20343 pw.println(feat.version); 20344 } else { 20345 pw.print(" "); 20346 pw.print(feat.name); 20347 if (feat.version > 0) { 20348 pw.print(" version="); 20349 pw.print(feat.version); 20350 } 20351 pw.println(); 20352 } 20353 } 20354 } 20355 20356 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 20357 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 20358 : "Activity Resolver Table:", " ", packageName, 20359 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20360 dumpState.setTitlePrinted(true); 20361 } 20362 } 20363 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 20364 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 20365 : "Receiver Resolver Table:", " ", packageName, 20366 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20367 dumpState.setTitlePrinted(true); 20368 } 20369 } 20370 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 20371 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 20372 : "Service Resolver Table:", " ", packageName, 20373 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20374 dumpState.setTitlePrinted(true); 20375 } 20376 } 20377 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 20378 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 20379 : "Provider Resolver Table:", " ", packageName, 20380 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20381 dumpState.setTitlePrinted(true); 20382 } 20383 } 20384 20385 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 20386 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 20387 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 20388 int user = mSettings.mPreferredActivities.keyAt(i); 20389 if (pir.dump(pw, 20390 dumpState.getTitlePrinted() 20391 ? "\nPreferred Activities User " + user + ":" 20392 : "Preferred Activities User " + user + ":", " ", 20393 packageName, true, false)) { 20394 dumpState.setTitlePrinted(true); 20395 } 20396 } 20397 } 20398 20399 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 20400 pw.flush(); 20401 FileOutputStream fout = new FileOutputStream(fd); 20402 BufferedOutputStream str = new BufferedOutputStream(fout); 20403 XmlSerializer serializer = new FastXmlSerializer(); 20404 try { 20405 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 20406 serializer.startDocument(null, true); 20407 serializer.setFeature( 20408 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 20409 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 20410 serializer.endDocument(); 20411 serializer.flush(); 20412 } catch (IllegalArgumentException e) { 20413 pw.println("Failed writing: " + e); 20414 } catch (IllegalStateException e) { 20415 pw.println("Failed writing: " + e); 20416 } catch (IOException e) { 20417 pw.println("Failed writing: " + e); 20418 } 20419 } 20420 20421 if (!checkin 20422 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 20423 && packageName == null) { 20424 pw.println(); 20425 int count = mSettings.mPackages.size(); 20426 if (count == 0) { 20427 pw.println("No applications!"); 20428 pw.println(); 20429 } else { 20430 final String prefix = " "; 20431 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 20432 if (allPackageSettings.size() == 0) { 20433 pw.println("No domain preferred apps!"); 20434 pw.println(); 20435 } else { 20436 pw.println("App verification status:"); 20437 pw.println(); 20438 count = 0; 20439 for (PackageSetting ps : allPackageSettings) { 20440 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 20441 if (ivi == null || ivi.getPackageName() == null) continue; 20442 pw.println(prefix + "Package: " + ivi.getPackageName()); 20443 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 20444 pw.println(prefix + "Status: " + ivi.getStatusString()); 20445 pw.println(); 20446 count++; 20447 } 20448 if (count == 0) { 20449 pw.println(prefix + "No app verification established."); 20450 pw.println(); 20451 } 20452 for (int userId : sUserManager.getUserIds()) { 20453 pw.println("App linkages for user " + userId + ":"); 20454 pw.println(); 20455 count = 0; 20456 for (PackageSetting ps : allPackageSettings) { 20457 final long status = ps.getDomainVerificationStatusForUser(userId); 20458 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 20459 && !DEBUG_DOMAIN_VERIFICATION) { 20460 continue; 20461 } 20462 pw.println(prefix + "Package: " + ps.name); 20463 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 20464 String statusStr = IntentFilterVerificationInfo. 20465 getStatusStringFromValue(status); 20466 pw.println(prefix + "Status: " + statusStr); 20467 pw.println(); 20468 count++; 20469 } 20470 if (count == 0) { 20471 pw.println(prefix + "No configured app linkages."); 20472 pw.println(); 20473 } 20474 } 20475 } 20476 } 20477 } 20478 20479 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 20480 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 20481 if (packageName == null && permissionNames == null) { 20482 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 20483 if (iperm == 0) { 20484 if (dumpState.onTitlePrinted()) 20485 pw.println(); 20486 pw.println("AppOp Permissions:"); 20487 } 20488 pw.print(" AppOp Permission "); 20489 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 20490 pw.println(":"); 20491 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 20492 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 20493 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 20494 } 20495 } 20496 } 20497 } 20498 20499 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 20500 boolean printedSomething = false; 20501 for (PackageParser.Provider p : mProviders.mProviders.values()) { 20502 if (packageName != null && !packageName.equals(p.info.packageName)) { 20503 continue; 20504 } 20505 if (!printedSomething) { 20506 if (dumpState.onTitlePrinted()) 20507 pw.println(); 20508 pw.println("Registered ContentProviders:"); 20509 printedSomething = true; 20510 } 20511 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 20512 pw.print(" "); pw.println(p.toString()); 20513 } 20514 printedSomething = false; 20515 for (Map.Entry<String, PackageParser.Provider> entry : 20516 mProvidersByAuthority.entrySet()) { 20517 PackageParser.Provider p = entry.getValue(); 20518 if (packageName != null && !packageName.equals(p.info.packageName)) { 20519 continue; 20520 } 20521 if (!printedSomething) { 20522 if (dumpState.onTitlePrinted()) 20523 pw.println(); 20524 pw.println("ContentProvider Authorities:"); 20525 printedSomething = true; 20526 } 20527 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 20528 pw.print(" "); pw.println(p.toString()); 20529 if (p.info != null && p.info.applicationInfo != null) { 20530 final String appInfo = p.info.applicationInfo.toString(); 20531 pw.print(" applicationInfo="); pw.println(appInfo); 20532 } 20533 } 20534 } 20535 20536 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 20537 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 20538 } 20539 20540 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 20541 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 20542 } 20543 20544 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 20545 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 20546 } 20547 20548 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 20549 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 20550 } 20551 20552 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 20553 // XXX should handle packageName != null by dumping only install data that 20554 // the given package is involved with. 20555 if (dumpState.onTitlePrinted()) pw.println(); 20556 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 20557 } 20558 20559 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 20560 // XXX should handle packageName != null by dumping only install data that 20561 // the given package is involved with. 20562 if (dumpState.onTitlePrinted()) pw.println(); 20563 20564 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 20565 ipw.println(); 20566 ipw.println("Frozen packages:"); 20567 ipw.increaseIndent(); 20568 if (mFrozenPackages.size() == 0) { 20569 ipw.println("(none)"); 20570 } else { 20571 for (int i = 0; i < mFrozenPackages.size(); i++) { 20572 ipw.println(mFrozenPackages.valueAt(i)); 20573 } 20574 } 20575 ipw.decreaseIndent(); 20576 } 20577 20578 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 20579 if (dumpState.onTitlePrinted()) pw.println(); 20580 dumpDexoptStateLPr(pw, packageName); 20581 } 20582 20583 if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) { 20584 if (dumpState.onTitlePrinted()) pw.println(); 20585 dumpCompilerStatsLPr(pw, packageName); 20586 } 20587 20588 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 20589 if (dumpState.onTitlePrinted()) pw.println(); 20590 mSettings.dumpReadMessagesLPr(pw, dumpState); 20591 20592 pw.println(); 20593 pw.println("Package warning messages:"); 20594 BufferedReader in = null; 20595 String line = null; 20596 try { 20597 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 20598 while ((line = in.readLine()) != null) { 20599 if (line.contains("ignored: updated version")) continue; 20600 pw.println(line); 20601 } 20602 } catch (IOException ignored) { 20603 } finally { 20604 IoUtils.closeQuietly(in); 20605 } 20606 } 20607 20608 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 20609 BufferedReader in = null; 20610 String line = null; 20611 try { 20612 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 20613 while ((line = in.readLine()) != null) { 20614 if (line.contains("ignored: updated version")) continue; 20615 pw.print("msg,"); 20616 pw.println(line); 20617 } 20618 } catch (IOException ignored) { 20619 } finally { 20620 IoUtils.closeQuietly(in); 20621 } 20622 } 20623 } 20624 } 20625 20626 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 20627 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 20628 ipw.println(); 20629 ipw.println("Dexopt state:"); 20630 ipw.increaseIndent(); 20631 Collection<PackageParser.Package> packages = null; 20632 if (packageName != null) { 20633 PackageParser.Package targetPackage = mPackages.get(packageName); 20634 if (targetPackage != null) { 20635 packages = Collections.singletonList(targetPackage); 20636 } else { 20637 ipw.println("Unable to find package: " + packageName); 20638 return; 20639 } 20640 } else { 20641 packages = mPackages.values(); 20642 } 20643 20644 for (PackageParser.Package pkg : packages) { 20645 ipw.println("[" + pkg.packageName + "]"); 20646 ipw.increaseIndent(); 20647 mPackageDexOptimizer.dumpDexoptState(ipw, pkg); 20648 ipw.decreaseIndent(); 20649 } 20650 } 20651 20652 private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) { 20653 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 20654 ipw.println(); 20655 ipw.println("Compiler stats:"); 20656 ipw.increaseIndent(); 20657 Collection<PackageParser.Package> packages = null; 20658 if (packageName != null) { 20659 PackageParser.Package targetPackage = mPackages.get(packageName); 20660 if (targetPackage != null) { 20661 packages = Collections.singletonList(targetPackage); 20662 } else { 20663 ipw.println("Unable to find package: " + packageName); 20664 return; 20665 } 20666 } else { 20667 packages = mPackages.values(); 20668 } 20669 20670 for (PackageParser.Package pkg : packages) { 20671 ipw.println("[" + pkg.packageName + "]"); 20672 ipw.increaseIndent(); 20673 20674 CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName); 20675 if (stats == null) { 20676 ipw.println("(No recorded stats)"); 20677 } else { 20678 stats.dump(ipw); 20679 } 20680 ipw.decreaseIndent(); 20681 } 20682 } 20683 20684 private String dumpDomainString(String packageName) { 20685 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 20686 .getList(); 20687 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 20688 20689 ArraySet<String> result = new ArraySet<>(); 20690 if (iviList.size() > 0) { 20691 for (IntentFilterVerificationInfo ivi : iviList) { 20692 for (String host : ivi.getDomains()) { 20693 result.add(host); 20694 } 20695 } 20696 } 20697 if (filters != null && filters.size() > 0) { 20698 for (IntentFilter filter : filters) { 20699 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 20700 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 20701 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 20702 result.addAll(filter.getHostsList()); 20703 } 20704 } 20705 } 20706 20707 StringBuilder sb = new StringBuilder(result.size() * 16); 20708 for (String domain : result) { 20709 if (sb.length() > 0) sb.append(" "); 20710 sb.append(domain); 20711 } 20712 return sb.toString(); 20713 } 20714 20715 // ------- apps on sdcard specific code ------- 20716 static final boolean DEBUG_SD_INSTALL = false; 20717 20718 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 20719 20720 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 20721 20722 private boolean mMediaMounted = false; 20723 20724 static String getEncryptKey() { 20725 try { 20726 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 20727 SD_ENCRYPTION_KEYSTORE_NAME); 20728 if (sdEncKey == null) { 20729 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 20730 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 20731 if (sdEncKey == null) { 20732 Slog.e(TAG, "Failed to create encryption keys"); 20733 return null; 20734 } 20735 } 20736 return sdEncKey; 20737 } catch (NoSuchAlgorithmException nsae) { 20738 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 20739 return null; 20740 } catch (IOException ioe) { 20741 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 20742 return null; 20743 } 20744 } 20745 20746 /* 20747 * Update media status on PackageManager. 20748 */ 20749 @Override 20750 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 20751 int callingUid = Binder.getCallingUid(); 20752 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 20753 throw new SecurityException("Media status can only be updated by the system"); 20754 } 20755 // reader; this apparently protects mMediaMounted, but should probably 20756 // be a different lock in that case. 20757 synchronized (mPackages) { 20758 Log.i(TAG, "Updating external media status from " 20759 + (mMediaMounted ? "mounted" : "unmounted") + " to " 20760 + (mediaStatus ? "mounted" : "unmounted")); 20761 if (DEBUG_SD_INSTALL) 20762 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 20763 + ", mMediaMounted=" + mMediaMounted); 20764 if (mediaStatus == mMediaMounted) { 20765 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 20766 : 0, -1); 20767 mHandler.sendMessage(msg); 20768 return; 20769 } 20770 mMediaMounted = mediaStatus; 20771 } 20772 // Queue up an async operation since the package installation may take a 20773 // little while. 20774 mHandler.post(new Runnable() { 20775 public void run() { 20776 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 20777 } 20778 }); 20779 } 20780 20781 /** 20782 * Called by StorageManagerService when the initial ASECs to scan are available. 20783 * Should block until all the ASEC containers are finished being scanned. 20784 */ 20785 public void scanAvailableAsecs() { 20786 updateExternalMediaStatusInner(true, false, false); 20787 } 20788 20789 /* 20790 * Collect information of applications on external media, map them against 20791 * existing containers and update information based on current mount status. 20792 * Please note that we always have to report status if reportStatus has been 20793 * set to true especially when unloading packages. 20794 */ 20795 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 20796 boolean externalStorage) { 20797 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 20798 int[] uidArr = EmptyArray.INT; 20799 20800 final String[] list = PackageHelper.getSecureContainerList(); 20801 if (ArrayUtils.isEmpty(list)) { 20802 Log.i(TAG, "No secure containers found"); 20803 } else { 20804 // Process list of secure containers and categorize them 20805 // as active or stale based on their package internal state. 20806 20807 // reader 20808 synchronized (mPackages) { 20809 for (String cid : list) { 20810 // Leave stages untouched for now; installer service owns them 20811 if (PackageInstallerService.isStageName(cid)) continue; 20812 20813 if (DEBUG_SD_INSTALL) 20814 Log.i(TAG, "Processing container " + cid); 20815 String pkgName = getAsecPackageName(cid); 20816 if (pkgName == null) { 20817 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 20818 continue; 20819 } 20820 if (DEBUG_SD_INSTALL) 20821 Log.i(TAG, "Looking for pkg : " + pkgName); 20822 20823 final PackageSetting ps = mSettings.mPackages.get(pkgName); 20824 if (ps == null) { 20825 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 20826 continue; 20827 } 20828 20829 /* 20830 * Skip packages that are not external if we're unmounting 20831 * external storage. 20832 */ 20833 if (externalStorage && !isMounted && !isExternal(ps)) { 20834 continue; 20835 } 20836 20837 final AsecInstallArgs args = new AsecInstallArgs(cid, 20838 getAppDexInstructionSets(ps), ps.isForwardLocked()); 20839 // The package status is changed only if the code path 20840 // matches between settings and the container id. 20841 if (ps.codePathString != null 20842 && ps.codePathString.startsWith(args.getCodePath())) { 20843 if (DEBUG_SD_INSTALL) { 20844 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 20845 + " at code path: " + ps.codePathString); 20846 } 20847 20848 // We do have a valid package installed on sdcard 20849 processCids.put(args, ps.codePathString); 20850 final int uid = ps.appId; 20851 if (uid != -1) { 20852 uidArr = ArrayUtils.appendInt(uidArr, uid); 20853 } 20854 } else { 20855 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 20856 + ps.codePathString); 20857 } 20858 } 20859 } 20860 20861 Arrays.sort(uidArr); 20862 } 20863 20864 // Process packages with valid entries. 20865 if (isMounted) { 20866 if (DEBUG_SD_INSTALL) 20867 Log.i(TAG, "Loading packages"); 20868 loadMediaPackages(processCids, uidArr, externalStorage); 20869 startCleaningPackages(); 20870 mInstallerService.onSecureContainersAvailable(); 20871 } else { 20872 if (DEBUG_SD_INSTALL) 20873 Log.i(TAG, "Unloading packages"); 20874 unloadMediaPackages(processCids, uidArr, reportStatus); 20875 } 20876 } 20877 20878 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 20879 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 20880 final int size = infos.size(); 20881 final String[] packageNames = new String[size]; 20882 final int[] packageUids = new int[size]; 20883 for (int i = 0; i < size; i++) { 20884 final ApplicationInfo info = infos.get(i); 20885 packageNames[i] = info.packageName; 20886 packageUids[i] = info.uid; 20887 } 20888 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 20889 finishedReceiver); 20890 } 20891 20892 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 20893 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 20894 sendResourcesChangedBroadcast(mediaStatus, replacing, 20895 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 20896 } 20897 20898 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 20899 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 20900 int size = pkgList.length; 20901 if (size > 0) { 20902 // Send broadcasts here 20903 Bundle extras = new Bundle(); 20904 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 20905 if (uidArr != null) { 20906 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 20907 } 20908 if (replacing) { 20909 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 20910 } 20911 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 20912 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 20913 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 20914 } 20915 } 20916 20917 /* 20918 * Look at potentially valid container ids from processCids If package 20919 * information doesn't match the one on record or package scanning fails, 20920 * the cid is added to list of removeCids. We currently don't delete stale 20921 * containers. 20922 */ 20923 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 20924 boolean externalStorage) { 20925 ArrayList<String> pkgList = new ArrayList<String>(); 20926 Set<AsecInstallArgs> keys = processCids.keySet(); 20927 20928 for (AsecInstallArgs args : keys) { 20929 String codePath = processCids.get(args); 20930 if (DEBUG_SD_INSTALL) 20931 Log.i(TAG, "Loading container : " + args.cid); 20932 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 20933 try { 20934 // Make sure there are no container errors first. 20935 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 20936 Slog.e(TAG, "Failed to mount cid : " + args.cid 20937 + " when installing from sdcard"); 20938 continue; 20939 } 20940 // Check code path here. 20941 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 20942 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 20943 + " does not match one in settings " + codePath); 20944 continue; 20945 } 20946 // Parse package 20947 int parseFlags = mDefParseFlags; 20948 if (args.isExternalAsec()) { 20949 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 20950 } 20951 if (args.isFwdLocked()) { 20952 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 20953 } 20954 20955 synchronized (mInstallLock) { 20956 PackageParser.Package pkg = null; 20957 try { 20958 // Sadly we don't know the package name yet to freeze it 20959 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 20960 SCAN_IGNORE_FROZEN, 0, null); 20961 } catch (PackageManagerException e) { 20962 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 20963 } 20964 // Scan the package 20965 if (pkg != null) { 20966 /* 20967 * TODO why is the lock being held? doPostInstall is 20968 * called in other places without the lock. This needs 20969 * to be straightened out. 20970 */ 20971 // writer 20972 synchronized (mPackages) { 20973 retCode = PackageManager.INSTALL_SUCCEEDED; 20974 pkgList.add(pkg.packageName); 20975 // Post process args 20976 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 20977 pkg.applicationInfo.uid); 20978 } 20979 } else { 20980 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 20981 } 20982 } 20983 20984 } finally { 20985 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 20986 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 20987 } 20988 } 20989 } 20990 // writer 20991 synchronized (mPackages) { 20992 // If the platform SDK has changed since the last time we booted, 20993 // we need to re-grant app permission to catch any new ones that 20994 // appear. This is really a hack, and means that apps can in some 20995 // cases get permissions that the user didn't initially explicitly 20996 // allow... it would be nice to have some better way to handle 20997 // this situation. 20998 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 20999 : mSettings.getInternalVersion(); 21000 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 21001 : StorageManager.UUID_PRIVATE_INTERNAL; 21002 21003 int updateFlags = UPDATE_PERMISSIONS_ALL; 21004 if (ver.sdkVersion != mSdkVersion) { 21005 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 21006 + mSdkVersion + "; regranting permissions for external"); 21007 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 21008 } 21009 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 21010 21011 // Yay, everything is now upgraded 21012 ver.forceCurrent(); 21013 21014 // can downgrade to reader 21015 // Persist settings 21016 mSettings.writeLPr(); 21017 } 21018 // Send a broadcast to let everyone know we are done processing 21019 if (pkgList.size() > 0) { 21020 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 21021 } 21022 } 21023 21024 /* 21025 * Utility method to unload a list of specified containers 21026 */ 21027 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 21028 // Just unmount all valid containers. 21029 for (AsecInstallArgs arg : cidArgs) { 21030 synchronized (mInstallLock) { 21031 arg.doPostDeleteLI(false); 21032 } 21033 } 21034 } 21035 21036 /* 21037 * Unload packages mounted on external media. This involves deleting package 21038 * data from internal structures, sending broadcasts about disabled packages, 21039 * gc'ing to free up references, unmounting all secure containers 21040 * corresponding to packages on external media, and posting a 21041 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 21042 * that we always have to post this message if status has been requested no 21043 * matter what. 21044 */ 21045 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 21046 final boolean reportStatus) { 21047 if (DEBUG_SD_INSTALL) 21048 Log.i(TAG, "unloading media packages"); 21049 ArrayList<String> pkgList = new ArrayList<String>(); 21050 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 21051 final Set<AsecInstallArgs> keys = processCids.keySet(); 21052 for (AsecInstallArgs args : keys) { 21053 String pkgName = args.getPackageName(); 21054 if (DEBUG_SD_INSTALL) 21055 Log.i(TAG, "Trying to unload pkg : " + pkgName); 21056 // Delete package internally 21057 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 21058 synchronized (mInstallLock) { 21059 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 21060 final boolean res; 21061 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 21062 "unloadMediaPackages")) { 21063 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 21064 null); 21065 } 21066 if (res) { 21067 pkgList.add(pkgName); 21068 } else { 21069 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 21070 failedList.add(args); 21071 } 21072 } 21073 } 21074 21075 // reader 21076 synchronized (mPackages) { 21077 // We didn't update the settings after removing each package; 21078 // write them now for all packages. 21079 mSettings.writeLPr(); 21080 } 21081 21082 // We have to absolutely send UPDATED_MEDIA_STATUS only 21083 // after confirming that all the receivers processed the ordered 21084 // broadcast when packages get disabled, force a gc to clean things up. 21085 // and unload all the containers. 21086 if (pkgList.size() > 0) { 21087 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 21088 new IIntentReceiver.Stub() { 21089 public void performReceive(Intent intent, int resultCode, String data, 21090 Bundle extras, boolean ordered, boolean sticky, 21091 int sendingUser) throws RemoteException { 21092 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 21093 reportStatus ? 1 : 0, 1, keys); 21094 mHandler.sendMessage(msg); 21095 } 21096 }); 21097 } else { 21098 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 21099 keys); 21100 mHandler.sendMessage(msg); 21101 } 21102 } 21103 21104 private void loadPrivatePackages(final VolumeInfo vol) { 21105 mHandler.post(new Runnable() { 21106 @Override 21107 public void run() { 21108 loadPrivatePackagesInner(vol); 21109 } 21110 }); 21111 } 21112 21113 private void loadPrivatePackagesInner(VolumeInfo vol) { 21114 final String volumeUuid = vol.fsUuid; 21115 if (TextUtils.isEmpty(volumeUuid)) { 21116 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 21117 return; 21118 } 21119 21120 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 21121 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 21122 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 21123 21124 final VersionInfo ver; 21125 final List<PackageSetting> packages; 21126 synchronized (mPackages) { 21127 ver = mSettings.findOrCreateVersion(volumeUuid); 21128 packages = mSettings.getVolumePackagesLPr(volumeUuid); 21129 } 21130 21131 for (PackageSetting ps : packages) { 21132 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 21133 synchronized (mInstallLock) { 21134 final PackageParser.Package pkg; 21135 try { 21136 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 21137 loaded.add(pkg.applicationInfo); 21138 21139 } catch (PackageManagerException e) { 21140 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 21141 } 21142 21143 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 21144 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 21145 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 21146 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 21147 } 21148 } 21149 } 21150 21151 // Reconcile app data for all started/unlocked users 21152 final StorageManager sm = mContext.getSystemService(StorageManager.class); 21153 final UserManager um = mContext.getSystemService(UserManager.class); 21154 UserManagerInternal umInternal = getUserManagerInternal(); 21155 for (UserInfo user : um.getUsers()) { 21156 final int flags; 21157 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 21158 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 21159 } else if (umInternal.isUserRunning(user.id)) { 21160 flags = StorageManager.FLAG_STORAGE_DE; 21161 } else { 21162 continue; 21163 } 21164 21165 try { 21166 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 21167 synchronized (mInstallLock) { 21168 reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */); 21169 } 21170 } catch (IllegalStateException e) { 21171 // Device was probably ejected, and we'll process that event momentarily 21172 Slog.w(TAG, "Failed to prepare storage: " + e); 21173 } 21174 } 21175 21176 synchronized (mPackages) { 21177 int updateFlags = UPDATE_PERMISSIONS_ALL; 21178 if (ver.sdkVersion != mSdkVersion) { 21179 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 21180 + mSdkVersion + "; regranting permissions for " + volumeUuid); 21181 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 21182 } 21183 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 21184 21185 // Yay, everything is now upgraded 21186 ver.forceCurrent(); 21187 21188 mSettings.writeLPr(); 21189 } 21190 21191 for (PackageFreezer freezer : freezers) { 21192 freezer.close(); 21193 } 21194 21195 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 21196 sendResourcesChangedBroadcast(true, false, loaded, null); 21197 } 21198 21199 private void unloadPrivatePackages(final VolumeInfo vol) { 21200 mHandler.post(new Runnable() { 21201 @Override 21202 public void run() { 21203 unloadPrivatePackagesInner(vol); 21204 } 21205 }); 21206 } 21207 21208 private void unloadPrivatePackagesInner(VolumeInfo vol) { 21209 final String volumeUuid = vol.fsUuid; 21210 if (TextUtils.isEmpty(volumeUuid)) { 21211 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 21212 return; 21213 } 21214 21215 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 21216 synchronized (mInstallLock) { 21217 synchronized (mPackages) { 21218 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 21219 for (PackageSetting ps : packages) { 21220 if (ps.pkg == null) continue; 21221 21222 final ApplicationInfo info = ps.pkg.applicationInfo; 21223 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 21224 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 21225 21226 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 21227 "unloadPrivatePackagesInner")) { 21228 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 21229 false, null)) { 21230 unloaded.add(info); 21231 } else { 21232 Slog.w(TAG, "Failed to unload " + ps.codePath); 21233 } 21234 } 21235 21236 // Try very hard to release any references to this package 21237 // so we don't risk the system server being killed due to 21238 // open FDs 21239 AttributeCache.instance().removePackage(ps.name); 21240 } 21241 21242 mSettings.writeLPr(); 21243 } 21244 } 21245 21246 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 21247 sendResourcesChangedBroadcast(false, false, unloaded, null); 21248 21249 // Try very hard to release any references to this path so we don't risk 21250 // the system server being killed due to open FDs 21251 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 21252 21253 for (int i = 0; i < 3; i++) { 21254 System.gc(); 21255 System.runFinalization(); 21256 } 21257 } 21258 21259 /** 21260 * Examine all users present on given mounted volume, and destroy data 21261 * belonging to users that are no longer valid, or whose user ID has been 21262 * recycled. 21263 */ 21264 private void reconcileUsers(String volumeUuid) { 21265 final List<File> files = new ArrayList<>(); 21266 Collections.addAll(files, FileUtils 21267 .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid))); 21268 Collections.addAll(files, FileUtils 21269 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid))); 21270 Collections.addAll(files, FileUtils 21271 .listFilesOrEmpty(Environment.getDataSystemDeDirectory())); 21272 Collections.addAll(files, FileUtils 21273 .listFilesOrEmpty(Environment.getDataSystemCeDirectory())); 21274 Collections.addAll(files, FileUtils 21275 .listFilesOrEmpty(Environment.getDataMiscCeDirectory())); 21276 for (File file : files) { 21277 if (!file.isDirectory()) continue; 21278 21279 final int userId; 21280 final UserInfo info; 21281 try { 21282 userId = Integer.parseInt(file.getName()); 21283 info = sUserManager.getUserInfo(userId); 21284 } catch (NumberFormatException e) { 21285 Slog.w(TAG, "Invalid user directory " + file); 21286 continue; 21287 } 21288 21289 boolean destroyUser = false; 21290 if (info == null) { 21291 logCriticalInfo(Log.WARN, "Destroying user directory " + file 21292 + " because no matching user was found"); 21293 destroyUser = true; 21294 } else if (!mOnlyCore) { 21295 try { 21296 UserManagerService.enforceSerialNumber(file, info.serialNumber); 21297 } catch (IOException e) { 21298 logCriticalInfo(Log.WARN, "Destroying user directory " + file 21299 + " because we failed to enforce serial number: " + e); 21300 destroyUser = true; 21301 } 21302 } 21303 21304 if (destroyUser) { 21305 synchronized (mInstallLock) { 21306 mUserDataPreparer.destroyUserDataLI(volumeUuid, userId, 21307 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 21308 } 21309 } 21310 } 21311 } 21312 21313 private void assertPackageKnown(String volumeUuid, String packageName) 21314 throws PackageManagerException { 21315 synchronized (mPackages) { 21316 // Normalize package name to handle renamed packages 21317 packageName = normalizePackageNameLPr(packageName); 21318 21319 final PackageSetting ps = mSettings.mPackages.get(packageName); 21320 if (ps == null) { 21321 throw new PackageManagerException("Package " + packageName + " is unknown"); 21322 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 21323 throw new PackageManagerException( 21324 "Package " + packageName + " found on unknown volume " + volumeUuid 21325 + "; expected volume " + ps.volumeUuid); 21326 } 21327 } 21328 } 21329 21330 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 21331 throws PackageManagerException { 21332 synchronized (mPackages) { 21333 // Normalize package name to handle renamed packages 21334 packageName = normalizePackageNameLPr(packageName); 21335 21336 final PackageSetting ps = mSettings.mPackages.get(packageName); 21337 if (ps == null) { 21338 throw new PackageManagerException("Package " + packageName + " is unknown"); 21339 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 21340 throw new PackageManagerException( 21341 "Package " + packageName + " found on unknown volume " + volumeUuid 21342 + "; expected volume " + ps.volumeUuid); 21343 } else if (!ps.getInstalled(userId)) { 21344 throw new PackageManagerException( 21345 "Package " + packageName + " not installed for user " + userId); 21346 } 21347 } 21348 } 21349 21350 private List<String> collectAbsoluteCodePaths() { 21351 synchronized (mPackages) { 21352 List<String> codePaths = new ArrayList<>(); 21353 final int packageCount = mSettings.mPackages.size(); 21354 for (int i = 0; i < packageCount; i++) { 21355 final PackageSetting ps = mSettings.mPackages.valueAt(i); 21356 codePaths.add(ps.codePath.getAbsolutePath()); 21357 } 21358 return codePaths; 21359 } 21360 } 21361 21362 /** 21363 * Examine all apps present on given mounted volume, and destroy apps that 21364 * aren't expected, either due to uninstallation or reinstallation on 21365 * another volume. 21366 */ 21367 private void reconcileApps(String volumeUuid) { 21368 List<String> absoluteCodePaths = collectAbsoluteCodePaths(); 21369 List<File> filesToDelete = null; 21370 21371 final File[] files = FileUtils.listFilesOrEmpty( 21372 Environment.getDataAppDirectory(volumeUuid)); 21373 for (File file : files) { 21374 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 21375 && !PackageInstallerService.isStageName(file.getName()); 21376 if (!isPackage) { 21377 // Ignore entries which are not packages 21378 continue; 21379 } 21380 21381 String absolutePath = file.getAbsolutePath(); 21382 21383 boolean pathValid = false; 21384 final int absoluteCodePathCount = absoluteCodePaths.size(); 21385 for (int i = 0; i < absoluteCodePathCount; i++) { 21386 String absoluteCodePath = absoluteCodePaths.get(i); 21387 if (absolutePath.startsWith(absoluteCodePath)) { 21388 pathValid = true; 21389 break; 21390 } 21391 } 21392 21393 if (!pathValid) { 21394 if (filesToDelete == null) { 21395 filesToDelete = new ArrayList<>(); 21396 } 21397 filesToDelete.add(file); 21398 } 21399 } 21400 21401 if (filesToDelete != null) { 21402 final int fileToDeleteCount = filesToDelete.size(); 21403 for (int i = 0; i < fileToDeleteCount; i++) { 21404 File fileToDelete = filesToDelete.get(i); 21405 logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete); 21406 synchronized (mInstallLock) { 21407 removeCodePathLI(fileToDelete); 21408 } 21409 } 21410 } 21411 } 21412 21413 /** 21414 * Reconcile all app data for the given user. 21415 * <p> 21416 * Verifies that directories exist and that ownership and labeling is 21417 * correct for all installed apps on all mounted volumes. 21418 */ 21419 void reconcileAppsData(int userId, int flags, boolean migrateAppsData) { 21420 final StorageManager storage = mContext.getSystemService(StorageManager.class); 21421 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 21422 final String volumeUuid = vol.getFsUuid(); 21423 synchronized (mInstallLock) { 21424 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData); 21425 } 21426 } 21427 } 21428 21429 /** 21430 * Reconcile all app data on given mounted volume. 21431 * <p> 21432 * Destroys app data that isn't expected, either due to uninstallation or 21433 * reinstallation on another volume. 21434 * <p> 21435 * Verifies that directories exist and that ownership and labeling is 21436 * correct for all installed apps. 21437 */ 21438 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags, 21439 boolean migrateAppData) { 21440 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 21441 + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData); 21442 21443 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 21444 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 21445 21446 // First look for stale data that doesn't belong, and check if things 21447 // have changed since we did our last restorecon 21448 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 21449 if (StorageManager.isFileEncryptedNativeOrEmulated() 21450 && !StorageManager.isUserKeyUnlocked(userId)) { 21451 throw new RuntimeException( 21452 "Yikes, someone asked us to reconcile CE storage while " + userId 21453 + " was still locked; this would have caused massive data loss!"); 21454 } 21455 21456 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 21457 for (File file : files) { 21458 final String packageName = file.getName(); 21459 try { 21460 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 21461 } catch (PackageManagerException e) { 21462 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 21463 try { 21464 mInstaller.destroyAppData(volumeUuid, packageName, userId, 21465 StorageManager.FLAG_STORAGE_CE, 0); 21466 } catch (InstallerException e2) { 21467 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 21468 } 21469 } 21470 } 21471 } 21472 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 21473 final File[] files = FileUtils.listFilesOrEmpty(deDir); 21474 for (File file : files) { 21475 final String packageName = file.getName(); 21476 try { 21477 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 21478 } catch (PackageManagerException e) { 21479 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 21480 try { 21481 mInstaller.destroyAppData(volumeUuid, packageName, userId, 21482 StorageManager.FLAG_STORAGE_DE, 0); 21483 } catch (InstallerException e2) { 21484 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 21485 } 21486 } 21487 } 21488 } 21489 21490 // Ensure that data directories are ready to roll for all packages 21491 // installed for this volume and user 21492 final List<PackageSetting> packages; 21493 synchronized (mPackages) { 21494 packages = mSettings.getVolumePackagesLPr(volumeUuid); 21495 } 21496 int preparedCount = 0; 21497 for (PackageSetting ps : packages) { 21498 final String packageName = ps.name; 21499 if (ps.pkg == null) { 21500 Slog.w(TAG, "Odd, missing scanned package " + packageName); 21501 // TODO: might be due to legacy ASEC apps; we should circle back 21502 // and reconcile again once they're scanned 21503 continue; 21504 } 21505 21506 if (ps.getInstalled(userId)) { 21507 prepareAppDataLIF(ps.pkg, userId, flags); 21508 21509 if (migrateAppData && maybeMigrateAppDataLIF(ps.pkg, userId)) { 21510 // We may have just shuffled around app data directories, so 21511 // prepare them one more time 21512 prepareAppDataLIF(ps.pkg, userId, flags); 21513 } 21514 21515 preparedCount++; 21516 } 21517 } 21518 21519 Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages"); 21520 } 21521 21522 /** 21523 * Prepare app data for the given app just after it was installed or 21524 * upgraded. This method carefully only touches users that it's installed 21525 * for, and it forces a restorecon to handle any seinfo changes. 21526 * <p> 21527 * Verifies that directories exist and that ownership and labeling is 21528 * correct for all installed apps. If there is an ownership mismatch, it 21529 * will try recovering system apps by wiping data; third-party app data is 21530 * left intact. 21531 * <p> 21532 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 21533 */ 21534 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 21535 final PackageSetting ps; 21536 synchronized (mPackages) { 21537 ps = mSettings.mPackages.get(pkg.packageName); 21538 mSettings.writeKernelMappingLPr(ps); 21539 } 21540 21541 final UserManager um = mContext.getSystemService(UserManager.class); 21542 UserManagerInternal umInternal = getUserManagerInternal(); 21543 for (UserInfo user : um.getUsers()) { 21544 final int flags; 21545 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 21546 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 21547 } else if (umInternal.isUserRunning(user.id)) { 21548 flags = StorageManager.FLAG_STORAGE_DE; 21549 } else { 21550 continue; 21551 } 21552 21553 if (ps.getInstalled(user.id)) { 21554 // TODO: when user data is locked, mark that we're still dirty 21555 prepareAppDataLIF(pkg, user.id, flags); 21556 } 21557 } 21558 } 21559 21560 /** 21561 * Prepare app data for the given app. 21562 * <p> 21563 * Verifies that directories exist and that ownership and labeling is 21564 * correct for all installed apps. If there is an ownership mismatch, this 21565 * will try recovering system apps by wiping data; third-party app data is 21566 * left intact. 21567 */ 21568 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 21569 if (pkg == null) { 21570 Slog.wtf(TAG, "Package was null!", new Throwable()); 21571 return; 21572 } 21573 prepareAppDataLeafLIF(pkg, userId, flags); 21574 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 21575 for (int i = 0; i < childCount; i++) { 21576 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 21577 } 21578 } 21579 21580 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 21581 if (DEBUG_APP_DATA) { 21582 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 21583 + Integer.toHexString(flags)); 21584 } 21585 21586 final String volumeUuid = pkg.volumeUuid; 21587 final String packageName = pkg.packageName; 21588 final ApplicationInfo app = pkg.applicationInfo; 21589 final int appId = UserHandle.getAppId(app.uid); 21590 21591 Preconditions.checkNotNull(app.seinfo); 21592 21593 long ceDataInode = -1; 21594 try { 21595 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 21596 appId, app.seinfo, app.targetSdkVersion); 21597 } catch (InstallerException e) { 21598 if (app.isSystemApp()) { 21599 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 21600 + ", but trying to recover: " + e); 21601 destroyAppDataLeafLIF(pkg, userId, flags); 21602 try { 21603 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 21604 appId, app.seinfo, app.targetSdkVersion); 21605 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 21606 } catch (InstallerException e2) { 21607 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 21608 } 21609 } else { 21610 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 21611 } 21612 } 21613 21614 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) { 21615 // TODO: mark this structure as dirty so we persist it! 21616 synchronized (mPackages) { 21617 final PackageSetting ps = mSettings.mPackages.get(packageName); 21618 if (ps != null) { 21619 ps.setCeDataInode(ceDataInode, userId); 21620 } 21621 } 21622 } 21623 21624 prepareAppDataContentsLeafLIF(pkg, userId, flags); 21625 } 21626 21627 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 21628 if (pkg == null) { 21629 Slog.wtf(TAG, "Package was null!", new Throwable()); 21630 return; 21631 } 21632 prepareAppDataContentsLeafLIF(pkg, userId, flags); 21633 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 21634 for (int i = 0; i < childCount; i++) { 21635 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 21636 } 21637 } 21638 21639 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 21640 final String volumeUuid = pkg.volumeUuid; 21641 final String packageName = pkg.packageName; 21642 final ApplicationInfo app = pkg.applicationInfo; 21643 21644 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 21645 // Create a native library symlink only if we have native libraries 21646 // and if the native libraries are 32 bit libraries. We do not provide 21647 // this symlink for 64 bit libraries. 21648 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 21649 final String nativeLibPath = app.nativeLibraryDir; 21650 try { 21651 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 21652 nativeLibPath, userId); 21653 } catch (InstallerException e) { 21654 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 21655 } 21656 } 21657 } 21658 } 21659 21660 /** 21661 * For system apps on non-FBE devices, this method migrates any existing 21662 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 21663 * requested by the app. 21664 */ 21665 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 21666 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 21667 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 21668 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 21669 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 21670 try { 21671 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 21672 storageTarget); 21673 } catch (InstallerException e) { 21674 logCriticalInfo(Log.WARN, 21675 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 21676 } 21677 return true; 21678 } else { 21679 return false; 21680 } 21681 } 21682 21683 public PackageFreezer freezePackage(String packageName, String killReason) { 21684 return freezePackage(packageName, UserHandle.USER_ALL, killReason); 21685 } 21686 21687 public PackageFreezer freezePackage(String packageName, int userId, String killReason) { 21688 return new PackageFreezer(packageName, userId, killReason); 21689 } 21690 21691 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 21692 String killReason) { 21693 return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason); 21694 } 21695 21696 public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags, 21697 String killReason) { 21698 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 21699 return new PackageFreezer(); 21700 } else { 21701 return freezePackage(packageName, userId, killReason); 21702 } 21703 } 21704 21705 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 21706 String killReason) { 21707 return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason); 21708 } 21709 21710 public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags, 21711 String killReason) { 21712 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 21713 return new PackageFreezer(); 21714 } else { 21715 return freezePackage(packageName, userId, killReason); 21716 } 21717 } 21718 21719 /** 21720 * Class that freezes and kills the given package upon creation, and 21721 * unfreezes it upon closing. This is typically used when doing surgery on 21722 * app code/data to prevent the app from running while you're working. 21723 */ 21724 private class PackageFreezer implements AutoCloseable { 21725 private final String mPackageName; 21726 private final PackageFreezer[] mChildren; 21727 21728 private final boolean mWeFroze; 21729 21730 private final AtomicBoolean mClosed = new AtomicBoolean(); 21731 private final CloseGuard mCloseGuard = CloseGuard.get(); 21732 21733 /** 21734 * Create and return a stub freezer that doesn't actually do anything, 21735 * typically used when someone requested 21736 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 21737 * {@link PackageManager#DELETE_DONT_KILL_APP}. 21738 */ 21739 public PackageFreezer() { 21740 mPackageName = null; 21741 mChildren = null; 21742 mWeFroze = false; 21743 mCloseGuard.open("close"); 21744 } 21745 21746 public PackageFreezer(String packageName, int userId, String killReason) { 21747 synchronized (mPackages) { 21748 mPackageName = packageName; 21749 mWeFroze = mFrozenPackages.add(mPackageName); 21750 21751 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 21752 if (ps != null) { 21753 killApplication(ps.name, ps.appId, userId, killReason); 21754 } 21755 21756 final PackageParser.Package p = mPackages.get(packageName); 21757 if (p != null && p.childPackages != null) { 21758 final int N = p.childPackages.size(); 21759 mChildren = new PackageFreezer[N]; 21760 for (int i = 0; i < N; i++) { 21761 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 21762 userId, killReason); 21763 } 21764 } else { 21765 mChildren = null; 21766 } 21767 } 21768 mCloseGuard.open("close"); 21769 } 21770 21771 @Override 21772 protected void finalize() throws Throwable { 21773 try { 21774 mCloseGuard.warnIfOpen(); 21775 close(); 21776 } finally { 21777 super.finalize(); 21778 } 21779 } 21780 21781 @Override 21782 public void close() { 21783 mCloseGuard.close(); 21784 if (mClosed.compareAndSet(false, true)) { 21785 synchronized (mPackages) { 21786 if (mWeFroze) { 21787 mFrozenPackages.remove(mPackageName); 21788 } 21789 21790 if (mChildren != null) { 21791 for (PackageFreezer freezer : mChildren) { 21792 freezer.close(); 21793 } 21794 } 21795 } 21796 } 21797 } 21798 } 21799 21800 /** 21801 * Verify that given package is currently frozen. 21802 */ 21803 private void checkPackageFrozen(String packageName) { 21804 synchronized (mPackages) { 21805 if (!mFrozenPackages.contains(packageName)) { 21806 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 21807 } 21808 } 21809 } 21810 21811 @Override 21812 public int movePackage(final String packageName, final String volumeUuid) { 21813 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 21814 21815 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 21816 final int moveId = mNextMoveId.getAndIncrement(); 21817 mHandler.post(new Runnable() { 21818 @Override 21819 public void run() { 21820 try { 21821 movePackageInternal(packageName, volumeUuid, moveId, user); 21822 } catch (PackageManagerException e) { 21823 Slog.w(TAG, "Failed to move " + packageName, e); 21824 mMoveCallbacks.notifyStatusChanged(moveId, 21825 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 21826 } 21827 } 21828 }); 21829 return moveId; 21830 } 21831 21832 private void movePackageInternal(final String packageName, final String volumeUuid, 21833 final int moveId, UserHandle user) throws PackageManagerException { 21834 final StorageManager storage = mContext.getSystemService(StorageManager.class); 21835 final PackageManager pm = mContext.getPackageManager(); 21836 21837 final boolean currentAsec; 21838 final String currentVolumeUuid; 21839 final File codeFile; 21840 final String installerPackageName; 21841 final String packageAbiOverride; 21842 final int appId; 21843 final String seinfo; 21844 final String label; 21845 final int targetSdkVersion; 21846 final PackageFreezer freezer; 21847 final int[] installedUserIds; 21848 21849 // reader 21850 synchronized (mPackages) { 21851 final PackageParser.Package pkg = mPackages.get(packageName); 21852 final PackageSetting ps = mSettings.mPackages.get(packageName); 21853 if (pkg == null || ps == null) { 21854 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 21855 } 21856 21857 if (pkg.applicationInfo.isSystemApp()) { 21858 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 21859 "Cannot move system application"); 21860 } 21861 21862 final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid); 21863 final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean( 21864 com.android.internal.R.bool.config_allow3rdPartyAppOnInternal); 21865 if (isInternalStorage && !allow3rdPartyOnInternal) { 21866 throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL, 21867 "3rd party apps are not allowed on internal storage"); 21868 } 21869 21870 if (pkg.applicationInfo.isExternalAsec()) { 21871 currentAsec = true; 21872 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 21873 } else if (pkg.applicationInfo.isForwardLocked()) { 21874 currentAsec = true; 21875 currentVolumeUuid = "forward_locked"; 21876 } else { 21877 currentAsec = false; 21878 currentVolumeUuid = ps.volumeUuid; 21879 21880 final File probe = new File(pkg.codePath); 21881 final File probeOat = new File(probe, "oat"); 21882 if (!probe.isDirectory() || !probeOat.isDirectory()) { 21883 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 21884 "Move only supported for modern cluster style installs"); 21885 } 21886 } 21887 21888 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 21889 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 21890 "Package already moved to " + volumeUuid); 21891 } 21892 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 21893 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 21894 "Device admin cannot be moved"); 21895 } 21896 21897 if (mFrozenPackages.contains(packageName)) { 21898 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 21899 "Failed to move already frozen package"); 21900 } 21901 21902 codeFile = new File(pkg.codePath); 21903 installerPackageName = ps.installerPackageName; 21904 packageAbiOverride = ps.cpuAbiOverrideString; 21905 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 21906 seinfo = pkg.applicationInfo.seinfo; 21907 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 21908 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 21909 freezer = freezePackage(packageName, "movePackageInternal"); 21910 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 21911 } 21912 21913 final Bundle extras = new Bundle(); 21914 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 21915 extras.putString(Intent.EXTRA_TITLE, label); 21916 mMoveCallbacks.notifyCreated(moveId, extras); 21917 21918 int installFlags; 21919 final boolean moveCompleteApp; 21920 final File measurePath; 21921 21922 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 21923 installFlags = INSTALL_INTERNAL; 21924 moveCompleteApp = !currentAsec; 21925 measurePath = Environment.getDataAppDirectory(volumeUuid); 21926 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 21927 installFlags = INSTALL_EXTERNAL; 21928 moveCompleteApp = false; 21929 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 21930 } else { 21931 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 21932 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 21933 || !volume.isMountedWritable()) { 21934 freezer.close(); 21935 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 21936 "Move location not mounted private volume"); 21937 } 21938 21939 Preconditions.checkState(!currentAsec); 21940 21941 installFlags = INSTALL_INTERNAL; 21942 moveCompleteApp = true; 21943 measurePath = Environment.getDataAppDirectory(volumeUuid); 21944 } 21945 21946 final PackageStats stats = new PackageStats(null, -1); 21947 synchronized (mInstaller) { 21948 for (int userId : installedUserIds) { 21949 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 21950 freezer.close(); 21951 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 21952 "Failed to measure package size"); 21953 } 21954 } 21955 } 21956 21957 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 21958 + stats.dataSize); 21959 21960 final long startFreeBytes = measurePath.getFreeSpace(); 21961 final long sizeBytes; 21962 if (moveCompleteApp) { 21963 sizeBytes = stats.codeSize + stats.dataSize; 21964 } else { 21965 sizeBytes = stats.codeSize; 21966 } 21967 21968 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 21969 freezer.close(); 21970 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 21971 "Not enough free space to move"); 21972 } 21973 21974 mMoveCallbacks.notifyStatusChanged(moveId, 10); 21975 21976 final CountDownLatch installedLatch = new CountDownLatch(1); 21977 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 21978 @Override 21979 public void onUserActionRequired(Intent intent) throws RemoteException { 21980 throw new IllegalStateException(); 21981 } 21982 21983 @Override 21984 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 21985 Bundle extras) throws RemoteException { 21986 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 21987 + PackageManager.installStatusToString(returnCode, msg)); 21988 21989 installedLatch.countDown(); 21990 freezer.close(); 21991 21992 final int status = PackageManager.installStatusToPublicStatus(returnCode); 21993 switch (status) { 21994 case PackageInstaller.STATUS_SUCCESS: 21995 mMoveCallbacks.notifyStatusChanged(moveId, 21996 PackageManager.MOVE_SUCCEEDED); 21997 break; 21998 case PackageInstaller.STATUS_FAILURE_STORAGE: 21999 mMoveCallbacks.notifyStatusChanged(moveId, 22000 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 22001 break; 22002 default: 22003 mMoveCallbacks.notifyStatusChanged(moveId, 22004 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 22005 break; 22006 } 22007 } 22008 }; 22009 22010 final MoveInfo move; 22011 if (moveCompleteApp) { 22012 // Kick off a thread to report progress estimates 22013 new Thread() { 22014 @Override 22015 public void run() { 22016 while (true) { 22017 try { 22018 if (installedLatch.await(1, TimeUnit.SECONDS)) { 22019 break; 22020 } 22021 } catch (InterruptedException ignored) { 22022 } 22023 22024 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 22025 final int progress = 10 + (int) MathUtils.constrain( 22026 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 22027 mMoveCallbacks.notifyStatusChanged(moveId, progress); 22028 } 22029 } 22030 }.start(); 22031 22032 final String dataAppName = codeFile.getName(); 22033 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 22034 dataAppName, appId, seinfo, targetSdkVersion); 22035 } else { 22036 move = null; 22037 } 22038 22039 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 22040 22041 final Message msg = mHandler.obtainMessage(INIT_COPY); 22042 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 22043 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 22044 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 22045 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/, 22046 PackageManager.INSTALL_REASON_UNKNOWN); 22047 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 22048 msg.obj = params; 22049 22050 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 22051 System.identityHashCode(msg.obj)); 22052 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 22053 System.identityHashCode(msg.obj)); 22054 22055 mHandler.sendMessage(msg); 22056 } 22057 22058 @Override 22059 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 22060 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 22061 22062 final int realMoveId = mNextMoveId.getAndIncrement(); 22063 final Bundle extras = new Bundle(); 22064 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 22065 mMoveCallbacks.notifyCreated(realMoveId, extras); 22066 22067 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 22068 @Override 22069 public void onCreated(int moveId, Bundle extras) { 22070 // Ignored 22071 } 22072 22073 @Override 22074 public void onStatusChanged(int moveId, int status, long estMillis) { 22075 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 22076 } 22077 }; 22078 22079 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22080 storage.setPrimaryStorageUuid(volumeUuid, callback); 22081 return realMoveId; 22082 } 22083 22084 @Override 22085 public int getMoveStatus(int moveId) { 22086 mContext.enforceCallingOrSelfPermission( 22087 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22088 return mMoveCallbacks.mLastStatus.get(moveId); 22089 } 22090 22091 @Override 22092 public void registerMoveCallback(IPackageMoveObserver callback) { 22093 mContext.enforceCallingOrSelfPermission( 22094 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22095 mMoveCallbacks.register(callback); 22096 } 22097 22098 @Override 22099 public void unregisterMoveCallback(IPackageMoveObserver callback) { 22100 mContext.enforceCallingOrSelfPermission( 22101 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22102 mMoveCallbacks.unregister(callback); 22103 } 22104 22105 @Override 22106 public boolean setInstallLocation(int loc) { 22107 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 22108 null); 22109 if (getInstallLocation() == loc) { 22110 return true; 22111 } 22112 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 22113 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 22114 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 22115 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 22116 return true; 22117 } 22118 return false; 22119 } 22120 22121 @Override 22122 public int getInstallLocation() { 22123 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 22124 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 22125 PackageHelper.APP_INSTALL_AUTO); 22126 } 22127 22128 /** Called by UserManagerService */ 22129 void cleanUpUser(UserManagerService userManager, int userHandle) { 22130 synchronized (mPackages) { 22131 mDirtyUsers.remove(userHandle); 22132 mUserNeedsBadging.delete(userHandle); 22133 mSettings.removeUserLPw(userHandle); 22134 mPendingBroadcasts.remove(userHandle); 22135 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 22136 removeUnusedPackagesLPw(userManager, userHandle); 22137 } 22138 } 22139 22140 /** 22141 * We're removing userHandle and would like to remove any downloaded packages 22142 * that are no longer in use by any other user. 22143 * @param userHandle the user being removed 22144 */ 22145 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 22146 final boolean DEBUG_CLEAN_APKS = false; 22147 int [] users = userManager.getUserIds(); 22148 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 22149 while (psit.hasNext()) { 22150 PackageSetting ps = psit.next(); 22151 if (ps.pkg == null) { 22152 continue; 22153 } 22154 final String packageName = ps.pkg.packageName; 22155 // Skip over if system app 22156 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 22157 continue; 22158 } 22159 if (DEBUG_CLEAN_APKS) { 22160 Slog.i(TAG, "Checking package " + packageName); 22161 } 22162 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 22163 if (keep) { 22164 if (DEBUG_CLEAN_APKS) { 22165 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 22166 } 22167 } else { 22168 for (int i = 0; i < users.length; i++) { 22169 if (users[i] != userHandle && ps.getInstalled(users[i])) { 22170 keep = true; 22171 if (DEBUG_CLEAN_APKS) { 22172 Slog.i(TAG, " Keeping package " + packageName + " for user " 22173 + users[i]); 22174 } 22175 break; 22176 } 22177 } 22178 } 22179 if (!keep) { 22180 if (DEBUG_CLEAN_APKS) { 22181 Slog.i(TAG, " Removing package " + packageName); 22182 } 22183 mHandler.post(new Runnable() { 22184 public void run() { 22185 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 22186 userHandle, 0); 22187 } //end run 22188 }); 22189 } 22190 } 22191 } 22192 22193 /** Called by UserManagerService */ 22194 void createNewUser(int userId, String[] disallowedPackages) { 22195 synchronized (mInstallLock) { 22196 mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages); 22197 } 22198 synchronized (mPackages) { 22199 scheduleWritePackageRestrictionsLocked(userId); 22200 scheduleWritePackageListLocked(userId); 22201 applyFactoryDefaultBrowserLPw(userId); 22202 primeDomainVerificationsLPw(userId); 22203 } 22204 } 22205 22206 void onNewUserCreated(final int userId) { 22207 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 22208 // If permission review for legacy apps is required, we represent 22209 // dagerous permissions for such apps as always granted runtime 22210 // permissions to keep per user flag state whether review is needed. 22211 // Hence, if a new user is added we have to propagate dangerous 22212 // permission grants for these legacy apps. 22213 if (mPermissionReviewRequired) { 22214 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 22215 | UPDATE_PERMISSIONS_REPLACE_ALL); 22216 } 22217 } 22218 22219 @Override 22220 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 22221 mContext.enforceCallingOrSelfPermission( 22222 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 22223 "Only package verification agents can read the verifier device identity"); 22224 22225 synchronized (mPackages) { 22226 return mSettings.getVerifierDeviceIdentityLPw(); 22227 } 22228 } 22229 22230 @Override 22231 public void setPermissionEnforced(String permission, boolean enforced) { 22232 // TODO: Now that we no longer change GID for storage, this should to away. 22233 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 22234 "setPermissionEnforced"); 22235 if (READ_EXTERNAL_STORAGE.equals(permission)) { 22236 synchronized (mPackages) { 22237 if (mSettings.mReadExternalStorageEnforced == null 22238 || mSettings.mReadExternalStorageEnforced != enforced) { 22239 mSettings.mReadExternalStorageEnforced = enforced; 22240 mSettings.writeLPr(); 22241 } 22242 } 22243 // kill any non-foreground processes so we restart them and 22244 // grant/revoke the GID. 22245 final IActivityManager am = ActivityManager.getService(); 22246 if (am != null) { 22247 final long token = Binder.clearCallingIdentity(); 22248 try { 22249 am.killProcessesBelowForeground("setPermissionEnforcement"); 22250 } catch (RemoteException e) { 22251 } finally { 22252 Binder.restoreCallingIdentity(token); 22253 } 22254 } 22255 } else { 22256 throw new IllegalArgumentException("No selective enforcement for " + permission); 22257 } 22258 } 22259 22260 @Override 22261 @Deprecated 22262 public boolean isPermissionEnforced(String permission) { 22263 return true; 22264 } 22265 22266 @Override 22267 public boolean isStorageLow() { 22268 final long token = Binder.clearCallingIdentity(); 22269 try { 22270 final DeviceStorageMonitorInternal 22271 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 22272 if (dsm != null) { 22273 return dsm.isMemoryLow(); 22274 } else { 22275 return false; 22276 } 22277 } finally { 22278 Binder.restoreCallingIdentity(token); 22279 } 22280 } 22281 22282 @Override 22283 public IPackageInstaller getPackageInstaller() { 22284 return mInstallerService; 22285 } 22286 22287 private boolean userNeedsBadging(int userId) { 22288 int index = mUserNeedsBadging.indexOfKey(userId); 22289 if (index < 0) { 22290 final UserInfo userInfo; 22291 final long token = Binder.clearCallingIdentity(); 22292 try { 22293 userInfo = sUserManager.getUserInfo(userId); 22294 } finally { 22295 Binder.restoreCallingIdentity(token); 22296 } 22297 final boolean b; 22298 if (userInfo != null && userInfo.isManagedProfile()) { 22299 b = true; 22300 } else { 22301 b = false; 22302 } 22303 mUserNeedsBadging.put(userId, b); 22304 return b; 22305 } 22306 return mUserNeedsBadging.valueAt(index); 22307 } 22308 22309 @Override 22310 public KeySet getKeySetByAlias(String packageName, String alias) { 22311 if (packageName == null || alias == null) { 22312 return null; 22313 } 22314 synchronized(mPackages) { 22315 final PackageParser.Package pkg = mPackages.get(packageName); 22316 if (pkg == null) { 22317 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22318 throw new IllegalArgumentException("Unknown package: " + packageName); 22319 } 22320 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22321 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 22322 } 22323 } 22324 22325 @Override 22326 public KeySet getSigningKeySet(String packageName) { 22327 if (packageName == null) { 22328 return null; 22329 } 22330 synchronized(mPackages) { 22331 final PackageParser.Package pkg = mPackages.get(packageName); 22332 if (pkg == null) { 22333 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22334 throw new IllegalArgumentException("Unknown package: " + packageName); 22335 } 22336 if (pkg.applicationInfo.uid != Binder.getCallingUid() 22337 && Process.SYSTEM_UID != Binder.getCallingUid()) { 22338 throw new SecurityException("May not access signing KeySet of other apps."); 22339 } 22340 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22341 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 22342 } 22343 } 22344 22345 @Override 22346 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 22347 if (packageName == null || ks == null) { 22348 return false; 22349 } 22350 synchronized(mPackages) { 22351 final PackageParser.Package pkg = mPackages.get(packageName); 22352 if (pkg == null) { 22353 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22354 throw new IllegalArgumentException("Unknown package: " + packageName); 22355 } 22356 IBinder ksh = ks.getToken(); 22357 if (ksh instanceof KeySetHandle) { 22358 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22359 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 22360 } 22361 return false; 22362 } 22363 } 22364 22365 @Override 22366 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 22367 if (packageName == null || ks == null) { 22368 return false; 22369 } 22370 synchronized(mPackages) { 22371 final PackageParser.Package pkg = mPackages.get(packageName); 22372 if (pkg == null) { 22373 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22374 throw new IllegalArgumentException("Unknown package: " + packageName); 22375 } 22376 IBinder ksh = ks.getToken(); 22377 if (ksh instanceof KeySetHandle) { 22378 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22379 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 22380 } 22381 return false; 22382 } 22383 } 22384 22385 private void deletePackageIfUnusedLPr(final String packageName) { 22386 PackageSetting ps = mSettings.mPackages.get(packageName); 22387 if (ps == null) { 22388 return; 22389 } 22390 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 22391 // TODO Implement atomic delete if package is unused 22392 // It is currently possible that the package will be deleted even if it is installed 22393 // after this method returns. 22394 mHandler.post(new Runnable() { 22395 public void run() { 22396 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 22397 0, PackageManager.DELETE_ALL_USERS); 22398 } 22399 }); 22400 } 22401 } 22402 22403 /** 22404 * Check and throw if the given before/after packages would be considered a 22405 * downgrade. 22406 */ 22407 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 22408 throws PackageManagerException { 22409 if (after.versionCode < before.mVersionCode) { 22410 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 22411 "Update version code " + after.versionCode + " is older than current " 22412 + before.mVersionCode); 22413 } else if (after.versionCode == before.mVersionCode) { 22414 if (after.baseRevisionCode < before.baseRevisionCode) { 22415 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 22416 "Update base revision code " + after.baseRevisionCode 22417 + " is older than current " + before.baseRevisionCode); 22418 } 22419 22420 if (!ArrayUtils.isEmpty(after.splitNames)) { 22421 for (int i = 0; i < after.splitNames.length; i++) { 22422 final String splitName = after.splitNames[i]; 22423 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 22424 if (j != -1) { 22425 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 22426 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 22427 "Update split " + splitName + " revision code " 22428 + after.splitRevisionCodes[i] + " is older than current " 22429 + before.splitRevisionCodes[j]); 22430 } 22431 } 22432 } 22433 } 22434 } 22435 } 22436 22437 private static class MoveCallbacks extends Handler { 22438 private static final int MSG_CREATED = 1; 22439 private static final int MSG_STATUS_CHANGED = 2; 22440 22441 private final RemoteCallbackList<IPackageMoveObserver> 22442 mCallbacks = new RemoteCallbackList<>(); 22443 22444 private final SparseIntArray mLastStatus = new SparseIntArray(); 22445 22446 public MoveCallbacks(Looper looper) { 22447 super(looper); 22448 } 22449 22450 public void register(IPackageMoveObserver callback) { 22451 mCallbacks.register(callback); 22452 } 22453 22454 public void unregister(IPackageMoveObserver callback) { 22455 mCallbacks.unregister(callback); 22456 } 22457 22458 @Override 22459 public void handleMessage(Message msg) { 22460 final SomeArgs args = (SomeArgs) msg.obj; 22461 final int n = mCallbacks.beginBroadcast(); 22462 for (int i = 0; i < n; i++) { 22463 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 22464 try { 22465 invokeCallback(callback, msg.what, args); 22466 } catch (RemoteException ignored) { 22467 } 22468 } 22469 mCallbacks.finishBroadcast(); 22470 args.recycle(); 22471 } 22472 22473 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 22474 throws RemoteException { 22475 switch (what) { 22476 case MSG_CREATED: { 22477 callback.onCreated(args.argi1, (Bundle) args.arg2); 22478 break; 22479 } 22480 case MSG_STATUS_CHANGED: { 22481 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 22482 break; 22483 } 22484 } 22485 } 22486 22487 private void notifyCreated(int moveId, Bundle extras) { 22488 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 22489 22490 final SomeArgs args = SomeArgs.obtain(); 22491 args.argi1 = moveId; 22492 args.arg2 = extras; 22493 obtainMessage(MSG_CREATED, args).sendToTarget(); 22494 } 22495 22496 private void notifyStatusChanged(int moveId, int status) { 22497 notifyStatusChanged(moveId, status, -1); 22498 } 22499 22500 private void notifyStatusChanged(int moveId, int status, long estMillis) { 22501 Slog.v(TAG, "Move " + moveId + " status " + status); 22502 22503 final SomeArgs args = SomeArgs.obtain(); 22504 args.argi1 = moveId; 22505 args.argi2 = status; 22506 args.arg3 = estMillis; 22507 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 22508 22509 synchronized (mLastStatus) { 22510 mLastStatus.put(moveId, status); 22511 } 22512 } 22513 } 22514 22515 private final static class OnPermissionChangeListeners extends Handler { 22516 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 22517 22518 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 22519 new RemoteCallbackList<>(); 22520 22521 public OnPermissionChangeListeners(Looper looper) { 22522 super(looper); 22523 } 22524 22525 @Override 22526 public void handleMessage(Message msg) { 22527 switch (msg.what) { 22528 case MSG_ON_PERMISSIONS_CHANGED: { 22529 final int uid = msg.arg1; 22530 handleOnPermissionsChanged(uid); 22531 } break; 22532 } 22533 } 22534 22535 public void addListenerLocked(IOnPermissionsChangeListener listener) { 22536 mPermissionListeners.register(listener); 22537 22538 } 22539 22540 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 22541 mPermissionListeners.unregister(listener); 22542 } 22543 22544 public void onPermissionsChanged(int uid) { 22545 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 22546 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 22547 } 22548 } 22549 22550 private void handleOnPermissionsChanged(int uid) { 22551 final int count = mPermissionListeners.beginBroadcast(); 22552 try { 22553 for (int i = 0; i < count; i++) { 22554 IOnPermissionsChangeListener callback = mPermissionListeners 22555 .getBroadcastItem(i); 22556 try { 22557 callback.onPermissionsChanged(uid); 22558 } catch (RemoteException e) { 22559 Log.e(TAG, "Permission listener is dead", e); 22560 } 22561 } 22562 } finally { 22563 mPermissionListeners.finishBroadcast(); 22564 } 22565 } 22566 } 22567 22568 private class PackageManagerInternalImpl extends PackageManagerInternal { 22569 @Override 22570 public void setLocationPackagesProvider(PackagesProvider provider) { 22571 synchronized (mPackages) { 22572 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 22573 } 22574 } 22575 22576 @Override 22577 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 22578 synchronized (mPackages) { 22579 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 22580 } 22581 } 22582 22583 @Override 22584 public void setSmsAppPackagesProvider(PackagesProvider provider) { 22585 synchronized (mPackages) { 22586 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 22587 } 22588 } 22589 22590 @Override 22591 public void setDialerAppPackagesProvider(PackagesProvider provider) { 22592 synchronized (mPackages) { 22593 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 22594 } 22595 } 22596 22597 @Override 22598 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 22599 synchronized (mPackages) { 22600 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 22601 } 22602 } 22603 22604 @Override 22605 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 22606 synchronized (mPackages) { 22607 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 22608 } 22609 } 22610 22611 @Override 22612 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 22613 synchronized (mPackages) { 22614 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 22615 packageName, userId); 22616 } 22617 } 22618 22619 @Override 22620 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 22621 synchronized (mPackages) { 22622 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 22623 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 22624 packageName, userId); 22625 } 22626 } 22627 22628 @Override 22629 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 22630 synchronized (mPackages) { 22631 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 22632 packageName, userId); 22633 } 22634 } 22635 22636 @Override 22637 public void setKeepUninstalledPackages(final List<String> packageList) { 22638 Preconditions.checkNotNull(packageList); 22639 List<String> removedFromList = null; 22640 synchronized (mPackages) { 22641 if (mKeepUninstalledPackages != null) { 22642 final int packagesCount = mKeepUninstalledPackages.size(); 22643 for (int i = 0; i < packagesCount; i++) { 22644 String oldPackage = mKeepUninstalledPackages.get(i); 22645 if (packageList != null && packageList.contains(oldPackage)) { 22646 continue; 22647 } 22648 if (removedFromList == null) { 22649 removedFromList = new ArrayList<>(); 22650 } 22651 removedFromList.add(oldPackage); 22652 } 22653 } 22654 mKeepUninstalledPackages = new ArrayList<>(packageList); 22655 if (removedFromList != null) { 22656 final int removedCount = removedFromList.size(); 22657 for (int i = 0; i < removedCount; i++) { 22658 deletePackageIfUnusedLPr(removedFromList.get(i)); 22659 } 22660 } 22661 } 22662 } 22663 22664 @Override 22665 public boolean isPermissionsReviewRequired(String packageName, int userId) { 22666 synchronized (mPackages) { 22667 // If we do not support permission review, done. 22668 if (!mPermissionReviewRequired) { 22669 return false; 22670 } 22671 22672 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 22673 if (packageSetting == null) { 22674 return false; 22675 } 22676 22677 // Permission review applies only to apps not supporting the new permission model. 22678 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 22679 return false; 22680 } 22681 22682 // Legacy apps have the permission and get user consent on launch. 22683 PermissionsState permissionsState = packageSetting.getPermissionsState(); 22684 return permissionsState.isPermissionReviewRequired(userId); 22685 } 22686 } 22687 22688 @Override 22689 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 22690 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 22691 } 22692 22693 @Override 22694 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 22695 int userId) { 22696 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 22697 } 22698 22699 @Override 22700 public void setDeviceAndProfileOwnerPackages( 22701 int deviceOwnerUserId, String deviceOwnerPackage, 22702 SparseArray<String> profileOwnerPackages) { 22703 mProtectedPackages.setDeviceAndProfileOwnerPackages( 22704 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages); 22705 } 22706 22707 @Override 22708 public boolean isPackageDataProtected(int userId, String packageName) { 22709 return mProtectedPackages.isPackageDataProtected(userId, packageName); 22710 } 22711 22712 @Override 22713 public boolean isPackageEphemeral(int userId, String packageName) { 22714 synchronized (mPackages) { 22715 PackageParser.Package p = mPackages.get(packageName); 22716 return p != null ? p.applicationInfo.isEphemeralApp() : false; 22717 } 22718 } 22719 22720 @Override 22721 public boolean wasPackageEverLaunched(String packageName, int userId) { 22722 synchronized (mPackages) { 22723 return mSettings.wasPackageEverLaunchedLPr(packageName, userId); 22724 } 22725 } 22726 22727 @Override 22728 public void grantRuntimePermission(String packageName, String name, int userId, 22729 boolean overridePolicy) { 22730 PackageManagerService.this.grantRuntimePermission(packageName, name, userId, 22731 overridePolicy); 22732 } 22733 22734 @Override 22735 public void revokeRuntimePermission(String packageName, String name, int userId, 22736 boolean overridePolicy) { 22737 PackageManagerService.this.revokeRuntimePermission(packageName, name, userId, 22738 overridePolicy); 22739 } 22740 22741 @Override 22742 public String getNameForUid(int uid) { 22743 return PackageManagerService.this.getNameForUid(uid); 22744 } 22745 22746 @Override 22747 public void requestEphemeralResolutionPhaseTwo(EphemeralResponse responseObj, 22748 Intent origIntent, String resolvedType, Intent launchIntent, 22749 String callingPackage, int userId) { 22750 PackageManagerService.this.requestEphemeralResolutionPhaseTwo( 22751 responseObj, origIntent, resolvedType, launchIntent, callingPackage, userId); 22752 } 22753 22754 @Override 22755 public void grantEphemeralAccess(int userId, Intent intent, 22756 int targetAppId, int ephemeralAppId) { 22757 synchronized (mPackages) { 22758 mEphemeralApplicationRegistry.grantEphemeralAccessLPw(userId, intent, 22759 targetAppId, ephemeralAppId); 22760 } 22761 } 22762 22763 public String getSetupWizardPackageName() { 22764 return mSetupWizardPackage; 22765 } 22766 22767 public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) { 22768 if (policy != null) { 22769 mExternalSourcesPolicy = policy; 22770 } 22771 } 22772 } 22773 22774 @Override 22775 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 22776 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 22777 synchronized (mPackages) { 22778 final long identity = Binder.clearCallingIdentity(); 22779 try { 22780 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 22781 packageNames, userId); 22782 } finally { 22783 Binder.restoreCallingIdentity(identity); 22784 } 22785 } 22786 } 22787 22788 private static void enforceSystemOrPhoneCaller(String tag) { 22789 int callingUid = Binder.getCallingUid(); 22790 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 22791 throw new SecurityException( 22792 "Cannot call " + tag + " from UID " + callingUid); 22793 } 22794 } 22795 22796 boolean isHistoricalPackageUsageAvailable() { 22797 return mPackageUsage.isHistoricalPackageUsageAvailable(); 22798 } 22799 22800 /** 22801 * Return a <b>copy</b> of the collection of packages known to the package manager. 22802 * @return A copy of the values of mPackages. 22803 */ 22804 Collection<PackageParser.Package> getPackages() { 22805 synchronized (mPackages) { 22806 return new ArrayList<>(mPackages.values()); 22807 } 22808 } 22809 22810 /** 22811 * Logs process start information (including base APK hash) to the security log. 22812 * @hide 22813 */ 22814 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 22815 String apkFile, int pid) { 22816 if (!SecurityLog.isLoggingEnabled()) { 22817 return; 22818 } 22819 Bundle data = new Bundle(); 22820 data.putLong("startTimestamp", System.currentTimeMillis()); 22821 data.putString("processName", processName); 22822 data.putInt("uid", uid); 22823 data.putString("seinfo", seinfo); 22824 data.putString("apkFile", apkFile); 22825 data.putInt("pid", pid); 22826 Message msg = mProcessLoggingHandler.obtainMessage( 22827 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 22828 msg.setData(data); 22829 mProcessLoggingHandler.sendMessage(msg); 22830 } 22831 22832 public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) { 22833 return mCompilerStats.getPackageStats(pkgName); 22834 } 22835 22836 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) { 22837 return getOrCreateCompilerPackageStats(pkg.packageName); 22838 } 22839 22840 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) { 22841 return mCompilerStats.getOrCreatePackageStats(pkgName); 22842 } 22843 22844 public void deleteCompilerPackageStats(String pkgName) { 22845 mCompilerStats.deletePackageStats(pkgName); 22846 } 22847 22848 @Override 22849 public int getInstallReason(String packageName, int userId) { 22850 enforceCrossUserPermission(Binder.getCallingUid(), userId, 22851 true /* requireFullPermission */, false /* checkShell */, 22852 "get install reason"); 22853 synchronized (mPackages) { 22854 final PackageSetting ps = mSettings.mPackages.get(packageName); 22855 if (ps != null) { 22856 return ps.getInstallReason(userId); 22857 } 22858 } 22859 return PackageManager.INSTALL_REASON_UNKNOWN; 22860 } 22861 22862 @Override 22863 public boolean canRequestPackageInstalls(String packageName, int userId) { 22864 int callingUid = Binder.getCallingUid(); 22865 int uid = getPackageUid(packageName, 0, userId); 22866 if (callingUid != uid && callingUid != Process.ROOT_UID 22867 && callingUid != Process.SYSTEM_UID) { 22868 throw new SecurityException( 22869 "Caller uid " + callingUid + " does not own package " + packageName); 22870 } 22871 ApplicationInfo info = getApplicationInfo(packageName, 0, userId); 22872 if (info == null) { 22873 return false; 22874 } 22875 if (info.targetSdkVersion < Build.VERSION_CODES.O) { 22876 throw new UnsupportedOperationException( 22877 "Operation only supported on apps targeting Android O or higher"); 22878 } 22879 String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES; 22880 String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission); 22881 if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) { 22882 throw new SecurityException("Need to declare " + appOpPermission + " to call this api"); 22883 } 22884 if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) { 22885 return false; 22886 } 22887 if (mExternalSourcesPolicy != null) { 22888 int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid); 22889 if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) { 22890 return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED; 22891 } 22892 } 22893 return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED; 22894 } 22895} 22896