PackageManagerService.java revision 022b8eaa1def76dca0ac9b409065588f55c71597
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.READ_EXTERNAL_STORAGE; 20import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; 21import static android.Manifest.permission.WRITE_MEDIA_STORAGE; 22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 27import static android.content.pm.PackageManager.DELETE_KEEP_DATA; 28import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 29import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED; 30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 31import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 32import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED; 34import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET; 35import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 36import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 37import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 38import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 40import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID; 41import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 42import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 43import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 44import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 45import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 46import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 47import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 48import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 49import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 50import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 51import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 52import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 53import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 54import static android.content.pm.PackageManager.INSTALL_INTERNAL; 55import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 56import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK; 58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 61import static android.content.pm.PackageManager.MATCH_ALL; 62import static android.content.pm.PackageManager.MATCH_ANY_USER; 63import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 64import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE; 65import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE; 66import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS; 67import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY; 68import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES; 69import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY; 70import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES; 71import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL; 72import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN; 73import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 74import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 75import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 76import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 77import static android.content.pm.PackageManager.PERMISSION_DENIED; 78import static android.content.pm.PackageManager.PERMISSION_GRANTED; 79import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED; 80import static android.content.pm.PackageParser.isApkFile; 81import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 82import static android.system.OsConstants.O_CREAT; 83import static android.system.OsConstants.O_RDWR; 84 85import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 86import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 87import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 88import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 89import static com.android.internal.util.ArrayUtils.appendInt; 90import static com.android.server.pm.Installer.DEXOPT_PUBLIC; 91import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 92import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 93import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 94import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 95import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 96import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason; 97import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter; 98import static com.android.server.pm.PackageManagerServiceCompilerMapping.getNonProfileGuidedCompilerFilter; 99import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 100import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 101import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 102 103import android.Manifest; 104import android.annotation.NonNull; 105import android.annotation.Nullable; 106import android.annotation.UserIdInt; 107import android.app.ActivityManager; 108import android.app.AppOpsManager; 109import android.app.IActivityManager; 110import android.app.ResourcesManager; 111import android.app.admin.IDevicePolicyManager; 112import android.app.admin.SecurityLog; 113import android.app.backup.IBackupManager; 114import android.content.BroadcastReceiver; 115import android.content.ComponentName; 116import android.content.ContentResolver; 117import android.content.Context; 118import android.content.IIntentReceiver; 119import android.content.Intent; 120import android.content.IntentFilter; 121import android.content.IntentSender; 122import android.content.IntentSender.SendIntentException; 123import android.content.ServiceConnection; 124import android.content.pm.ActivityInfo; 125import android.content.pm.ApplicationInfo; 126import android.content.pm.AppsQueryHelper; 127import android.content.pm.ComponentInfo; 128import android.content.pm.EphemeralApplicationInfo; 129import android.content.pm.EphemeralRequest; 130import android.content.pm.EphemeralResolveInfo; 131import android.content.pm.EphemeralResponse; 132import android.content.pm.FeatureInfo; 133import android.content.pm.IOnPermissionsChangeListener; 134import android.content.pm.IPackageDataObserver; 135import android.content.pm.IPackageDeleteObserver; 136import android.content.pm.IPackageDeleteObserver2; 137import android.content.pm.IPackageInstallObserver2; 138import android.content.pm.IPackageInstaller; 139import android.content.pm.IPackageManager; 140import android.content.pm.IPackageMoveObserver; 141import android.content.pm.IPackageStatsObserver; 142import android.content.pm.InstrumentationInfo; 143import android.content.pm.IntentFilterVerificationInfo; 144import android.content.pm.KeySet; 145import android.content.pm.PackageCleanItem; 146import android.content.pm.PackageInfo; 147import android.content.pm.PackageInfoLite; 148import android.content.pm.PackageInstaller; 149import android.content.pm.PackageManager; 150import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 151import android.content.pm.PackageManagerInternal; 152import android.content.pm.PackageParser; 153import android.content.pm.PackageParser.ActivityIntentInfo; 154import android.content.pm.PackageParser.PackageLite; 155import android.content.pm.PackageParser.PackageParserException; 156import android.content.pm.PackageStats; 157import android.content.pm.PackageUserState; 158import android.content.pm.ParceledListSlice; 159import android.content.pm.PermissionGroupInfo; 160import android.content.pm.PermissionInfo; 161import android.content.pm.ProviderInfo; 162import android.content.pm.ResolveInfo; 163import android.content.pm.ServiceInfo; 164import android.content.pm.Signature; 165import android.content.pm.UserInfo; 166import android.content.pm.VerifierDeviceIdentity; 167import android.content.pm.VerifierInfo; 168import android.content.res.Resources; 169import android.graphics.Bitmap; 170import android.hardware.display.DisplayManager; 171import android.net.Uri; 172import android.os.Binder; 173import android.os.Build; 174import android.os.Bundle; 175import android.os.Debug; 176import android.os.Environment; 177import android.os.Environment.UserEnvironment; 178import android.os.FileUtils; 179import android.os.Handler; 180import android.os.IBinder; 181import android.os.Looper; 182import android.os.Message; 183import android.os.Parcel; 184import android.os.ParcelFileDescriptor; 185import android.os.PatternMatcher; 186import android.os.Process; 187import android.os.RemoteCallbackList; 188import android.os.RemoteException; 189import android.os.ResultReceiver; 190import android.os.SELinux; 191import android.os.ServiceManager; 192import android.os.ShellCallback; 193import android.os.SystemClock; 194import android.os.SystemProperties; 195import android.os.Trace; 196import android.os.UserHandle; 197import android.os.UserManager; 198import android.os.UserManagerInternal; 199import android.os.storage.IStorageManager; 200import android.os.storage.StorageManagerInternal; 201import android.os.storage.StorageEventListener; 202import android.os.storage.StorageManager; 203import android.os.storage.VolumeInfo; 204import android.os.storage.VolumeRecord; 205import android.provider.Settings.Global; 206import android.provider.Settings.Secure; 207import android.security.KeyStore; 208import android.security.SystemKeyStore; 209import android.system.ErrnoException; 210import android.system.Os; 211import android.text.TextUtils; 212import android.text.format.DateUtils; 213import android.util.ArrayMap; 214import android.util.ArraySet; 215import android.util.Base64; 216import android.util.DisplayMetrics; 217import android.util.EventLog; 218import android.util.ExceptionUtils; 219import android.util.Log; 220import android.util.LogPrinter; 221import android.util.MathUtils; 222import android.util.Pair; 223import android.util.PrintStreamPrinter; 224import android.util.Slog; 225import android.util.SparseArray; 226import android.util.SparseBooleanArray; 227import android.util.SparseIntArray; 228import android.util.Xml; 229import android.util.jar.StrictJarFile; 230import android.view.Display; 231 232import com.android.internal.R; 233import com.android.internal.annotations.GuardedBy; 234import com.android.internal.app.IMediaContainerService; 235import com.android.internal.app.ResolverActivity; 236import com.android.internal.content.NativeLibraryHelper; 237import com.android.internal.content.PackageHelper; 238import com.android.internal.logging.MetricsLogger; 239import com.android.internal.logging.nano.MetricsProto.MetricsEvent; 240import com.android.internal.os.IParcelFileDescriptorFactory; 241import com.android.internal.os.RoSystemProperties; 242import com.android.internal.os.SomeArgs; 243import com.android.internal.os.Zygote; 244import com.android.internal.telephony.CarrierAppUtils; 245import com.android.internal.util.ArrayUtils; 246import com.android.internal.util.FastPrintWriter; 247import com.android.internal.util.FastXmlSerializer; 248import com.android.internal.util.IndentingPrintWriter; 249import com.android.internal.util.Preconditions; 250import com.android.internal.util.XmlUtils; 251import com.android.server.AttributeCache; 252import com.android.server.EventLogTags; 253import com.android.server.FgThread; 254import com.android.server.IntentResolver; 255import com.android.server.LocalServices; 256import com.android.server.ServiceThread; 257import com.android.server.SystemConfig; 258import com.android.server.Watchdog; 259import com.android.server.net.NetworkPolicyManagerInternal; 260import com.android.server.pm.Installer.InstallerException; 261import com.android.server.pm.PermissionsState.PermissionState; 262import com.android.server.pm.Settings.DatabaseVersion; 263import com.android.server.pm.Settings.VersionInfo; 264import com.android.server.pm.dex.DexManager; 265import com.android.server.storage.DeviceStorageMonitorInternal; 266 267import dalvik.system.CloseGuard; 268import dalvik.system.DexFile; 269import dalvik.system.VMRuntime; 270 271import libcore.io.IoUtils; 272import libcore.util.EmptyArray; 273 274import org.xmlpull.v1.XmlPullParser; 275import org.xmlpull.v1.XmlPullParserException; 276import org.xmlpull.v1.XmlSerializer; 277 278import java.io.BufferedOutputStream; 279import java.io.BufferedReader; 280import java.io.ByteArrayInputStream; 281import java.io.ByteArrayOutputStream; 282import java.io.File; 283import java.io.FileDescriptor; 284import java.io.FileInputStream; 285import java.io.FileNotFoundException; 286import java.io.FileOutputStream; 287import java.io.FileReader; 288import java.io.FilenameFilter; 289import java.io.IOException; 290import java.io.PrintWriter; 291import java.nio.charset.StandardCharsets; 292import java.security.DigestInputStream; 293import java.security.MessageDigest; 294import java.security.NoSuchAlgorithmException; 295import java.security.PublicKey; 296import java.security.SecureRandom; 297import java.security.cert.Certificate; 298import java.security.cert.CertificateEncodingException; 299import java.security.cert.CertificateException; 300import java.text.SimpleDateFormat; 301import java.util.ArrayList; 302import java.util.Arrays; 303import java.util.Collection; 304import java.util.Collections; 305import java.util.Comparator; 306import java.util.Date; 307import java.util.HashSet; 308import java.util.HashMap; 309import java.util.Iterator; 310import java.util.List; 311import java.util.Map; 312import java.util.Objects; 313import java.util.Set; 314import java.util.concurrent.CountDownLatch; 315import java.util.concurrent.TimeUnit; 316import java.util.concurrent.atomic.AtomicBoolean; 317import java.util.concurrent.atomic.AtomicInteger; 318 319/** 320 * Keep track of all those APKs everywhere. 321 * <p> 322 * Internally there are two important locks: 323 * <ul> 324 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 325 * and other related state. It is a fine-grained lock that should only be held 326 * momentarily, as it's one of the most contended locks in the system. 327 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 328 * operations typically involve heavy lifting of application data on disk. Since 329 * {@code installd} is single-threaded, and it's operations can often be slow, 330 * this lock should never be acquired while already holding {@link #mPackages}. 331 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 332 * holding {@link #mInstallLock}. 333 * </ul> 334 * Many internal methods rely on the caller to hold the appropriate locks, and 335 * this contract is expressed through method name suffixes: 336 * <ul> 337 * <li>fooLI(): the caller must hold {@link #mInstallLock} 338 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 339 * being modified must be frozen 340 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 341 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 342 * </ul> 343 * <p> 344 * Because this class is very central to the platform's security; please run all 345 * CTS and unit tests whenever making modifications: 346 * 347 * <pre> 348 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 349 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases 350 * </pre> 351 */ 352public class PackageManagerService extends IPackageManager.Stub { 353 static final String TAG = "PackageManager"; 354 static final boolean DEBUG_SETTINGS = false; 355 static final boolean DEBUG_PREFERRED = false; 356 static final boolean DEBUG_UPGRADE = false; 357 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 358 private static final boolean DEBUG_BACKUP = false; 359 private static final boolean DEBUG_INSTALL = false; 360 private static final boolean DEBUG_REMOVE = false; 361 private static final boolean DEBUG_BROADCASTS = false; 362 private static final boolean DEBUG_SHOW_INFO = false; 363 private static final boolean DEBUG_PACKAGE_INFO = false; 364 private static final boolean DEBUG_INTENT_MATCHING = false; 365 private static final boolean DEBUG_PACKAGE_SCANNING = false; 366 private static final boolean DEBUG_VERIFY = false; 367 private static final boolean DEBUG_FILTERS = false; 368 369 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 370 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 371 // user, but by default initialize to this. 372 static final boolean DEBUG_DEXOPT = false; 373 374 private static final boolean DEBUG_ABI_SELECTION = false; 375 private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE; 376 private static final boolean DEBUG_TRIAGED_MISSING = false; 377 private static final boolean DEBUG_APP_DATA = false; 378 379 /** REMOVE. According to Svet, this was only used to reset permissions during development. */ 380 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 381 382 private static final boolean DISABLE_EPHEMERAL_APPS = false; 383 private static final boolean HIDE_EPHEMERAL_APIS = true; 384 385 private static final boolean ENABLE_QUOTA = 386 SystemProperties.getBoolean("persist.fw.quota", false); 387 388 private static final int RADIO_UID = Process.PHONE_UID; 389 private static final int LOG_UID = Process.LOG_UID; 390 private static final int NFC_UID = Process.NFC_UID; 391 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 392 private static final int SHELL_UID = Process.SHELL_UID; 393 394 // Cap the size of permission trees that 3rd party apps can define 395 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 396 397 // Suffix used during package installation when copying/moving 398 // package apks to install directory. 399 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 400 401 static final int SCAN_NO_DEX = 1<<1; 402 static final int SCAN_FORCE_DEX = 1<<2; 403 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 404 static final int SCAN_NEW_INSTALL = 1<<4; 405 static final int SCAN_UPDATE_TIME = 1<<5; 406 static final int SCAN_BOOTING = 1<<6; 407 static final int SCAN_TRUSTED_OVERLAY = 1<<7; 408 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8; 409 static final int SCAN_REPLACING = 1<<9; 410 static final int SCAN_REQUIRE_KNOWN = 1<<10; 411 static final int SCAN_MOVE = 1<<11; 412 static final int SCAN_INITIAL = 1<<12; 413 static final int SCAN_CHECK_ONLY = 1<<13; 414 static final int SCAN_DONT_KILL_APP = 1<<14; 415 static final int SCAN_IGNORE_FROZEN = 1<<15; 416 static final int REMOVE_CHATTY = 1<<16; 417 static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<17; 418 419 private static final int[] EMPTY_INT_ARRAY = new int[0]; 420 421 /** 422 * Timeout (in milliseconds) after which the watchdog should declare that 423 * our handler thread is wedged. The usual default for such things is one 424 * minute but we sometimes do very lengthy I/O operations on this thread, 425 * such as installing multi-gigabyte applications, so ours needs to be longer. 426 */ 427 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 428 429 /** 430 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 431 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 432 * settings entry if available, otherwise we use the hardcoded default. If it's been 433 * more than this long since the last fstrim, we force one during the boot sequence. 434 * 435 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 436 * one gets run at the next available charging+idle time. This final mandatory 437 * no-fstrim check kicks in only of the other scheduling criteria is never met. 438 */ 439 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 440 441 /** 442 * Whether verification is enabled by default. 443 */ 444 private static final boolean DEFAULT_VERIFY_ENABLE = true; 445 446 /** 447 * The default maximum time to wait for the verification agent to return in 448 * milliseconds. 449 */ 450 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 451 452 /** 453 * The default response for package verification timeout. 454 * 455 * This can be either PackageManager.VERIFICATION_ALLOW or 456 * PackageManager.VERIFICATION_REJECT. 457 */ 458 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 459 460 static final String PLATFORM_PACKAGE_NAME = "android"; 461 462 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 463 464 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 465 DEFAULT_CONTAINER_PACKAGE, 466 "com.android.defcontainer.DefaultContainerService"); 467 468 private static final String KILL_APP_REASON_GIDS_CHANGED = 469 "permission grant or revoke changed gids"; 470 471 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 472 "permissions revoked"; 473 474 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 475 476 private static final String PACKAGE_SCHEME = "package"; 477 478 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 479 /** 480 * If VENDOR_OVERLAY_THEME_PROPERTY is set, search for runtime resource overlay APKs also in 481 * VENDOR_OVERLAY_DIR/<value of VENDOR_OVERLAY_THEME_PROPERTY> in addition to 482 * VENDOR_OVERLAY_DIR. 483 */ 484 private static final String VENDOR_OVERLAY_THEME_PROPERTY = "ro.boot.vendor.overlay.theme"; 485 /** 486 * Same as VENDOR_OVERLAY_THEME_PROPERTY, except persistent. If set will override whatever 487 * is in VENDOR_OVERLAY_THEME_PROPERTY. 488 */ 489 private static final String VENDOR_OVERLAY_THEME_PERSIST_PROPERTY 490 = "persist.vendor.overlay.theme"; 491 492 /** Permission grant: not grant the permission. */ 493 private static final int GRANT_DENIED = 1; 494 495 /** Permission grant: grant the permission as an install permission. */ 496 private static final int GRANT_INSTALL = 2; 497 498 /** Permission grant: grant the permission as a runtime one. */ 499 private static final int GRANT_RUNTIME = 3; 500 501 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 502 private static final int GRANT_UPGRADE = 4; 503 504 /** Canonical intent used to identify what counts as a "web browser" app */ 505 private static final Intent sBrowserIntent; 506 static { 507 sBrowserIntent = new Intent(); 508 sBrowserIntent.setAction(Intent.ACTION_VIEW); 509 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 510 sBrowserIntent.setData(Uri.parse("http:")); 511 } 512 513 /** 514 * The set of all protected actions [i.e. those actions for which a high priority 515 * intent filter is disallowed]. 516 */ 517 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 518 static { 519 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 520 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 521 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 522 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 523 } 524 525 // Compilation reasons. 526 public static final int REASON_FIRST_BOOT = 0; 527 public static final int REASON_BOOT = 1; 528 public static final int REASON_INSTALL = 2; 529 public static final int REASON_BACKGROUND_DEXOPT = 3; 530 public static final int REASON_AB_OTA = 4; 531 public static final int REASON_NON_SYSTEM_LIBRARY = 5; 532 public static final int REASON_SHARED_APK = 6; 533 public static final int REASON_FORCED_DEXOPT = 7; 534 public static final int REASON_CORE_APP = 8; 535 536 public static final int REASON_LAST = REASON_CORE_APP; 537 538 /** Special library name that skips shared libraries check during compilation. */ 539 private static final String SKIP_SHARED_LIBRARY_CHECK = "&"; 540 541 /** All dangerous permission names in the same order as the events in MetricsEvent */ 542 private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList( 543 Manifest.permission.READ_CALENDAR, 544 Manifest.permission.WRITE_CALENDAR, 545 Manifest.permission.CAMERA, 546 Manifest.permission.READ_CONTACTS, 547 Manifest.permission.WRITE_CONTACTS, 548 Manifest.permission.GET_ACCOUNTS, 549 Manifest.permission.ACCESS_FINE_LOCATION, 550 Manifest.permission.ACCESS_COARSE_LOCATION, 551 Manifest.permission.RECORD_AUDIO, 552 Manifest.permission.READ_PHONE_STATE, 553 Manifest.permission.CALL_PHONE, 554 Manifest.permission.READ_CALL_LOG, 555 Manifest.permission.WRITE_CALL_LOG, 556 Manifest.permission.ADD_VOICEMAIL, 557 Manifest.permission.USE_SIP, 558 Manifest.permission.PROCESS_OUTGOING_CALLS, 559 Manifest.permission.READ_CELL_BROADCASTS, 560 Manifest.permission.BODY_SENSORS, 561 Manifest.permission.SEND_SMS, 562 Manifest.permission.RECEIVE_SMS, 563 Manifest.permission.READ_SMS, 564 Manifest.permission.RECEIVE_WAP_PUSH, 565 Manifest.permission.RECEIVE_MMS, 566 Manifest.permission.READ_EXTERNAL_STORAGE, 567 Manifest.permission.WRITE_EXTERNAL_STORAGE, 568 Manifest.permission.READ_PHONE_NUMBER); 569 570 final ServiceThread mHandlerThread; 571 572 final PackageHandler mHandler; 573 574 private final ProcessLoggingHandler mProcessLoggingHandler; 575 576 /** 577 * Messages for {@link #mHandler} that need to wait for system ready before 578 * being dispatched. 579 */ 580 private ArrayList<Message> mPostSystemReadyMessages; 581 582 final int mSdkVersion = Build.VERSION.SDK_INT; 583 584 final Context mContext; 585 final boolean mFactoryTest; 586 final boolean mOnlyCore; 587 final DisplayMetrics mMetrics; 588 final int mDefParseFlags; 589 final String[] mSeparateProcesses; 590 final boolean mIsUpgrade; 591 final boolean mIsPreNUpgrade; 592 final boolean mIsPreNMR1Upgrade; 593 594 @GuardedBy("mPackages") 595 private boolean mDexOptDialogShown; 596 597 /** The location for ASEC container files on internal storage. */ 598 final String mAsecInternalPath; 599 600 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 601 // LOCK HELD. Can be called with mInstallLock held. 602 @GuardedBy("mInstallLock") 603 final Installer mInstaller; 604 605 /** Directory where installed third-party apps stored */ 606 final File mAppInstallDir; 607 final File mEphemeralInstallDir; 608 609 /** 610 * Directory to which applications installed internally have their 611 * 32 bit native libraries copied. 612 */ 613 private File mAppLib32InstallDir; 614 615 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 616 // apps. 617 final File mDrmAppPrivateInstallDir; 618 619 // ---------------------------------------------------------------- 620 621 // Lock for state used when installing and doing other long running 622 // operations. Methods that must be called with this lock held have 623 // the suffix "LI". 624 final Object mInstallLock = new Object(); 625 626 // ---------------------------------------------------------------- 627 628 // Keys are String (package name), values are Package. This also serves 629 // as the lock for the global state. Methods that must be called with 630 // this lock held have the prefix "LP". 631 @GuardedBy("mPackages") 632 final ArrayMap<String, PackageParser.Package> mPackages = 633 new ArrayMap<String, PackageParser.Package>(); 634 635 final ArrayMap<String, Set<String>> mKnownCodebase = 636 new ArrayMap<String, Set<String>>(); 637 638 // Tracks available target package names -> overlay package paths. 639 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 640 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 641 642 /** 643 * Tracks new system packages [received in an OTA] that we expect to 644 * find updated user-installed versions. Keys are package name, values 645 * are package location. 646 */ 647 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 648 /** 649 * Tracks high priority intent filters for protected actions. During boot, certain 650 * filter actions are protected and should never be allowed to have a high priority 651 * intent filter for them. However, there is one, and only one exception -- the 652 * setup wizard. It must be able to define a high priority intent filter for these 653 * actions to ensure there are no escapes from the wizard. We need to delay processing 654 * of these during boot as we need to look at all of the system packages in order 655 * to know which component is the setup wizard. 656 */ 657 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 658 /** 659 * Whether or not processing protected filters should be deferred. 660 */ 661 private boolean mDeferProtectedFilters = true; 662 663 /** 664 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 665 */ 666 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 667 /** 668 * Whether or not system app permissions should be promoted from install to runtime. 669 */ 670 boolean mPromoteSystemApps; 671 672 @GuardedBy("mPackages") 673 final Settings mSettings; 674 675 /** 676 * Set of package names that are currently "frozen", which means active 677 * surgery is being done on the code/data for that package. The platform 678 * will refuse to launch frozen packages to avoid race conditions. 679 * 680 * @see PackageFreezer 681 */ 682 @GuardedBy("mPackages") 683 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 684 685 final ProtectedPackages mProtectedPackages; 686 687 boolean mFirstBoot; 688 689 // System configuration read by SystemConfig. 690 final int[] mGlobalGids; 691 final SparseArray<ArraySet<String>> mSystemPermissions; 692 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 693 694 // If mac_permissions.xml was found for seinfo labeling. 695 boolean mFoundPolicyFile; 696 697 private final EphemeralApplicationRegistry mEphemeralApplicationRegistry; 698 699 public static final class SharedLibraryEntry { 700 public final String path; 701 public final String apk; 702 703 SharedLibraryEntry(String _path, String _apk) { 704 path = _path; 705 apk = _apk; 706 } 707 } 708 709 // Currently known shared libraries. 710 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 711 new ArrayMap<String, SharedLibraryEntry>(); 712 713 // All available activities, for your resolving pleasure. 714 final ActivityIntentResolver mActivities = 715 new ActivityIntentResolver(); 716 717 // All available receivers, for your resolving pleasure. 718 final ActivityIntentResolver mReceivers = 719 new ActivityIntentResolver(); 720 721 // All available services, for your resolving pleasure. 722 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 723 724 // All available providers, for your resolving pleasure. 725 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 726 727 // Mapping from provider base names (first directory in content URI codePath) 728 // to the provider information. 729 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 730 new ArrayMap<String, PackageParser.Provider>(); 731 732 // Mapping from instrumentation class names to info about them. 733 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 734 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 735 736 // Mapping from permission names to info about them. 737 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 738 new ArrayMap<String, PackageParser.PermissionGroup>(); 739 740 // Packages whose data we have transfered into another package, thus 741 // should no longer exist. 742 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 743 744 // Broadcast actions that are only available to the system. 745 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 746 747 /** List of packages waiting for verification. */ 748 final SparseArray<PackageVerificationState> mPendingVerification 749 = new SparseArray<PackageVerificationState>(); 750 751 /** Set of packages associated with each app op permission. */ 752 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 753 754 final PackageInstallerService mInstallerService; 755 756 private final PackageDexOptimizer mPackageDexOptimizer; 757 // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package 758 // is used by other apps). 759 private final DexManager mDexManager; 760 761 private AtomicInteger mNextMoveId = new AtomicInteger(); 762 private final MoveCallbacks mMoveCallbacks; 763 764 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 765 766 // Cache of users who need badging. 767 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 768 769 /** Token for keys in mPendingVerification. */ 770 private int mPendingVerificationToken = 0; 771 772 volatile boolean mSystemReady; 773 volatile boolean mSafeMode; 774 volatile boolean mHasSystemUidErrors; 775 776 ApplicationInfo mAndroidApplication; 777 final ActivityInfo mResolveActivity = new ActivityInfo(); 778 final ResolveInfo mResolveInfo = new ResolveInfo(); 779 ComponentName mResolveComponentName; 780 PackageParser.Package mPlatformPackage; 781 ComponentName mCustomResolverComponentName; 782 783 boolean mResolverReplaced = false; 784 785 private final @Nullable ComponentName mIntentFilterVerifierComponent; 786 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 787 788 private int mIntentFilterVerificationToken = 0; 789 790 /** The service connection to the ephemeral resolver */ 791 final EphemeralResolverConnection mEphemeralResolverConnection; 792 793 /** Component used to install ephemeral applications */ 794 ComponentName mEphemeralInstallerComponent; 795 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 796 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 797 798 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 799 = new SparseArray<IntentFilterVerificationState>(); 800 801 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy; 802 803 // List of packages names to keep cached, even if they are uninstalled for all users 804 private List<String> mKeepUninstalledPackages; 805 806 private UserManagerInternal mUserManagerInternal; 807 808 private static class IFVerificationParams { 809 PackageParser.Package pkg; 810 boolean replacing; 811 int userId; 812 int verifierUid; 813 814 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 815 int _userId, int _verifierUid) { 816 pkg = _pkg; 817 replacing = _replacing; 818 userId = _userId; 819 replacing = _replacing; 820 verifierUid = _verifierUid; 821 } 822 } 823 824 private interface IntentFilterVerifier<T extends IntentFilter> { 825 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 826 T filter, String packageName); 827 void startVerifications(int userId); 828 void receiveVerificationResponse(int verificationId); 829 } 830 831 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 832 private Context mContext; 833 private ComponentName mIntentFilterVerifierComponent; 834 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 835 836 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 837 mContext = context; 838 mIntentFilterVerifierComponent = verifierComponent; 839 } 840 841 private String getDefaultScheme() { 842 return IntentFilter.SCHEME_HTTPS; 843 } 844 845 @Override 846 public void startVerifications(int userId) { 847 // Launch verifications requests 848 int count = mCurrentIntentFilterVerifications.size(); 849 for (int n=0; n<count; n++) { 850 int verificationId = mCurrentIntentFilterVerifications.get(n); 851 final IntentFilterVerificationState ivs = 852 mIntentFilterVerificationStates.get(verificationId); 853 854 String packageName = ivs.getPackageName(); 855 856 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 857 final int filterCount = filters.size(); 858 ArraySet<String> domainsSet = new ArraySet<>(); 859 for (int m=0; m<filterCount; m++) { 860 PackageParser.ActivityIntentInfo filter = filters.get(m); 861 domainsSet.addAll(filter.getHostsList()); 862 } 863 synchronized (mPackages) { 864 if (mSettings.createIntentFilterVerificationIfNeededLPw( 865 packageName, domainsSet) != null) { 866 scheduleWriteSettingsLocked(); 867 } 868 } 869 sendVerificationRequest(userId, verificationId, ivs); 870 } 871 mCurrentIntentFilterVerifications.clear(); 872 } 873 874 private void sendVerificationRequest(int userId, int verificationId, 875 IntentFilterVerificationState ivs) { 876 877 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 878 verificationIntent.putExtra( 879 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 880 verificationId); 881 verificationIntent.putExtra( 882 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 883 getDefaultScheme()); 884 verificationIntent.putExtra( 885 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 886 ivs.getHostsString()); 887 verificationIntent.putExtra( 888 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 889 ivs.getPackageName()); 890 verificationIntent.setComponent(mIntentFilterVerifierComponent); 891 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 892 893 UserHandle user = new UserHandle(userId); 894 mContext.sendBroadcastAsUser(verificationIntent, user); 895 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 896 "Sending IntentFilter verification broadcast"); 897 } 898 899 public void receiveVerificationResponse(int verificationId) { 900 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 901 902 final boolean verified = ivs.isVerified(); 903 904 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 905 final int count = filters.size(); 906 if (DEBUG_DOMAIN_VERIFICATION) { 907 Slog.i(TAG, "Received verification response " + verificationId 908 + " for " + count + " filters, verified=" + verified); 909 } 910 for (int n=0; n<count; n++) { 911 PackageParser.ActivityIntentInfo filter = filters.get(n); 912 filter.setVerified(verified); 913 914 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 915 + " verified with result:" + verified + " and hosts:" 916 + ivs.getHostsString()); 917 } 918 919 mIntentFilterVerificationStates.remove(verificationId); 920 921 final String packageName = ivs.getPackageName(); 922 IntentFilterVerificationInfo ivi = null; 923 924 synchronized (mPackages) { 925 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 926 } 927 if (ivi == null) { 928 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 929 + verificationId + " packageName:" + packageName); 930 return; 931 } 932 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 933 "Updating IntentFilterVerificationInfo for package " + packageName 934 +" verificationId:" + verificationId); 935 936 synchronized (mPackages) { 937 if (verified) { 938 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 939 } else { 940 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 941 } 942 scheduleWriteSettingsLocked(); 943 944 final int userId = ivs.getUserId(); 945 if (userId != UserHandle.USER_ALL) { 946 final int userStatus = 947 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 948 949 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 950 boolean needUpdate = false; 951 952 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 953 // already been set by the User thru the Disambiguation dialog 954 switch (userStatus) { 955 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 956 if (verified) { 957 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 958 } else { 959 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 960 } 961 needUpdate = true; 962 break; 963 964 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 965 if (verified) { 966 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 967 needUpdate = true; 968 } 969 break; 970 971 default: 972 // Nothing to do 973 } 974 975 if (needUpdate) { 976 mSettings.updateIntentFilterVerificationStatusLPw( 977 packageName, updatedStatus, userId); 978 scheduleWritePackageRestrictionsLocked(userId); 979 } 980 } 981 } 982 } 983 984 @Override 985 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 986 ActivityIntentInfo filter, String packageName) { 987 if (!hasValidDomains(filter)) { 988 return false; 989 } 990 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 991 if (ivs == null) { 992 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 993 packageName); 994 } 995 if (DEBUG_DOMAIN_VERIFICATION) { 996 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 997 } 998 ivs.addFilter(filter); 999 return true; 1000 } 1001 1002 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 1003 int userId, int verificationId, String packageName) { 1004 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 1005 verifierUid, userId, packageName); 1006 ivs.setPendingState(); 1007 synchronized (mPackages) { 1008 mIntentFilterVerificationStates.append(verificationId, ivs); 1009 mCurrentIntentFilterVerifications.add(verificationId); 1010 } 1011 return ivs; 1012 } 1013 } 1014 1015 private static boolean hasValidDomains(ActivityIntentInfo filter) { 1016 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 1017 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 1018 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 1019 } 1020 1021 // Set of pending broadcasts for aggregating enable/disable of components. 1022 static class PendingPackageBroadcasts { 1023 // for each user id, a map of <package name -> components within that package> 1024 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 1025 1026 public PendingPackageBroadcasts() { 1027 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 1028 } 1029 1030 public ArrayList<String> get(int userId, String packageName) { 1031 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1032 return packages.get(packageName); 1033 } 1034 1035 public void put(int userId, String packageName, ArrayList<String> components) { 1036 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1037 packages.put(packageName, components); 1038 } 1039 1040 public void remove(int userId, String packageName) { 1041 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 1042 if (packages != null) { 1043 packages.remove(packageName); 1044 } 1045 } 1046 1047 public void remove(int userId) { 1048 mUidMap.remove(userId); 1049 } 1050 1051 public int userIdCount() { 1052 return mUidMap.size(); 1053 } 1054 1055 public int userIdAt(int n) { 1056 return mUidMap.keyAt(n); 1057 } 1058 1059 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 1060 return mUidMap.get(userId); 1061 } 1062 1063 public int size() { 1064 // total number of pending broadcast entries across all userIds 1065 int num = 0; 1066 for (int i = 0; i< mUidMap.size(); i++) { 1067 num += mUidMap.valueAt(i).size(); 1068 } 1069 return num; 1070 } 1071 1072 public void clear() { 1073 mUidMap.clear(); 1074 } 1075 1076 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1077 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1078 if (map == null) { 1079 map = new ArrayMap<String, ArrayList<String>>(); 1080 mUidMap.put(userId, map); 1081 } 1082 return map; 1083 } 1084 } 1085 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1086 1087 // Service Connection to remote media container service to copy 1088 // package uri's from external media onto secure containers 1089 // or internal storage. 1090 private IMediaContainerService mContainerService = null; 1091 1092 static final int SEND_PENDING_BROADCAST = 1; 1093 static final int MCS_BOUND = 3; 1094 static final int END_COPY = 4; 1095 static final int INIT_COPY = 5; 1096 static final int MCS_UNBIND = 6; 1097 static final int START_CLEANING_PACKAGE = 7; 1098 static final int FIND_INSTALL_LOC = 8; 1099 static final int POST_INSTALL = 9; 1100 static final int MCS_RECONNECT = 10; 1101 static final int MCS_GIVE_UP = 11; 1102 static final int UPDATED_MEDIA_STATUS = 12; 1103 static final int WRITE_SETTINGS = 13; 1104 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1105 static final int PACKAGE_VERIFIED = 15; 1106 static final int CHECK_PENDING_VERIFICATION = 16; 1107 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1108 static final int INTENT_FILTER_VERIFIED = 18; 1109 static final int WRITE_PACKAGE_LIST = 19; 1110 static final int EPHEMERAL_RESOLUTION_PHASE_TWO = 20; 1111 1112 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1113 1114 // Delay time in millisecs 1115 static final int BROADCAST_DELAY = 10 * 1000; 1116 1117 static UserManagerService sUserManager; 1118 1119 // Stores a list of users whose package restrictions file needs to be updated 1120 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1121 1122 final private DefaultContainerConnection mDefContainerConn = 1123 new DefaultContainerConnection(); 1124 class DefaultContainerConnection implements ServiceConnection { 1125 public void onServiceConnected(ComponentName name, IBinder service) { 1126 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1127 final IMediaContainerService imcs = IMediaContainerService.Stub 1128 .asInterface(Binder.allowBlocking(service)); 1129 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1130 } 1131 1132 public void onServiceDisconnected(ComponentName name) { 1133 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1134 } 1135 } 1136 1137 // Recordkeeping of restore-after-install operations that are currently in flight 1138 // between the Package Manager and the Backup Manager 1139 static class PostInstallData { 1140 public InstallArgs args; 1141 public PackageInstalledInfo res; 1142 1143 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1144 args = _a; 1145 res = _r; 1146 } 1147 } 1148 1149 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1150 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1151 1152 // XML tags for backup/restore of various bits of state 1153 private static final String TAG_PREFERRED_BACKUP = "pa"; 1154 private static final String TAG_DEFAULT_APPS = "da"; 1155 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1156 1157 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1158 private static final String TAG_ALL_GRANTS = "rt-grants"; 1159 private static final String TAG_GRANT = "grant"; 1160 private static final String ATTR_PACKAGE_NAME = "pkg"; 1161 1162 private static final String TAG_PERMISSION = "perm"; 1163 private static final String ATTR_PERMISSION_NAME = "name"; 1164 private static final String ATTR_IS_GRANTED = "g"; 1165 private static final String ATTR_USER_SET = "set"; 1166 private static final String ATTR_USER_FIXED = "fixed"; 1167 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1168 1169 // System/policy permission grants are not backed up 1170 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1171 FLAG_PERMISSION_POLICY_FIXED 1172 | FLAG_PERMISSION_SYSTEM_FIXED 1173 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1174 1175 // And we back up these user-adjusted states 1176 private static final int USER_RUNTIME_GRANT_MASK = 1177 FLAG_PERMISSION_USER_SET 1178 | FLAG_PERMISSION_USER_FIXED 1179 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1180 1181 final @Nullable String mRequiredVerifierPackage; 1182 final @NonNull String mRequiredInstallerPackage; 1183 final @NonNull String mRequiredUninstallerPackage; 1184 final @Nullable String mSetupWizardPackage; 1185 final @Nullable String mStorageManagerPackage; 1186 final @NonNull String mServicesSystemSharedLibraryPackageName; 1187 final @NonNull String mSharedSystemSharedLibraryPackageName; 1188 1189 final boolean mPermissionReviewRequired; 1190 1191 private final PackageUsage mPackageUsage = new PackageUsage(); 1192 private final CompilerStats mCompilerStats = new CompilerStats(); 1193 1194 class PackageHandler extends Handler { 1195 private boolean mBound = false; 1196 final ArrayList<HandlerParams> mPendingInstalls = 1197 new ArrayList<HandlerParams>(); 1198 1199 private boolean connectToService() { 1200 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1201 " DefaultContainerService"); 1202 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1203 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1204 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1205 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1206 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1207 mBound = true; 1208 return true; 1209 } 1210 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1211 return false; 1212 } 1213 1214 private void disconnectService() { 1215 mContainerService = null; 1216 mBound = false; 1217 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1218 mContext.unbindService(mDefContainerConn); 1219 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1220 } 1221 1222 PackageHandler(Looper looper) { 1223 super(looper); 1224 } 1225 1226 public void handleMessage(Message msg) { 1227 try { 1228 doHandleMessage(msg); 1229 } finally { 1230 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1231 } 1232 } 1233 1234 void doHandleMessage(Message msg) { 1235 switch (msg.what) { 1236 case INIT_COPY: { 1237 HandlerParams params = (HandlerParams) msg.obj; 1238 int idx = mPendingInstalls.size(); 1239 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1240 // If a bind was already initiated we dont really 1241 // need to do anything. The pending install 1242 // will be processed later on. 1243 if (!mBound) { 1244 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1245 System.identityHashCode(mHandler)); 1246 // If this is the only one pending we might 1247 // have to bind to the service again. 1248 if (!connectToService()) { 1249 Slog.e(TAG, "Failed to bind to media container service"); 1250 params.serviceError(); 1251 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1252 System.identityHashCode(mHandler)); 1253 if (params.traceMethod != null) { 1254 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1255 params.traceCookie); 1256 } 1257 return; 1258 } else { 1259 // Once we bind to the service, the first 1260 // pending request will be processed. 1261 mPendingInstalls.add(idx, params); 1262 } 1263 } else { 1264 mPendingInstalls.add(idx, params); 1265 // Already bound to the service. Just make 1266 // sure we trigger off processing the first request. 1267 if (idx == 0) { 1268 mHandler.sendEmptyMessage(MCS_BOUND); 1269 } 1270 } 1271 break; 1272 } 1273 case MCS_BOUND: { 1274 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1275 if (msg.obj != null) { 1276 mContainerService = (IMediaContainerService) msg.obj; 1277 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1278 System.identityHashCode(mHandler)); 1279 } 1280 if (mContainerService == null) { 1281 if (!mBound) { 1282 // Something seriously wrong since we are not bound and we are not 1283 // waiting for connection. Bail out. 1284 Slog.e(TAG, "Cannot bind to media container service"); 1285 for (HandlerParams params : mPendingInstalls) { 1286 // Indicate service bind error 1287 params.serviceError(); 1288 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1289 System.identityHashCode(params)); 1290 if (params.traceMethod != null) { 1291 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1292 params.traceMethod, params.traceCookie); 1293 } 1294 return; 1295 } 1296 mPendingInstalls.clear(); 1297 } else { 1298 Slog.w(TAG, "Waiting to connect to media container service"); 1299 } 1300 } else if (mPendingInstalls.size() > 0) { 1301 HandlerParams params = mPendingInstalls.get(0); 1302 if (params != null) { 1303 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1304 System.identityHashCode(params)); 1305 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1306 if (params.startCopy()) { 1307 // We are done... look for more work or to 1308 // go idle. 1309 if (DEBUG_SD_INSTALL) Log.i(TAG, 1310 "Checking for more work or unbind..."); 1311 // Delete pending install 1312 if (mPendingInstalls.size() > 0) { 1313 mPendingInstalls.remove(0); 1314 } 1315 if (mPendingInstalls.size() == 0) { 1316 if (mBound) { 1317 if (DEBUG_SD_INSTALL) Log.i(TAG, 1318 "Posting delayed MCS_UNBIND"); 1319 removeMessages(MCS_UNBIND); 1320 Message ubmsg = obtainMessage(MCS_UNBIND); 1321 // Unbind after a little delay, to avoid 1322 // continual thrashing. 1323 sendMessageDelayed(ubmsg, 10000); 1324 } 1325 } else { 1326 // There are more pending requests in queue. 1327 // Just post MCS_BOUND message to trigger processing 1328 // of next pending install. 1329 if (DEBUG_SD_INSTALL) Log.i(TAG, 1330 "Posting MCS_BOUND for next work"); 1331 mHandler.sendEmptyMessage(MCS_BOUND); 1332 } 1333 } 1334 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1335 } 1336 } else { 1337 // Should never happen ideally. 1338 Slog.w(TAG, "Empty queue"); 1339 } 1340 break; 1341 } 1342 case MCS_RECONNECT: { 1343 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1344 if (mPendingInstalls.size() > 0) { 1345 if (mBound) { 1346 disconnectService(); 1347 } 1348 if (!connectToService()) { 1349 Slog.e(TAG, "Failed to bind to media container service"); 1350 for (HandlerParams params : mPendingInstalls) { 1351 // Indicate service bind error 1352 params.serviceError(); 1353 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1354 System.identityHashCode(params)); 1355 } 1356 mPendingInstalls.clear(); 1357 } 1358 } 1359 break; 1360 } 1361 case MCS_UNBIND: { 1362 // If there is no actual work left, then time to unbind. 1363 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1364 1365 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1366 if (mBound) { 1367 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1368 1369 disconnectService(); 1370 } 1371 } else if (mPendingInstalls.size() > 0) { 1372 // There are more pending requests in queue. 1373 // Just post MCS_BOUND message to trigger processing 1374 // of next pending install. 1375 mHandler.sendEmptyMessage(MCS_BOUND); 1376 } 1377 1378 break; 1379 } 1380 case MCS_GIVE_UP: { 1381 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1382 HandlerParams params = mPendingInstalls.remove(0); 1383 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1384 System.identityHashCode(params)); 1385 break; 1386 } 1387 case SEND_PENDING_BROADCAST: { 1388 String packages[]; 1389 ArrayList<String> components[]; 1390 int size = 0; 1391 int uids[]; 1392 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1393 synchronized (mPackages) { 1394 if (mPendingBroadcasts == null) { 1395 return; 1396 } 1397 size = mPendingBroadcasts.size(); 1398 if (size <= 0) { 1399 // Nothing to be done. Just return 1400 return; 1401 } 1402 packages = new String[size]; 1403 components = new ArrayList[size]; 1404 uids = new int[size]; 1405 int i = 0; // filling out the above arrays 1406 1407 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1408 int packageUserId = mPendingBroadcasts.userIdAt(n); 1409 Iterator<Map.Entry<String, ArrayList<String>>> it 1410 = mPendingBroadcasts.packagesForUserId(packageUserId) 1411 .entrySet().iterator(); 1412 while (it.hasNext() && i < size) { 1413 Map.Entry<String, ArrayList<String>> ent = it.next(); 1414 packages[i] = ent.getKey(); 1415 components[i] = ent.getValue(); 1416 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1417 uids[i] = (ps != null) 1418 ? UserHandle.getUid(packageUserId, ps.appId) 1419 : -1; 1420 i++; 1421 } 1422 } 1423 size = i; 1424 mPendingBroadcasts.clear(); 1425 } 1426 // Send broadcasts 1427 for (int i = 0; i < size; i++) { 1428 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1429 } 1430 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1431 break; 1432 } 1433 case START_CLEANING_PACKAGE: { 1434 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1435 final String packageName = (String)msg.obj; 1436 final int userId = msg.arg1; 1437 final boolean andCode = msg.arg2 != 0; 1438 synchronized (mPackages) { 1439 if (userId == UserHandle.USER_ALL) { 1440 int[] users = sUserManager.getUserIds(); 1441 for (int user : users) { 1442 mSettings.addPackageToCleanLPw( 1443 new PackageCleanItem(user, packageName, andCode)); 1444 } 1445 } else { 1446 mSettings.addPackageToCleanLPw( 1447 new PackageCleanItem(userId, packageName, andCode)); 1448 } 1449 } 1450 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1451 startCleaningPackages(); 1452 } break; 1453 case POST_INSTALL: { 1454 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1455 1456 PostInstallData data = mRunningInstalls.get(msg.arg1); 1457 final boolean didRestore = (msg.arg2 != 0); 1458 mRunningInstalls.delete(msg.arg1); 1459 1460 if (data != null) { 1461 InstallArgs args = data.args; 1462 PackageInstalledInfo parentRes = data.res; 1463 1464 final boolean grantPermissions = (args.installFlags 1465 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1466 final boolean killApp = (args.installFlags 1467 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1468 final String[] grantedPermissions = args.installGrantPermissions; 1469 1470 // Handle the parent package 1471 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1472 grantedPermissions, didRestore, args.installerPackageName, 1473 args.observer); 1474 1475 // Handle the child packages 1476 final int childCount = (parentRes.addedChildPackages != null) 1477 ? parentRes.addedChildPackages.size() : 0; 1478 for (int i = 0; i < childCount; i++) { 1479 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1480 handlePackagePostInstall(childRes, grantPermissions, killApp, 1481 grantedPermissions, false, args.installerPackageName, 1482 args.observer); 1483 } 1484 1485 // Log tracing if needed 1486 if (args.traceMethod != null) { 1487 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1488 args.traceCookie); 1489 } 1490 } else { 1491 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1492 } 1493 1494 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1495 } break; 1496 case UPDATED_MEDIA_STATUS: { 1497 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1498 boolean reportStatus = msg.arg1 == 1; 1499 boolean doGc = msg.arg2 == 1; 1500 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1501 if (doGc) { 1502 // Force a gc to clear up stale containers. 1503 Runtime.getRuntime().gc(); 1504 } 1505 if (msg.obj != null) { 1506 @SuppressWarnings("unchecked") 1507 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1508 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1509 // Unload containers 1510 unloadAllContainers(args); 1511 } 1512 if (reportStatus) { 1513 try { 1514 if (DEBUG_SD_INSTALL) Log.i(TAG, 1515 "Invoking StorageManagerService call back"); 1516 PackageHelper.getStorageManager().finishMediaUpdate(); 1517 } catch (RemoteException e) { 1518 Log.e(TAG, "StorageManagerService not running?"); 1519 } 1520 } 1521 } break; 1522 case WRITE_SETTINGS: { 1523 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1524 synchronized (mPackages) { 1525 removeMessages(WRITE_SETTINGS); 1526 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1527 mSettings.writeLPr(); 1528 mDirtyUsers.clear(); 1529 } 1530 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1531 } break; 1532 case WRITE_PACKAGE_RESTRICTIONS: { 1533 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1534 synchronized (mPackages) { 1535 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1536 for (int userId : mDirtyUsers) { 1537 mSettings.writePackageRestrictionsLPr(userId); 1538 } 1539 mDirtyUsers.clear(); 1540 } 1541 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1542 } break; 1543 case WRITE_PACKAGE_LIST: { 1544 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1545 synchronized (mPackages) { 1546 removeMessages(WRITE_PACKAGE_LIST); 1547 mSettings.writePackageListLPr(msg.arg1); 1548 } 1549 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1550 } break; 1551 case CHECK_PENDING_VERIFICATION: { 1552 final int verificationId = msg.arg1; 1553 final PackageVerificationState state = mPendingVerification.get(verificationId); 1554 1555 if ((state != null) && !state.timeoutExtended()) { 1556 final InstallArgs args = state.getInstallArgs(); 1557 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1558 1559 Slog.i(TAG, "Verification timed out for " + originUri); 1560 mPendingVerification.remove(verificationId); 1561 1562 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1563 1564 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1565 Slog.i(TAG, "Continuing with installation of " + originUri); 1566 state.setVerifierResponse(Binder.getCallingUid(), 1567 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1568 broadcastPackageVerified(verificationId, originUri, 1569 PackageManager.VERIFICATION_ALLOW, 1570 state.getInstallArgs().getUser()); 1571 try { 1572 ret = args.copyApk(mContainerService, true); 1573 } catch (RemoteException e) { 1574 Slog.e(TAG, "Could not contact the ContainerService"); 1575 } 1576 } else { 1577 broadcastPackageVerified(verificationId, originUri, 1578 PackageManager.VERIFICATION_REJECT, 1579 state.getInstallArgs().getUser()); 1580 } 1581 1582 Trace.asyncTraceEnd( 1583 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1584 1585 processPendingInstall(args, ret); 1586 mHandler.sendEmptyMessage(MCS_UNBIND); 1587 } 1588 break; 1589 } 1590 case PACKAGE_VERIFIED: { 1591 final int verificationId = msg.arg1; 1592 1593 final PackageVerificationState state = mPendingVerification.get(verificationId); 1594 if (state == null) { 1595 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1596 break; 1597 } 1598 1599 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1600 1601 state.setVerifierResponse(response.callerUid, response.code); 1602 1603 if (state.isVerificationComplete()) { 1604 mPendingVerification.remove(verificationId); 1605 1606 final InstallArgs args = state.getInstallArgs(); 1607 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1608 1609 int ret; 1610 if (state.isInstallAllowed()) { 1611 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1612 broadcastPackageVerified(verificationId, originUri, 1613 response.code, state.getInstallArgs().getUser()); 1614 try { 1615 ret = args.copyApk(mContainerService, true); 1616 } catch (RemoteException e) { 1617 Slog.e(TAG, "Could not contact the ContainerService"); 1618 } 1619 } else { 1620 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1621 } 1622 1623 Trace.asyncTraceEnd( 1624 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1625 1626 processPendingInstall(args, ret); 1627 mHandler.sendEmptyMessage(MCS_UNBIND); 1628 } 1629 1630 break; 1631 } 1632 case START_INTENT_FILTER_VERIFICATIONS: { 1633 IFVerificationParams params = (IFVerificationParams) msg.obj; 1634 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1635 params.replacing, params.pkg); 1636 break; 1637 } 1638 case INTENT_FILTER_VERIFIED: { 1639 final int verificationId = msg.arg1; 1640 1641 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1642 verificationId); 1643 if (state == null) { 1644 Slog.w(TAG, "Invalid IntentFilter verification token " 1645 + verificationId + " received"); 1646 break; 1647 } 1648 1649 final int userId = state.getUserId(); 1650 1651 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1652 "Processing IntentFilter verification with token:" 1653 + verificationId + " and userId:" + userId); 1654 1655 final IntentFilterVerificationResponse response = 1656 (IntentFilterVerificationResponse) msg.obj; 1657 1658 state.setVerifierResponse(response.callerUid, response.code); 1659 1660 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1661 "IntentFilter verification with token:" + verificationId 1662 + " and userId:" + userId 1663 + " is settings verifier response with response code:" 1664 + response.code); 1665 1666 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1667 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1668 + response.getFailedDomainsString()); 1669 } 1670 1671 if (state.isVerificationComplete()) { 1672 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1673 } else { 1674 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1675 "IntentFilter verification with token:" + verificationId 1676 + " was not said to be complete"); 1677 } 1678 1679 break; 1680 } 1681 case EPHEMERAL_RESOLUTION_PHASE_TWO: { 1682 EphemeralResolver.doEphemeralResolutionPhaseTwo(mContext, 1683 mEphemeralResolverConnection, 1684 (EphemeralRequest) msg.obj, 1685 mEphemeralInstallerActivity, 1686 mHandler); 1687 } 1688 } 1689 } 1690 } 1691 1692 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1693 boolean killApp, String[] grantedPermissions, 1694 boolean launchedForRestore, String installerPackage, 1695 IPackageInstallObserver2 installObserver) { 1696 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1697 // Send the removed broadcasts 1698 if (res.removedInfo != null) { 1699 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1700 } 1701 1702 // Now that we successfully installed the package, grant runtime 1703 // permissions if requested before broadcasting the install. 1704 if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion 1705 >= Build.VERSION_CODES.M) { 1706 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1707 } 1708 1709 final boolean update = res.removedInfo != null 1710 && res.removedInfo.removedPackage != null; 1711 1712 // If this is the first time we have child packages for a disabled privileged 1713 // app that had no children, we grant requested runtime permissions to the new 1714 // children if the parent on the system image had them already granted. 1715 if (res.pkg.parentPackage != null) { 1716 synchronized (mPackages) { 1717 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1718 } 1719 } 1720 1721 synchronized (mPackages) { 1722 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1723 } 1724 1725 final String packageName = res.pkg.applicationInfo.packageName; 1726 1727 // Determine the set of users who are adding this package for 1728 // the first time vs. those who are seeing an update. 1729 int[] firstUsers = EMPTY_INT_ARRAY; 1730 int[] updateUsers = EMPTY_INT_ARRAY; 1731 if (res.origUsers == null || res.origUsers.length == 0) { 1732 firstUsers = res.newUsers; 1733 } else { 1734 for (int newUser : res.newUsers) { 1735 boolean isNew = true; 1736 for (int origUser : res.origUsers) { 1737 if (origUser == newUser) { 1738 isNew = false; 1739 break; 1740 } 1741 } 1742 if (isNew) { 1743 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1744 } else { 1745 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1746 } 1747 } 1748 } 1749 1750 // Send installed broadcasts if the install/update is not ephemeral 1751 if (!isEphemeral(res.pkg)) { 1752 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1753 1754 // Send added for users that see the package for the first time 1755 // sendPackageAddedForNewUsers also deals with system apps 1756 int appId = UserHandle.getAppId(res.uid); 1757 boolean isSystem = res.pkg.applicationInfo.isSystemApp(); 1758 sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers); 1759 1760 // Send added for users that don't see the package for the first time 1761 Bundle extras = new Bundle(1); 1762 extras.putInt(Intent.EXTRA_UID, res.uid); 1763 if (update) { 1764 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1765 } 1766 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1767 extras, 0 /*flags*/, null /*targetPackage*/, 1768 null /*finishedReceiver*/, updateUsers); 1769 1770 // Send replaced for users that don't see the package for the first time 1771 if (update) { 1772 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1773 packageName, extras, 0 /*flags*/, 1774 null /*targetPackage*/, null /*finishedReceiver*/, 1775 updateUsers); 1776 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1777 null /*package*/, null /*extras*/, 0 /*flags*/, 1778 packageName /*targetPackage*/, 1779 null /*finishedReceiver*/, updateUsers); 1780 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 1781 // First-install and we did a restore, so we're responsible for the 1782 // first-launch broadcast. 1783 if (DEBUG_BACKUP) { 1784 Slog.i(TAG, "Post-restore of " + packageName 1785 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers)); 1786 } 1787 sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers); 1788 } 1789 1790 // Send broadcast package appeared if forward locked/external for all users 1791 // treat asec-hosted packages like removable media on upgrade 1792 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1793 if (DEBUG_INSTALL) { 1794 Slog.i(TAG, "upgrading pkg " + res.pkg 1795 + " is ASEC-hosted -> AVAILABLE"); 1796 } 1797 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1798 ArrayList<String> pkgList = new ArrayList<>(1); 1799 pkgList.add(packageName); 1800 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1801 } 1802 } 1803 1804 // Work that needs to happen on first install within each user 1805 if (firstUsers != null && firstUsers.length > 0) { 1806 synchronized (mPackages) { 1807 for (int userId : firstUsers) { 1808 // If this app is a browser and it's newly-installed for some 1809 // users, clear any default-browser state in those users. The 1810 // app's nature doesn't depend on the user, so we can just check 1811 // its browser nature in any user and generalize. 1812 if (packageIsBrowser(packageName, userId)) { 1813 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1814 } 1815 1816 // We may also need to apply pending (restored) runtime 1817 // permission grants within these users. 1818 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1819 } 1820 } 1821 } 1822 1823 // Log current value of "unknown sources" setting 1824 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1825 getUnknownSourcesSettings()); 1826 1827 // Force a gc to clear up things 1828 Runtime.getRuntime().gc(); 1829 1830 // Remove the replaced package's older resources safely now 1831 // We delete after a gc for applications on sdcard. 1832 if (res.removedInfo != null && res.removedInfo.args != null) { 1833 synchronized (mInstallLock) { 1834 res.removedInfo.args.doPostDeleteLI(true); 1835 } 1836 } 1837 } 1838 1839 // If someone is watching installs - notify them 1840 if (installObserver != null) { 1841 try { 1842 Bundle extras = extrasForInstallResult(res); 1843 installObserver.onPackageInstalled(res.name, res.returnCode, 1844 res.returnMsg, extras); 1845 } catch (RemoteException e) { 1846 Slog.i(TAG, "Observer no longer exists."); 1847 } 1848 } 1849 } 1850 1851 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1852 PackageParser.Package pkg) { 1853 if (pkg.parentPackage == null) { 1854 return; 1855 } 1856 if (pkg.requestedPermissions == null) { 1857 return; 1858 } 1859 final PackageSetting disabledSysParentPs = mSettings 1860 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1861 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1862 || !disabledSysParentPs.isPrivileged() 1863 || (disabledSysParentPs.childPackageNames != null 1864 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1865 return; 1866 } 1867 final int[] allUserIds = sUserManager.getUserIds(); 1868 final int permCount = pkg.requestedPermissions.size(); 1869 for (int i = 0; i < permCount; i++) { 1870 String permission = pkg.requestedPermissions.get(i); 1871 BasePermission bp = mSettings.mPermissions.get(permission); 1872 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1873 continue; 1874 } 1875 for (int userId : allUserIds) { 1876 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1877 permission, userId)) { 1878 grantRuntimePermission(pkg.packageName, permission, userId); 1879 } 1880 } 1881 } 1882 } 1883 1884 private StorageEventListener mStorageListener = new StorageEventListener() { 1885 @Override 1886 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1887 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1888 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1889 final String volumeUuid = vol.getFsUuid(); 1890 1891 // Clean up any users or apps that were removed or recreated 1892 // while this volume was missing 1893 reconcileUsers(volumeUuid); 1894 reconcileApps(volumeUuid); 1895 1896 // Clean up any install sessions that expired or were 1897 // cancelled while this volume was missing 1898 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1899 1900 loadPrivatePackages(vol); 1901 1902 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1903 unloadPrivatePackages(vol); 1904 } 1905 } 1906 1907 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1908 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1909 updateExternalMediaStatus(true, false); 1910 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1911 updateExternalMediaStatus(false, false); 1912 } 1913 } 1914 } 1915 1916 @Override 1917 public void onVolumeForgotten(String fsUuid) { 1918 if (TextUtils.isEmpty(fsUuid)) { 1919 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1920 return; 1921 } 1922 1923 // Remove any apps installed on the forgotten volume 1924 synchronized (mPackages) { 1925 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1926 for (PackageSetting ps : packages) { 1927 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1928 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1929 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 1930 1931 // Try very hard to release any references to this package 1932 // so we don't risk the system server being killed due to 1933 // open FDs 1934 AttributeCache.instance().removePackage(ps.name); 1935 } 1936 1937 mSettings.onVolumeForgotten(fsUuid); 1938 mSettings.writeLPr(); 1939 } 1940 } 1941 }; 1942 1943 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 1944 String[] grantedPermissions) { 1945 for (int userId : userIds) { 1946 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1947 } 1948 1949 // We could have touched GID membership, so flush out packages.list 1950 synchronized (mPackages) { 1951 mSettings.writePackageListLPr(); 1952 } 1953 } 1954 1955 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1956 String[] grantedPermissions) { 1957 SettingBase sb = (SettingBase) pkg.mExtras; 1958 if (sb == null) { 1959 return; 1960 } 1961 1962 PermissionsState permissionsState = sb.getPermissionsState(); 1963 1964 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 1965 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 1966 1967 for (String permission : pkg.requestedPermissions) { 1968 final BasePermission bp; 1969 synchronized (mPackages) { 1970 bp = mSettings.mPermissions.get(permission); 1971 } 1972 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 1973 && (grantedPermissions == null 1974 || ArrayUtils.contains(grantedPermissions, permission))) { 1975 final int flags = permissionsState.getPermissionFlags(permission, userId); 1976 // Installer cannot change immutable permissions. 1977 if ((flags & immutableFlags) == 0) { 1978 grantRuntimePermission(pkg.packageName, permission, userId); 1979 } 1980 } 1981 } 1982 } 1983 1984 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1985 Bundle extras = null; 1986 switch (res.returnCode) { 1987 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1988 extras = new Bundle(); 1989 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1990 res.origPermission); 1991 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1992 res.origPackage); 1993 break; 1994 } 1995 case PackageManager.INSTALL_SUCCEEDED: { 1996 extras = new Bundle(); 1997 extras.putBoolean(Intent.EXTRA_REPLACING, 1998 res.removedInfo != null && res.removedInfo.removedPackage != null); 1999 break; 2000 } 2001 } 2002 return extras; 2003 } 2004 2005 void scheduleWriteSettingsLocked() { 2006 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2007 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2008 } 2009 } 2010 2011 void scheduleWritePackageListLocked(int userId) { 2012 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) { 2013 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST); 2014 msg.arg1 = userId; 2015 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY); 2016 } 2017 } 2018 2019 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2020 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2021 scheduleWritePackageRestrictionsLocked(userId); 2022 } 2023 2024 void scheduleWritePackageRestrictionsLocked(int userId) { 2025 final int[] userIds = (userId == UserHandle.USER_ALL) 2026 ? sUserManager.getUserIds() : new int[]{userId}; 2027 for (int nextUserId : userIds) { 2028 if (!sUserManager.exists(nextUserId)) return; 2029 mDirtyUsers.add(nextUserId); 2030 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2031 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2032 } 2033 } 2034 } 2035 2036 public static PackageManagerService main(Context context, Installer installer, 2037 boolean factoryTest, boolean onlyCore) { 2038 // Self-check for initial settings. 2039 PackageManagerServiceCompilerMapping.checkProperties(); 2040 2041 PackageManagerService m = new PackageManagerService(context, installer, 2042 factoryTest, onlyCore); 2043 m.enableSystemUserPackages(); 2044 ServiceManager.addService("package", m); 2045 return m; 2046 } 2047 2048 private void enableSystemUserPackages() { 2049 if (!UserManager.isSplitSystemUser()) { 2050 return; 2051 } 2052 // For system user, enable apps based on the following conditions: 2053 // - app is whitelisted or belong to one of these groups: 2054 // -- system app which has no launcher icons 2055 // -- system app which has INTERACT_ACROSS_USERS permission 2056 // -- system IME app 2057 // - app is not in the blacklist 2058 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2059 Set<String> enableApps = new ArraySet<>(); 2060 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2061 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2062 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2063 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2064 enableApps.addAll(wlApps); 2065 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2066 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2067 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2068 enableApps.removeAll(blApps); 2069 Log.i(TAG, "Applications installed for system user: " + enableApps); 2070 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2071 UserHandle.SYSTEM); 2072 final int allAppsSize = allAps.size(); 2073 synchronized (mPackages) { 2074 for (int i = 0; i < allAppsSize; i++) { 2075 String pName = allAps.get(i); 2076 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2077 // Should not happen, but we shouldn't be failing if it does 2078 if (pkgSetting == null) { 2079 continue; 2080 } 2081 boolean install = enableApps.contains(pName); 2082 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2083 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2084 + " for system user"); 2085 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2086 } 2087 } 2088 } 2089 } 2090 2091 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2092 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2093 Context.DISPLAY_SERVICE); 2094 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2095 } 2096 2097 /** 2098 * Requests that files preopted on a secondary system partition be copied to the data partition 2099 * if possible. Note that the actual copying of the files is accomplished by init for security 2100 * reasons. This simply requests that the copy takes place and awaits confirmation of its 2101 * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy. 2102 */ 2103 private static void requestCopyPreoptedFiles() { 2104 final int WAIT_TIME_MS = 100; 2105 final String CP_PREOPT_PROPERTY = "sys.cppreopt"; 2106 if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) { 2107 SystemProperties.set(CP_PREOPT_PROPERTY, "requested"); 2108 // We will wait for up to 100 seconds. 2109 final long timeEnd = SystemClock.uptimeMillis() + 100 * 1000; 2110 while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) { 2111 try { 2112 Thread.sleep(WAIT_TIME_MS); 2113 } catch (InterruptedException e) { 2114 // Do nothing 2115 } 2116 if (SystemClock.uptimeMillis() > timeEnd) { 2117 SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out"); 2118 Slog.wtf(TAG, "cppreopt did not finish!"); 2119 break; 2120 } 2121 } 2122 } 2123 } 2124 2125 public PackageManagerService(Context context, Installer installer, 2126 boolean factoryTest, boolean onlyCore) { 2127 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager"); 2128 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2129 SystemClock.uptimeMillis()); 2130 2131 if (mSdkVersion <= 0) { 2132 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2133 } 2134 2135 mContext = context; 2136 2137 mPermissionReviewRequired = context.getResources().getBoolean( 2138 R.bool.config_permissionReviewRequired); 2139 2140 mFactoryTest = factoryTest; 2141 mOnlyCore = onlyCore; 2142 mMetrics = new DisplayMetrics(); 2143 mSettings = new Settings(mPackages); 2144 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2145 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2146 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2147 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2148 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2149 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2150 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2151 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2152 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2153 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2154 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2155 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2156 2157 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2158 if (separateProcesses != null && separateProcesses.length() > 0) { 2159 if ("*".equals(separateProcesses)) { 2160 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2161 mSeparateProcesses = null; 2162 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2163 } else { 2164 mDefParseFlags = 0; 2165 mSeparateProcesses = separateProcesses.split(","); 2166 Slog.w(TAG, "Running with debug.separate_processes: " 2167 + separateProcesses); 2168 } 2169 } else { 2170 mDefParseFlags = 0; 2171 mSeparateProcesses = null; 2172 } 2173 2174 mInstaller = installer; 2175 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2176 "*dexopt*"); 2177 mDexManager = new DexManager(); 2178 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2179 2180 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2181 FgThread.get().getLooper()); 2182 2183 getDefaultDisplayMetrics(context, mMetrics); 2184 2185 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config"); 2186 SystemConfig systemConfig = SystemConfig.getInstance(); 2187 mGlobalGids = systemConfig.getGlobalGids(); 2188 mSystemPermissions = systemConfig.getSystemPermissions(); 2189 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2190 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2191 2192 mProtectedPackages = new ProtectedPackages(mContext); 2193 2194 synchronized (mInstallLock) { 2195 // writer 2196 synchronized (mPackages) { 2197 mHandlerThread = new ServiceThread(TAG, 2198 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2199 mHandlerThread.start(); 2200 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2201 mProcessLoggingHandler = new ProcessLoggingHandler(); 2202 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2203 2204 mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this); 2205 2206 File dataDir = Environment.getDataDirectory(); 2207 mAppInstallDir = new File(dataDir, "app"); 2208 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2209 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2210 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2211 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2212 2213 sUserManager = new UserManagerService(context, this, mPackages); 2214 2215 // Propagate permission configuration in to package manager. 2216 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2217 = systemConfig.getPermissions(); 2218 for (int i=0; i<permConfig.size(); i++) { 2219 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2220 BasePermission bp = mSettings.mPermissions.get(perm.name); 2221 if (bp == null) { 2222 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2223 mSettings.mPermissions.put(perm.name, bp); 2224 } 2225 if (perm.gids != null) { 2226 bp.setGids(perm.gids, perm.perUser); 2227 } 2228 } 2229 2230 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2231 for (int i=0; i<libConfig.size(); i++) { 2232 mSharedLibraries.put(libConfig.keyAt(i), 2233 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2234 } 2235 2236 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2237 2238 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings"); 2239 mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false)); 2240 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2241 2242 // Clean up orphaned packages for which the code path doesn't exist 2243 // and they are an update to a system app - caused by bug/32321269 2244 final int packageSettingCount = mSettings.mPackages.size(); 2245 for (int i = packageSettingCount - 1; i >= 0; i--) { 2246 PackageSetting ps = mSettings.mPackages.valueAt(i); 2247 if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists()) 2248 && mSettings.getDisabledSystemPkgLPr(ps.name) != null) { 2249 mSettings.mPackages.removeAt(i); 2250 mSettings.enableSystemPackageLPw(ps.name); 2251 } 2252 } 2253 2254 if (mFirstBoot) { 2255 requestCopyPreoptedFiles(); 2256 } 2257 2258 String customResolverActivity = Resources.getSystem().getString( 2259 R.string.config_customResolverActivity); 2260 if (TextUtils.isEmpty(customResolverActivity)) { 2261 customResolverActivity = null; 2262 } else { 2263 mCustomResolverComponentName = ComponentName.unflattenFromString( 2264 customResolverActivity); 2265 } 2266 2267 long startTime = SystemClock.uptimeMillis(); 2268 2269 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2270 startTime); 2271 2272 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2273 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2274 2275 if (bootClassPath == null) { 2276 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2277 } 2278 2279 if (systemServerClassPath == null) { 2280 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2281 } 2282 2283 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2284 final String[] dexCodeInstructionSets = 2285 getDexCodeInstructionSets( 2286 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2287 2288 /** 2289 * Ensure all external libraries have had dexopt run on them. 2290 */ 2291 if (mSharedLibraries.size() > 0) { 2292 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 2293 // NOTE: For now, we're compiling these system "shared libraries" 2294 // (and framework jars) into all available architectures. It's possible 2295 // to compile them only when we come across an app that uses them (there's 2296 // already logic for that in scanPackageLI) but that adds some complexity. 2297 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2298 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2299 final String lib = libEntry.path; 2300 if (lib == null) { 2301 continue; 2302 } 2303 2304 try { 2305 // Shared libraries do not have profiles so we perform a full 2306 // AOT compilation (if needed). 2307 int dexoptNeeded = DexFile.getDexOptNeeded( 2308 lib, dexCodeInstructionSet, 2309 getCompilerFilterForReason(REASON_SHARED_APK), 2310 false /* newProfile */); 2311 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2312 mInstaller.dexopt(lib, Process.SYSTEM_UID, "*", 2313 dexCodeInstructionSet, dexoptNeeded, null, 2314 DEXOPT_PUBLIC, 2315 getCompilerFilterForReason(REASON_SHARED_APK), 2316 StorageManager.UUID_PRIVATE_INTERNAL, 2317 SKIP_SHARED_LIBRARY_CHECK); 2318 } 2319 } catch (FileNotFoundException e) { 2320 Slog.w(TAG, "Library not found: " + lib); 2321 } catch (IOException | InstallerException e) { 2322 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2323 + e.getMessage()); 2324 } 2325 } 2326 } 2327 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2328 } 2329 2330 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2331 2332 final VersionInfo ver = mSettings.getInternalVersion(); 2333 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2334 2335 // when upgrading from pre-M, promote system app permissions from install to runtime 2336 mPromoteSystemApps = 2337 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2338 2339 // When upgrading from pre-N, we need to handle package extraction like first boot, 2340 // as there is no profiling data available. 2341 mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N; 2342 2343 mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1; 2344 2345 // save off the names of pre-existing system packages prior to scanning; we don't 2346 // want to automatically grant runtime permissions for new system apps 2347 if (mPromoteSystemApps) { 2348 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2349 while (pkgSettingIter.hasNext()) { 2350 PackageSetting ps = pkgSettingIter.next(); 2351 if (isSystemApp(ps)) { 2352 mExistingSystemPackages.add(ps.name); 2353 } 2354 } 2355 } 2356 2357 // Set flag to monitor and not change apk file paths when 2358 // scanning install directories. 2359 int scanFlags = SCAN_BOOTING | SCAN_INITIAL; 2360 2361 if (mIsUpgrade || mFirstBoot) { 2362 scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE; 2363 } 2364 2365 // Collect vendor overlay packages. (Do this before scanning any apps.) 2366 // For security and version matching reason, only consider 2367 // overlay packages if they reside in the right directory. 2368 String overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PERSIST_PROPERTY); 2369 if (overlayThemeDir.isEmpty()) { 2370 overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PROPERTY); 2371 } 2372 if (!overlayThemeDir.isEmpty()) { 2373 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR, overlayThemeDir), mDefParseFlags 2374 | PackageParser.PARSE_IS_SYSTEM 2375 | PackageParser.PARSE_IS_SYSTEM_DIR 2376 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2377 } 2378 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags 2379 | PackageParser.PARSE_IS_SYSTEM 2380 | PackageParser.PARSE_IS_SYSTEM_DIR 2381 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2382 2383 // Find base frameworks (resource packages without code). 2384 scanDirTracedLI(frameworkDir, mDefParseFlags 2385 | PackageParser.PARSE_IS_SYSTEM 2386 | PackageParser.PARSE_IS_SYSTEM_DIR 2387 | PackageParser.PARSE_IS_PRIVILEGED, 2388 scanFlags | SCAN_NO_DEX, 0); 2389 2390 // Collected privileged system packages. 2391 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2392 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2393 | PackageParser.PARSE_IS_SYSTEM 2394 | PackageParser.PARSE_IS_SYSTEM_DIR 2395 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2396 2397 // Collect ordinary system packages. 2398 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2399 scanDirTracedLI(systemAppDir, mDefParseFlags 2400 | PackageParser.PARSE_IS_SYSTEM 2401 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2402 2403 // Collect all vendor packages. 2404 File vendorAppDir = new File("/vendor/app"); 2405 try { 2406 vendorAppDir = vendorAppDir.getCanonicalFile(); 2407 } catch (IOException e) { 2408 // failed to look up canonical path, continue with original one 2409 } 2410 scanDirTracedLI(vendorAppDir, mDefParseFlags 2411 | PackageParser.PARSE_IS_SYSTEM 2412 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2413 2414 // Collect all OEM packages. 2415 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2416 scanDirTracedLI(oemAppDir, mDefParseFlags 2417 | PackageParser.PARSE_IS_SYSTEM 2418 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2419 2420 // Prune any system packages that no longer exist. 2421 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2422 if (!mOnlyCore) { 2423 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2424 while (psit.hasNext()) { 2425 PackageSetting ps = psit.next(); 2426 2427 /* 2428 * If this is not a system app, it can't be a 2429 * disable system app. 2430 */ 2431 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2432 continue; 2433 } 2434 2435 /* 2436 * If the package is scanned, it's not erased. 2437 */ 2438 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2439 if (scannedPkg != null) { 2440 /* 2441 * If the system app is both scanned and in the 2442 * disabled packages list, then it must have been 2443 * added via OTA. Remove it from the currently 2444 * scanned package so the previously user-installed 2445 * application can be scanned. 2446 */ 2447 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2448 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2449 + ps.name + "; removing system app. Last known codePath=" 2450 + ps.codePathString + ", installStatus=" + ps.installStatus 2451 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2452 + scannedPkg.mVersionCode); 2453 removePackageLI(scannedPkg, true); 2454 mExpectingBetter.put(ps.name, ps.codePath); 2455 } 2456 2457 continue; 2458 } 2459 2460 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2461 psit.remove(); 2462 logCriticalInfo(Log.WARN, "System package " + ps.name 2463 + " no longer exists; it's data will be wiped"); 2464 // Actual deletion of code and data will be handled by later 2465 // reconciliation step 2466 } else { 2467 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2468 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2469 possiblyDeletedUpdatedSystemApps.add(ps.name); 2470 } 2471 } 2472 } 2473 } 2474 2475 //look for any incomplete package installations 2476 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2477 for (int i = 0; i < deletePkgsList.size(); i++) { 2478 // Actual deletion of code and data will be handled by later 2479 // reconciliation step 2480 final String packageName = deletePkgsList.get(i).name; 2481 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2482 synchronized (mPackages) { 2483 mSettings.removePackageLPw(packageName); 2484 } 2485 } 2486 2487 //delete tmp files 2488 deleteTempPackageFiles(); 2489 2490 // Remove any shared userIDs that have no associated packages 2491 mSettings.pruneSharedUsersLPw(); 2492 2493 if (!mOnlyCore) { 2494 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2495 SystemClock.uptimeMillis()); 2496 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2497 2498 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2499 | PackageParser.PARSE_FORWARD_LOCK, 2500 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2501 2502 scanDirLI(mEphemeralInstallDir, mDefParseFlags 2503 | PackageParser.PARSE_IS_EPHEMERAL, 2504 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2505 2506 /** 2507 * Remove disable package settings for any updated system 2508 * apps that were removed via an OTA. If they're not a 2509 * previously-updated app, remove them completely. 2510 * Otherwise, just revoke their system-level permissions. 2511 */ 2512 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2513 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2514 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2515 2516 String msg; 2517 if (deletedPkg == null) { 2518 msg = "Updated system package " + deletedAppName 2519 + " no longer exists; it's data will be wiped"; 2520 // Actual deletion of code and data will be handled by later 2521 // reconciliation step 2522 } else { 2523 msg = "Updated system app + " + deletedAppName 2524 + " no longer present; removing system privileges for " 2525 + deletedAppName; 2526 2527 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2528 2529 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2530 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2531 } 2532 logCriticalInfo(Log.WARN, msg); 2533 } 2534 2535 /** 2536 * Make sure all system apps that we expected to appear on 2537 * the userdata partition actually showed up. If they never 2538 * appeared, crawl back and revive the system version. 2539 */ 2540 for (int i = 0; i < mExpectingBetter.size(); i++) { 2541 final String packageName = mExpectingBetter.keyAt(i); 2542 if (!mPackages.containsKey(packageName)) { 2543 final File scanFile = mExpectingBetter.valueAt(i); 2544 2545 logCriticalInfo(Log.WARN, "Expected better " + packageName 2546 + " but never showed up; reverting to system"); 2547 2548 int reparseFlags = mDefParseFlags; 2549 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2550 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2551 | PackageParser.PARSE_IS_SYSTEM_DIR 2552 | PackageParser.PARSE_IS_PRIVILEGED; 2553 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2554 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2555 | PackageParser.PARSE_IS_SYSTEM_DIR; 2556 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2557 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2558 | PackageParser.PARSE_IS_SYSTEM_DIR; 2559 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2560 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2561 | PackageParser.PARSE_IS_SYSTEM_DIR; 2562 } else { 2563 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2564 continue; 2565 } 2566 2567 mSettings.enableSystemPackageLPw(packageName); 2568 2569 try { 2570 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2571 } catch (PackageManagerException e) { 2572 Slog.e(TAG, "Failed to parse original system package: " 2573 + e.getMessage()); 2574 } 2575 } 2576 } 2577 } 2578 mExpectingBetter.clear(); 2579 2580 // Resolve the storage manager. 2581 mStorageManagerPackage = getStorageManagerPackageName(); 2582 2583 // Resolve protected action filters. Only the setup wizard is allowed to 2584 // have a high priority filter for these actions. 2585 mSetupWizardPackage = getSetupWizardPackageName(); 2586 if (mProtectedFilters.size() > 0) { 2587 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2588 Slog.i(TAG, "No setup wizard;" 2589 + " All protected intents capped to priority 0"); 2590 } 2591 for (ActivityIntentInfo filter : mProtectedFilters) { 2592 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2593 if (DEBUG_FILTERS) { 2594 Slog.i(TAG, "Found setup wizard;" 2595 + " allow priority " + filter.getPriority() + ";" 2596 + " package: " + filter.activity.info.packageName 2597 + " activity: " + filter.activity.className 2598 + " priority: " + filter.getPriority()); 2599 } 2600 // skip setup wizard; allow it to keep the high priority filter 2601 continue; 2602 } 2603 Slog.w(TAG, "Protected action; cap priority to 0;" 2604 + " package: " + filter.activity.info.packageName 2605 + " activity: " + filter.activity.className 2606 + " origPrio: " + filter.getPriority()); 2607 filter.setPriority(0); 2608 } 2609 } 2610 mDeferProtectedFilters = false; 2611 mProtectedFilters.clear(); 2612 2613 // Now that we know all of the shared libraries, update all clients to have 2614 // the correct library paths. 2615 updateAllSharedLibrariesLPw(); 2616 2617 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2618 // NOTE: We ignore potential failures here during a system scan (like 2619 // the rest of the commands above) because there's precious little we 2620 // can do about it. A settings error is reported, though. 2621 adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/); 2622 } 2623 2624 // Now that we know all the packages we are keeping, 2625 // read and update their last usage times. 2626 mPackageUsage.read(mPackages); 2627 mCompilerStats.read(); 2628 2629 // Read and update the usage of dex files. 2630 // At this point we know the code paths of the packages, so we can validate 2631 // the disk file and build the internal cache. 2632 // The usage file is expected to be small so loading and verifying it 2633 // should take a fairly small time compare to the other activities (e.g. package 2634 // scanning). 2635 final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>(); 2636 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 2637 for (int userId : currentUserIds) { 2638 userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList()); 2639 } 2640 mDexManager.load(userPackages); 2641 2642 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2643 SystemClock.uptimeMillis()); 2644 Slog.i(TAG, "Time to scan packages: " 2645 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2646 + " seconds"); 2647 2648 // If the platform SDK has changed since the last time we booted, 2649 // we need to re-grant app permission to catch any new ones that 2650 // appear. This is really a hack, and means that apps can in some 2651 // cases get permissions that the user didn't initially explicitly 2652 // allow... it would be nice to have some better way to handle 2653 // this situation. 2654 int updateFlags = UPDATE_PERMISSIONS_ALL; 2655 if (ver.sdkVersion != mSdkVersion) { 2656 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2657 + mSdkVersion + "; regranting permissions for internal storage"); 2658 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2659 } 2660 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2661 ver.sdkVersion = mSdkVersion; 2662 2663 // If this is the first boot or an update from pre-M, and it is a normal 2664 // boot, then we need to initialize the default preferred apps across 2665 // all defined users. 2666 if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) { 2667 for (UserInfo user : sUserManager.getUsers(true)) { 2668 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2669 applyFactoryDefaultBrowserLPw(user.id); 2670 primeDomainVerificationsLPw(user.id); 2671 } 2672 } 2673 2674 // Prepare storage for system user really early during boot, 2675 // since core system apps like SettingsProvider and SystemUI 2676 // can't wait for user to start 2677 final int storageFlags; 2678 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2679 storageFlags = StorageManager.FLAG_STORAGE_DE; 2680 } else { 2681 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2682 } 2683 reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2684 storageFlags, true /* migrateAppData */); 2685 2686 // If this is first boot after an OTA, and a normal boot, then 2687 // we need to clear code cache directories. 2688 // Note that we do *not* clear the application profiles. These remain valid 2689 // across OTAs and are used to drive profile verification (post OTA) and 2690 // profile compilation (without waiting to collect a fresh set of profiles). 2691 if (mIsUpgrade && !onlyCore) { 2692 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2693 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2694 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2695 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2696 // No apps are running this early, so no need to freeze 2697 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2698 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2699 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2700 } 2701 } 2702 ver.fingerprint = Build.FINGERPRINT; 2703 } 2704 2705 checkDefaultBrowser(); 2706 2707 // clear only after permissions and other defaults have been updated 2708 mExistingSystemPackages.clear(); 2709 mPromoteSystemApps = false; 2710 2711 // All the changes are done during package scanning. 2712 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2713 2714 // can downgrade to reader 2715 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings"); 2716 mSettings.writeLPr(); 2717 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2718 2719 // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty 2720 // early on (before the package manager declares itself as early) because other 2721 // components in the system server might ask for package contexts for these apps. 2722 // 2723 // Note that "onlyCore" in this context means the system is encrypted or encrypting 2724 // (i.e, that the data partition is unavailable). 2725 if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) { 2726 long start = System.nanoTime(); 2727 List<PackageParser.Package> coreApps = new ArrayList<>(); 2728 for (PackageParser.Package pkg : mPackages.values()) { 2729 if (pkg.coreApp) { 2730 coreApps.add(pkg); 2731 } 2732 } 2733 2734 int[] stats = performDexOptUpgrade(coreApps, false, 2735 getCompilerFilterForReason(REASON_CORE_APP)); 2736 2737 final int elapsedTimeSeconds = 2738 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start); 2739 MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds); 2740 2741 if (DEBUG_DEXOPT) { 2742 Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" + 2743 stats[0] + ", " + stats[1] + ", " + stats[2] + ")"); 2744 } 2745 2746 2747 // TODO: Should we log these stats to tron too ? 2748 // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]); 2749 // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]); 2750 // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]); 2751 // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size()); 2752 } 2753 2754 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2755 SystemClock.uptimeMillis()); 2756 2757 if (!mOnlyCore) { 2758 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2759 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2760 mRequiredUninstallerPackage = getRequiredUninstallerLPr(); 2761 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2762 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2763 mIntentFilterVerifierComponent); 2764 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2765 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES); 2766 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2767 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED); 2768 } else { 2769 mRequiredVerifierPackage = null; 2770 mRequiredInstallerPackage = null; 2771 mRequiredUninstallerPackage = null; 2772 mIntentFilterVerifierComponent = null; 2773 mIntentFilterVerifier = null; 2774 mServicesSystemSharedLibraryPackageName = null; 2775 mSharedSystemSharedLibraryPackageName = null; 2776 } 2777 2778 mInstallerService = new PackageInstallerService(context, this); 2779 2780 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2781 if (ephemeralResolverComponent != null) { 2782 if (DEBUG_EPHEMERAL) { 2783 Slog.i(TAG, "Ephemeral resolver: " + ephemeralResolverComponent); 2784 } 2785 mEphemeralResolverConnection = 2786 new EphemeralResolverConnection(mContext, ephemeralResolverComponent); 2787 } else { 2788 mEphemeralResolverConnection = null; 2789 } 2790 mEphemeralInstallerComponent = getEphemeralInstallerLPr(); 2791 if (mEphemeralInstallerComponent != null) { 2792 if (DEBUG_EPHEMERAL) { 2793 Slog.i(TAG, "Ephemeral installer: " + mEphemeralInstallerComponent); 2794 } 2795 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2796 } 2797 2798 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2799 } // synchronized (mPackages) 2800 } // synchronized (mInstallLock) 2801 2802 // Now after opening every single application zip, make sure they 2803 // are all flushed. Not really needed, but keeps things nice and 2804 // tidy. 2805 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC"); 2806 Runtime.getRuntime().gc(); 2807 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2808 2809 // The initial scanning above does many calls into installd while 2810 // holding the mPackages lock, but we're mostly interested in yelling 2811 // once we have a booted system. 2812 mInstaller.setWarnIfHeld(mPackages); 2813 2814 // Expose private service for system components to use. 2815 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2816 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2817 } 2818 2819 @Override 2820 public boolean isFirstBoot() { 2821 return mFirstBoot; 2822 } 2823 2824 @Override 2825 public boolean isOnlyCoreApps() { 2826 return mOnlyCore; 2827 } 2828 2829 @Override 2830 public boolean isUpgrade() { 2831 return mIsUpgrade; 2832 } 2833 2834 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2835 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2836 2837 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2838 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2839 UserHandle.USER_SYSTEM); 2840 if (matches.size() == 1) { 2841 return matches.get(0).getComponentInfo().packageName; 2842 } else if (matches.size() == 0) { 2843 Log.e(TAG, "There should probably be a verifier, but, none were found"); 2844 return null; 2845 } 2846 throw new RuntimeException("There must be exactly one verifier; found " + matches); 2847 } 2848 2849 private @NonNull String getRequiredSharedLibraryLPr(String libraryName) { 2850 synchronized (mPackages) { 2851 SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName); 2852 if (libraryEntry == null) { 2853 throw new IllegalStateException("Missing required shared library:" + libraryName); 2854 } 2855 return libraryEntry.apk; 2856 } 2857 } 2858 2859 private @NonNull String getRequiredInstallerLPr() { 2860 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2861 intent.addCategory(Intent.CATEGORY_DEFAULT); 2862 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2863 2864 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2865 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2866 UserHandle.USER_SYSTEM); 2867 if (matches.size() == 1) { 2868 ResolveInfo resolveInfo = matches.get(0); 2869 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 2870 throw new RuntimeException("The installer must be a privileged app"); 2871 } 2872 return matches.get(0).getComponentInfo().packageName; 2873 } else { 2874 throw new RuntimeException("There must be exactly one installer; found " + matches); 2875 } 2876 } 2877 2878 private @NonNull String getRequiredUninstallerLPr() { 2879 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 2880 intent.addCategory(Intent.CATEGORY_DEFAULT); 2881 intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null)); 2882 2883 final ResolveInfo resolveInfo = resolveIntent(intent, null, 2884 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2885 UserHandle.USER_SYSTEM); 2886 if (resolveInfo == null || 2887 mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) { 2888 throw new RuntimeException("There must be exactly one uninstaller; found " 2889 + resolveInfo); 2890 } 2891 return resolveInfo.getComponentInfo().packageName; 2892 } 2893 2894 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2895 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2896 2897 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2898 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2899 UserHandle.USER_SYSTEM); 2900 ResolveInfo best = null; 2901 final int N = matches.size(); 2902 for (int i = 0; i < N; i++) { 2903 final ResolveInfo cur = matches.get(i); 2904 final String packageName = cur.getComponentInfo().packageName; 2905 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2906 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2907 continue; 2908 } 2909 2910 if (best == null || cur.priority > best.priority) { 2911 best = cur; 2912 } 2913 } 2914 2915 if (best != null) { 2916 return best.getComponentInfo().getComponentName(); 2917 } else { 2918 throw new RuntimeException("There must be at least one intent filter verifier"); 2919 } 2920 } 2921 2922 private @Nullable ComponentName getEphemeralResolverLPr() { 2923 final String[] packageArray = 2924 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2925 if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) { 2926 if (DEBUG_EPHEMERAL) { 2927 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2928 } 2929 return null; 2930 } 2931 2932 final int resolveFlags = 2933 MATCH_DIRECT_BOOT_AWARE 2934 | MATCH_DIRECT_BOOT_UNAWARE 2935 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 2936 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2937 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 2938 resolveFlags, UserHandle.USER_SYSTEM); 2939 2940 final int N = resolvers.size(); 2941 if (N == 0) { 2942 if (DEBUG_EPHEMERAL) { 2943 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2944 } 2945 return null; 2946 } 2947 2948 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2949 for (int i = 0; i < N; i++) { 2950 final ResolveInfo info = resolvers.get(i); 2951 2952 if (info.serviceInfo == null) { 2953 continue; 2954 } 2955 2956 final String packageName = info.serviceInfo.packageName; 2957 if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) { 2958 if (DEBUG_EPHEMERAL) { 2959 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2960 + " pkg: " + packageName + ", info:" + info); 2961 } 2962 continue; 2963 } 2964 2965 if (DEBUG_EPHEMERAL) { 2966 Slog.v(TAG, "Ephemeral resolver found;" 2967 + " pkg: " + packageName + ", info:" + info); 2968 } 2969 return new ComponentName(packageName, info.serviceInfo.name); 2970 } 2971 if (DEBUG_EPHEMERAL) { 2972 Slog.v(TAG, "Ephemeral resolver NOT found"); 2973 } 2974 return null; 2975 } 2976 2977 private @Nullable ComponentName getEphemeralInstallerLPr() { 2978 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2979 intent.addCategory(Intent.CATEGORY_DEFAULT); 2980 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2981 2982 final int resolveFlags = 2983 MATCH_DIRECT_BOOT_AWARE 2984 | MATCH_DIRECT_BOOT_UNAWARE 2985 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 2986 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2987 resolveFlags, UserHandle.USER_SYSTEM); 2988 Iterator<ResolveInfo> iter = matches.iterator(); 2989 while (iter.hasNext()) { 2990 final ResolveInfo rInfo = iter.next(); 2991 final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName); 2992 if (ps != null) { 2993 final PermissionsState permissionsState = ps.getPermissionsState(); 2994 if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) { 2995 continue; 2996 } 2997 } 2998 iter.remove(); 2999 } 3000 if (matches.size() == 0) { 3001 return null; 3002 } else if (matches.size() == 1) { 3003 return matches.get(0).getComponentInfo().getComponentName(); 3004 } else { 3005 throw new RuntimeException( 3006 "There must be at most one ephemeral installer; found " + matches); 3007 } 3008 } 3009 3010 private void primeDomainVerificationsLPw(int userId) { 3011 if (DEBUG_DOMAIN_VERIFICATION) { 3012 Slog.d(TAG, "Priming domain verifications in user " + userId); 3013 } 3014 3015 SystemConfig systemConfig = SystemConfig.getInstance(); 3016 ArraySet<String> packages = systemConfig.getLinkedApps(); 3017 3018 for (String packageName : packages) { 3019 PackageParser.Package pkg = mPackages.get(packageName); 3020 if (pkg != null) { 3021 if (!pkg.isSystemApp()) { 3022 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 3023 continue; 3024 } 3025 3026 ArraySet<String> domains = null; 3027 for (PackageParser.Activity a : pkg.activities) { 3028 for (ActivityIntentInfo filter : a.intents) { 3029 if (hasValidDomains(filter)) { 3030 if (domains == null) { 3031 domains = new ArraySet<String>(); 3032 } 3033 domains.addAll(filter.getHostsList()); 3034 } 3035 } 3036 } 3037 3038 if (domains != null && domains.size() > 0) { 3039 if (DEBUG_DOMAIN_VERIFICATION) { 3040 Slog.v(TAG, " + " + packageName); 3041 } 3042 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 3043 // state w.r.t. the formal app-linkage "no verification attempted" state; 3044 // and then 'always' in the per-user state actually used for intent resolution. 3045 final IntentFilterVerificationInfo ivi; 3046 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains); 3047 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 3048 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 3049 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 3050 } else { 3051 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 3052 + "' does not handle web links"); 3053 } 3054 } else { 3055 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 3056 } 3057 } 3058 3059 scheduleWritePackageRestrictionsLocked(userId); 3060 scheduleWriteSettingsLocked(); 3061 } 3062 3063 private void applyFactoryDefaultBrowserLPw(int userId) { 3064 // The default browser app's package name is stored in a string resource, 3065 // with a product-specific overlay used for vendor customization. 3066 String browserPkg = mContext.getResources().getString( 3067 com.android.internal.R.string.default_browser); 3068 if (!TextUtils.isEmpty(browserPkg)) { 3069 // non-empty string => required to be a known package 3070 PackageSetting ps = mSettings.mPackages.get(browserPkg); 3071 if (ps == null) { 3072 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 3073 browserPkg = null; 3074 } else { 3075 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3076 } 3077 } 3078 3079 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3080 // default. If there's more than one, just leave everything alone. 3081 if (browserPkg == null) { 3082 calculateDefaultBrowserLPw(userId); 3083 } 3084 } 3085 3086 private void calculateDefaultBrowserLPw(int userId) { 3087 List<String> allBrowsers = resolveAllBrowserApps(userId); 3088 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3089 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3090 } 3091 3092 private List<String> resolveAllBrowserApps(int userId) { 3093 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3094 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3095 PackageManager.MATCH_ALL, userId); 3096 3097 final int count = list.size(); 3098 List<String> result = new ArrayList<String>(count); 3099 for (int i=0; i<count; i++) { 3100 ResolveInfo info = list.get(i); 3101 if (info.activityInfo == null 3102 || !info.handleAllWebDataURI 3103 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3104 || result.contains(info.activityInfo.packageName)) { 3105 continue; 3106 } 3107 result.add(info.activityInfo.packageName); 3108 } 3109 3110 return result; 3111 } 3112 3113 private boolean packageIsBrowser(String packageName, int userId) { 3114 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3115 PackageManager.MATCH_ALL, userId); 3116 final int N = list.size(); 3117 for (int i = 0; i < N; i++) { 3118 ResolveInfo info = list.get(i); 3119 if (packageName.equals(info.activityInfo.packageName)) { 3120 return true; 3121 } 3122 } 3123 return false; 3124 } 3125 3126 private void checkDefaultBrowser() { 3127 final int myUserId = UserHandle.myUserId(); 3128 final String packageName = getDefaultBrowserPackageName(myUserId); 3129 if (packageName != null) { 3130 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3131 if (info == null) { 3132 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3133 synchronized (mPackages) { 3134 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3135 } 3136 } 3137 } 3138 } 3139 3140 @Override 3141 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3142 throws RemoteException { 3143 try { 3144 return super.onTransact(code, data, reply, flags); 3145 } catch (RuntimeException e) { 3146 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3147 Slog.wtf(TAG, "Package Manager Crash", e); 3148 } 3149 throw e; 3150 } 3151 } 3152 3153 static int[] appendInts(int[] cur, int[] add) { 3154 if (add == null) return cur; 3155 if (cur == null) return add; 3156 final int N = add.length; 3157 for (int i=0; i<N; i++) { 3158 cur = appendInt(cur, add[i]); 3159 } 3160 return cur; 3161 } 3162 3163 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3164 if (!sUserManager.exists(userId)) return null; 3165 if (ps == null) { 3166 return null; 3167 } 3168 final PackageParser.Package p = ps.pkg; 3169 if (p == null) { 3170 return null; 3171 } 3172 3173 final PermissionsState permissionsState = ps.getPermissionsState(); 3174 3175 // Compute GIDs only if requested 3176 final int[] gids = (flags & PackageManager.GET_GIDS) == 0 3177 ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId); 3178 // Compute granted permissions only if package has requested permissions 3179 final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions) 3180 ? Collections.<String>emptySet() : permissionsState.getPermissions(userId); 3181 final PackageUserState state = ps.readUserState(userId); 3182 3183 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0 3184 && ps.isSystem()) { 3185 flags |= MATCH_ANY_USER; 3186 } 3187 3188 return PackageParser.generatePackageInfo(p, gids, flags, 3189 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3190 } 3191 3192 @Override 3193 public void checkPackageStartable(String packageName, int userId) { 3194 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3195 3196 synchronized (mPackages) { 3197 final PackageSetting ps = mSettings.mPackages.get(packageName); 3198 if (ps == null) { 3199 throw new SecurityException("Package " + packageName + " was not found!"); 3200 } 3201 3202 if (!ps.getInstalled(userId)) { 3203 throw new SecurityException( 3204 "Package " + packageName + " was not installed for user " + userId + "!"); 3205 } 3206 3207 if (mSafeMode && !ps.isSystem()) { 3208 throw new SecurityException("Package " + packageName + " not a system app!"); 3209 } 3210 3211 if (mFrozenPackages.contains(packageName)) { 3212 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3213 } 3214 3215 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3216 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3217 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3218 } 3219 } 3220 } 3221 3222 @Override 3223 public boolean isPackageAvailable(String packageName, int userId) { 3224 if (!sUserManager.exists(userId)) return false; 3225 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3226 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3227 synchronized (mPackages) { 3228 PackageParser.Package p = mPackages.get(packageName); 3229 if (p != null) { 3230 final PackageSetting ps = (PackageSetting) p.mExtras; 3231 if (ps != null) { 3232 final PackageUserState state = ps.readUserState(userId); 3233 if (state != null) { 3234 return PackageParser.isAvailable(state); 3235 } 3236 } 3237 } 3238 } 3239 return false; 3240 } 3241 3242 @Override 3243 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3244 if (!sUserManager.exists(userId)) return null; 3245 flags = updateFlagsForPackage(flags, userId, packageName); 3246 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3247 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3248 3249 // reader 3250 synchronized (mPackages) { 3251 // Normalize package name to hanlde renamed packages 3252 packageName = normalizePackageNameLPr(packageName); 3253 3254 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3255 PackageParser.Package p = null; 3256 if (matchFactoryOnly) { 3257 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3258 if (ps != null) { 3259 return generatePackageInfo(ps, flags, userId); 3260 } 3261 } 3262 if (p == null) { 3263 p = mPackages.get(packageName); 3264 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3265 return null; 3266 } 3267 } 3268 if (DEBUG_PACKAGE_INFO) 3269 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3270 if (p != null) { 3271 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3272 } 3273 if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) { 3274 final PackageSetting ps = mSettings.mPackages.get(packageName); 3275 return generatePackageInfo(ps, flags, userId); 3276 } 3277 } 3278 return null; 3279 } 3280 3281 @Override 3282 public String[] currentToCanonicalPackageNames(String[] names) { 3283 String[] out = new String[names.length]; 3284 // reader 3285 synchronized (mPackages) { 3286 for (int i=names.length-1; i>=0; i--) { 3287 PackageSetting ps = mSettings.mPackages.get(names[i]); 3288 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3289 } 3290 } 3291 return out; 3292 } 3293 3294 @Override 3295 public String[] canonicalToCurrentPackageNames(String[] names) { 3296 String[] out = new String[names.length]; 3297 // reader 3298 synchronized (mPackages) { 3299 for (int i=names.length-1; i>=0; i--) { 3300 String cur = mSettings.getRenamedPackageLPr(names[i]); 3301 out[i] = cur != null ? cur : names[i]; 3302 } 3303 } 3304 return out; 3305 } 3306 3307 @Override 3308 public int getPackageUid(String packageName, int flags, int userId) { 3309 if (!sUserManager.exists(userId)) return -1; 3310 flags = updateFlagsForPackage(flags, userId, packageName); 3311 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3312 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3313 3314 // reader 3315 synchronized (mPackages) { 3316 final PackageParser.Package p = mPackages.get(packageName); 3317 if (p != null && p.isMatch(flags)) { 3318 return UserHandle.getUid(userId, p.applicationInfo.uid); 3319 } 3320 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3321 final PackageSetting ps = mSettings.mPackages.get(packageName); 3322 if (ps != null && ps.isMatch(flags)) { 3323 return UserHandle.getUid(userId, ps.appId); 3324 } 3325 } 3326 } 3327 3328 return -1; 3329 } 3330 3331 @Override 3332 public int[] getPackageGids(String packageName, int flags, int userId) { 3333 if (!sUserManager.exists(userId)) return null; 3334 flags = updateFlagsForPackage(flags, userId, packageName); 3335 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3336 false /* requireFullPermission */, false /* checkShell */, 3337 "getPackageGids"); 3338 3339 // reader 3340 synchronized (mPackages) { 3341 final PackageParser.Package p = mPackages.get(packageName); 3342 if (p != null && p.isMatch(flags)) { 3343 PackageSetting ps = (PackageSetting) p.mExtras; 3344 // TODO: Shouldn't this be checking for package installed state for userId and 3345 // return null? 3346 return ps.getPermissionsState().computeGids(userId); 3347 } 3348 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3349 final PackageSetting ps = mSettings.mPackages.get(packageName); 3350 if (ps != null && ps.isMatch(flags)) { 3351 return ps.getPermissionsState().computeGids(userId); 3352 } 3353 } 3354 } 3355 3356 return null; 3357 } 3358 3359 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3360 if (bp.perm != null) { 3361 return PackageParser.generatePermissionInfo(bp.perm, flags); 3362 } 3363 PermissionInfo pi = new PermissionInfo(); 3364 pi.name = bp.name; 3365 pi.packageName = bp.sourcePackage; 3366 pi.nonLocalizedLabel = bp.name; 3367 pi.protectionLevel = bp.protectionLevel; 3368 return pi; 3369 } 3370 3371 @Override 3372 public PermissionInfo getPermissionInfo(String name, int flags) { 3373 // reader 3374 synchronized (mPackages) { 3375 final BasePermission p = mSettings.mPermissions.get(name); 3376 if (p != null) { 3377 return generatePermissionInfo(p, flags); 3378 } 3379 return null; 3380 } 3381 } 3382 3383 @Override 3384 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3385 int flags) { 3386 // reader 3387 synchronized (mPackages) { 3388 if (group != null && !mPermissionGroups.containsKey(group)) { 3389 // This is thrown as NameNotFoundException 3390 return null; 3391 } 3392 3393 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3394 for (BasePermission p : mSettings.mPermissions.values()) { 3395 if (group == null) { 3396 if (p.perm == null || p.perm.info.group == null) { 3397 out.add(generatePermissionInfo(p, flags)); 3398 } 3399 } else { 3400 if (p.perm != null && group.equals(p.perm.info.group)) { 3401 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3402 } 3403 } 3404 } 3405 return new ParceledListSlice<>(out); 3406 } 3407 } 3408 3409 @Override 3410 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3411 // reader 3412 synchronized (mPackages) { 3413 return PackageParser.generatePermissionGroupInfo( 3414 mPermissionGroups.get(name), flags); 3415 } 3416 } 3417 3418 @Override 3419 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3420 // reader 3421 synchronized (mPackages) { 3422 final int N = mPermissionGroups.size(); 3423 ArrayList<PermissionGroupInfo> out 3424 = new ArrayList<PermissionGroupInfo>(N); 3425 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3426 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3427 } 3428 return new ParceledListSlice<>(out); 3429 } 3430 } 3431 3432 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3433 int userId) { 3434 if (!sUserManager.exists(userId)) return null; 3435 PackageSetting ps = mSettings.mPackages.get(packageName); 3436 if (ps != null) { 3437 if (ps.pkg == null) { 3438 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3439 if (pInfo != null) { 3440 return pInfo.applicationInfo; 3441 } 3442 return null; 3443 } 3444 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3445 ps.readUserState(userId), userId); 3446 } 3447 return null; 3448 } 3449 3450 @Override 3451 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3452 if (!sUserManager.exists(userId)) return null; 3453 flags = updateFlagsForApplication(flags, userId, packageName); 3454 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3455 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3456 3457 // writer 3458 synchronized (mPackages) { 3459 // Normalize package name to hanlde renamed packages 3460 packageName = normalizePackageNameLPr(packageName); 3461 3462 PackageParser.Package p = mPackages.get(packageName); 3463 if (DEBUG_PACKAGE_INFO) Log.v( 3464 TAG, "getApplicationInfo " + packageName 3465 + ": " + p); 3466 if (p != null) { 3467 PackageSetting ps = mSettings.mPackages.get(packageName); 3468 if (ps == null) return null; 3469 // Note: isEnabledLP() does not apply here - always return info 3470 return PackageParser.generateApplicationInfo( 3471 p, flags, ps.readUserState(userId), userId); 3472 } 3473 if ("android".equals(packageName)||"system".equals(packageName)) { 3474 return mAndroidApplication; 3475 } 3476 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3477 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3478 } 3479 } 3480 return null; 3481 } 3482 3483 private String normalizePackageNameLPr(String packageName) { 3484 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 3485 return normalizedPackageName != null ? normalizedPackageName : packageName; 3486 } 3487 3488 @Override 3489 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3490 final IPackageDataObserver observer) { 3491 mContext.enforceCallingOrSelfPermission( 3492 android.Manifest.permission.CLEAR_APP_CACHE, null); 3493 // Queue up an async operation since clearing cache may take a little while. 3494 mHandler.post(new Runnable() { 3495 public void run() { 3496 mHandler.removeCallbacks(this); 3497 boolean success = true; 3498 synchronized (mInstallLock) { 3499 try { 3500 mInstaller.freeCache(volumeUuid, freeStorageSize); 3501 } catch (InstallerException e) { 3502 Slog.w(TAG, "Couldn't clear application caches: " + e); 3503 success = false; 3504 } 3505 } 3506 if (observer != null) { 3507 try { 3508 observer.onRemoveCompleted(null, success); 3509 } catch (RemoteException e) { 3510 Slog.w(TAG, "RemoveException when invoking call back"); 3511 } 3512 } 3513 } 3514 }); 3515 } 3516 3517 @Override 3518 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3519 final IntentSender pi) { 3520 mContext.enforceCallingOrSelfPermission( 3521 android.Manifest.permission.CLEAR_APP_CACHE, null); 3522 // Queue up an async operation since clearing cache may take a little while. 3523 mHandler.post(new Runnable() { 3524 public void run() { 3525 mHandler.removeCallbacks(this); 3526 boolean success = true; 3527 synchronized (mInstallLock) { 3528 try { 3529 mInstaller.freeCache(volumeUuid, freeStorageSize); 3530 } catch (InstallerException e) { 3531 Slog.w(TAG, "Couldn't clear application caches: " + e); 3532 success = false; 3533 } 3534 } 3535 if(pi != null) { 3536 try { 3537 // Callback via pending intent 3538 int code = success ? 1 : 0; 3539 pi.sendIntent(null, code, null, 3540 null, null); 3541 } catch (SendIntentException e1) { 3542 Slog.i(TAG, "Failed to send pending intent"); 3543 } 3544 } 3545 } 3546 }); 3547 } 3548 3549 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3550 synchronized (mInstallLock) { 3551 try { 3552 mInstaller.freeCache(volumeUuid, freeStorageSize); 3553 } catch (InstallerException e) { 3554 throw new IOException("Failed to free enough space", e); 3555 } 3556 } 3557 } 3558 3559 /** 3560 * Update given flags based on encryption status of current user. 3561 */ 3562 private int updateFlags(int flags, int userId) { 3563 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3564 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3565 // Caller expressed an explicit opinion about what encryption 3566 // aware/unaware components they want to see, so fall through and 3567 // give them what they want 3568 } else { 3569 // Caller expressed no opinion, so match based on user state 3570 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 3571 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3572 } else { 3573 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3574 } 3575 } 3576 return flags; 3577 } 3578 3579 private UserManagerInternal getUserManagerInternal() { 3580 if (mUserManagerInternal == null) { 3581 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 3582 } 3583 return mUserManagerInternal; 3584 } 3585 3586 /** 3587 * Update given flags when being used to request {@link PackageInfo}. 3588 */ 3589 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3590 final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM; 3591 boolean triaged = true; 3592 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3593 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3594 // Caller is asking for component details, so they'd better be 3595 // asking for specific encryption matching behavior, or be triaged 3596 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3597 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3598 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3599 triaged = false; 3600 } 3601 } 3602 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3603 | PackageManager.MATCH_SYSTEM_ONLY 3604 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3605 triaged = false; 3606 } 3607 if ((flags & PackageManager.MATCH_ANY_USER) != 0) { 3608 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 3609 "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at " 3610 + Debug.getCallers(5)); 3611 } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser 3612 && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) { 3613 // If the caller wants all packages and has a restricted profile associated with it, 3614 // then match all users. This is to make sure that launchers that need to access work 3615 // profile apps don't start breaking. TODO: Remove this hack when launchers stop using 3616 // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380 3617 flags |= PackageManager.MATCH_ANY_USER; 3618 } 3619 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3620 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3621 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3622 } 3623 return updateFlags(flags, userId); 3624 } 3625 3626 /** 3627 * Update given flags when being used to request {@link ApplicationInfo}. 3628 */ 3629 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3630 return updateFlagsForPackage(flags, userId, cookie); 3631 } 3632 3633 /** 3634 * Update given flags when being used to request {@link ComponentInfo}. 3635 */ 3636 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3637 if (cookie instanceof Intent) { 3638 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3639 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3640 } 3641 } 3642 3643 boolean triaged = true; 3644 // Caller is asking for component details, so they'd better be 3645 // asking for specific encryption matching behavior, or be triaged 3646 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3647 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3648 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3649 triaged = false; 3650 } 3651 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3652 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3653 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3654 } 3655 3656 return updateFlags(flags, userId); 3657 } 3658 3659 /** 3660 * Update given flags when being used to request {@link ResolveInfo}. 3661 */ 3662 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3663 // Safe mode means we shouldn't match any third-party components 3664 if (mSafeMode) { 3665 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3666 } 3667 final String ephemeralPkgName = getEphemeralPackageName(Binder.getCallingUid()); 3668 if (ephemeralPkgName != null) { 3669 flags |= PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY; 3670 flags |= PackageManager.MATCH_EPHEMERAL; 3671 } 3672 3673 return updateFlagsForComponent(flags, userId, cookie); 3674 } 3675 3676 @Override 3677 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3678 if (!sUserManager.exists(userId)) return null; 3679 flags = updateFlagsForComponent(flags, userId, component); 3680 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3681 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 3682 synchronized (mPackages) { 3683 PackageParser.Activity a = mActivities.mActivities.get(component); 3684 3685 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3686 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3687 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3688 if (ps == null) return null; 3689 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3690 userId); 3691 } 3692 if (mResolveComponentName.equals(component)) { 3693 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3694 new PackageUserState(), userId); 3695 } 3696 } 3697 return null; 3698 } 3699 3700 @Override 3701 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3702 String resolvedType) { 3703 synchronized (mPackages) { 3704 if (component.equals(mResolveComponentName)) { 3705 // The resolver supports EVERYTHING! 3706 return true; 3707 } 3708 PackageParser.Activity a = mActivities.mActivities.get(component); 3709 if (a == null) { 3710 return false; 3711 } 3712 for (int i=0; i<a.intents.size(); i++) { 3713 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3714 intent.getData(), intent.getCategories(), TAG) >= 0) { 3715 return true; 3716 } 3717 } 3718 return false; 3719 } 3720 } 3721 3722 @Override 3723 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3724 if (!sUserManager.exists(userId)) return null; 3725 flags = updateFlagsForComponent(flags, userId, component); 3726 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3727 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 3728 synchronized (mPackages) { 3729 PackageParser.Activity a = mReceivers.mActivities.get(component); 3730 if (DEBUG_PACKAGE_INFO) Log.v( 3731 TAG, "getReceiverInfo " + component + ": " + a); 3732 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3733 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3734 if (ps == null) return null; 3735 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3736 userId); 3737 } 3738 } 3739 return null; 3740 } 3741 3742 @Override 3743 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3744 if (!sUserManager.exists(userId)) return null; 3745 flags = updateFlagsForComponent(flags, userId, component); 3746 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3747 false /* requireFullPermission */, false /* checkShell */, "get service info"); 3748 synchronized (mPackages) { 3749 PackageParser.Service s = mServices.mServices.get(component); 3750 if (DEBUG_PACKAGE_INFO) Log.v( 3751 TAG, "getServiceInfo " + component + ": " + s); 3752 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3753 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3754 if (ps == null) return null; 3755 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3756 userId); 3757 } 3758 } 3759 return null; 3760 } 3761 3762 @Override 3763 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3764 if (!sUserManager.exists(userId)) return null; 3765 flags = updateFlagsForComponent(flags, userId, component); 3766 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3767 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 3768 synchronized (mPackages) { 3769 PackageParser.Provider p = mProviders.mProviders.get(component); 3770 if (DEBUG_PACKAGE_INFO) Log.v( 3771 TAG, "getProviderInfo " + component + ": " + p); 3772 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3773 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3774 if (ps == null) return null; 3775 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3776 userId); 3777 } 3778 } 3779 return null; 3780 } 3781 3782 @Override 3783 public String[] getSystemSharedLibraryNames() { 3784 Set<String> libSet; 3785 synchronized (mPackages) { 3786 libSet = mSharedLibraries.keySet(); 3787 int size = libSet.size(); 3788 if (size > 0) { 3789 String[] libs = new String[size]; 3790 libSet.toArray(libs); 3791 return libs; 3792 } 3793 } 3794 return null; 3795 } 3796 3797 @Override 3798 public @NonNull String getServicesSystemSharedLibraryPackageName() { 3799 synchronized (mPackages) { 3800 return mServicesSystemSharedLibraryPackageName; 3801 } 3802 } 3803 3804 @Override 3805 public @NonNull String getSharedSystemSharedLibraryPackageName() { 3806 synchronized (mPackages) { 3807 return mSharedSystemSharedLibraryPackageName; 3808 } 3809 } 3810 3811 @Override 3812 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 3813 synchronized (mPackages) { 3814 final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values()); 3815 3816 final FeatureInfo fi = new FeatureInfo(); 3817 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3818 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3819 res.add(fi); 3820 3821 return new ParceledListSlice<>(res); 3822 } 3823 } 3824 3825 @Override 3826 public boolean hasSystemFeature(String name, int version) { 3827 synchronized (mPackages) { 3828 final FeatureInfo feat = mAvailableFeatures.get(name); 3829 if (feat == null) { 3830 return false; 3831 } else { 3832 return feat.version >= version; 3833 } 3834 } 3835 } 3836 3837 @Override 3838 public int checkPermission(String permName, String pkgName, int userId) { 3839 if (!sUserManager.exists(userId)) { 3840 return PackageManager.PERMISSION_DENIED; 3841 } 3842 3843 synchronized (mPackages) { 3844 final PackageParser.Package p = mPackages.get(pkgName); 3845 if (p != null && p.mExtras != null) { 3846 final PackageSetting ps = (PackageSetting) p.mExtras; 3847 final PermissionsState permissionsState = ps.getPermissionsState(); 3848 if (permissionsState.hasPermission(permName, userId)) { 3849 return PackageManager.PERMISSION_GRANTED; 3850 } 3851 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3852 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3853 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3854 return PackageManager.PERMISSION_GRANTED; 3855 } 3856 } 3857 } 3858 3859 return PackageManager.PERMISSION_DENIED; 3860 } 3861 3862 @Override 3863 public int checkUidPermission(String permName, int uid) { 3864 final int userId = UserHandle.getUserId(uid); 3865 3866 if (!sUserManager.exists(userId)) { 3867 return PackageManager.PERMISSION_DENIED; 3868 } 3869 3870 synchronized (mPackages) { 3871 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3872 if (obj != null) { 3873 final SettingBase ps = (SettingBase) obj; 3874 final PermissionsState permissionsState = ps.getPermissionsState(); 3875 if (permissionsState.hasPermission(permName, userId)) { 3876 return PackageManager.PERMISSION_GRANTED; 3877 } 3878 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3879 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3880 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3881 return PackageManager.PERMISSION_GRANTED; 3882 } 3883 } else { 3884 ArraySet<String> perms = mSystemPermissions.get(uid); 3885 if (perms != null) { 3886 if (perms.contains(permName)) { 3887 return PackageManager.PERMISSION_GRANTED; 3888 } 3889 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3890 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3891 return PackageManager.PERMISSION_GRANTED; 3892 } 3893 } 3894 } 3895 } 3896 3897 return PackageManager.PERMISSION_DENIED; 3898 } 3899 3900 @Override 3901 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3902 if (UserHandle.getCallingUserId() != userId) { 3903 mContext.enforceCallingPermission( 3904 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3905 "isPermissionRevokedByPolicy for user " + userId); 3906 } 3907 3908 if (checkPermission(permission, packageName, userId) 3909 == PackageManager.PERMISSION_GRANTED) { 3910 return false; 3911 } 3912 3913 final long identity = Binder.clearCallingIdentity(); 3914 try { 3915 final int flags = getPermissionFlags(permission, packageName, userId); 3916 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3917 } finally { 3918 Binder.restoreCallingIdentity(identity); 3919 } 3920 } 3921 3922 @Override 3923 public String getPermissionControllerPackageName() { 3924 synchronized (mPackages) { 3925 return mRequiredInstallerPackage; 3926 } 3927 } 3928 3929 /** 3930 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3931 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3932 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3933 * @param message the message to log on security exception 3934 */ 3935 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3936 boolean checkShell, String message) { 3937 if (userId < 0) { 3938 throw new IllegalArgumentException("Invalid userId " + userId); 3939 } 3940 if (checkShell) { 3941 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3942 } 3943 if (userId == UserHandle.getUserId(callingUid)) return; 3944 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3945 if (requireFullPermission) { 3946 mContext.enforceCallingOrSelfPermission( 3947 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3948 } else { 3949 try { 3950 mContext.enforceCallingOrSelfPermission( 3951 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3952 } catch (SecurityException se) { 3953 mContext.enforceCallingOrSelfPermission( 3954 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3955 } 3956 } 3957 } 3958 } 3959 3960 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3961 if (callingUid == Process.SHELL_UID) { 3962 if (userHandle >= 0 3963 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3964 throw new SecurityException("Shell does not have permission to access user " 3965 + userHandle); 3966 } else if (userHandle < 0) { 3967 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3968 + Debug.getCallers(3)); 3969 } 3970 } 3971 } 3972 3973 private BasePermission findPermissionTreeLP(String permName) { 3974 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3975 if (permName.startsWith(bp.name) && 3976 permName.length() > bp.name.length() && 3977 permName.charAt(bp.name.length()) == '.') { 3978 return bp; 3979 } 3980 } 3981 return null; 3982 } 3983 3984 private BasePermission checkPermissionTreeLP(String permName) { 3985 if (permName != null) { 3986 BasePermission bp = findPermissionTreeLP(permName); 3987 if (bp != null) { 3988 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3989 return bp; 3990 } 3991 throw new SecurityException("Calling uid " 3992 + Binder.getCallingUid() 3993 + " is not allowed to add to permission tree " 3994 + bp.name + " owned by uid " + bp.uid); 3995 } 3996 } 3997 throw new SecurityException("No permission tree found for " + permName); 3998 } 3999 4000 static boolean compareStrings(CharSequence s1, CharSequence s2) { 4001 if (s1 == null) { 4002 return s2 == null; 4003 } 4004 if (s2 == null) { 4005 return false; 4006 } 4007 if (s1.getClass() != s2.getClass()) { 4008 return false; 4009 } 4010 return s1.equals(s2); 4011 } 4012 4013 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 4014 if (pi1.icon != pi2.icon) return false; 4015 if (pi1.logo != pi2.logo) return false; 4016 if (pi1.protectionLevel != pi2.protectionLevel) return false; 4017 if (!compareStrings(pi1.name, pi2.name)) return false; 4018 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 4019 // We'll take care of setting this one. 4020 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 4021 // These are not currently stored in settings. 4022 //if (!compareStrings(pi1.group, pi2.group)) return false; 4023 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 4024 //if (pi1.labelRes != pi2.labelRes) return false; 4025 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 4026 return true; 4027 } 4028 4029 int permissionInfoFootprint(PermissionInfo info) { 4030 int size = info.name.length(); 4031 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 4032 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 4033 return size; 4034 } 4035 4036 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 4037 int size = 0; 4038 for (BasePermission perm : mSettings.mPermissions.values()) { 4039 if (perm.uid == tree.uid) { 4040 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 4041 } 4042 } 4043 return size; 4044 } 4045 4046 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 4047 // We calculate the max size of permissions defined by this uid and throw 4048 // if that plus the size of 'info' would exceed our stated maximum. 4049 if (tree.uid != Process.SYSTEM_UID) { 4050 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 4051 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 4052 throw new SecurityException("Permission tree size cap exceeded"); 4053 } 4054 } 4055 } 4056 4057 boolean addPermissionLocked(PermissionInfo info, boolean async) { 4058 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 4059 throw new SecurityException("Label must be specified in permission"); 4060 } 4061 BasePermission tree = checkPermissionTreeLP(info.name); 4062 BasePermission bp = mSettings.mPermissions.get(info.name); 4063 boolean added = bp == null; 4064 boolean changed = true; 4065 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 4066 if (added) { 4067 enforcePermissionCapLocked(info, tree); 4068 bp = new BasePermission(info.name, tree.sourcePackage, 4069 BasePermission.TYPE_DYNAMIC); 4070 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 4071 throw new SecurityException( 4072 "Not allowed to modify non-dynamic permission " 4073 + info.name); 4074 } else { 4075 if (bp.protectionLevel == fixedLevel 4076 && bp.perm.owner.equals(tree.perm.owner) 4077 && bp.uid == tree.uid 4078 && comparePermissionInfos(bp.perm.info, info)) { 4079 changed = false; 4080 } 4081 } 4082 bp.protectionLevel = fixedLevel; 4083 info = new PermissionInfo(info); 4084 info.protectionLevel = fixedLevel; 4085 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 4086 bp.perm.info.packageName = tree.perm.info.packageName; 4087 bp.uid = tree.uid; 4088 if (added) { 4089 mSettings.mPermissions.put(info.name, bp); 4090 } 4091 if (changed) { 4092 if (!async) { 4093 mSettings.writeLPr(); 4094 } else { 4095 scheduleWriteSettingsLocked(); 4096 } 4097 } 4098 return added; 4099 } 4100 4101 @Override 4102 public boolean addPermission(PermissionInfo info) { 4103 synchronized (mPackages) { 4104 return addPermissionLocked(info, false); 4105 } 4106 } 4107 4108 @Override 4109 public boolean addPermissionAsync(PermissionInfo info) { 4110 synchronized (mPackages) { 4111 return addPermissionLocked(info, true); 4112 } 4113 } 4114 4115 @Override 4116 public void removePermission(String name) { 4117 synchronized (mPackages) { 4118 checkPermissionTreeLP(name); 4119 BasePermission bp = mSettings.mPermissions.get(name); 4120 if (bp != null) { 4121 if (bp.type != BasePermission.TYPE_DYNAMIC) { 4122 throw new SecurityException( 4123 "Not allowed to modify non-dynamic permission " 4124 + name); 4125 } 4126 mSettings.mPermissions.remove(name); 4127 mSettings.writeLPr(); 4128 } 4129 } 4130 } 4131 4132 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 4133 BasePermission bp) { 4134 int index = pkg.requestedPermissions.indexOf(bp.name); 4135 if (index == -1) { 4136 throw new SecurityException("Package " + pkg.packageName 4137 + " has not requested permission " + bp.name); 4138 } 4139 if (!bp.isRuntime() && !bp.isDevelopment()) { 4140 throw new SecurityException("Permission " + bp.name 4141 + " is not a changeable permission type"); 4142 } 4143 } 4144 4145 @Override 4146 public void grantRuntimePermission(String packageName, String name, final int userId) { 4147 grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */); 4148 } 4149 4150 private void grantRuntimePermission(String packageName, String name, final int userId, 4151 boolean overridePolicy) { 4152 if (!sUserManager.exists(userId)) { 4153 Log.e(TAG, "No such user:" + userId); 4154 return; 4155 } 4156 4157 mContext.enforceCallingOrSelfPermission( 4158 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 4159 "grantRuntimePermission"); 4160 4161 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4162 true /* requireFullPermission */, true /* checkShell */, 4163 "grantRuntimePermission"); 4164 4165 final int uid; 4166 final SettingBase sb; 4167 4168 synchronized (mPackages) { 4169 final PackageParser.Package pkg = mPackages.get(packageName); 4170 if (pkg == null) { 4171 throw new IllegalArgumentException("Unknown package: " + packageName); 4172 } 4173 4174 final BasePermission bp = mSettings.mPermissions.get(name); 4175 if (bp == null) { 4176 throw new IllegalArgumentException("Unknown permission: " + name); 4177 } 4178 4179 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4180 4181 // If a permission review is required for legacy apps we represent 4182 // their permissions as always granted runtime ones since we need 4183 // to keep the review required permission flag per user while an 4184 // install permission's state is shared across all users. 4185 if (mPermissionReviewRequired 4186 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4187 && bp.isRuntime()) { 4188 return; 4189 } 4190 4191 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 4192 sb = (SettingBase) pkg.mExtras; 4193 if (sb == null) { 4194 throw new IllegalArgumentException("Unknown package: " + packageName); 4195 } 4196 4197 final PermissionsState permissionsState = sb.getPermissionsState(); 4198 4199 final int flags = permissionsState.getPermissionFlags(name, userId); 4200 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4201 throw new SecurityException("Cannot grant system fixed permission " 4202 + name + " for package " + packageName); 4203 } 4204 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) { 4205 throw new SecurityException("Cannot grant policy fixed permission " 4206 + name + " for package " + packageName); 4207 } 4208 4209 if (bp.isDevelopment()) { 4210 // Development permissions must be handled specially, since they are not 4211 // normal runtime permissions. For now they apply to all users. 4212 if (permissionsState.grantInstallPermission(bp) != 4213 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4214 scheduleWriteSettingsLocked(); 4215 } 4216 return; 4217 } 4218 4219 if (pkg.applicationInfo.isEphemeralApp() && !bp.isEphemeral()) { 4220 throw new SecurityException("Cannot grant non-ephemeral permission" 4221 + name + " for package " + packageName); 4222 } 4223 4224 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4225 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4226 return; 4227 } 4228 4229 final int result = permissionsState.grantRuntimePermission(bp, userId); 4230 switch (result) { 4231 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4232 return; 4233 } 4234 4235 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4236 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4237 mHandler.post(new Runnable() { 4238 @Override 4239 public void run() { 4240 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4241 } 4242 }); 4243 } 4244 break; 4245 } 4246 4247 if (bp.isRuntime()) { 4248 logPermissionGranted(mContext, name, packageName); 4249 } 4250 4251 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4252 4253 // Not critical if that is lost - app has to request again. 4254 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4255 } 4256 4257 // Only need to do this if user is initialized. Otherwise it's a new user 4258 // and there are no processes running as the user yet and there's no need 4259 // to make an expensive call to remount processes for the changed permissions. 4260 if (READ_EXTERNAL_STORAGE.equals(name) 4261 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4262 final long token = Binder.clearCallingIdentity(); 4263 try { 4264 if (sUserManager.isInitialized(userId)) { 4265 StorageManagerInternal storageManagerInternal = LocalServices.getService( 4266 StorageManagerInternal.class); 4267 storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName); 4268 } 4269 } finally { 4270 Binder.restoreCallingIdentity(token); 4271 } 4272 } 4273 } 4274 4275 @Override 4276 public void revokeRuntimePermission(String packageName, String name, int userId) { 4277 revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */); 4278 } 4279 4280 private void revokeRuntimePermission(String packageName, String name, int userId, 4281 boolean overridePolicy) { 4282 if (!sUserManager.exists(userId)) { 4283 Log.e(TAG, "No such user:" + userId); 4284 return; 4285 } 4286 4287 mContext.enforceCallingOrSelfPermission( 4288 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4289 "revokeRuntimePermission"); 4290 4291 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4292 true /* requireFullPermission */, true /* checkShell */, 4293 "revokeRuntimePermission"); 4294 4295 final int appId; 4296 4297 synchronized (mPackages) { 4298 final PackageParser.Package pkg = mPackages.get(packageName); 4299 if (pkg == null) { 4300 throw new IllegalArgumentException("Unknown package: " + packageName); 4301 } 4302 4303 final BasePermission bp = mSettings.mPermissions.get(name); 4304 if (bp == null) { 4305 throw new IllegalArgumentException("Unknown permission: " + name); 4306 } 4307 4308 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4309 4310 // If a permission review is required for legacy apps we represent 4311 // their permissions as always granted runtime ones since we need 4312 // to keep the review required permission flag per user while an 4313 // install permission's state is shared across all users. 4314 if (mPermissionReviewRequired 4315 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4316 && bp.isRuntime()) { 4317 return; 4318 } 4319 4320 SettingBase sb = (SettingBase) pkg.mExtras; 4321 if (sb == null) { 4322 throw new IllegalArgumentException("Unknown package: " + packageName); 4323 } 4324 4325 final PermissionsState permissionsState = sb.getPermissionsState(); 4326 4327 final int flags = permissionsState.getPermissionFlags(name, userId); 4328 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4329 throw new SecurityException("Cannot revoke system fixed permission " 4330 + name + " for package " + packageName); 4331 } 4332 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) { 4333 throw new SecurityException("Cannot revoke policy fixed permission " 4334 + name + " for package " + packageName); 4335 } 4336 4337 if (bp.isDevelopment()) { 4338 // Development permissions must be handled specially, since they are not 4339 // normal runtime permissions. For now they apply to all users. 4340 if (permissionsState.revokeInstallPermission(bp) != 4341 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4342 scheduleWriteSettingsLocked(); 4343 } 4344 return; 4345 } 4346 4347 if (permissionsState.revokeRuntimePermission(bp, userId) == 4348 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4349 return; 4350 } 4351 4352 if (bp.isRuntime()) { 4353 logPermissionRevoked(mContext, name, packageName); 4354 } 4355 4356 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4357 4358 // Critical, after this call app should never have the permission. 4359 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4360 4361 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4362 } 4363 4364 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4365 } 4366 4367 /** 4368 * Get the first event id for the permission. 4369 * 4370 * <p>There are four events for each permission: <ul> 4371 * <li>Request permission: first id + 0</li> 4372 * <li>Grant permission: first id + 1</li> 4373 * <li>Request for permission denied: first id + 2</li> 4374 * <li>Revoke permission: first id + 3</li> 4375 * </ul></p> 4376 * 4377 * @param name name of the permission 4378 * 4379 * @return The first event id for the permission 4380 */ 4381 private static int getBaseEventId(@NonNull String name) { 4382 int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name); 4383 4384 if (eventIdIndex == -1) { 4385 if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE 4386 || "user".equals(Build.TYPE)) { 4387 Log.i(TAG, "Unknown permission " + name); 4388 4389 return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN; 4390 } else { 4391 // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated. 4392 // 4393 // Also update 4394 // - EventLogger#ALL_DANGEROUS_PERMISSIONS 4395 // - metrics_constants.proto 4396 throw new IllegalStateException("Unknown permission " + name); 4397 } 4398 } 4399 4400 return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4; 4401 } 4402 4403 /** 4404 * Log that a permission was revoked. 4405 * 4406 * @param context Context of the caller 4407 * @param name name of the permission 4408 * @param packageName package permission if for 4409 */ 4410 private static void logPermissionRevoked(@NonNull Context context, @NonNull String name, 4411 @NonNull String packageName) { 4412 MetricsLogger.action(context, getBaseEventId(name) + 3, packageName); 4413 } 4414 4415 /** 4416 * Log that a permission request was granted. 4417 * 4418 * @param context Context of the caller 4419 * @param name name of the permission 4420 * @param packageName package permission if for 4421 */ 4422 private static void logPermissionGranted(@NonNull Context context, @NonNull String name, 4423 @NonNull String packageName) { 4424 MetricsLogger.action(context, getBaseEventId(name) + 1, packageName); 4425 } 4426 4427 @Override 4428 public void resetRuntimePermissions() { 4429 mContext.enforceCallingOrSelfPermission( 4430 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4431 "revokeRuntimePermission"); 4432 4433 int callingUid = Binder.getCallingUid(); 4434 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4435 mContext.enforceCallingOrSelfPermission( 4436 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4437 "resetRuntimePermissions"); 4438 } 4439 4440 synchronized (mPackages) { 4441 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4442 for (int userId : UserManagerService.getInstance().getUserIds()) { 4443 final int packageCount = mPackages.size(); 4444 for (int i = 0; i < packageCount; i++) { 4445 PackageParser.Package pkg = mPackages.valueAt(i); 4446 if (!(pkg.mExtras instanceof PackageSetting)) { 4447 continue; 4448 } 4449 PackageSetting ps = (PackageSetting) pkg.mExtras; 4450 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4451 } 4452 } 4453 } 4454 } 4455 4456 @Override 4457 public int getPermissionFlags(String name, String packageName, int userId) { 4458 if (!sUserManager.exists(userId)) { 4459 return 0; 4460 } 4461 4462 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4463 4464 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4465 true /* requireFullPermission */, false /* checkShell */, 4466 "getPermissionFlags"); 4467 4468 synchronized (mPackages) { 4469 final PackageParser.Package pkg = mPackages.get(packageName); 4470 if (pkg == null) { 4471 return 0; 4472 } 4473 4474 final BasePermission bp = mSettings.mPermissions.get(name); 4475 if (bp == null) { 4476 return 0; 4477 } 4478 4479 SettingBase sb = (SettingBase) pkg.mExtras; 4480 if (sb == null) { 4481 return 0; 4482 } 4483 4484 PermissionsState permissionsState = sb.getPermissionsState(); 4485 return permissionsState.getPermissionFlags(name, userId); 4486 } 4487 } 4488 4489 @Override 4490 public void updatePermissionFlags(String name, String packageName, int flagMask, 4491 int flagValues, int userId) { 4492 if (!sUserManager.exists(userId)) { 4493 return; 4494 } 4495 4496 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4497 4498 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4499 true /* requireFullPermission */, true /* checkShell */, 4500 "updatePermissionFlags"); 4501 4502 // Only the system can change these flags and nothing else. 4503 if (getCallingUid() != Process.SYSTEM_UID) { 4504 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4505 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4506 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4507 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4508 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4509 } 4510 4511 synchronized (mPackages) { 4512 final PackageParser.Package pkg = mPackages.get(packageName); 4513 if (pkg == null) { 4514 throw new IllegalArgumentException("Unknown package: " + packageName); 4515 } 4516 4517 final BasePermission bp = mSettings.mPermissions.get(name); 4518 if (bp == null) { 4519 throw new IllegalArgumentException("Unknown permission: " + name); 4520 } 4521 4522 SettingBase sb = (SettingBase) pkg.mExtras; 4523 if (sb == null) { 4524 throw new IllegalArgumentException("Unknown package: " + packageName); 4525 } 4526 4527 PermissionsState permissionsState = sb.getPermissionsState(); 4528 4529 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4530 4531 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4532 // Install and runtime permissions are stored in different places, 4533 // so figure out what permission changed and persist the change. 4534 if (permissionsState.getInstallPermissionState(name) != null) { 4535 scheduleWriteSettingsLocked(); 4536 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4537 || hadState) { 4538 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4539 } 4540 } 4541 } 4542 } 4543 4544 /** 4545 * Update the permission flags for all packages and runtime permissions of a user in order 4546 * to allow device or profile owner to remove POLICY_FIXED. 4547 */ 4548 @Override 4549 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4550 if (!sUserManager.exists(userId)) { 4551 return; 4552 } 4553 4554 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4555 4556 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4557 true /* requireFullPermission */, true /* checkShell */, 4558 "updatePermissionFlagsForAllApps"); 4559 4560 // Only the system can change system fixed flags. 4561 if (getCallingUid() != Process.SYSTEM_UID) { 4562 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4563 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4564 } 4565 4566 synchronized (mPackages) { 4567 boolean changed = false; 4568 final int packageCount = mPackages.size(); 4569 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4570 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4571 SettingBase sb = (SettingBase) pkg.mExtras; 4572 if (sb == null) { 4573 continue; 4574 } 4575 PermissionsState permissionsState = sb.getPermissionsState(); 4576 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4577 userId, flagMask, flagValues); 4578 } 4579 if (changed) { 4580 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4581 } 4582 } 4583 } 4584 4585 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4586 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4587 != PackageManager.PERMISSION_GRANTED 4588 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4589 != PackageManager.PERMISSION_GRANTED) { 4590 throw new SecurityException(message + " requires " 4591 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4592 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4593 } 4594 } 4595 4596 @Override 4597 public boolean shouldShowRequestPermissionRationale(String permissionName, 4598 String packageName, int userId) { 4599 if (UserHandle.getCallingUserId() != userId) { 4600 mContext.enforceCallingPermission( 4601 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4602 "canShowRequestPermissionRationale for user " + userId); 4603 } 4604 4605 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4606 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4607 return false; 4608 } 4609 4610 if (checkPermission(permissionName, packageName, userId) 4611 == PackageManager.PERMISSION_GRANTED) { 4612 return false; 4613 } 4614 4615 final int flags; 4616 4617 final long identity = Binder.clearCallingIdentity(); 4618 try { 4619 flags = getPermissionFlags(permissionName, 4620 packageName, userId); 4621 } finally { 4622 Binder.restoreCallingIdentity(identity); 4623 } 4624 4625 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4626 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4627 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4628 4629 if ((flags & fixedFlags) != 0) { 4630 return false; 4631 } 4632 4633 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4634 } 4635 4636 @Override 4637 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4638 mContext.enforceCallingOrSelfPermission( 4639 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4640 "addOnPermissionsChangeListener"); 4641 4642 synchronized (mPackages) { 4643 mOnPermissionChangeListeners.addListenerLocked(listener); 4644 } 4645 } 4646 4647 @Override 4648 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4649 synchronized (mPackages) { 4650 mOnPermissionChangeListeners.removeListenerLocked(listener); 4651 } 4652 } 4653 4654 @Override 4655 public boolean isProtectedBroadcast(String actionName) { 4656 synchronized (mPackages) { 4657 if (mProtectedBroadcasts.contains(actionName)) { 4658 return true; 4659 } else if (actionName != null) { 4660 // TODO: remove these terrible hacks 4661 if (actionName.startsWith("android.net.netmon.lingerExpired") 4662 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 4663 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 4664 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 4665 return true; 4666 } 4667 } 4668 } 4669 return false; 4670 } 4671 4672 @Override 4673 public int checkSignatures(String pkg1, String pkg2) { 4674 synchronized (mPackages) { 4675 final PackageParser.Package p1 = mPackages.get(pkg1); 4676 final PackageParser.Package p2 = mPackages.get(pkg2); 4677 if (p1 == null || p1.mExtras == null 4678 || p2 == null || p2.mExtras == null) { 4679 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4680 } 4681 return compareSignatures(p1.mSignatures, p2.mSignatures); 4682 } 4683 } 4684 4685 @Override 4686 public int checkUidSignatures(int uid1, int uid2) { 4687 // Map to base uids. 4688 uid1 = UserHandle.getAppId(uid1); 4689 uid2 = UserHandle.getAppId(uid2); 4690 // reader 4691 synchronized (mPackages) { 4692 Signature[] s1; 4693 Signature[] s2; 4694 Object obj = mSettings.getUserIdLPr(uid1); 4695 if (obj != null) { 4696 if (obj instanceof SharedUserSetting) { 4697 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4698 } else if (obj instanceof PackageSetting) { 4699 s1 = ((PackageSetting)obj).signatures.mSignatures; 4700 } else { 4701 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4702 } 4703 } else { 4704 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4705 } 4706 obj = mSettings.getUserIdLPr(uid2); 4707 if (obj != null) { 4708 if (obj instanceof SharedUserSetting) { 4709 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4710 } else if (obj instanceof PackageSetting) { 4711 s2 = ((PackageSetting)obj).signatures.mSignatures; 4712 } else { 4713 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4714 } 4715 } else { 4716 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4717 } 4718 return compareSignatures(s1, s2); 4719 } 4720 } 4721 4722 /** 4723 * This method should typically only be used when granting or revoking 4724 * permissions, since the app may immediately restart after this call. 4725 * <p> 4726 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 4727 * guard your work against the app being relaunched. 4728 */ 4729 private void killUid(int appId, int userId, String reason) { 4730 final long identity = Binder.clearCallingIdentity(); 4731 try { 4732 IActivityManager am = ActivityManager.getService(); 4733 if (am != null) { 4734 try { 4735 am.killUid(appId, userId, reason); 4736 } catch (RemoteException e) { 4737 /* ignore - same process */ 4738 } 4739 } 4740 } finally { 4741 Binder.restoreCallingIdentity(identity); 4742 } 4743 } 4744 4745 /** 4746 * Compares two sets of signatures. Returns: 4747 * <br /> 4748 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4749 * <br /> 4750 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4751 * <br /> 4752 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4753 * <br /> 4754 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4755 * <br /> 4756 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4757 */ 4758 static int compareSignatures(Signature[] s1, Signature[] s2) { 4759 if (s1 == null) { 4760 return s2 == null 4761 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4762 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4763 } 4764 4765 if (s2 == null) { 4766 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4767 } 4768 4769 if (s1.length != s2.length) { 4770 return PackageManager.SIGNATURE_NO_MATCH; 4771 } 4772 4773 // Since both signature sets are of size 1, we can compare without HashSets. 4774 if (s1.length == 1) { 4775 return s1[0].equals(s2[0]) ? 4776 PackageManager.SIGNATURE_MATCH : 4777 PackageManager.SIGNATURE_NO_MATCH; 4778 } 4779 4780 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4781 for (Signature sig : s1) { 4782 set1.add(sig); 4783 } 4784 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4785 for (Signature sig : s2) { 4786 set2.add(sig); 4787 } 4788 // Make sure s2 contains all signatures in s1. 4789 if (set1.equals(set2)) { 4790 return PackageManager.SIGNATURE_MATCH; 4791 } 4792 return PackageManager.SIGNATURE_NO_MATCH; 4793 } 4794 4795 /** 4796 * If the database version for this type of package (internal storage or 4797 * external storage) is less than the version where package signatures 4798 * were updated, return true. 4799 */ 4800 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4801 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4802 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4803 } 4804 4805 /** 4806 * Used for backward compatibility to make sure any packages with 4807 * certificate chains get upgraded to the new style. {@code existingSigs} 4808 * will be in the old format (since they were stored on disk from before the 4809 * system upgrade) and {@code scannedSigs} will be in the newer format. 4810 */ 4811 private int compareSignaturesCompat(PackageSignatures existingSigs, 4812 PackageParser.Package scannedPkg) { 4813 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4814 return PackageManager.SIGNATURE_NO_MATCH; 4815 } 4816 4817 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4818 for (Signature sig : existingSigs.mSignatures) { 4819 existingSet.add(sig); 4820 } 4821 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4822 for (Signature sig : scannedPkg.mSignatures) { 4823 try { 4824 Signature[] chainSignatures = sig.getChainSignatures(); 4825 for (Signature chainSig : chainSignatures) { 4826 scannedCompatSet.add(chainSig); 4827 } 4828 } catch (CertificateEncodingException e) { 4829 scannedCompatSet.add(sig); 4830 } 4831 } 4832 /* 4833 * Make sure the expanded scanned set contains all signatures in the 4834 * existing one. 4835 */ 4836 if (scannedCompatSet.equals(existingSet)) { 4837 // Migrate the old signatures to the new scheme. 4838 existingSigs.assignSignatures(scannedPkg.mSignatures); 4839 // The new KeySets will be re-added later in the scanning process. 4840 synchronized (mPackages) { 4841 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4842 } 4843 return PackageManager.SIGNATURE_MATCH; 4844 } 4845 return PackageManager.SIGNATURE_NO_MATCH; 4846 } 4847 4848 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4849 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4850 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4851 } 4852 4853 private int compareSignaturesRecover(PackageSignatures existingSigs, 4854 PackageParser.Package scannedPkg) { 4855 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4856 return PackageManager.SIGNATURE_NO_MATCH; 4857 } 4858 4859 String msg = null; 4860 try { 4861 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4862 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4863 + scannedPkg.packageName); 4864 return PackageManager.SIGNATURE_MATCH; 4865 } 4866 } catch (CertificateException e) { 4867 msg = e.getMessage(); 4868 } 4869 4870 logCriticalInfo(Log.INFO, 4871 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4872 return PackageManager.SIGNATURE_NO_MATCH; 4873 } 4874 4875 @Override 4876 public List<String> getAllPackages() { 4877 synchronized (mPackages) { 4878 return new ArrayList<String>(mPackages.keySet()); 4879 } 4880 } 4881 4882 @Override 4883 public String[] getPackagesForUid(int uid) { 4884 final int userId = UserHandle.getUserId(uid); 4885 uid = UserHandle.getAppId(uid); 4886 // reader 4887 synchronized (mPackages) { 4888 Object obj = mSettings.getUserIdLPr(uid); 4889 if (obj instanceof SharedUserSetting) { 4890 final SharedUserSetting sus = (SharedUserSetting) obj; 4891 final int N = sus.packages.size(); 4892 String[] res = new String[N]; 4893 final Iterator<PackageSetting> it = sus.packages.iterator(); 4894 int i = 0; 4895 while (it.hasNext()) { 4896 PackageSetting ps = it.next(); 4897 if (ps.getInstalled(userId)) { 4898 res[i++] = ps.name; 4899 } else { 4900 res = ArrayUtils.removeElement(String.class, res, res[i]); 4901 } 4902 } 4903 return res; 4904 } else if (obj instanceof PackageSetting) { 4905 final PackageSetting ps = (PackageSetting) obj; 4906 return new String[] { ps.name }; 4907 } 4908 } 4909 return null; 4910 } 4911 4912 @Override 4913 public String getNameForUid(int uid) { 4914 // reader 4915 synchronized (mPackages) { 4916 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4917 if (obj instanceof SharedUserSetting) { 4918 final SharedUserSetting sus = (SharedUserSetting) obj; 4919 return sus.name + ":" + sus.userId; 4920 } else if (obj instanceof PackageSetting) { 4921 final PackageSetting ps = (PackageSetting) obj; 4922 return ps.name; 4923 } 4924 } 4925 return null; 4926 } 4927 4928 @Override 4929 public int getUidForSharedUser(String sharedUserName) { 4930 if(sharedUserName == null) { 4931 return -1; 4932 } 4933 // reader 4934 synchronized (mPackages) { 4935 SharedUserSetting suid; 4936 try { 4937 suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4938 if (suid != null) { 4939 return suid.userId; 4940 } 4941 } catch (PackageManagerException ignore) { 4942 // can't happen, but, still need to catch it 4943 } 4944 return -1; 4945 } 4946 } 4947 4948 @Override 4949 public int getFlagsForUid(int uid) { 4950 synchronized (mPackages) { 4951 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4952 if (obj instanceof SharedUserSetting) { 4953 final SharedUserSetting sus = (SharedUserSetting) obj; 4954 return sus.pkgFlags; 4955 } else if (obj instanceof PackageSetting) { 4956 final PackageSetting ps = (PackageSetting) obj; 4957 return ps.pkgFlags; 4958 } 4959 } 4960 return 0; 4961 } 4962 4963 @Override 4964 public int getPrivateFlagsForUid(int uid) { 4965 synchronized (mPackages) { 4966 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4967 if (obj instanceof SharedUserSetting) { 4968 final SharedUserSetting sus = (SharedUserSetting) obj; 4969 return sus.pkgPrivateFlags; 4970 } else if (obj instanceof PackageSetting) { 4971 final PackageSetting ps = (PackageSetting) obj; 4972 return ps.pkgPrivateFlags; 4973 } 4974 } 4975 return 0; 4976 } 4977 4978 @Override 4979 public boolean isUidPrivileged(int uid) { 4980 uid = UserHandle.getAppId(uid); 4981 // reader 4982 synchronized (mPackages) { 4983 Object obj = mSettings.getUserIdLPr(uid); 4984 if (obj instanceof SharedUserSetting) { 4985 final SharedUserSetting sus = (SharedUserSetting) obj; 4986 final Iterator<PackageSetting> it = sus.packages.iterator(); 4987 while (it.hasNext()) { 4988 if (it.next().isPrivileged()) { 4989 return true; 4990 } 4991 } 4992 } else if (obj instanceof PackageSetting) { 4993 final PackageSetting ps = (PackageSetting) obj; 4994 return ps.isPrivileged(); 4995 } 4996 } 4997 return false; 4998 } 4999 5000 @Override 5001 public String[] getAppOpPermissionPackages(String permissionName) { 5002 synchronized (mPackages) { 5003 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 5004 if (pkgs == null) { 5005 return null; 5006 } 5007 return pkgs.toArray(new String[pkgs.size()]); 5008 } 5009 } 5010 5011 @Override 5012 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 5013 int flags, int userId) { 5014 try { 5015 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 5016 5017 if (!sUserManager.exists(userId)) return null; 5018 flags = updateFlagsForResolve(flags, userId, intent); 5019 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5020 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 5021 5022 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5023 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 5024 flags, userId); 5025 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5026 5027 final ResolveInfo bestChoice = 5028 chooseBestActivity(intent, resolvedType, flags, query, userId); 5029 return bestChoice; 5030 } finally { 5031 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5032 } 5033 } 5034 5035 @Override 5036 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 5037 IntentFilter filter, int match, ComponentName activity) { 5038 final int userId = UserHandle.getCallingUserId(); 5039 if (DEBUG_PREFERRED) { 5040 Log.v(TAG, "setLastChosenActivity intent=" + intent 5041 + " resolvedType=" + resolvedType 5042 + " flags=" + flags 5043 + " filter=" + filter 5044 + " match=" + match 5045 + " activity=" + activity); 5046 filter.dump(new PrintStreamPrinter(System.out), " "); 5047 } 5048 intent.setComponent(null); 5049 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5050 userId); 5051 // Find any earlier preferred or last chosen entries and nuke them 5052 findPreferredActivity(intent, resolvedType, 5053 flags, query, 0, false, true, false, userId); 5054 // Add the new activity as the last chosen for this filter 5055 addPreferredActivityInternal(filter, match, null, activity, false, userId, 5056 "Setting last chosen"); 5057 } 5058 5059 @Override 5060 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 5061 final int userId = UserHandle.getCallingUserId(); 5062 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 5063 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5064 userId); 5065 return findPreferredActivity(intent, resolvedType, flags, query, 0, 5066 false, false, false, userId); 5067 } 5068 5069 private boolean isEphemeralDisabled() { 5070 // ephemeral apps have been disabled across the board 5071 if (DISABLE_EPHEMERAL_APPS) { 5072 return true; 5073 } 5074 // system isn't up yet; can't read settings, so, assume no ephemeral apps 5075 if (!mSystemReady) { 5076 return true; 5077 } 5078 // we can't get a content resolver until the system is ready; these checks must happen last 5079 final ContentResolver resolver = mContext.getContentResolver(); 5080 if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) { 5081 return true; 5082 } 5083 return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0; 5084 } 5085 5086 private boolean isEphemeralAllowed( 5087 Intent intent, List<ResolveInfo> resolvedActivities, int userId, 5088 boolean skipPackageCheck) { 5089 // Short circuit and return early if possible. 5090 if (isEphemeralDisabled()) { 5091 return false; 5092 } 5093 final int callingUser = UserHandle.getCallingUserId(); 5094 if (callingUser != UserHandle.USER_SYSTEM) { 5095 return false; 5096 } 5097 if (mEphemeralResolverConnection == null) { 5098 return false; 5099 } 5100 if (mEphemeralInstallerComponent == null) { 5101 return false; 5102 } 5103 if (intent.getComponent() != null) { 5104 return false; 5105 } 5106 if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) { 5107 return false; 5108 } 5109 if (!skipPackageCheck && intent.getPackage() != null) { 5110 return false; 5111 } 5112 final boolean isWebUri = hasWebURI(intent); 5113 if (!isWebUri || intent.getData().getHost() == null) { 5114 return false; 5115 } 5116 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 5117 synchronized (mPackages) { 5118 final int count = (resolvedActivities == null ? 0 : resolvedActivities.size()); 5119 for (int n = 0; n < count; n++) { 5120 ResolveInfo info = resolvedActivities.get(n); 5121 String packageName = info.activityInfo.packageName; 5122 PackageSetting ps = mSettings.mPackages.get(packageName); 5123 if (ps != null) { 5124 // Try to get the status from User settings first 5125 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5126 int status = (int) (packedStatus >> 32); 5127 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 5128 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5129 if (DEBUG_EPHEMERAL) { 5130 Slog.v(TAG, "DENY ephemeral apps;" 5131 + " pkg: " + packageName + ", status: " + status); 5132 } 5133 return false; 5134 } 5135 } 5136 } 5137 } 5138 // We've exhausted all ways to deny ephemeral application; let the system look for them. 5139 return true; 5140 } 5141 5142 private void requestEphemeralResolutionPhaseTwo(EphemeralResponse responseObj, 5143 Intent origIntent, String resolvedType, Intent launchIntent, String callingPackage, 5144 int userId) { 5145 final Message msg = mHandler.obtainMessage(EPHEMERAL_RESOLUTION_PHASE_TWO, 5146 new EphemeralRequest(responseObj, origIntent, resolvedType, launchIntent, 5147 callingPackage, userId)); 5148 mHandler.sendMessage(msg); 5149 } 5150 5151 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 5152 int flags, List<ResolveInfo> query, int userId) { 5153 if (query != null) { 5154 final int N = query.size(); 5155 if (N == 1) { 5156 return query.get(0); 5157 } else if (N > 1) { 5158 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 5159 // If there is more than one activity with the same priority, 5160 // then let the user decide between them. 5161 ResolveInfo r0 = query.get(0); 5162 ResolveInfo r1 = query.get(1); 5163 if (DEBUG_INTENT_MATCHING || debug) { 5164 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 5165 + r1.activityInfo.name + "=" + r1.priority); 5166 } 5167 // If the first activity has a higher priority, or a different 5168 // default, then it is always desirable to pick it. 5169 if (r0.priority != r1.priority 5170 || r0.preferredOrder != r1.preferredOrder 5171 || r0.isDefault != r1.isDefault) { 5172 return query.get(0); 5173 } 5174 // If we have saved a preference for a preferred activity for 5175 // this Intent, use that. 5176 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 5177 flags, query, r0.priority, true, false, debug, userId); 5178 if (ri != null) { 5179 return ri; 5180 } 5181 ri = new ResolveInfo(mResolveInfo); 5182 ri.activityInfo = new ActivityInfo(ri.activityInfo); 5183 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 5184 // If all of the options come from the same package, show the application's 5185 // label and icon instead of the generic resolver's. 5186 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 5187 // and then throw away the ResolveInfo itself, meaning that the caller loses 5188 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 5189 // a fallback for this case; we only set the target package's resources on 5190 // the ResolveInfo, not the ActivityInfo. 5191 final String intentPackage = intent.getPackage(); 5192 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 5193 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 5194 ri.resolvePackageName = intentPackage; 5195 if (userNeedsBadging(userId)) { 5196 ri.noResourceId = true; 5197 } else { 5198 ri.icon = appi.icon; 5199 } 5200 ri.iconResourceId = appi.icon; 5201 ri.labelRes = appi.labelRes; 5202 } 5203 ri.activityInfo.applicationInfo = new ApplicationInfo( 5204 ri.activityInfo.applicationInfo); 5205 if (userId != 0) { 5206 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 5207 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 5208 } 5209 // Make sure that the resolver is displayable in car mode 5210 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 5211 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 5212 return ri; 5213 } 5214 } 5215 return null; 5216 } 5217 5218 /** 5219 * Return true if the given list is not empty and all of its contents have 5220 * an activityInfo with the given package name. 5221 */ 5222 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 5223 if (ArrayUtils.isEmpty(list)) { 5224 return false; 5225 } 5226 for (int i = 0, N = list.size(); i < N; i++) { 5227 final ResolveInfo ri = list.get(i); 5228 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 5229 if (ai == null || !packageName.equals(ai.packageName)) { 5230 return false; 5231 } 5232 } 5233 return true; 5234 } 5235 5236 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 5237 int flags, List<ResolveInfo> query, boolean debug, int userId) { 5238 final int N = query.size(); 5239 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 5240 .get(userId); 5241 // Get the list of persistent preferred activities that handle the intent 5242 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 5243 List<PersistentPreferredActivity> pprefs = ppir != null 5244 ? ppir.queryIntent(intent, resolvedType, 5245 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 5246 (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0, 5247 (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId) 5248 : null; 5249 if (pprefs != null && pprefs.size() > 0) { 5250 final int M = pprefs.size(); 5251 for (int i=0; i<M; i++) { 5252 final PersistentPreferredActivity ppa = pprefs.get(i); 5253 if (DEBUG_PREFERRED || debug) { 5254 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 5255 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 5256 + "\n component=" + ppa.mComponent); 5257 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5258 } 5259 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 5260 flags | MATCH_DISABLED_COMPONENTS, userId); 5261 if (DEBUG_PREFERRED || debug) { 5262 Slog.v(TAG, "Found persistent preferred activity:"); 5263 if (ai != null) { 5264 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5265 } else { 5266 Slog.v(TAG, " null"); 5267 } 5268 } 5269 if (ai == null) { 5270 // This previously registered persistent preferred activity 5271 // component is no longer known. Ignore it and do NOT remove it. 5272 continue; 5273 } 5274 for (int j=0; j<N; j++) { 5275 final ResolveInfo ri = query.get(j); 5276 if (!ri.activityInfo.applicationInfo.packageName 5277 .equals(ai.applicationInfo.packageName)) { 5278 continue; 5279 } 5280 if (!ri.activityInfo.name.equals(ai.name)) { 5281 continue; 5282 } 5283 // Found a persistent preference that can handle the intent. 5284 if (DEBUG_PREFERRED || debug) { 5285 Slog.v(TAG, "Returning persistent preferred activity: " + 5286 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5287 } 5288 return ri; 5289 } 5290 } 5291 } 5292 return null; 5293 } 5294 5295 // TODO: handle preferred activities missing while user has amnesia 5296 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5297 List<ResolveInfo> query, int priority, boolean always, 5298 boolean removeMatches, boolean debug, int userId) { 5299 if (!sUserManager.exists(userId)) return null; 5300 flags = updateFlagsForResolve(flags, userId, intent); 5301 // writer 5302 synchronized (mPackages) { 5303 if (intent.getSelector() != null) { 5304 intent = intent.getSelector(); 5305 } 5306 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 5307 5308 // Try to find a matching persistent preferred activity. 5309 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5310 debug, userId); 5311 5312 // If a persistent preferred activity matched, use it. 5313 if (pri != null) { 5314 return pri; 5315 } 5316 5317 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5318 // Get the list of preferred activities that handle the intent 5319 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5320 List<PreferredActivity> prefs = pir != null 5321 ? pir.queryIntent(intent, resolvedType, 5322 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 5323 (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0, 5324 (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId) 5325 : null; 5326 if (prefs != null && prefs.size() > 0) { 5327 boolean changed = false; 5328 try { 5329 // First figure out how good the original match set is. 5330 // We will only allow preferred activities that came 5331 // from the same match quality. 5332 int match = 0; 5333 5334 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5335 5336 final int N = query.size(); 5337 for (int j=0; j<N; j++) { 5338 final ResolveInfo ri = query.get(j); 5339 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5340 + ": 0x" + Integer.toHexString(match)); 5341 if (ri.match > match) { 5342 match = ri.match; 5343 } 5344 } 5345 5346 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5347 + Integer.toHexString(match)); 5348 5349 match &= IntentFilter.MATCH_CATEGORY_MASK; 5350 final int M = prefs.size(); 5351 for (int i=0; i<M; i++) { 5352 final PreferredActivity pa = prefs.get(i); 5353 if (DEBUG_PREFERRED || debug) { 5354 Slog.v(TAG, "Checking PreferredActivity ds=" 5355 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5356 + "\n component=" + pa.mPref.mComponent); 5357 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5358 } 5359 if (pa.mPref.mMatch != match) { 5360 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5361 + Integer.toHexString(pa.mPref.mMatch)); 5362 continue; 5363 } 5364 // If it's not an "always" type preferred activity and that's what we're 5365 // looking for, skip it. 5366 if (always && !pa.mPref.mAlways) { 5367 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5368 continue; 5369 } 5370 final ActivityInfo ai = getActivityInfo( 5371 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5372 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5373 userId); 5374 if (DEBUG_PREFERRED || debug) { 5375 Slog.v(TAG, "Found preferred activity:"); 5376 if (ai != null) { 5377 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5378 } else { 5379 Slog.v(TAG, " null"); 5380 } 5381 } 5382 if (ai == null) { 5383 // This previously registered preferred activity 5384 // component is no longer known. Most likely an update 5385 // to the app was installed and in the new version this 5386 // component no longer exists. Clean it up by removing 5387 // it from the preferred activities list, and skip it. 5388 Slog.w(TAG, "Removing dangling preferred activity: " 5389 + pa.mPref.mComponent); 5390 pir.removeFilter(pa); 5391 changed = true; 5392 continue; 5393 } 5394 for (int j=0; j<N; j++) { 5395 final ResolveInfo ri = query.get(j); 5396 if (!ri.activityInfo.applicationInfo.packageName 5397 .equals(ai.applicationInfo.packageName)) { 5398 continue; 5399 } 5400 if (!ri.activityInfo.name.equals(ai.name)) { 5401 continue; 5402 } 5403 5404 if (removeMatches) { 5405 pir.removeFilter(pa); 5406 changed = true; 5407 if (DEBUG_PREFERRED) { 5408 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 5409 } 5410 break; 5411 } 5412 5413 // Okay we found a previously set preferred or last chosen app. 5414 // If the result set is different from when this 5415 // was created, we need to clear it and re-ask the 5416 // user their preference, if we're looking for an "always" type entry. 5417 if (always && !pa.mPref.sameSet(query)) { 5418 Slog.i(TAG, "Result set changed, dropping preferred activity for " 5419 + intent + " type " + resolvedType); 5420 if (DEBUG_PREFERRED) { 5421 Slog.v(TAG, "Removing preferred activity since set changed " 5422 + pa.mPref.mComponent); 5423 } 5424 pir.removeFilter(pa); 5425 // Re-add the filter as a "last chosen" entry (!always) 5426 PreferredActivity lastChosen = new PreferredActivity( 5427 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 5428 pir.addFilter(lastChosen); 5429 changed = true; 5430 return null; 5431 } 5432 5433 // Yay! Either the set matched or we're looking for the last chosen 5434 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 5435 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5436 return ri; 5437 } 5438 } 5439 } finally { 5440 if (changed) { 5441 if (DEBUG_PREFERRED) { 5442 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 5443 } 5444 scheduleWritePackageRestrictionsLocked(userId); 5445 } 5446 } 5447 } 5448 } 5449 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 5450 return null; 5451 } 5452 5453 /* 5454 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 5455 */ 5456 @Override 5457 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 5458 int targetUserId) { 5459 mContext.enforceCallingOrSelfPermission( 5460 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 5461 List<CrossProfileIntentFilter> matches = 5462 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 5463 if (matches != null) { 5464 int size = matches.size(); 5465 for (int i = 0; i < size; i++) { 5466 if (matches.get(i).getTargetUserId() == targetUserId) return true; 5467 } 5468 } 5469 if (hasWebURI(intent)) { 5470 // cross-profile app linking works only towards the parent. 5471 final UserInfo parent = getProfileParent(sourceUserId); 5472 synchronized(mPackages) { 5473 int flags = updateFlagsForResolve(0, parent.id, intent); 5474 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5475 intent, resolvedType, flags, sourceUserId, parent.id); 5476 return xpDomainInfo != null; 5477 } 5478 } 5479 return false; 5480 } 5481 5482 private UserInfo getProfileParent(int userId) { 5483 final long identity = Binder.clearCallingIdentity(); 5484 try { 5485 return sUserManager.getProfileParent(userId); 5486 } finally { 5487 Binder.restoreCallingIdentity(identity); 5488 } 5489 } 5490 5491 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5492 String resolvedType, int userId) { 5493 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5494 if (resolver != null) { 5495 return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, 5496 false /*visibleToEphemeral*/, false /*isEphemeral*/, userId); 5497 } 5498 return null; 5499 } 5500 5501 @Override 5502 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 5503 String resolvedType, int flags, int userId) { 5504 try { 5505 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5506 5507 return new ParceledListSlice<>( 5508 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 5509 } finally { 5510 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5511 } 5512 } 5513 5514 /** 5515 * Returns the package name of the calling Uid if it's an ephemeral app. If it isn't 5516 * ephemeral, returns {@code null}. 5517 */ 5518 private String getEphemeralPackageName(int callingUid) { 5519 final int appId = UserHandle.getAppId(callingUid); 5520 synchronized (mPackages) { 5521 final Object obj = mSettings.getUserIdLPr(appId); 5522 if (obj instanceof PackageSetting) { 5523 final PackageSetting ps = (PackageSetting) obj; 5524 return ps.pkg.applicationInfo.isEphemeralApp() ? ps.pkg.packageName : null; 5525 } 5526 } 5527 return null; 5528 } 5529 5530 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 5531 String resolvedType, int flags, int userId) { 5532 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5533 final String ephemeralPkgName = getEphemeralPackageName(Binder.getCallingUid()); 5534 flags = updateFlagsForResolve(flags, userId, intent); 5535 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5536 false /* requireFullPermission */, false /* checkShell */, 5537 "query intent activities"); 5538 ComponentName comp = intent.getComponent(); 5539 if (comp == null) { 5540 if (intent.getSelector() != null) { 5541 intent = intent.getSelector(); 5542 comp = intent.getComponent(); 5543 } 5544 } 5545 5546 if (comp != null) { 5547 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5548 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5549 if (ai != null) { 5550 // When specifying an explicit component, we prevent the activity from being 5551 // used when either 1) the calling package is normal and the activity is within 5552 // an ephemeral application or 2) the calling package is ephemeral and the 5553 // activity is not visible to ephemeral applications. 5554 boolean blockResolution = 5555 (ephemeralPkgName == null 5556 && (ai.applicationInfo.privateFlags 5557 & ApplicationInfo.PRIVATE_FLAG_EPHEMERAL) != 0) 5558 || (ephemeralPkgName != null 5559 && (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0); 5560 if (!blockResolution) { 5561 final ResolveInfo ri = new ResolveInfo(); 5562 ri.activityInfo = ai; 5563 list.add(ri); 5564 } 5565 } 5566 return list; 5567 } 5568 5569 // reader 5570 boolean sortResult = false; 5571 boolean addEphemeral = false; 5572 List<ResolveInfo> result; 5573 final String pkgName = intent.getPackage(); 5574 synchronized (mPackages) { 5575 if (pkgName == null) { 5576 List<CrossProfileIntentFilter> matchingFilters = 5577 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5578 // Check for results that need to skip the current profile. 5579 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5580 resolvedType, flags, userId); 5581 if (xpResolveInfo != null) { 5582 List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1); 5583 xpResult.add(xpResolveInfo); 5584 return filterForEphemeral( 5585 filterIfNotSystemUser(xpResult, userId), ephemeralPkgName); 5586 } 5587 5588 // Check for results in the current profile. 5589 result = filterIfNotSystemUser(mActivities.queryIntent( 5590 intent, resolvedType, flags, userId), userId); 5591 addEphemeral = 5592 isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/); 5593 5594 // Check for cross profile results. 5595 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5596 xpResolveInfo = queryCrossProfileIntents( 5597 matchingFilters, intent, resolvedType, flags, userId, 5598 hasNonNegativePriorityResult); 5599 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5600 boolean isVisibleToUser = filterIfNotSystemUser( 5601 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5602 if (isVisibleToUser) { 5603 result.add(xpResolveInfo); 5604 sortResult = true; 5605 } 5606 } 5607 if (hasWebURI(intent)) { 5608 CrossProfileDomainInfo xpDomainInfo = null; 5609 final UserInfo parent = getProfileParent(userId); 5610 if (parent != null) { 5611 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5612 flags, userId, parent.id); 5613 } 5614 if (xpDomainInfo != null) { 5615 if (xpResolveInfo != null) { 5616 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5617 // in the result. 5618 result.remove(xpResolveInfo); 5619 } 5620 if (result.size() == 0 && !addEphemeral) { 5621 // No result in current profile, but found candidate in parent user. 5622 // And we are not going to add emphemeral app, so we can return the 5623 // result straight away. 5624 result.add(xpDomainInfo.resolveInfo); 5625 return filterForEphemeral(result, ephemeralPkgName); 5626 } 5627 } else if (result.size() <= 1 && !addEphemeral) { 5628 // No result in parent user and <= 1 result in current profile, and we 5629 // are not going to add emphemeral app, so we can return the result without 5630 // further processing. 5631 return filterForEphemeral(result, ephemeralPkgName); 5632 } 5633 // We have more than one candidate (combining results from current and parent 5634 // profile), so we need filtering and sorting. 5635 result = filterCandidatesWithDomainPreferredActivitiesLPr( 5636 intent, flags, result, xpDomainInfo, userId); 5637 sortResult = true; 5638 } 5639 } else { 5640 final PackageParser.Package pkg = mPackages.get(pkgName); 5641 if (pkg != null) { 5642 result = filterForEphemeral(filterIfNotSystemUser( 5643 mActivities.queryIntentForPackage( 5644 intent, resolvedType, flags, pkg.activities, userId), 5645 userId), ephemeralPkgName); 5646 } else { 5647 // the caller wants to resolve for a particular package; however, there 5648 // were no installed results, so, try to find an ephemeral result 5649 addEphemeral = isEphemeralAllowed( 5650 intent, null /*result*/, userId, true /*skipPackageCheck*/); 5651 result = new ArrayList<ResolveInfo>(); 5652 } 5653 } 5654 } 5655 if (addEphemeral) { 5656 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 5657 final EphemeralRequest requestObject = new EphemeralRequest( 5658 null /*responseObj*/, intent /*origIntent*/, resolvedType, 5659 null /*launchIntent*/, null /*callingPackage*/, userId); 5660 final EphemeralResponse intentInfo = EphemeralResolver.doEphemeralResolutionPhaseOne( 5661 mContext, mEphemeralResolverConnection, requestObject); 5662 if (intentInfo != null) { 5663 if (DEBUG_EPHEMERAL) { 5664 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 5665 } 5666 final ResolveInfo ephemeralInstaller = new ResolveInfo(mEphemeralInstallerInfo); 5667 ephemeralInstaller.ephemeralResponse = intentInfo; 5668 // make sure this resolver is the default 5669 ephemeralInstaller.isDefault = true; 5670 ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 5671 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 5672 // add a non-generic filter 5673 ephemeralInstaller.filter = new IntentFilter(intent.getAction()); 5674 ephemeralInstaller.filter.addDataPath( 5675 intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL); 5676 result.add(ephemeralInstaller); 5677 } 5678 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5679 } 5680 if (sortResult) { 5681 Collections.sort(result, mResolvePrioritySorter); 5682 } 5683 return filterForEphemeral(result, ephemeralPkgName); 5684 } 5685 5686 private static class CrossProfileDomainInfo { 5687 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5688 ResolveInfo resolveInfo; 5689 /* Best domain verification status of the activities found in the other profile */ 5690 int bestDomainVerificationStatus; 5691 } 5692 5693 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5694 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5695 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5696 sourceUserId)) { 5697 return null; 5698 } 5699 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5700 resolvedType, flags, parentUserId); 5701 5702 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5703 return null; 5704 } 5705 CrossProfileDomainInfo result = null; 5706 int size = resultTargetUser.size(); 5707 for (int i = 0; i < size; i++) { 5708 ResolveInfo riTargetUser = resultTargetUser.get(i); 5709 // Intent filter verification is only for filters that specify a host. So don't return 5710 // those that handle all web uris. 5711 if (riTargetUser.handleAllWebDataURI) { 5712 continue; 5713 } 5714 String packageName = riTargetUser.activityInfo.packageName; 5715 PackageSetting ps = mSettings.mPackages.get(packageName); 5716 if (ps == null) { 5717 continue; 5718 } 5719 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5720 int status = (int)(verificationState >> 32); 5721 if (result == null) { 5722 result = new CrossProfileDomainInfo(); 5723 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5724 sourceUserId, parentUserId); 5725 result.bestDomainVerificationStatus = status; 5726 } else { 5727 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5728 result.bestDomainVerificationStatus); 5729 } 5730 } 5731 // Don't consider matches with status NEVER across profiles. 5732 if (result != null && result.bestDomainVerificationStatus 5733 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5734 return null; 5735 } 5736 return result; 5737 } 5738 5739 /** 5740 * Verification statuses are ordered from the worse to the best, except for 5741 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5742 */ 5743 private int bestDomainVerificationStatus(int status1, int status2) { 5744 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5745 return status2; 5746 } 5747 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5748 return status1; 5749 } 5750 return (int) MathUtils.max(status1, status2); 5751 } 5752 5753 private boolean isUserEnabled(int userId) { 5754 long callingId = Binder.clearCallingIdentity(); 5755 try { 5756 UserInfo userInfo = sUserManager.getUserInfo(userId); 5757 return userInfo != null && userInfo.isEnabled(); 5758 } finally { 5759 Binder.restoreCallingIdentity(callingId); 5760 } 5761 } 5762 5763 /** 5764 * Filter out activities with systemUserOnly flag set, when current user is not System. 5765 * 5766 * @return filtered list 5767 */ 5768 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5769 if (userId == UserHandle.USER_SYSTEM) { 5770 return resolveInfos; 5771 } 5772 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5773 ResolveInfo info = resolveInfos.get(i); 5774 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5775 resolveInfos.remove(i); 5776 } 5777 } 5778 return resolveInfos; 5779 } 5780 5781 /** 5782 * Filters out ephemeral activities. 5783 * <p>When resolving for an ephemeral app, only activities that 1) are defined in the 5784 * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned. 5785 * 5786 * @param resolveInfos The pre-filtered list of resolved activities 5787 * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering 5788 * is performed. 5789 * @return A filtered list of resolved activities. 5790 */ 5791 private List<ResolveInfo> filterForEphemeral(List<ResolveInfo> resolveInfos, 5792 String ephemeralPkgName) { 5793 if (ephemeralPkgName == null) { 5794 return resolveInfos; 5795 } 5796 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5797 ResolveInfo info = resolveInfos.get(i); 5798 final boolean isEphemeralApp = info.activityInfo.applicationInfo.isEphemeralApp(); 5799 // allow activities that are defined in the provided package 5800 if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) { 5801 continue; 5802 } 5803 // allow activities that have been explicitly exposed to ephemeral apps 5804 if (!isEphemeralApp 5805 && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) { 5806 continue; 5807 } 5808 resolveInfos.remove(i); 5809 } 5810 return resolveInfos; 5811 } 5812 5813 /** 5814 * @param resolveInfos list of resolve infos in descending priority order 5815 * @return if the list contains a resolve info with non-negative priority 5816 */ 5817 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5818 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5819 } 5820 5821 private static boolean hasWebURI(Intent intent) { 5822 if (intent.getData() == null) { 5823 return false; 5824 } 5825 final String scheme = intent.getScheme(); 5826 if (TextUtils.isEmpty(scheme)) { 5827 return false; 5828 } 5829 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5830 } 5831 5832 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5833 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5834 int userId) { 5835 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5836 5837 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5838 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5839 candidates.size()); 5840 } 5841 5842 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5843 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5844 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5845 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5846 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5847 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5848 5849 synchronized (mPackages) { 5850 final int count = candidates.size(); 5851 // First, try to use linked apps. Partition the candidates into four lists: 5852 // one for the final results, one for the "do not use ever", one for "undefined status" 5853 // and finally one for "browser app type". 5854 for (int n=0; n<count; n++) { 5855 ResolveInfo info = candidates.get(n); 5856 String packageName = info.activityInfo.packageName; 5857 PackageSetting ps = mSettings.mPackages.get(packageName); 5858 if (ps != null) { 5859 // Add to the special match all list (Browser use case) 5860 if (info.handleAllWebDataURI) { 5861 matchAllList.add(info); 5862 continue; 5863 } 5864 // Try to get the status from User settings first 5865 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5866 int status = (int)(packedStatus >> 32); 5867 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5868 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5869 if (DEBUG_DOMAIN_VERIFICATION) { 5870 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5871 + " : linkgen=" + linkGeneration); 5872 } 5873 // Use link-enabled generation as preferredOrder, i.e. 5874 // prefer newly-enabled over earlier-enabled. 5875 info.preferredOrder = linkGeneration; 5876 alwaysList.add(info); 5877 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5878 if (DEBUG_DOMAIN_VERIFICATION) { 5879 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5880 } 5881 neverList.add(info); 5882 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5883 if (DEBUG_DOMAIN_VERIFICATION) { 5884 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5885 } 5886 alwaysAskList.add(info); 5887 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5888 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5889 if (DEBUG_DOMAIN_VERIFICATION) { 5890 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5891 } 5892 undefinedList.add(info); 5893 } 5894 } 5895 } 5896 5897 // We'll want to include browser possibilities in a few cases 5898 boolean includeBrowser = false; 5899 5900 // First try to add the "always" resolution(s) for the current user, if any 5901 if (alwaysList.size() > 0) { 5902 result.addAll(alwaysList); 5903 } else { 5904 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5905 result.addAll(undefinedList); 5906 // Maybe add one for the other profile. 5907 if (xpDomainInfo != null && ( 5908 xpDomainInfo.bestDomainVerificationStatus 5909 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5910 result.add(xpDomainInfo.resolveInfo); 5911 } 5912 includeBrowser = true; 5913 } 5914 5915 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5916 // If there were 'always' entries their preferred order has been set, so we also 5917 // back that off to make the alternatives equivalent 5918 if (alwaysAskList.size() > 0) { 5919 for (ResolveInfo i : result) { 5920 i.preferredOrder = 0; 5921 } 5922 result.addAll(alwaysAskList); 5923 includeBrowser = true; 5924 } 5925 5926 if (includeBrowser) { 5927 // Also add browsers (all of them or only the default one) 5928 if (DEBUG_DOMAIN_VERIFICATION) { 5929 Slog.v(TAG, " ...including browsers in candidate set"); 5930 } 5931 if ((matchFlags & MATCH_ALL) != 0) { 5932 result.addAll(matchAllList); 5933 } else { 5934 // Browser/generic handling case. If there's a default browser, go straight 5935 // to that (but only if there is no other higher-priority match). 5936 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5937 int maxMatchPrio = 0; 5938 ResolveInfo defaultBrowserMatch = null; 5939 final int numCandidates = matchAllList.size(); 5940 for (int n = 0; n < numCandidates; n++) { 5941 ResolveInfo info = matchAllList.get(n); 5942 // track the highest overall match priority... 5943 if (info.priority > maxMatchPrio) { 5944 maxMatchPrio = info.priority; 5945 } 5946 // ...and the highest-priority default browser match 5947 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5948 if (defaultBrowserMatch == null 5949 || (defaultBrowserMatch.priority < info.priority)) { 5950 if (debug) { 5951 Slog.v(TAG, "Considering default browser match " + info); 5952 } 5953 defaultBrowserMatch = info; 5954 } 5955 } 5956 } 5957 if (defaultBrowserMatch != null 5958 && defaultBrowserMatch.priority >= maxMatchPrio 5959 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5960 { 5961 if (debug) { 5962 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5963 } 5964 result.add(defaultBrowserMatch); 5965 } else { 5966 result.addAll(matchAllList); 5967 } 5968 } 5969 5970 // If there is nothing selected, add all candidates and remove the ones that the user 5971 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5972 if (result.size() == 0) { 5973 result.addAll(candidates); 5974 result.removeAll(neverList); 5975 } 5976 } 5977 } 5978 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5979 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5980 result.size()); 5981 for (ResolveInfo info : result) { 5982 Slog.v(TAG, " + " + info.activityInfo); 5983 } 5984 } 5985 return result; 5986 } 5987 5988 // Returns a packed value as a long: 5989 // 5990 // high 'int'-sized word: link status: undefined/ask/never/always. 5991 // low 'int'-sized word: relative priority among 'always' results. 5992 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5993 long result = ps.getDomainVerificationStatusForUser(userId); 5994 // if none available, get the master status 5995 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5996 if (ps.getIntentFilterVerificationInfo() != null) { 5997 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5998 } 5999 } 6000 return result; 6001 } 6002 6003 private ResolveInfo querySkipCurrentProfileIntents( 6004 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 6005 int flags, int sourceUserId) { 6006 if (matchingFilters != null) { 6007 int size = matchingFilters.size(); 6008 for (int i = 0; i < size; i ++) { 6009 CrossProfileIntentFilter filter = matchingFilters.get(i); 6010 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 6011 // Checking if there are activities in the target user that can handle the 6012 // intent. 6013 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 6014 resolvedType, flags, sourceUserId); 6015 if (resolveInfo != null) { 6016 return resolveInfo; 6017 } 6018 } 6019 } 6020 } 6021 return null; 6022 } 6023 6024 // Return matching ResolveInfo in target user if any. 6025 private ResolveInfo queryCrossProfileIntents( 6026 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 6027 int flags, int sourceUserId, boolean matchInCurrentProfile) { 6028 if (matchingFilters != null) { 6029 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 6030 // match the same intent. For performance reasons, it is better not to 6031 // run queryIntent twice for the same userId 6032 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 6033 int size = matchingFilters.size(); 6034 for (int i = 0; i < size; i++) { 6035 CrossProfileIntentFilter filter = matchingFilters.get(i); 6036 int targetUserId = filter.getTargetUserId(); 6037 boolean skipCurrentProfile = 6038 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 6039 boolean skipCurrentProfileIfNoMatchFound = 6040 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 6041 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 6042 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 6043 // Checking if there are activities in the target user that can handle the 6044 // intent. 6045 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 6046 resolvedType, flags, sourceUserId); 6047 if (resolveInfo != null) return resolveInfo; 6048 alreadyTriedUserIds.put(targetUserId, true); 6049 } 6050 } 6051 } 6052 return null; 6053 } 6054 6055 /** 6056 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 6057 * will forward the intent to the filter's target user. 6058 * Otherwise, returns null. 6059 */ 6060 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 6061 String resolvedType, int flags, int sourceUserId) { 6062 int targetUserId = filter.getTargetUserId(); 6063 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 6064 resolvedType, flags, targetUserId); 6065 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 6066 // If all the matches in the target profile are suspended, return null. 6067 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 6068 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 6069 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 6070 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 6071 targetUserId); 6072 } 6073 } 6074 } 6075 return null; 6076 } 6077 6078 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 6079 int sourceUserId, int targetUserId) { 6080 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 6081 long ident = Binder.clearCallingIdentity(); 6082 boolean targetIsProfile; 6083 try { 6084 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 6085 } finally { 6086 Binder.restoreCallingIdentity(ident); 6087 } 6088 String className; 6089 if (targetIsProfile) { 6090 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 6091 } else { 6092 className = FORWARD_INTENT_TO_PARENT; 6093 } 6094 ComponentName forwardingActivityComponentName = new ComponentName( 6095 mAndroidApplication.packageName, className); 6096 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 6097 sourceUserId); 6098 if (!targetIsProfile) { 6099 forwardingActivityInfo.showUserIcon = targetUserId; 6100 forwardingResolveInfo.noResourceId = true; 6101 } 6102 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 6103 forwardingResolveInfo.priority = 0; 6104 forwardingResolveInfo.preferredOrder = 0; 6105 forwardingResolveInfo.match = 0; 6106 forwardingResolveInfo.isDefault = true; 6107 forwardingResolveInfo.filter = filter; 6108 forwardingResolveInfo.targetUserId = targetUserId; 6109 return forwardingResolveInfo; 6110 } 6111 6112 @Override 6113 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 6114 Intent[] specifics, String[] specificTypes, Intent intent, 6115 String resolvedType, int flags, int userId) { 6116 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 6117 specificTypes, intent, resolvedType, flags, userId)); 6118 } 6119 6120 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 6121 Intent[] specifics, String[] specificTypes, Intent intent, 6122 String resolvedType, int flags, int userId) { 6123 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6124 flags = updateFlagsForResolve(flags, userId, intent); 6125 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6126 false /* requireFullPermission */, false /* checkShell */, 6127 "query intent activity options"); 6128 final String resultsAction = intent.getAction(); 6129 6130 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 6131 | PackageManager.GET_RESOLVED_FILTER, userId); 6132 6133 if (DEBUG_INTENT_MATCHING) { 6134 Log.v(TAG, "Query " + intent + ": " + results); 6135 } 6136 6137 int specificsPos = 0; 6138 int N; 6139 6140 // todo: note that the algorithm used here is O(N^2). This 6141 // isn't a problem in our current environment, but if we start running 6142 // into situations where we have more than 5 or 10 matches then this 6143 // should probably be changed to something smarter... 6144 6145 // First we go through and resolve each of the specific items 6146 // that were supplied, taking care of removing any corresponding 6147 // duplicate items in the generic resolve list. 6148 if (specifics != null) { 6149 for (int i=0; i<specifics.length; i++) { 6150 final Intent sintent = specifics[i]; 6151 if (sintent == null) { 6152 continue; 6153 } 6154 6155 if (DEBUG_INTENT_MATCHING) { 6156 Log.v(TAG, "Specific #" + i + ": " + sintent); 6157 } 6158 6159 String action = sintent.getAction(); 6160 if (resultsAction != null && resultsAction.equals(action)) { 6161 // If this action was explicitly requested, then don't 6162 // remove things that have it. 6163 action = null; 6164 } 6165 6166 ResolveInfo ri = null; 6167 ActivityInfo ai = null; 6168 6169 ComponentName comp = sintent.getComponent(); 6170 if (comp == null) { 6171 ri = resolveIntent( 6172 sintent, 6173 specificTypes != null ? specificTypes[i] : null, 6174 flags, userId); 6175 if (ri == null) { 6176 continue; 6177 } 6178 if (ri == mResolveInfo) { 6179 // ACK! Must do something better with this. 6180 } 6181 ai = ri.activityInfo; 6182 comp = new ComponentName(ai.applicationInfo.packageName, 6183 ai.name); 6184 } else { 6185 ai = getActivityInfo(comp, flags, userId); 6186 if (ai == null) { 6187 continue; 6188 } 6189 } 6190 6191 // Look for any generic query activities that are duplicates 6192 // of this specific one, and remove them from the results. 6193 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 6194 N = results.size(); 6195 int j; 6196 for (j=specificsPos; j<N; j++) { 6197 ResolveInfo sri = results.get(j); 6198 if ((sri.activityInfo.name.equals(comp.getClassName()) 6199 && sri.activityInfo.applicationInfo.packageName.equals( 6200 comp.getPackageName())) 6201 || (action != null && sri.filter.matchAction(action))) { 6202 results.remove(j); 6203 if (DEBUG_INTENT_MATCHING) Log.v( 6204 TAG, "Removing duplicate item from " + j 6205 + " due to specific " + specificsPos); 6206 if (ri == null) { 6207 ri = sri; 6208 } 6209 j--; 6210 N--; 6211 } 6212 } 6213 6214 // Add this specific item to its proper place. 6215 if (ri == null) { 6216 ri = new ResolveInfo(); 6217 ri.activityInfo = ai; 6218 } 6219 results.add(specificsPos, ri); 6220 ri.specificIndex = i; 6221 specificsPos++; 6222 } 6223 } 6224 6225 // Now we go through the remaining generic results and remove any 6226 // duplicate actions that are found here. 6227 N = results.size(); 6228 for (int i=specificsPos; i<N-1; i++) { 6229 final ResolveInfo rii = results.get(i); 6230 if (rii.filter == null) { 6231 continue; 6232 } 6233 6234 // Iterate over all of the actions of this result's intent 6235 // filter... typically this should be just one. 6236 final Iterator<String> it = rii.filter.actionsIterator(); 6237 if (it == null) { 6238 continue; 6239 } 6240 while (it.hasNext()) { 6241 final String action = it.next(); 6242 if (resultsAction != null && resultsAction.equals(action)) { 6243 // If this action was explicitly requested, then don't 6244 // remove things that have it. 6245 continue; 6246 } 6247 for (int j=i+1; j<N; j++) { 6248 final ResolveInfo rij = results.get(j); 6249 if (rij.filter != null && rij.filter.hasAction(action)) { 6250 results.remove(j); 6251 if (DEBUG_INTENT_MATCHING) Log.v( 6252 TAG, "Removing duplicate item from " + j 6253 + " due to action " + action + " at " + i); 6254 j--; 6255 N--; 6256 } 6257 } 6258 } 6259 6260 // If the caller didn't request filter information, drop it now 6261 // so we don't have to marshall/unmarshall it. 6262 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6263 rii.filter = null; 6264 } 6265 } 6266 6267 // Filter out the caller activity if so requested. 6268 if (caller != null) { 6269 N = results.size(); 6270 for (int i=0; i<N; i++) { 6271 ActivityInfo ainfo = results.get(i).activityInfo; 6272 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 6273 && caller.getClassName().equals(ainfo.name)) { 6274 results.remove(i); 6275 break; 6276 } 6277 } 6278 } 6279 6280 // If the caller didn't request filter information, 6281 // drop them now so we don't have to 6282 // marshall/unmarshall it. 6283 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6284 N = results.size(); 6285 for (int i=0; i<N; i++) { 6286 results.get(i).filter = null; 6287 } 6288 } 6289 6290 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 6291 return results; 6292 } 6293 6294 @Override 6295 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 6296 String resolvedType, int flags, int userId) { 6297 return new ParceledListSlice<>( 6298 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 6299 } 6300 6301 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 6302 String resolvedType, int flags, int userId) { 6303 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6304 flags = updateFlagsForResolve(flags, userId, intent); 6305 ComponentName comp = intent.getComponent(); 6306 if (comp == null) { 6307 if (intent.getSelector() != null) { 6308 intent = intent.getSelector(); 6309 comp = intent.getComponent(); 6310 } 6311 } 6312 if (comp != null) { 6313 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6314 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 6315 if (ai != null) { 6316 ResolveInfo ri = new ResolveInfo(); 6317 ri.activityInfo = ai; 6318 list.add(ri); 6319 } 6320 return list; 6321 } 6322 6323 // reader 6324 synchronized (mPackages) { 6325 String pkgName = intent.getPackage(); 6326 if (pkgName == null) { 6327 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 6328 } 6329 final PackageParser.Package pkg = mPackages.get(pkgName); 6330 if (pkg != null) { 6331 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 6332 userId); 6333 } 6334 return Collections.emptyList(); 6335 } 6336 } 6337 6338 @Override 6339 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 6340 if (!sUserManager.exists(userId)) return null; 6341 flags = updateFlagsForResolve(flags, userId, intent); 6342 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 6343 if (query != null) { 6344 if (query.size() >= 1) { 6345 // If there is more than one service with the same priority, 6346 // just arbitrarily pick the first one. 6347 return query.get(0); 6348 } 6349 } 6350 return null; 6351 } 6352 6353 @Override 6354 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 6355 String resolvedType, int flags, int userId) { 6356 return new ParceledListSlice<>( 6357 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 6358 } 6359 6360 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 6361 String resolvedType, int flags, int userId) { 6362 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6363 flags = updateFlagsForResolve(flags, userId, intent); 6364 ComponentName comp = intent.getComponent(); 6365 if (comp == null) { 6366 if (intent.getSelector() != null) { 6367 intent = intent.getSelector(); 6368 comp = intent.getComponent(); 6369 } 6370 } 6371 if (comp != null) { 6372 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6373 final ServiceInfo si = getServiceInfo(comp, flags, userId); 6374 if (si != null) { 6375 final ResolveInfo ri = new ResolveInfo(); 6376 ri.serviceInfo = si; 6377 list.add(ri); 6378 } 6379 return list; 6380 } 6381 6382 // reader 6383 synchronized (mPackages) { 6384 String pkgName = intent.getPackage(); 6385 if (pkgName == null) { 6386 return mServices.queryIntent(intent, resolvedType, flags, userId); 6387 } 6388 final PackageParser.Package pkg = mPackages.get(pkgName); 6389 if (pkg != null) { 6390 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 6391 userId); 6392 } 6393 return Collections.emptyList(); 6394 } 6395 } 6396 6397 @Override 6398 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 6399 String resolvedType, int flags, int userId) { 6400 return new ParceledListSlice<>( 6401 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 6402 } 6403 6404 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 6405 Intent intent, String resolvedType, int flags, int userId) { 6406 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6407 flags = updateFlagsForResolve(flags, userId, intent); 6408 ComponentName comp = intent.getComponent(); 6409 if (comp == null) { 6410 if (intent.getSelector() != null) { 6411 intent = intent.getSelector(); 6412 comp = intent.getComponent(); 6413 } 6414 } 6415 if (comp != null) { 6416 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6417 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 6418 if (pi != null) { 6419 final ResolveInfo ri = new ResolveInfo(); 6420 ri.providerInfo = pi; 6421 list.add(ri); 6422 } 6423 return list; 6424 } 6425 6426 // reader 6427 synchronized (mPackages) { 6428 String pkgName = intent.getPackage(); 6429 if (pkgName == null) { 6430 return mProviders.queryIntent(intent, resolvedType, flags, userId); 6431 } 6432 final PackageParser.Package pkg = mPackages.get(pkgName); 6433 if (pkg != null) { 6434 return mProviders.queryIntentForPackage( 6435 intent, resolvedType, flags, pkg.providers, userId); 6436 } 6437 return Collections.emptyList(); 6438 } 6439 } 6440 6441 @Override 6442 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 6443 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6444 flags = updateFlagsForPackage(flags, userId, null); 6445 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 6446 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6447 true /* requireFullPermission */, false /* checkShell */, 6448 "get installed packages"); 6449 6450 // writer 6451 synchronized (mPackages) { 6452 ArrayList<PackageInfo> list; 6453 if (listUninstalled) { 6454 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 6455 for (PackageSetting ps : mSettings.mPackages.values()) { 6456 final PackageInfo pi; 6457 if (ps.pkg != null) { 6458 pi = generatePackageInfo(ps, flags, userId); 6459 } else { 6460 pi = generatePackageInfo(ps, flags, userId); 6461 } 6462 if (pi != null) { 6463 list.add(pi); 6464 } 6465 } 6466 } else { 6467 list = new ArrayList<PackageInfo>(mPackages.size()); 6468 for (PackageParser.Package p : mPackages.values()) { 6469 final PackageInfo pi = 6470 generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 6471 if (pi != null) { 6472 list.add(pi); 6473 } 6474 } 6475 } 6476 6477 return new ParceledListSlice<PackageInfo>(list); 6478 } 6479 } 6480 6481 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 6482 String[] permissions, boolean[] tmp, int flags, int userId) { 6483 int numMatch = 0; 6484 final PermissionsState permissionsState = ps.getPermissionsState(); 6485 for (int i=0; i<permissions.length; i++) { 6486 final String permission = permissions[i]; 6487 if (permissionsState.hasPermission(permission, userId)) { 6488 tmp[i] = true; 6489 numMatch++; 6490 } else { 6491 tmp[i] = false; 6492 } 6493 } 6494 if (numMatch == 0) { 6495 return; 6496 } 6497 final PackageInfo pi; 6498 if (ps.pkg != null) { 6499 pi = generatePackageInfo(ps, flags, userId); 6500 } else { 6501 pi = generatePackageInfo(ps, flags, userId); 6502 } 6503 // The above might return null in cases of uninstalled apps or install-state 6504 // skew across users/profiles. 6505 if (pi != null) { 6506 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 6507 if (numMatch == permissions.length) { 6508 pi.requestedPermissions = permissions; 6509 } else { 6510 pi.requestedPermissions = new String[numMatch]; 6511 numMatch = 0; 6512 for (int i=0; i<permissions.length; i++) { 6513 if (tmp[i]) { 6514 pi.requestedPermissions[numMatch] = permissions[i]; 6515 numMatch++; 6516 } 6517 } 6518 } 6519 } 6520 list.add(pi); 6521 } 6522 } 6523 6524 @Override 6525 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 6526 String[] permissions, int flags, int userId) { 6527 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6528 flags = updateFlagsForPackage(flags, userId, permissions); 6529 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6530 true /* requireFullPermission */, false /* checkShell */, 6531 "get packages holding permissions"); 6532 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 6533 6534 // writer 6535 synchronized (mPackages) { 6536 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 6537 boolean[] tmpBools = new boolean[permissions.length]; 6538 if (listUninstalled) { 6539 for (PackageSetting ps : mSettings.mPackages.values()) { 6540 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6541 userId); 6542 } 6543 } else { 6544 for (PackageParser.Package pkg : mPackages.values()) { 6545 PackageSetting ps = (PackageSetting)pkg.mExtras; 6546 if (ps != null) { 6547 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6548 userId); 6549 } 6550 } 6551 } 6552 6553 return new ParceledListSlice<PackageInfo>(list); 6554 } 6555 } 6556 6557 @Override 6558 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 6559 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6560 flags = updateFlagsForApplication(flags, userId, null); 6561 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 6562 6563 // writer 6564 synchronized (mPackages) { 6565 ArrayList<ApplicationInfo> list; 6566 if (listUninstalled) { 6567 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 6568 for (PackageSetting ps : mSettings.mPackages.values()) { 6569 ApplicationInfo ai; 6570 int effectiveFlags = flags; 6571 if (ps.isSystem()) { 6572 effectiveFlags |= PackageManager.MATCH_ANY_USER; 6573 } 6574 if (ps.pkg != null) { 6575 ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags, 6576 ps.readUserState(userId), userId); 6577 } else { 6578 ai = generateApplicationInfoFromSettingsLPw(ps.name, effectiveFlags, 6579 userId); 6580 } 6581 if (ai != null) { 6582 list.add(ai); 6583 } 6584 } 6585 } else { 6586 list = new ArrayList<ApplicationInfo>(mPackages.size()); 6587 for (PackageParser.Package p : mPackages.values()) { 6588 if (p.mExtras != null) { 6589 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6590 ((PackageSetting)p.mExtras).readUserState(userId), userId); 6591 if (ai != null) { 6592 list.add(ai); 6593 } 6594 } 6595 } 6596 } 6597 6598 return new ParceledListSlice<ApplicationInfo>(list); 6599 } 6600 } 6601 6602 @Override 6603 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 6604 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6605 return null; 6606 } 6607 6608 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6609 "getEphemeralApplications"); 6610 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6611 true /* requireFullPermission */, false /* checkShell */, 6612 "getEphemeralApplications"); 6613 synchronized (mPackages) { 6614 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 6615 .getEphemeralApplicationsLPw(userId); 6616 if (ephemeralApps != null) { 6617 return new ParceledListSlice<>(ephemeralApps); 6618 } 6619 } 6620 return null; 6621 } 6622 6623 @Override 6624 public boolean isEphemeralApplication(String packageName, int userId) { 6625 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6626 true /* requireFullPermission */, false /* checkShell */, 6627 "isEphemeral"); 6628 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6629 return false; 6630 } 6631 6632 if (!isCallerSameApp(packageName)) { 6633 return false; 6634 } 6635 synchronized (mPackages) { 6636 PackageParser.Package pkg = mPackages.get(packageName); 6637 if (pkg != null) { 6638 return pkg.applicationInfo.isEphemeralApp(); 6639 } 6640 } 6641 return false; 6642 } 6643 6644 @Override 6645 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6646 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6647 return null; 6648 } 6649 6650 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6651 true /* requireFullPermission */, false /* checkShell */, 6652 "getCookie"); 6653 if (!isCallerSameApp(packageName)) { 6654 return null; 6655 } 6656 synchronized (mPackages) { 6657 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6658 packageName, userId); 6659 } 6660 } 6661 6662 @Override 6663 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6664 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6665 return true; 6666 } 6667 6668 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6669 true /* requireFullPermission */, true /* checkShell */, 6670 "setCookie"); 6671 if (!isCallerSameApp(packageName)) { 6672 return false; 6673 } 6674 synchronized (mPackages) { 6675 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6676 packageName, cookie, userId); 6677 } 6678 } 6679 6680 @Override 6681 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6682 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6683 return null; 6684 } 6685 6686 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6687 "getEphemeralApplicationIcon"); 6688 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6689 true /* requireFullPermission */, false /* checkShell */, 6690 "getEphemeralApplicationIcon"); 6691 synchronized (mPackages) { 6692 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6693 packageName, userId); 6694 } 6695 } 6696 6697 private boolean isCallerSameApp(String packageName) { 6698 PackageParser.Package pkg = mPackages.get(packageName); 6699 return pkg != null 6700 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6701 } 6702 6703 @Override 6704 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 6705 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 6706 } 6707 6708 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 6709 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6710 6711 // reader 6712 synchronized (mPackages) { 6713 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6714 final int userId = UserHandle.getCallingUserId(); 6715 while (i.hasNext()) { 6716 final PackageParser.Package p = i.next(); 6717 if (p.applicationInfo == null) continue; 6718 6719 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 6720 && !p.applicationInfo.isDirectBootAware(); 6721 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 6722 && p.applicationInfo.isDirectBootAware(); 6723 6724 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 6725 && (!mSafeMode || isSystemApp(p)) 6726 && (matchesUnaware || matchesAware)) { 6727 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6728 if (ps != null) { 6729 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6730 ps.readUserState(userId), userId); 6731 if (ai != null) { 6732 finalList.add(ai); 6733 } 6734 } 6735 } 6736 } 6737 } 6738 6739 return finalList; 6740 } 6741 6742 @Override 6743 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6744 if (!sUserManager.exists(userId)) return null; 6745 flags = updateFlagsForComponent(flags, userId, name); 6746 // reader 6747 synchronized (mPackages) { 6748 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6749 PackageSetting ps = provider != null 6750 ? mSettings.mPackages.get(provider.owner.packageName) 6751 : null; 6752 return ps != null 6753 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6754 ? PackageParser.generateProviderInfo(provider, flags, 6755 ps.readUserState(userId), userId) 6756 : null; 6757 } 6758 } 6759 6760 /** 6761 * @deprecated 6762 */ 6763 @Deprecated 6764 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6765 // reader 6766 synchronized (mPackages) { 6767 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6768 .entrySet().iterator(); 6769 final int userId = UserHandle.getCallingUserId(); 6770 while (i.hasNext()) { 6771 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6772 PackageParser.Provider p = entry.getValue(); 6773 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6774 6775 if (ps != null && p.syncable 6776 && (!mSafeMode || (p.info.applicationInfo.flags 6777 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6778 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6779 ps.readUserState(userId), userId); 6780 if (info != null) { 6781 outNames.add(entry.getKey()); 6782 outInfo.add(info); 6783 } 6784 } 6785 } 6786 } 6787 } 6788 6789 @Override 6790 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6791 int uid, int flags) { 6792 final int userId = processName != null ? UserHandle.getUserId(uid) 6793 : UserHandle.getCallingUserId(); 6794 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6795 flags = updateFlagsForComponent(flags, userId, processName); 6796 6797 ArrayList<ProviderInfo> finalList = null; 6798 // reader 6799 synchronized (mPackages) { 6800 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6801 while (i.hasNext()) { 6802 final PackageParser.Provider p = i.next(); 6803 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6804 if (ps != null && p.info.authority != null 6805 && (processName == null 6806 || (p.info.processName.equals(processName) 6807 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6808 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6809 if (finalList == null) { 6810 finalList = new ArrayList<ProviderInfo>(3); 6811 } 6812 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6813 ps.readUserState(userId), userId); 6814 if (info != null) { 6815 finalList.add(info); 6816 } 6817 } 6818 } 6819 } 6820 6821 if (finalList != null) { 6822 Collections.sort(finalList, mProviderInitOrderSorter); 6823 return new ParceledListSlice<ProviderInfo>(finalList); 6824 } 6825 6826 return ParceledListSlice.emptyList(); 6827 } 6828 6829 @Override 6830 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6831 // reader 6832 synchronized (mPackages) { 6833 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6834 return PackageParser.generateInstrumentationInfo(i, flags); 6835 } 6836 } 6837 6838 @Override 6839 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 6840 String targetPackage, int flags) { 6841 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 6842 } 6843 6844 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 6845 int flags) { 6846 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 6847 6848 // reader 6849 synchronized (mPackages) { 6850 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6851 while (i.hasNext()) { 6852 final PackageParser.Instrumentation p = i.next(); 6853 if (targetPackage == null 6854 || targetPackage.equals(p.info.targetPackage)) { 6855 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6856 flags); 6857 if (ii != null) { 6858 finalList.add(ii); 6859 } 6860 } 6861 } 6862 } 6863 6864 return finalList; 6865 } 6866 6867 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6868 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6869 if (overlays == null) { 6870 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6871 return; 6872 } 6873 for (PackageParser.Package opkg : overlays.values()) { 6874 // Not much to do if idmap fails: we already logged the error 6875 // and we certainly don't want to abort installation of pkg simply 6876 // because an overlay didn't fit properly. For these reasons, 6877 // ignore the return value of createIdmapForPackagePairLI. 6878 createIdmapForPackagePairLI(pkg, opkg); 6879 } 6880 } 6881 6882 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6883 PackageParser.Package opkg) { 6884 if (!opkg.mTrustedOverlay) { 6885 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6886 opkg.baseCodePath + ": overlay not trusted"); 6887 return false; 6888 } 6889 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6890 if (overlaySet == null) { 6891 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6892 opkg.baseCodePath + " but target package has no known overlays"); 6893 return false; 6894 } 6895 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6896 // TODO: generate idmap for split APKs 6897 try { 6898 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6899 } catch (InstallerException e) { 6900 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6901 + opkg.baseCodePath); 6902 return false; 6903 } 6904 PackageParser.Package[] overlayArray = 6905 overlaySet.values().toArray(new PackageParser.Package[0]); 6906 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6907 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6908 return p1.mOverlayPriority - p2.mOverlayPriority; 6909 } 6910 }; 6911 Arrays.sort(overlayArray, cmp); 6912 6913 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6914 int i = 0; 6915 for (PackageParser.Package p : overlayArray) { 6916 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6917 } 6918 return true; 6919 } 6920 6921 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6922 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]"); 6923 try { 6924 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6925 } finally { 6926 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6927 } 6928 } 6929 6930 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 6931 final File[] files = dir.listFiles(); 6932 if (ArrayUtils.isEmpty(files)) { 6933 Log.d(TAG, "No files in app dir " + dir); 6934 return; 6935 } 6936 6937 if (DEBUG_PACKAGE_SCANNING) { 6938 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6939 + " flags=0x" + Integer.toHexString(parseFlags)); 6940 } 6941 ParallelPackageParser parallelPackageParser = new ParallelPackageParser( 6942 mSeparateProcesses, mOnlyCore, mMetrics); 6943 6944 // Submit files for parsing in parallel 6945 int fileCount = 0; 6946 for (File file : files) { 6947 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6948 && !PackageInstallerService.isStageName(file.getName()); 6949 if (!isPackage) { 6950 // Ignore entries which are not packages 6951 continue; 6952 } 6953 parallelPackageParser.submit(file, parseFlags); 6954 fileCount++; 6955 } 6956 6957 // Process results one by one 6958 for (; fileCount > 0; fileCount--) { 6959 ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take(); 6960 Throwable throwable = parseResult.throwable; 6961 int errorCode = PackageManager.INSTALL_SUCCEEDED; 6962 6963 if (throwable == null) { 6964 try { 6965 scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags, 6966 currentTime, null); 6967 } catch (PackageManagerException e) { 6968 errorCode = e.error; 6969 Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage()); 6970 } 6971 } else if (throwable instanceof PackageParser.PackageParserException) { 6972 PackageParser.PackageParserException e = (PackageParser.PackageParserException) 6973 throwable; 6974 errorCode = e.error; 6975 Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage()); 6976 } else { 6977 throw new IllegalStateException("Unexpected exception occurred while parsing " 6978 + parseResult.scanFile, throwable); 6979 } 6980 6981 // Delete invalid userdata apps 6982 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6983 errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) { 6984 logCriticalInfo(Log.WARN, 6985 "Deleting invalid package at " + parseResult.scanFile); 6986 removeCodePathLI(parseResult.scanFile); 6987 } 6988 } 6989 parallelPackageParser.close(); 6990 } 6991 6992 private static File getSettingsProblemFile() { 6993 File dataDir = Environment.getDataDirectory(); 6994 File systemDir = new File(dataDir, "system"); 6995 File fname = new File(systemDir, "uiderrors.txt"); 6996 return fname; 6997 } 6998 6999 static void reportSettingsProblem(int priority, String msg) { 7000 logCriticalInfo(priority, msg); 7001 } 7002 7003 static void logCriticalInfo(int priority, String msg) { 7004 Slog.println(priority, TAG, msg); 7005 EventLogTags.writePmCriticalInfo(msg); 7006 try { 7007 File fname = getSettingsProblemFile(); 7008 FileOutputStream out = new FileOutputStream(fname, true); 7009 PrintWriter pw = new FastPrintWriter(out); 7010 SimpleDateFormat formatter = new SimpleDateFormat(); 7011 String dateString = formatter.format(new Date(System.currentTimeMillis())); 7012 pw.println(dateString + ": " + msg); 7013 pw.close(); 7014 FileUtils.setPermissions( 7015 fname.toString(), 7016 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 7017 -1, -1); 7018 } catch (java.io.IOException e) { 7019 } 7020 } 7021 7022 private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) { 7023 if (srcFile.isDirectory()) { 7024 final File baseFile = new File(pkg.baseCodePath); 7025 long maxModifiedTime = baseFile.lastModified(); 7026 if (pkg.splitCodePaths != null) { 7027 for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) { 7028 final File splitFile = new File(pkg.splitCodePaths[i]); 7029 maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified()); 7030 } 7031 } 7032 return maxModifiedTime; 7033 } 7034 return srcFile.lastModified(); 7035 } 7036 7037 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 7038 final int policyFlags) throws PackageManagerException { 7039 // When upgrading from pre-N MR1, verify the package time stamp using the package 7040 // directory and not the APK file. 7041 final long lastModifiedTime = mIsPreNMR1Upgrade 7042 ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile); 7043 if (ps != null 7044 && ps.codePath.equals(srcFile) 7045 && ps.timeStamp == lastModifiedTime 7046 && !isCompatSignatureUpdateNeeded(pkg) 7047 && !isRecoverSignatureUpdateNeeded(pkg)) { 7048 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 7049 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7050 ArraySet<PublicKey> signingKs; 7051 synchronized (mPackages) { 7052 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 7053 } 7054 if (ps.signatures.mSignatures != null 7055 && ps.signatures.mSignatures.length != 0 7056 && signingKs != null) { 7057 // Optimization: reuse the existing cached certificates 7058 // if the package appears to be unchanged. 7059 pkg.mSignatures = ps.signatures.mSignatures; 7060 pkg.mSigningKeys = signingKs; 7061 return; 7062 } 7063 7064 Slog.w(TAG, "PackageSetting for " + ps.name 7065 + " is missing signatures. Collecting certs again to recover them."); 7066 } else { 7067 Slog.i(TAG, srcFile.toString() + " changed; collecting certs"); 7068 } 7069 7070 try { 7071 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 7072 PackageParser.collectCertificates(pkg, policyFlags); 7073 } catch (PackageParserException e) { 7074 throw PackageManagerException.from(e); 7075 } finally { 7076 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7077 } 7078 } 7079 7080 /** 7081 * Traces a package scan. 7082 * @see #scanPackageLI(File, int, int, long, UserHandle) 7083 */ 7084 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 7085 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7086 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]"); 7087 try { 7088 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 7089 } finally { 7090 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7091 } 7092 } 7093 7094 /** 7095 * Scans a package and returns the newly parsed package. 7096 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 7097 */ 7098 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 7099 long currentTime, UserHandle user) throws PackageManagerException { 7100 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 7101 PackageParser pp = new PackageParser(); 7102 pp.setSeparateProcesses(mSeparateProcesses); 7103 pp.setOnlyCoreApps(mOnlyCore); 7104 pp.setDisplayMetrics(mMetrics); 7105 7106 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 7107 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 7108 } 7109 7110 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 7111 final PackageParser.Package pkg; 7112 try { 7113 pkg = pp.parsePackage(scanFile, parseFlags); 7114 } catch (PackageParserException e) { 7115 throw PackageManagerException.from(e); 7116 } finally { 7117 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7118 } 7119 7120 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 7121 } 7122 7123 /** 7124 * Scans a package and returns the newly parsed package. 7125 * @throws PackageManagerException on a parse error. 7126 */ 7127 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 7128 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 7129 throws PackageManagerException { 7130 // If the package has children and this is the first dive in the function 7131 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 7132 // packages (parent and children) would be successfully scanned before the 7133 // actual scan since scanning mutates internal state and we want to atomically 7134 // install the package and its children. 7135 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7136 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7137 scanFlags |= SCAN_CHECK_ONLY; 7138 } 7139 } else { 7140 scanFlags &= ~SCAN_CHECK_ONLY; 7141 } 7142 7143 // Scan the parent 7144 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 7145 scanFlags, currentTime, user); 7146 7147 // Scan the children 7148 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7149 for (int i = 0; i < childCount; i++) { 7150 PackageParser.Package childPackage = pkg.childPackages.get(i); 7151 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 7152 currentTime, user); 7153 } 7154 7155 7156 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7157 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 7158 } 7159 7160 return scannedPkg; 7161 } 7162 7163 /** 7164 * Scans a package and returns the newly parsed package. 7165 * @throws PackageManagerException on a parse error. 7166 */ 7167 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 7168 int policyFlags, int scanFlags, long currentTime, UserHandle user) 7169 throws PackageManagerException { 7170 PackageSetting ps = null; 7171 PackageSetting updatedPkg; 7172 // reader 7173 synchronized (mPackages) { 7174 // Look to see if we already know about this package. 7175 String oldName = mSettings.getRenamedPackageLPr(pkg.packageName); 7176 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 7177 // This package has been renamed to its original name. Let's 7178 // use that. 7179 ps = mSettings.getPackageLPr(oldName); 7180 } 7181 // If there was no original package, see one for the real package name. 7182 if (ps == null) { 7183 ps = mSettings.getPackageLPr(pkg.packageName); 7184 } 7185 // Check to see if this package could be hiding/updating a system 7186 // package. Must look for it either under the original or real 7187 // package name depending on our state. 7188 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 7189 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 7190 7191 // If this is a package we don't know about on the system partition, we 7192 // may need to remove disabled child packages on the system partition 7193 // or may need to not add child packages if the parent apk is updated 7194 // on the data partition and no longer defines this child package. 7195 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 7196 // If this is a parent package for an updated system app and this system 7197 // app got an OTA update which no longer defines some of the child packages 7198 // we have to prune them from the disabled system packages. 7199 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 7200 if (disabledPs != null) { 7201 final int scannedChildCount = (pkg.childPackages != null) 7202 ? pkg.childPackages.size() : 0; 7203 final int disabledChildCount = disabledPs.childPackageNames != null 7204 ? disabledPs.childPackageNames.size() : 0; 7205 for (int i = 0; i < disabledChildCount; i++) { 7206 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 7207 boolean disabledPackageAvailable = false; 7208 for (int j = 0; j < scannedChildCount; j++) { 7209 PackageParser.Package childPkg = pkg.childPackages.get(j); 7210 if (childPkg.packageName.equals(disabledChildPackageName)) { 7211 disabledPackageAvailable = true; 7212 break; 7213 } 7214 } 7215 if (!disabledPackageAvailable) { 7216 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 7217 } 7218 } 7219 } 7220 } 7221 } 7222 7223 boolean updatedPkgBetter = false; 7224 // First check if this is a system package that may involve an update 7225 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 7226 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 7227 // it needs to drop FLAG_PRIVILEGED. 7228 if (locationIsPrivileged(scanFile)) { 7229 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7230 } else { 7231 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7232 } 7233 7234 if (ps != null && !ps.codePath.equals(scanFile)) { 7235 // The path has changed from what was last scanned... check the 7236 // version of the new path against what we have stored to determine 7237 // what to do. 7238 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 7239 if (pkg.mVersionCode <= ps.versionCode) { 7240 // The system package has been updated and the code path does not match 7241 // Ignore entry. Skip it. 7242 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 7243 + " ignored: updated version " + ps.versionCode 7244 + " better than this " + pkg.mVersionCode); 7245 if (!updatedPkg.codePath.equals(scanFile)) { 7246 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 7247 + ps.name + " changing from " + updatedPkg.codePathString 7248 + " to " + scanFile); 7249 updatedPkg.codePath = scanFile; 7250 updatedPkg.codePathString = scanFile.toString(); 7251 updatedPkg.resourcePath = scanFile; 7252 updatedPkg.resourcePathString = scanFile.toString(); 7253 } 7254 updatedPkg.pkg = pkg; 7255 updatedPkg.versionCode = pkg.mVersionCode; 7256 7257 // Update the disabled system child packages to point to the package too. 7258 final int childCount = updatedPkg.childPackageNames != null 7259 ? updatedPkg.childPackageNames.size() : 0; 7260 for (int i = 0; i < childCount; i++) { 7261 String childPackageName = updatedPkg.childPackageNames.get(i); 7262 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 7263 childPackageName); 7264 if (updatedChildPkg != null) { 7265 updatedChildPkg.pkg = pkg; 7266 updatedChildPkg.versionCode = pkg.mVersionCode; 7267 } 7268 } 7269 7270 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 7271 + scanFile + " ignored: updated version " + ps.versionCode 7272 + " better than this " + pkg.mVersionCode); 7273 } else { 7274 // The current app on the system partition is better than 7275 // what we have updated to on the data partition; switch 7276 // back to the system partition version. 7277 // At this point, its safely assumed that package installation for 7278 // apps in system partition will go through. If not there won't be a working 7279 // version of the app 7280 // writer 7281 synchronized (mPackages) { 7282 // Just remove the loaded entries from package lists. 7283 mPackages.remove(ps.name); 7284 } 7285 7286 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7287 + " reverting from " + ps.codePathString 7288 + ": new version " + pkg.mVersionCode 7289 + " better than installed " + ps.versionCode); 7290 7291 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7292 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7293 synchronized (mInstallLock) { 7294 args.cleanUpResourcesLI(); 7295 } 7296 synchronized (mPackages) { 7297 mSettings.enableSystemPackageLPw(ps.name); 7298 } 7299 updatedPkgBetter = true; 7300 } 7301 } 7302 } 7303 7304 if (updatedPkg != null) { 7305 // An updated system app will not have the PARSE_IS_SYSTEM flag set 7306 // initially 7307 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 7308 7309 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 7310 // flag set initially 7311 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 7312 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 7313 } 7314 } 7315 7316 // Verify certificates against what was last scanned 7317 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 7318 7319 /* 7320 * A new system app appeared, but we already had a non-system one of the 7321 * same name installed earlier. 7322 */ 7323 boolean shouldHideSystemApp = false; 7324 if (updatedPkg == null && ps != null 7325 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 7326 /* 7327 * Check to make sure the signatures match first. If they don't, 7328 * wipe the installed application and its data. 7329 */ 7330 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 7331 != PackageManager.SIGNATURE_MATCH) { 7332 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 7333 + " signatures don't match existing userdata copy; removing"); 7334 try (PackageFreezer freezer = freezePackage(pkg.packageName, 7335 "scanPackageInternalLI")) { 7336 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 7337 } 7338 ps = null; 7339 } else { 7340 /* 7341 * If the newly-added system app is an older version than the 7342 * already installed version, hide it. It will be scanned later 7343 * and re-added like an update. 7344 */ 7345 if (pkg.mVersionCode <= ps.versionCode) { 7346 shouldHideSystemApp = true; 7347 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 7348 + " but new version " + pkg.mVersionCode + " better than installed " 7349 + ps.versionCode + "; hiding system"); 7350 } else { 7351 /* 7352 * The newly found system app is a newer version that the 7353 * one previously installed. Simply remove the 7354 * already-installed application and replace it with our own 7355 * while keeping the application data. 7356 */ 7357 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7358 + " reverting from " + ps.codePathString + ": new version " 7359 + pkg.mVersionCode + " better than installed " + ps.versionCode); 7360 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7361 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7362 synchronized (mInstallLock) { 7363 args.cleanUpResourcesLI(); 7364 } 7365 } 7366 } 7367 } 7368 7369 // The apk is forward locked (not public) if its code and resources 7370 // are kept in different files. (except for app in either system or 7371 // vendor path). 7372 // TODO grab this value from PackageSettings 7373 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7374 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 7375 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 7376 } 7377 } 7378 7379 // TODO: extend to support forward-locked splits 7380 String resourcePath = null; 7381 String baseResourcePath = null; 7382 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 7383 if (ps != null && ps.resourcePathString != null) { 7384 resourcePath = ps.resourcePathString; 7385 baseResourcePath = ps.resourcePathString; 7386 } else { 7387 // Should not happen at all. Just log an error. 7388 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 7389 } 7390 } else { 7391 resourcePath = pkg.codePath; 7392 baseResourcePath = pkg.baseCodePath; 7393 } 7394 7395 // Set application objects path explicitly. 7396 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 7397 pkg.setApplicationInfoCodePath(pkg.codePath); 7398 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 7399 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 7400 pkg.setApplicationInfoResourcePath(resourcePath); 7401 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 7402 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 7403 7404 // Note that we invoke the following method only if we are about to unpack an application 7405 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 7406 | SCAN_UPDATE_SIGNATURE, currentTime, user); 7407 7408 /* 7409 * If the system app should be overridden by a previously installed 7410 * data, hide the system app now and let the /data/app scan pick it up 7411 * again. 7412 */ 7413 if (shouldHideSystemApp) { 7414 synchronized (mPackages) { 7415 mSettings.disableSystemPackageLPw(pkg.packageName, true); 7416 } 7417 } 7418 7419 return scannedPkg; 7420 } 7421 7422 private static String fixProcessName(String defProcessName, 7423 String processName) { 7424 if (processName == null) { 7425 return defProcessName; 7426 } 7427 return processName; 7428 } 7429 7430 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 7431 throws PackageManagerException { 7432 if (pkgSetting.signatures.mSignatures != null) { 7433 // Already existing package. Make sure signatures match 7434 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 7435 == PackageManager.SIGNATURE_MATCH; 7436 if (!match) { 7437 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 7438 == PackageManager.SIGNATURE_MATCH; 7439 } 7440 if (!match) { 7441 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 7442 == PackageManager.SIGNATURE_MATCH; 7443 } 7444 if (!match) { 7445 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 7446 + pkg.packageName + " signatures do not match the " 7447 + "previously installed version; ignoring!"); 7448 } 7449 } 7450 7451 // Check for shared user signatures 7452 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 7453 // Already existing package. Make sure signatures match 7454 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7455 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 7456 if (!match) { 7457 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 7458 == PackageManager.SIGNATURE_MATCH; 7459 } 7460 if (!match) { 7461 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 7462 == PackageManager.SIGNATURE_MATCH; 7463 } 7464 if (!match) { 7465 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 7466 "Package " + pkg.packageName 7467 + " has no signatures that match those in shared user " 7468 + pkgSetting.sharedUser.name + "; ignoring!"); 7469 } 7470 } 7471 } 7472 7473 /** 7474 * Enforces that only the system UID or root's UID can call a method exposed 7475 * via Binder. 7476 * 7477 * @param message used as message if SecurityException is thrown 7478 * @throws SecurityException if the caller is not system or root 7479 */ 7480 private static final void enforceSystemOrRoot(String message) { 7481 final int uid = Binder.getCallingUid(); 7482 if (uid != Process.SYSTEM_UID && uid != 0) { 7483 throw new SecurityException(message); 7484 } 7485 } 7486 7487 @Override 7488 public void performFstrimIfNeeded() { 7489 enforceSystemOrRoot("Only the system can request fstrim"); 7490 7491 // Before everything else, see whether we need to fstrim. 7492 try { 7493 IStorageManager sm = PackageHelper.getStorageManager(); 7494 if (sm != null) { 7495 boolean doTrim = false; 7496 final long interval = android.provider.Settings.Global.getLong( 7497 mContext.getContentResolver(), 7498 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 7499 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 7500 if (interval > 0) { 7501 final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance(); 7502 if (timeSinceLast > interval) { 7503 doTrim = true; 7504 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 7505 + "; running immediately"); 7506 } 7507 } 7508 if (doTrim) { 7509 final boolean dexOptDialogShown; 7510 synchronized (mPackages) { 7511 dexOptDialogShown = mDexOptDialogShown; 7512 } 7513 if (!isFirstBoot() && dexOptDialogShown) { 7514 try { 7515 ActivityManager.getService().showBootMessage( 7516 mContext.getResources().getString( 7517 R.string.android_upgrading_fstrim), true); 7518 } catch (RemoteException e) { 7519 } 7520 } 7521 sm.runMaintenance(); 7522 } 7523 } else { 7524 Slog.e(TAG, "storageManager service unavailable!"); 7525 } 7526 } catch (RemoteException e) { 7527 // Can't happen; StorageManagerService is local 7528 } 7529 } 7530 7531 @Override 7532 public void updatePackagesIfNeeded() { 7533 enforceSystemOrRoot("Only the system can request package update"); 7534 7535 // We need to re-extract after an OTA. 7536 boolean causeUpgrade = isUpgrade(); 7537 7538 // First boot or factory reset. 7539 // Note: we also handle devices that are upgrading to N right now as if it is their 7540 // first boot, as they do not have profile data. 7541 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 7542 7543 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 7544 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 7545 7546 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 7547 return; 7548 } 7549 7550 List<PackageParser.Package> pkgs; 7551 synchronized (mPackages) { 7552 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 7553 } 7554 7555 final long startTime = System.nanoTime(); 7556 final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */, 7557 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT)); 7558 7559 final int elapsedTimeSeconds = 7560 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 7561 7562 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]); 7563 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]); 7564 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]); 7565 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 7566 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 7567 } 7568 7569 /** 7570 * Performs dexopt on the set of packages in {@code packages} and returns an int array 7571 * containing statistics about the invocation. The array consists of three elements, 7572 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped} 7573 * and {@code numberOfPackagesFailed}. 7574 */ 7575 private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog, 7576 String compilerFilter) { 7577 7578 int numberOfPackagesVisited = 0; 7579 int numberOfPackagesOptimized = 0; 7580 int numberOfPackagesSkipped = 0; 7581 int numberOfPackagesFailed = 0; 7582 final int numberOfPackagesToDexopt = pkgs.size(); 7583 7584 for (PackageParser.Package pkg : pkgs) { 7585 numberOfPackagesVisited++; 7586 7587 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 7588 if (DEBUG_DEXOPT) { 7589 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 7590 } 7591 numberOfPackagesSkipped++; 7592 continue; 7593 } 7594 7595 if (DEBUG_DEXOPT) { 7596 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 7597 numberOfPackagesToDexopt + ": " + pkg.packageName); 7598 } 7599 7600 if (showDialog) { 7601 try { 7602 ActivityManager.getService().showBootMessage( 7603 mContext.getResources().getString(R.string.android_upgrading_apk, 7604 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 7605 } catch (RemoteException e) { 7606 } 7607 synchronized (mPackages) { 7608 mDexOptDialogShown = true; 7609 } 7610 } 7611 7612 // If the OTA updates a system app which was previously preopted to a non-preopted state 7613 // the app might end up being verified at runtime. That's because by default the apps 7614 // are verify-profile but for preopted apps there's no profile. 7615 // Do a hacky check to ensure that if we have no profiles (a reasonable indication 7616 // that before the OTA the app was preopted) the app gets compiled with a non-profile 7617 // filter (by default interpret-only). 7618 // Note that at this stage unused apps are already filtered. 7619 if (isSystemApp(pkg) && 7620 DexFile.isProfileGuidedCompilerFilter(compilerFilter) && 7621 !Environment.getReferenceProfile(pkg.packageName).exists()) { 7622 compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter); 7623 } 7624 7625 // checkProfiles is false to avoid merging profiles during boot which 7626 // might interfere with background compilation (b/28612421). 7627 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 7628 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 7629 // trade-off worth doing to save boot time work. 7630 int dexOptStatus = performDexOptTraced(pkg.packageName, 7631 false /* checkProfiles */, 7632 compilerFilter, 7633 false /* force */); 7634 switch (dexOptStatus) { 7635 case PackageDexOptimizer.DEX_OPT_PERFORMED: 7636 numberOfPackagesOptimized++; 7637 break; 7638 case PackageDexOptimizer.DEX_OPT_SKIPPED: 7639 numberOfPackagesSkipped++; 7640 break; 7641 case PackageDexOptimizer.DEX_OPT_FAILED: 7642 numberOfPackagesFailed++; 7643 break; 7644 default: 7645 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus); 7646 break; 7647 } 7648 } 7649 7650 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped, 7651 numberOfPackagesFailed }; 7652 } 7653 7654 @Override 7655 public void notifyPackageUse(String packageName, int reason) { 7656 synchronized (mPackages) { 7657 PackageParser.Package p = mPackages.get(packageName); 7658 if (p == null) { 7659 return; 7660 } 7661 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 7662 } 7663 } 7664 7665 @Override 7666 public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) { 7667 int userId = UserHandle.getCallingUserId(); 7668 ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId); 7669 if (ai == null) { 7670 Slog.w(TAG, "Loading a package that does not exist for the calling user. package=" 7671 + loadingPackageName + ", user=" + userId); 7672 return; 7673 } 7674 mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId); 7675 } 7676 7677 // TODO: this is not used nor needed. Delete it. 7678 @Override 7679 public boolean performDexOptIfNeeded(String packageName) { 7680 int dexOptStatus = performDexOptTraced(packageName, 7681 false /* checkProfiles */, getFullCompilerFilter(), false /* force */); 7682 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7683 } 7684 7685 @Override 7686 public boolean performDexOpt(String packageName, 7687 boolean checkProfiles, int compileReason, boolean force) { 7688 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7689 getCompilerFilterForReason(compileReason), force); 7690 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7691 } 7692 7693 @Override 7694 public boolean performDexOptMode(String packageName, 7695 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7696 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7697 targetCompilerFilter, force); 7698 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7699 } 7700 7701 private int performDexOptTraced(String packageName, 7702 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7703 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7704 try { 7705 return performDexOptInternal(packageName, checkProfiles, 7706 targetCompilerFilter, force); 7707 } finally { 7708 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7709 } 7710 } 7711 7712 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 7713 // if the package can now be considered up to date for the given filter. 7714 private int performDexOptInternal(String packageName, 7715 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7716 PackageParser.Package p; 7717 synchronized (mPackages) { 7718 p = mPackages.get(packageName); 7719 if (p == null) { 7720 // Package could not be found. Report failure. 7721 return PackageDexOptimizer.DEX_OPT_FAILED; 7722 } 7723 mPackageUsage.maybeWriteAsync(mPackages); 7724 mCompilerStats.maybeWriteAsync(); 7725 } 7726 long callingId = Binder.clearCallingIdentity(); 7727 try { 7728 synchronized (mInstallLock) { 7729 return performDexOptInternalWithDependenciesLI(p, checkProfiles, 7730 targetCompilerFilter, force); 7731 } 7732 } finally { 7733 Binder.restoreCallingIdentity(callingId); 7734 } 7735 } 7736 7737 public ArraySet<String> getOptimizablePackages() { 7738 ArraySet<String> pkgs = new ArraySet<String>(); 7739 synchronized (mPackages) { 7740 for (PackageParser.Package p : mPackages.values()) { 7741 if (PackageDexOptimizer.canOptimizePackage(p)) { 7742 pkgs.add(p.packageName); 7743 } 7744 } 7745 } 7746 return pkgs; 7747 } 7748 7749 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 7750 boolean checkProfiles, String targetCompilerFilter, 7751 boolean force) { 7752 // Select the dex optimizer based on the force parameter. 7753 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 7754 // allocate an object here. 7755 PackageDexOptimizer pdo = force 7756 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 7757 : mPackageDexOptimizer; 7758 7759 // Optimize all dependencies first. Note: we ignore the return value and march on 7760 // on errors. 7761 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 7762 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 7763 if (!deps.isEmpty()) { 7764 for (PackageParser.Package depPackage : deps) { 7765 // TODO: Analyze and investigate if we (should) profile libraries. 7766 // Currently this will do a full compilation of the library by default. 7767 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 7768 false /* checkProfiles */, 7769 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY), 7770 getOrCreateCompilerPackageStats(depPackage)); 7771 } 7772 } 7773 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 7774 targetCompilerFilter, getOrCreateCompilerPackageStats(p)); 7775 } 7776 7777 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 7778 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 7779 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 7780 Set<String> collectedNames = new HashSet<>(); 7781 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 7782 7783 retValue.remove(p); 7784 7785 return retValue; 7786 } else { 7787 return Collections.emptyList(); 7788 } 7789 } 7790 7791 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 7792 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7793 if (!collectedNames.contains(p.packageName)) { 7794 collectedNames.add(p.packageName); 7795 collected.add(p); 7796 7797 if (p.usesLibraries != null) { 7798 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 7799 } 7800 if (p.usesOptionalLibraries != null) { 7801 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7802 collectedNames); 7803 } 7804 } 7805 } 7806 7807 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7808 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7809 for (String libName : libs) { 7810 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7811 if (libPkg != null) { 7812 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7813 } 7814 } 7815 } 7816 7817 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7818 synchronized (mPackages) { 7819 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7820 if (lib != null && lib.apk != null) { 7821 return mPackages.get(lib.apk); 7822 } 7823 } 7824 return null; 7825 } 7826 7827 public void shutdown() { 7828 mPackageUsage.writeNow(mPackages); 7829 mCompilerStats.writeNow(); 7830 } 7831 7832 @Override 7833 public void dumpProfiles(String packageName) { 7834 PackageParser.Package pkg; 7835 synchronized (mPackages) { 7836 pkg = mPackages.get(packageName); 7837 if (pkg == null) { 7838 throw new IllegalArgumentException("Unknown package: " + packageName); 7839 } 7840 } 7841 /* Only the shell, root, or the app user should be able to dump profiles. */ 7842 int callingUid = Binder.getCallingUid(); 7843 if (callingUid != Process.SHELL_UID && 7844 callingUid != Process.ROOT_UID && 7845 callingUid != pkg.applicationInfo.uid) { 7846 throw new SecurityException("dumpProfiles"); 7847 } 7848 7849 synchronized (mInstallLock) { 7850 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles"); 7851 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 7852 try { 7853 List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly(); 7854 String codePaths = TextUtils.join(";", allCodePaths); 7855 mInstaller.dumpProfiles(sharedGid, packageName, codePaths); 7856 } catch (InstallerException e) { 7857 Slog.w(TAG, "Failed to dump profiles", e); 7858 } 7859 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7860 } 7861 } 7862 7863 @Override 7864 public void forceDexOpt(String packageName) { 7865 enforceSystemOrRoot("forceDexOpt"); 7866 7867 PackageParser.Package pkg; 7868 synchronized (mPackages) { 7869 pkg = mPackages.get(packageName); 7870 if (pkg == null) { 7871 throw new IllegalArgumentException("Unknown package: " + packageName); 7872 } 7873 } 7874 7875 synchronized (mInstallLock) { 7876 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7877 7878 // Whoever is calling forceDexOpt wants a fully compiled package. 7879 // Don't use profiles since that may cause compilation to be skipped. 7880 final int res = performDexOptInternalWithDependenciesLI(pkg, 7881 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 7882 true /* force */); 7883 7884 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7885 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7886 throw new IllegalStateException("Failed to dexopt: " + res); 7887 } 7888 } 7889 } 7890 7891 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7892 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7893 Slog.w(TAG, "Unable to update from " + oldPkg.name 7894 + " to " + newPkg.packageName 7895 + ": old package not in system partition"); 7896 return false; 7897 } else if (mPackages.get(oldPkg.name) != null) { 7898 Slog.w(TAG, "Unable to update from " + oldPkg.name 7899 + " to " + newPkg.packageName 7900 + ": old package still exists"); 7901 return false; 7902 } 7903 return true; 7904 } 7905 7906 void removeCodePathLI(File codePath) { 7907 if (codePath.isDirectory()) { 7908 try { 7909 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7910 } catch (InstallerException e) { 7911 Slog.w(TAG, "Failed to remove code path", e); 7912 } 7913 } else { 7914 codePath.delete(); 7915 } 7916 } 7917 7918 private int[] resolveUserIds(int userId) { 7919 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 7920 } 7921 7922 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7923 if (pkg == null) { 7924 Slog.wtf(TAG, "Package was null!", new Throwable()); 7925 return; 7926 } 7927 clearAppDataLeafLIF(pkg, userId, flags); 7928 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7929 for (int i = 0; i < childCount; i++) { 7930 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7931 } 7932 } 7933 7934 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7935 final PackageSetting ps; 7936 synchronized (mPackages) { 7937 ps = mSettings.mPackages.get(pkg.packageName); 7938 } 7939 for (int realUserId : resolveUserIds(userId)) { 7940 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7941 try { 7942 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7943 ceDataInode); 7944 } catch (InstallerException e) { 7945 Slog.w(TAG, String.valueOf(e)); 7946 } 7947 } 7948 } 7949 7950 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7951 if (pkg == null) { 7952 Slog.wtf(TAG, "Package was null!", new Throwable()); 7953 return; 7954 } 7955 destroyAppDataLeafLIF(pkg, userId, flags); 7956 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7957 for (int i = 0; i < childCount; i++) { 7958 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7959 } 7960 } 7961 7962 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7963 final PackageSetting ps; 7964 synchronized (mPackages) { 7965 ps = mSettings.mPackages.get(pkg.packageName); 7966 } 7967 for (int realUserId : resolveUserIds(userId)) { 7968 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7969 try { 7970 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7971 ceDataInode); 7972 } catch (InstallerException e) { 7973 Slog.w(TAG, String.valueOf(e)); 7974 } 7975 } 7976 } 7977 7978 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 7979 if (pkg == null) { 7980 Slog.wtf(TAG, "Package was null!", new Throwable()); 7981 return; 7982 } 7983 destroyAppProfilesLeafLIF(pkg); 7984 destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */); 7985 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7986 for (int i = 0; i < childCount; i++) { 7987 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 7988 destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId, 7989 true /* removeBaseMarker */); 7990 } 7991 } 7992 7993 private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId, 7994 boolean removeBaseMarker) { 7995 if (pkg.isForwardLocked()) { 7996 return; 7997 } 7998 7999 for (String path : pkg.getAllCodePathsExcludingResourceOnly()) { 8000 try { 8001 path = PackageManagerServiceUtils.realpath(new File(path)); 8002 } catch (IOException e) { 8003 // TODO: Should we return early here ? 8004 Slog.w(TAG, "Failed to get canonical path", e); 8005 continue; 8006 } 8007 8008 final String useMarker = path.replace('/', '@'); 8009 for (int realUserId : resolveUserIds(userId)) { 8010 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId); 8011 if (removeBaseMarker) { 8012 File foreignUseMark = new File(profileDir, useMarker); 8013 if (foreignUseMark.exists()) { 8014 if (!foreignUseMark.delete()) { 8015 Slog.w(TAG, "Unable to delete foreign user mark for package: " 8016 + pkg.packageName); 8017 } 8018 } 8019 } 8020 8021 File[] markers = profileDir.listFiles(); 8022 if (markers != null) { 8023 final String searchString = "@" + pkg.packageName + "@"; 8024 // We also delete all markers that contain the package name we're 8025 // uninstalling. These are associated with secondary dex-files belonging 8026 // to the package. Reconstructing the path of these dex files is messy 8027 // in general. 8028 for (File marker : markers) { 8029 if (marker.getName().indexOf(searchString) > 0) { 8030 if (!marker.delete()) { 8031 Slog.w(TAG, "Unable to delete foreign user mark for package: " 8032 + pkg.packageName); 8033 } 8034 } 8035 } 8036 } 8037 } 8038 } 8039 } 8040 8041 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 8042 try { 8043 mInstaller.destroyAppProfiles(pkg.packageName); 8044 } catch (InstallerException e) { 8045 Slog.w(TAG, String.valueOf(e)); 8046 } 8047 } 8048 8049 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 8050 if (pkg == null) { 8051 Slog.wtf(TAG, "Package was null!", new Throwable()); 8052 return; 8053 } 8054 clearAppProfilesLeafLIF(pkg); 8055 // We don't remove the base foreign use marker when clearing profiles because 8056 // we will rename it when the app is updated. Unlike the actual profile contents, 8057 // the foreign use marker is good across installs. 8058 destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */); 8059 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8060 for (int i = 0; i < childCount; i++) { 8061 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 8062 } 8063 } 8064 8065 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 8066 try { 8067 mInstaller.clearAppProfiles(pkg.packageName); 8068 } catch (InstallerException e) { 8069 Slog.w(TAG, String.valueOf(e)); 8070 } 8071 } 8072 8073 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 8074 long lastUpdateTime) { 8075 // Set parent install/update time 8076 PackageSetting ps = (PackageSetting) pkg.mExtras; 8077 if (ps != null) { 8078 ps.firstInstallTime = firstInstallTime; 8079 ps.lastUpdateTime = lastUpdateTime; 8080 } 8081 // Set children install/update time 8082 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8083 for (int i = 0; i < childCount; i++) { 8084 PackageParser.Package childPkg = pkg.childPackages.get(i); 8085 ps = (PackageSetting) childPkg.mExtras; 8086 if (ps != null) { 8087 ps.firstInstallTime = firstInstallTime; 8088 ps.lastUpdateTime = lastUpdateTime; 8089 } 8090 } 8091 } 8092 8093 private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 8094 PackageParser.Package changingLib) { 8095 if (file.path != null) { 8096 usesLibraryFiles.add(file.path); 8097 return; 8098 } 8099 PackageParser.Package p = mPackages.get(file.apk); 8100 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 8101 // If we are doing this while in the middle of updating a library apk, 8102 // then we need to make sure to use that new apk for determining the 8103 // dependencies here. (We haven't yet finished committing the new apk 8104 // to the package manager state.) 8105 if (p == null || p.packageName.equals(changingLib.packageName)) { 8106 p = changingLib; 8107 } 8108 } 8109 if (p != null) { 8110 usesLibraryFiles.addAll(p.getAllCodePaths()); 8111 } 8112 } 8113 8114 private void updateSharedLibrariesLPr(PackageParser.Package pkg, 8115 PackageParser.Package changingLib) throws PackageManagerException { 8116 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 8117 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 8118 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 8119 for (int i=0; i<N; i++) { 8120 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 8121 if (file == null) { 8122 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8123 "Package " + pkg.packageName + " requires unavailable shared library " 8124 + pkg.usesLibraries.get(i) + "; failing!"); 8125 } 8126 addSharedLibraryLPr(usesLibraryFiles, file, changingLib); 8127 } 8128 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 8129 for (int i=0; i<N; i++) { 8130 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 8131 if (file == null) { 8132 Slog.w(TAG, "Package " + pkg.packageName 8133 + " desires unavailable shared library " 8134 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 8135 } else { 8136 addSharedLibraryLPr(usesLibraryFiles, file, changingLib); 8137 } 8138 } 8139 N = usesLibraryFiles.size(); 8140 if (N > 0) { 8141 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 8142 } else { 8143 pkg.usesLibraryFiles = null; 8144 } 8145 } 8146 } 8147 8148 private static boolean hasString(List<String> list, List<String> which) { 8149 if (list == null) { 8150 return false; 8151 } 8152 for (int i=list.size()-1; i>=0; i--) { 8153 for (int j=which.size()-1; j>=0; j--) { 8154 if (which.get(j).equals(list.get(i))) { 8155 return true; 8156 } 8157 } 8158 } 8159 return false; 8160 } 8161 8162 private void updateAllSharedLibrariesLPw() { 8163 for (PackageParser.Package pkg : mPackages.values()) { 8164 try { 8165 updateSharedLibrariesLPr(pkg, null); 8166 } catch (PackageManagerException e) { 8167 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 8168 } 8169 } 8170 } 8171 8172 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 8173 PackageParser.Package changingPkg) { 8174 ArrayList<PackageParser.Package> res = null; 8175 for (PackageParser.Package pkg : mPackages.values()) { 8176 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 8177 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 8178 if (res == null) { 8179 res = new ArrayList<PackageParser.Package>(); 8180 } 8181 res.add(pkg); 8182 try { 8183 updateSharedLibrariesLPr(pkg, changingPkg); 8184 } catch (PackageManagerException e) { 8185 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 8186 } 8187 } 8188 } 8189 return res; 8190 } 8191 8192 /** 8193 * Derive the value of the {@code cpuAbiOverride} based on the provided 8194 * value and an optional stored value from the package settings. 8195 */ 8196 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 8197 String cpuAbiOverride = null; 8198 8199 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 8200 cpuAbiOverride = null; 8201 } else if (abiOverride != null) { 8202 cpuAbiOverride = abiOverride; 8203 } else if (settings != null) { 8204 cpuAbiOverride = settings.cpuAbiOverrideString; 8205 } 8206 8207 return cpuAbiOverride; 8208 } 8209 8210 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 8211 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 8212 throws PackageManagerException { 8213 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 8214 // If the package has children and this is the first dive in the function 8215 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 8216 // whether all packages (parent and children) would be successfully scanned 8217 // before the actual scan since scanning mutates internal state and we want 8218 // to atomically install the package and its children. 8219 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8220 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 8221 scanFlags |= SCAN_CHECK_ONLY; 8222 } 8223 } else { 8224 scanFlags &= ~SCAN_CHECK_ONLY; 8225 } 8226 8227 final PackageParser.Package scannedPkg; 8228 try { 8229 // Scan the parent 8230 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 8231 // Scan the children 8232 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8233 for (int i = 0; i < childCount; i++) { 8234 PackageParser.Package childPkg = pkg.childPackages.get(i); 8235 scanPackageLI(childPkg, policyFlags, 8236 scanFlags, currentTime, user); 8237 } 8238 } finally { 8239 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8240 } 8241 8242 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8243 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 8244 } 8245 8246 return scannedPkg; 8247 } 8248 8249 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 8250 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 8251 boolean success = false; 8252 try { 8253 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 8254 currentTime, user); 8255 success = true; 8256 return res; 8257 } finally { 8258 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 8259 // DELETE_DATA_ON_FAILURES is only used by frozen paths 8260 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 8261 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 8262 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 8263 } 8264 } 8265 } 8266 8267 /** 8268 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 8269 */ 8270 private static boolean apkHasCode(String fileName) { 8271 StrictJarFile jarFile = null; 8272 try { 8273 jarFile = new StrictJarFile(fileName, 8274 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 8275 return jarFile.findEntry("classes.dex") != null; 8276 } catch (IOException ignore) { 8277 } finally { 8278 try { 8279 if (jarFile != null) { 8280 jarFile.close(); 8281 } 8282 } catch (IOException ignore) {} 8283 } 8284 return false; 8285 } 8286 8287 /** 8288 * Enforces code policy for the package. This ensures that if an APK has 8289 * declared hasCode="true" in its manifest that the APK actually contains 8290 * code. 8291 * 8292 * @throws PackageManagerException If bytecode could not be found when it should exist 8293 */ 8294 private static void assertCodePolicy(PackageParser.Package pkg) 8295 throws PackageManagerException { 8296 final boolean shouldHaveCode = 8297 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 8298 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 8299 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8300 "Package " + pkg.baseCodePath + " code is missing"); 8301 } 8302 8303 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 8304 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 8305 final boolean splitShouldHaveCode = 8306 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 8307 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 8308 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8309 "Package " + pkg.splitCodePaths[i] + " code is missing"); 8310 } 8311 } 8312 } 8313 } 8314 8315 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 8316 final int policyFlags, final int scanFlags, long currentTime, UserHandle user) 8317 throws PackageManagerException { 8318 if (DEBUG_PACKAGE_SCANNING) { 8319 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8320 Log.d(TAG, "Scanning package " + pkg.packageName); 8321 } 8322 8323 applyPolicy(pkg, policyFlags); 8324 8325 assertPackageIsValid(pkg, policyFlags, scanFlags); 8326 8327 // Initialize package source and resource directories 8328 final File scanFile = new File(pkg.codePath); 8329 final File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 8330 final File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 8331 8332 SharedUserSetting suid = null; 8333 PackageSetting pkgSetting = null; 8334 8335 // Getting the package setting may have a side-effect, so if we 8336 // are only checking if scan would succeed, stash a copy of the 8337 // old setting to restore at the end. 8338 PackageSetting nonMutatedPs = null; 8339 8340 // We keep references to the derived CPU Abis from settings in oder to reuse 8341 // them in the case where we're not upgrading or booting for the first time. 8342 String primaryCpuAbiFromSettings = null; 8343 String secondaryCpuAbiFromSettings = null; 8344 8345 // writer 8346 synchronized (mPackages) { 8347 if (pkg.mSharedUserId != null) { 8348 // SIDE EFFECTS; may potentially allocate a new shared user 8349 suid = mSettings.getSharedUserLPw( 8350 pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/); 8351 if (DEBUG_PACKAGE_SCANNING) { 8352 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8353 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 8354 + "): packages=" + suid.packages); 8355 } 8356 } 8357 8358 // Check if we are renaming from an original package name. 8359 PackageSetting origPackage = null; 8360 String realName = null; 8361 if (pkg.mOriginalPackages != null) { 8362 // This package may need to be renamed to a previously 8363 // installed name. Let's check on that... 8364 final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage); 8365 if (pkg.mOriginalPackages.contains(renamed)) { 8366 // This package had originally been installed as the 8367 // original name, and we have already taken care of 8368 // transitioning to the new one. Just update the new 8369 // one to continue using the old name. 8370 realName = pkg.mRealPackage; 8371 if (!pkg.packageName.equals(renamed)) { 8372 // Callers into this function may have already taken 8373 // care of renaming the package; only do it here if 8374 // it is not already done. 8375 pkg.setPackageName(renamed); 8376 } 8377 } else { 8378 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 8379 if ((origPackage = mSettings.getPackageLPr( 8380 pkg.mOriginalPackages.get(i))) != null) { 8381 // We do have the package already installed under its 8382 // original name... should we use it? 8383 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 8384 // New package is not compatible with original. 8385 origPackage = null; 8386 continue; 8387 } else if (origPackage.sharedUser != null) { 8388 // Make sure uid is compatible between packages. 8389 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 8390 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 8391 + " to " + pkg.packageName + ": old uid " 8392 + origPackage.sharedUser.name 8393 + " differs from " + pkg.mSharedUserId); 8394 origPackage = null; 8395 continue; 8396 } 8397 // TODO: Add case when shared user id is added [b/28144775] 8398 } else { 8399 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 8400 + pkg.packageName + " to old name " + origPackage.name); 8401 } 8402 break; 8403 } 8404 } 8405 } 8406 } 8407 8408 if (mTransferedPackages.contains(pkg.packageName)) { 8409 Slog.w(TAG, "Package " + pkg.packageName 8410 + " was transferred to another, but its .apk remains"); 8411 } 8412 8413 // See comments in nonMutatedPs declaration 8414 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8415 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName); 8416 if (foundPs != null) { 8417 nonMutatedPs = new PackageSetting(foundPs); 8418 } 8419 } 8420 8421 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) { 8422 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName); 8423 if (foundPs != null) { 8424 primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString; 8425 secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString; 8426 } 8427 } 8428 8429 pkgSetting = mSettings.getPackageLPr(pkg.packageName); 8430 if (pkgSetting != null && pkgSetting.sharedUser != suid) { 8431 PackageManagerService.reportSettingsProblem(Log.WARN, 8432 "Package " + pkg.packageName + " shared user changed from " 8433 + (pkgSetting.sharedUser != null 8434 ? pkgSetting.sharedUser.name : "<nothing>") 8435 + " to " 8436 + (suid != null ? suid.name : "<nothing>") 8437 + "; replacing with new"); 8438 pkgSetting = null; 8439 } 8440 final PackageSetting oldPkgSetting = 8441 pkgSetting == null ? null : new PackageSetting(pkgSetting); 8442 final PackageSetting disabledPkgSetting = 8443 mSettings.getDisabledSystemPkgLPr(pkg.packageName); 8444 if (pkgSetting == null) { 8445 final String parentPackageName = (pkg.parentPackage != null) 8446 ? pkg.parentPackage.packageName : null; 8447 // REMOVE SharedUserSetting from method; update in a separate call 8448 pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage, 8449 disabledPkgSetting, realName, suid, destCodeFile, destResourceFile, 8450 pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi, 8451 pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode, 8452 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user, 8453 true /*allowInstall*/, parentPackageName, pkg.getChildPackageNames(), 8454 UserManagerService.getInstance()); 8455 // SIDE EFFECTS; updates system state; move elsewhere 8456 if (origPackage != null) { 8457 mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name); 8458 } 8459 mSettings.addUserToSettingLPw(pkgSetting); 8460 } else { 8461 // REMOVE SharedUserSetting from method; update in a separate call. 8462 // 8463 // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi, 8464 // secondaryCpuAbi are not known at this point so we always update them 8465 // to null here, only to reset them at a later point. 8466 Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile, 8467 pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi, 8468 pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags, 8469 pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(), 8470 UserManagerService.getInstance()); 8471 } 8472 // SIDE EFFECTS; persists system state to files on disk; move elsewhere 8473 mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting); 8474 8475 // SIDE EFFECTS; modifies system state; move elsewhere 8476 if (pkgSetting.origPackage != null) { 8477 // If we are first transitioning from an original package, 8478 // fix up the new package's name now. We need to do this after 8479 // looking up the package under its new name, so getPackageLP 8480 // can take care of fiddling things correctly. 8481 pkg.setPackageName(origPackage.name); 8482 8483 // File a report about this. 8484 String msg = "New package " + pkgSetting.realName 8485 + " renamed to replace old package " + pkgSetting.name; 8486 reportSettingsProblem(Log.WARN, msg); 8487 8488 // Make a note of it. 8489 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8490 mTransferedPackages.add(origPackage.name); 8491 } 8492 8493 // No longer need to retain this. 8494 pkgSetting.origPackage = null; 8495 } 8496 8497 // SIDE EFFECTS; modifies system state; move elsewhere 8498 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 8499 // Make a note of it. 8500 mTransferedPackages.add(pkg.packageName); 8501 } 8502 8503 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 8504 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 8505 } 8506 8507 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8508 // Check all shared libraries and map to their actual file path. 8509 // We only do this here for apps not on a system dir, because those 8510 // are the only ones that can fail an install due to this. We 8511 // will take care of the system apps by updating all of their 8512 // library paths after the scan is done. 8513 updateSharedLibrariesLPr(pkg, null); 8514 } 8515 8516 if (mFoundPolicyFile) { 8517 SELinuxMMAC.assignSeinfoValue(pkg); 8518 } 8519 8520 pkg.applicationInfo.uid = pkgSetting.appId; 8521 pkg.mExtras = pkgSetting; 8522 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 8523 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 8524 // We just determined the app is signed correctly, so bring 8525 // over the latest parsed certs. 8526 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8527 } else { 8528 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8529 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8530 "Package " + pkg.packageName + " upgrade keys do not match the " 8531 + "previously installed version"); 8532 } else { 8533 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8534 String msg = "System package " + pkg.packageName 8535 + " signature changed; retaining data."; 8536 reportSettingsProblem(Log.WARN, msg); 8537 } 8538 } 8539 } else { 8540 try { 8541 // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService 8542 verifySignaturesLP(pkgSetting, pkg); 8543 // We just determined the app is signed correctly, so bring 8544 // over the latest parsed certs. 8545 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8546 } catch (PackageManagerException e) { 8547 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8548 throw e; 8549 } 8550 // The signature has changed, but this package is in the system 8551 // image... let's recover! 8552 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8553 // However... if this package is part of a shared user, but it 8554 // doesn't match the signature of the shared user, let's fail. 8555 // What this means is that you can't change the signatures 8556 // associated with an overall shared user, which doesn't seem all 8557 // that unreasonable. 8558 if (pkgSetting.sharedUser != null) { 8559 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8560 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 8561 throw new PackageManagerException( 8562 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 8563 "Signature mismatch for shared user: " 8564 + pkgSetting.sharedUser); 8565 } 8566 } 8567 // File a report about this. 8568 String msg = "System package " + pkg.packageName 8569 + " signature changed; retaining data."; 8570 reportSettingsProblem(Log.WARN, msg); 8571 } 8572 } 8573 8574 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 8575 // This package wants to adopt ownership of permissions from 8576 // another package. 8577 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 8578 final String origName = pkg.mAdoptPermissions.get(i); 8579 final PackageSetting orig = mSettings.getPackageLPr(origName); 8580 if (orig != null) { 8581 if (verifyPackageUpdateLPr(orig, pkg)) { 8582 Slog.i(TAG, "Adopting permissions from " + origName + " to " 8583 + pkg.packageName); 8584 // SIDE EFFECTS; updates permissions system state; move elsewhere 8585 mSettings.transferPermissionsLPw(origName, pkg.packageName); 8586 } 8587 } 8588 } 8589 } 8590 } 8591 8592 pkg.applicationInfo.processName = fixProcessName( 8593 pkg.applicationInfo.packageName, 8594 pkg.applicationInfo.processName); 8595 8596 if (pkg != mPlatformPackage) { 8597 // Get all of our default paths setup 8598 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 8599 } 8600 8601 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 8602 8603 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 8604 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) { 8605 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi"); 8606 derivePackageAbi( 8607 pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir); 8608 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8609 8610 // Some system apps still use directory structure for native libraries 8611 // in which case we might end up not detecting abi solely based on apk 8612 // structure. Try to detect abi based on directory structure. 8613 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 8614 pkg.applicationInfo.primaryCpuAbi == null) { 8615 setBundledAppAbisAndRoots(pkg, pkgSetting); 8616 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 8617 } 8618 } else { 8619 // This is not a first boot or an upgrade, don't bother deriving the 8620 // ABI during the scan. Instead, trust the value that was stored in the 8621 // package setting. 8622 pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings; 8623 pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings; 8624 8625 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 8626 8627 if (DEBUG_ABI_SELECTION) { 8628 Slog.i(TAG, "Using ABIS and native lib paths from settings : " + 8629 pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " + 8630 pkg.applicationInfo.secondaryCpuAbi); 8631 } 8632 } 8633 } else { 8634 if ((scanFlags & SCAN_MOVE) != 0) { 8635 // We haven't run dex-opt for this move (since we've moved the compiled output too) 8636 // but we already have this packages package info in the PackageSetting. We just 8637 // use that and derive the native library path based on the new codepath. 8638 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 8639 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 8640 } 8641 8642 // Set native library paths again. For moves, the path will be updated based on the 8643 // ABIs we've determined above. For non-moves, the path will be updated based on the 8644 // ABIs we determined during compilation, but the path will depend on the final 8645 // package path (after the rename away from the stage path). 8646 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 8647 } 8648 8649 // This is a special case for the "system" package, where the ABI is 8650 // dictated by the zygote configuration (and init.rc). We should keep track 8651 // of this ABI so that we can deal with "normal" applications that run under 8652 // the same UID correctly. 8653 if (mPlatformPackage == pkg) { 8654 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 8655 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 8656 } 8657 8658 // If there's a mismatch between the abi-override in the package setting 8659 // and the abiOverride specified for the install. Warn about this because we 8660 // would've already compiled the app without taking the package setting into 8661 // account. 8662 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 8663 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 8664 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 8665 " for package " + pkg.packageName); 8666 } 8667 } 8668 8669 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8670 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8671 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 8672 8673 // Copy the derived override back to the parsed package, so that we can 8674 // update the package settings accordingly. 8675 pkg.cpuAbiOverride = cpuAbiOverride; 8676 8677 if (DEBUG_ABI_SELECTION) { 8678 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 8679 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 8680 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 8681 } 8682 8683 // Push the derived path down into PackageSettings so we know what to 8684 // clean up at uninstall time. 8685 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 8686 8687 if (DEBUG_ABI_SELECTION) { 8688 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 8689 " primary=" + pkg.applicationInfo.primaryCpuAbi + 8690 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 8691 } 8692 8693 // SIDE EFFECTS; removes DEX files from disk; move elsewhere 8694 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 8695 // We don't do this here during boot because we can do it all 8696 // at once after scanning all existing packages. 8697 // 8698 // We also do this *before* we perform dexopt on this package, so that 8699 // we can avoid redundant dexopts, and also to make sure we've got the 8700 // code and package path correct. 8701 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg); 8702 } 8703 8704 if (mFactoryTest && pkg.requestedPermissions.contains( 8705 android.Manifest.permission.FACTORY_TEST)) { 8706 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 8707 } 8708 8709 if (isSystemApp(pkg)) { 8710 pkgSetting.isOrphaned = true; 8711 } 8712 8713 // Take care of first install / last update times. 8714 final long scanFileTime = getLastModifiedTime(pkg, scanFile); 8715 if (currentTime != 0) { 8716 if (pkgSetting.firstInstallTime == 0) { 8717 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 8718 } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) { 8719 pkgSetting.lastUpdateTime = currentTime; 8720 } 8721 } else if (pkgSetting.firstInstallTime == 0) { 8722 // We need *something*. Take time time stamp of the file. 8723 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8724 } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8725 if (scanFileTime != pkgSetting.timeStamp) { 8726 // A package on the system image has changed; consider this 8727 // to be an update. 8728 pkgSetting.lastUpdateTime = scanFileTime; 8729 } 8730 } 8731 pkgSetting.setTimeStamp(scanFileTime); 8732 8733 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8734 if (nonMutatedPs != null) { 8735 synchronized (mPackages) { 8736 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 8737 } 8738 } 8739 } else { 8740 // Modify state for the given package setting 8741 commitPackageSettings(pkg, pkgSetting, user, scanFlags, 8742 (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/); 8743 } 8744 return pkg; 8745 } 8746 8747 /** 8748 * Applies policy to the parsed package based upon the given policy flags. 8749 * Ensures the package is in a good state. 8750 * <p> 8751 * Implementation detail: This method must NOT have any side effect. It would 8752 * ideally be static, but, it requires locks to read system state. 8753 */ 8754 private void applyPolicy(PackageParser.Package pkg, int policyFlags) { 8755 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 8756 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 8757 if (pkg.applicationInfo.isDirectBootAware()) { 8758 // we're direct boot aware; set for all components 8759 for (PackageParser.Service s : pkg.services) { 8760 s.info.encryptionAware = s.info.directBootAware = true; 8761 } 8762 for (PackageParser.Provider p : pkg.providers) { 8763 p.info.encryptionAware = p.info.directBootAware = true; 8764 } 8765 for (PackageParser.Activity a : pkg.activities) { 8766 a.info.encryptionAware = a.info.directBootAware = true; 8767 } 8768 for (PackageParser.Activity r : pkg.receivers) { 8769 r.info.encryptionAware = r.info.directBootAware = true; 8770 } 8771 } 8772 } else { 8773 // Only allow system apps to be flagged as core apps. 8774 pkg.coreApp = false; 8775 // clear flags not applicable to regular apps 8776 pkg.applicationInfo.privateFlags &= 8777 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 8778 pkg.applicationInfo.privateFlags &= 8779 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 8780 } 8781 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 8782 8783 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 8784 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 8785 } 8786 8787 if (!isSystemApp(pkg)) { 8788 // Only system apps can use these features. 8789 pkg.mOriginalPackages = null; 8790 pkg.mRealPackage = null; 8791 pkg.mAdoptPermissions = null; 8792 } 8793 } 8794 8795 /** 8796 * Asserts the parsed package is valid according to teh given policy. If the 8797 * package is invalid, for whatever reason, throws {@link PackgeManagerException}. 8798 * <p> 8799 * Implementation detail: This method must NOT have any side effects. It would 8800 * ideally be static, but, it requires locks to read system state. 8801 * 8802 * @throws PackageManagerException If the package fails any of the validation checks 8803 */ 8804 private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags) 8805 throws PackageManagerException { 8806 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 8807 assertCodePolicy(pkg); 8808 } 8809 8810 if (pkg.applicationInfo.getCodePath() == null || 8811 pkg.applicationInfo.getResourcePath() == null) { 8812 // Bail out. The resource and code paths haven't been set. 8813 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8814 "Code and resource paths haven't been set correctly"); 8815 } 8816 8817 // Make sure we're not adding any bogus keyset info 8818 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8819 ksms.assertScannedPackageValid(pkg); 8820 8821 synchronized (mPackages) { 8822 // The special "android" package can only be defined once 8823 if (pkg.packageName.equals("android")) { 8824 if (mAndroidApplication != null) { 8825 Slog.w(TAG, "*************************************************"); 8826 Slog.w(TAG, "Core android package being redefined. Skipping."); 8827 Slog.w(TAG, " codePath=" + pkg.codePath); 8828 Slog.w(TAG, "*************************************************"); 8829 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 8830 "Core android package being redefined. Skipping."); 8831 } 8832 } 8833 8834 // A package name must be unique; don't allow duplicates 8835 if (mPackages.containsKey(pkg.packageName) 8836 || mSharedLibraries.containsKey(pkg.packageName)) { 8837 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 8838 "Application package " + pkg.packageName 8839 + " already installed. Skipping duplicate."); 8840 } 8841 8842 // Only privileged apps and updated privileged apps can add child packages. 8843 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 8844 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 8845 throw new PackageManagerException("Only privileged apps can add child " 8846 + "packages. Ignoring package " + pkg.packageName); 8847 } 8848 final int childCount = pkg.childPackages.size(); 8849 for (int i = 0; i < childCount; i++) { 8850 PackageParser.Package childPkg = pkg.childPackages.get(i); 8851 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 8852 childPkg.packageName)) { 8853 throw new PackageManagerException("Can't override child of " 8854 + "another disabled app. Ignoring package " + pkg.packageName); 8855 } 8856 } 8857 } 8858 8859 // If we're only installing presumed-existing packages, require that the 8860 // scanned APK is both already known and at the path previously established 8861 // for it. Previously unknown packages we pick up normally, but if we have an 8862 // a priori expectation about this package's install presence, enforce it. 8863 // With a singular exception for new system packages. When an OTA contains 8864 // a new system package, we allow the codepath to change from a system location 8865 // to the user-installed location. If we don't allow this change, any newer, 8866 // user-installed version of the application will be ignored. 8867 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 8868 if (mExpectingBetter.containsKey(pkg.packageName)) { 8869 logCriticalInfo(Log.WARN, 8870 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 8871 } else { 8872 PackageSetting known = mSettings.getPackageLPr(pkg.packageName); 8873 if (known != null) { 8874 if (DEBUG_PACKAGE_SCANNING) { 8875 Log.d(TAG, "Examining " + pkg.codePath 8876 + " and requiring known paths " + known.codePathString 8877 + " & " + known.resourcePathString); 8878 } 8879 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 8880 || !pkg.applicationInfo.getResourcePath().equals( 8881 known.resourcePathString)) { 8882 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 8883 "Application package " + pkg.packageName 8884 + " found at " + pkg.applicationInfo.getCodePath() 8885 + " but expected at " + known.codePathString 8886 + "; ignoring."); 8887 } 8888 } 8889 } 8890 } 8891 8892 // Verify that this new package doesn't have any content providers 8893 // that conflict with existing packages. Only do this if the 8894 // package isn't already installed, since we don't want to break 8895 // things that are installed. 8896 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 8897 final int N = pkg.providers.size(); 8898 int i; 8899 for (i=0; i<N; i++) { 8900 PackageParser.Provider p = pkg.providers.get(i); 8901 if (p.info.authority != null) { 8902 String names[] = p.info.authority.split(";"); 8903 for (int j = 0; j < names.length; j++) { 8904 if (mProvidersByAuthority.containsKey(names[j])) { 8905 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8906 final String otherPackageName = 8907 ((other != null && other.getComponentName() != null) ? 8908 other.getComponentName().getPackageName() : "?"); 8909 throw new PackageManagerException( 8910 INSTALL_FAILED_CONFLICTING_PROVIDER, 8911 "Can't install because provider name " + names[j] 8912 + " (in package " + pkg.applicationInfo.packageName 8913 + ") is already used by " + otherPackageName); 8914 } 8915 } 8916 } 8917 } 8918 } 8919 } 8920 } 8921 8922 /** 8923 * Adds a scanned package to the system. When this method is finished, the package will 8924 * be available for query, resolution, etc... 8925 */ 8926 private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting, 8927 UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException { 8928 final String pkgName = pkg.packageName; 8929 if (mCustomResolverComponentName != null && 8930 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 8931 setUpCustomResolverActivity(pkg); 8932 } 8933 8934 if (pkg.packageName.equals("android")) { 8935 synchronized (mPackages) { 8936 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8937 // Set up information for our fall-back user intent resolution activity. 8938 mPlatformPackage = pkg; 8939 pkg.mVersionCode = mSdkVersion; 8940 mAndroidApplication = pkg.applicationInfo; 8941 8942 if (!mResolverReplaced) { 8943 mResolveActivity.applicationInfo = mAndroidApplication; 8944 mResolveActivity.name = ResolverActivity.class.getName(); 8945 mResolveActivity.packageName = mAndroidApplication.packageName; 8946 mResolveActivity.processName = "system:ui"; 8947 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8948 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 8949 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 8950 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 8951 mResolveActivity.exported = true; 8952 mResolveActivity.enabled = true; 8953 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 8954 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 8955 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 8956 | ActivityInfo.CONFIG_SCREEN_LAYOUT 8957 | ActivityInfo.CONFIG_ORIENTATION 8958 | ActivityInfo.CONFIG_KEYBOARD 8959 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 8960 mResolveInfo.activityInfo = mResolveActivity; 8961 mResolveInfo.priority = 0; 8962 mResolveInfo.preferredOrder = 0; 8963 mResolveInfo.match = 0; 8964 mResolveComponentName = new ComponentName( 8965 mAndroidApplication.packageName, mResolveActivity.name); 8966 } 8967 } 8968 } 8969 } 8970 8971 ArrayList<PackageParser.Package> clientLibPkgs = null; 8972 // writer 8973 synchronized (mPackages) { 8974 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8975 // Only system apps can add new shared libraries. 8976 if (pkg.libraryNames != null) { 8977 for (int i=0; i<pkg.libraryNames.size(); i++) { 8978 String name = pkg.libraryNames.get(i); 8979 boolean allowed = false; 8980 if (pkg.isUpdatedSystemApp()) { 8981 // New library entries can only be added through the 8982 // system image. This is important to get rid of a lot 8983 // of nasty edge cases: for example if we allowed a non- 8984 // system update of the app to add a library, then uninstalling 8985 // the update would make the library go away, and assumptions 8986 // we made such as through app install filtering would now 8987 // have allowed apps on the device which aren't compatible 8988 // with it. Better to just have the restriction here, be 8989 // conservative, and create many fewer cases that can negatively 8990 // impact the user experience. 8991 final PackageSetting sysPs = mSettings 8992 .getDisabledSystemPkgLPr(pkg.packageName); 8993 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 8994 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 8995 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 8996 allowed = true; 8997 break; 8998 } 8999 } 9000 } 9001 } else { 9002 allowed = true; 9003 } 9004 if (allowed) { 9005 if (!mSharedLibraries.containsKey(name)) { 9006 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 9007 } else if (!name.equals(pkg.packageName)) { 9008 Slog.w(TAG, "Package " + pkg.packageName + " library " 9009 + name + " already exists; skipping"); 9010 } 9011 } else { 9012 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 9013 + name + " that is not declared on system image; skipping"); 9014 } 9015 } 9016 if ((scanFlags & SCAN_BOOTING) == 0) { 9017 // If we are not booting, we need to update any applications 9018 // that are clients of our shared library. If we are booting, 9019 // this will all be done once the scan is complete. 9020 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 9021 } 9022 } 9023 } 9024 } 9025 9026 if ((scanFlags & SCAN_BOOTING) != 0) { 9027 // No apps can run during boot scan, so they don't need to be frozen 9028 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 9029 // Caller asked to not kill app, so it's probably not frozen 9030 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 9031 // Caller asked us to ignore frozen check for some reason; they 9032 // probably didn't know the package name 9033 } else { 9034 // We're doing major surgery on this package, so it better be frozen 9035 // right now to keep it from launching 9036 checkPackageFrozen(pkgName); 9037 } 9038 9039 // Also need to kill any apps that are dependent on the library. 9040 if (clientLibPkgs != null) { 9041 for (int i=0; i<clientLibPkgs.size(); i++) { 9042 PackageParser.Package clientPkg = clientLibPkgs.get(i); 9043 killApplication(clientPkg.applicationInfo.packageName, 9044 clientPkg.applicationInfo.uid, "update lib"); 9045 } 9046 } 9047 9048 // writer 9049 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 9050 9051 boolean createIdmapFailed = false; 9052 synchronized (mPackages) { 9053 // We don't expect installation to fail beyond this point 9054 9055 if (pkgSetting.pkg != null) { 9056 // Note that |user| might be null during the initial boot scan. If a codePath 9057 // for an app has changed during a boot scan, it's due to an app update that's 9058 // part of the system partition and marker changes must be applied to all users. 9059 final int userId = ((user != null) ? user : UserHandle.ALL).getIdentifier(); 9060 final int[] userIds = resolveUserIds(userId); 9061 maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg, userIds); 9062 } 9063 9064 // Add the new setting to mSettings 9065 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 9066 // Add the new setting to mPackages 9067 mPackages.put(pkg.applicationInfo.packageName, pkg); 9068 // Make sure we don't accidentally delete its data. 9069 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 9070 while (iter.hasNext()) { 9071 PackageCleanItem item = iter.next(); 9072 if (pkgName.equals(item.packageName)) { 9073 iter.remove(); 9074 } 9075 } 9076 9077 // Add the package's KeySets to the global KeySetManagerService 9078 KeySetManagerService ksms = mSettings.mKeySetManagerService; 9079 ksms.addScannedPackageLPw(pkg); 9080 9081 int N = pkg.providers.size(); 9082 StringBuilder r = null; 9083 int i; 9084 for (i=0; i<N; i++) { 9085 PackageParser.Provider p = pkg.providers.get(i); 9086 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 9087 p.info.processName); 9088 mProviders.addProvider(p); 9089 p.syncable = p.info.isSyncable; 9090 if (p.info.authority != null) { 9091 String names[] = p.info.authority.split(";"); 9092 p.info.authority = null; 9093 for (int j = 0; j < names.length; j++) { 9094 if (j == 1 && p.syncable) { 9095 // We only want the first authority for a provider to possibly be 9096 // syncable, so if we already added this provider using a different 9097 // authority clear the syncable flag. We copy the provider before 9098 // changing it because the mProviders object contains a reference 9099 // to a provider that we don't want to change. 9100 // Only do this for the second authority since the resulting provider 9101 // object can be the same for all future authorities for this provider. 9102 p = new PackageParser.Provider(p); 9103 p.syncable = false; 9104 } 9105 if (!mProvidersByAuthority.containsKey(names[j])) { 9106 mProvidersByAuthority.put(names[j], p); 9107 if (p.info.authority == null) { 9108 p.info.authority = names[j]; 9109 } else { 9110 p.info.authority = p.info.authority + ";" + names[j]; 9111 } 9112 if (DEBUG_PACKAGE_SCANNING) { 9113 if (chatty) 9114 Log.d(TAG, "Registered content provider: " + names[j] 9115 + ", className = " + p.info.name + ", isSyncable = " 9116 + p.info.isSyncable); 9117 } 9118 } else { 9119 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 9120 Slog.w(TAG, "Skipping provider name " + names[j] + 9121 " (in package " + pkg.applicationInfo.packageName + 9122 "): name already used by " 9123 + ((other != null && other.getComponentName() != null) 9124 ? other.getComponentName().getPackageName() : "?")); 9125 } 9126 } 9127 } 9128 if (chatty) { 9129 if (r == null) { 9130 r = new StringBuilder(256); 9131 } else { 9132 r.append(' '); 9133 } 9134 r.append(p.info.name); 9135 } 9136 } 9137 if (r != null) { 9138 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 9139 } 9140 9141 N = pkg.services.size(); 9142 r = null; 9143 for (i=0; i<N; i++) { 9144 PackageParser.Service s = pkg.services.get(i); 9145 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 9146 s.info.processName); 9147 mServices.addService(s); 9148 if (chatty) { 9149 if (r == null) { 9150 r = new StringBuilder(256); 9151 } else { 9152 r.append(' '); 9153 } 9154 r.append(s.info.name); 9155 } 9156 } 9157 if (r != null) { 9158 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 9159 } 9160 9161 N = pkg.receivers.size(); 9162 r = null; 9163 for (i=0; i<N; i++) { 9164 PackageParser.Activity a = pkg.receivers.get(i); 9165 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 9166 a.info.processName); 9167 mReceivers.addActivity(a, "receiver"); 9168 if (chatty) { 9169 if (r == null) { 9170 r = new StringBuilder(256); 9171 } else { 9172 r.append(' '); 9173 } 9174 r.append(a.info.name); 9175 } 9176 } 9177 if (r != null) { 9178 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 9179 } 9180 9181 N = pkg.activities.size(); 9182 r = null; 9183 for (i=0; i<N; i++) { 9184 PackageParser.Activity a = pkg.activities.get(i); 9185 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 9186 a.info.processName); 9187 mActivities.addActivity(a, "activity"); 9188 if (chatty) { 9189 if (r == null) { 9190 r = new StringBuilder(256); 9191 } else { 9192 r.append(' '); 9193 } 9194 r.append(a.info.name); 9195 } 9196 } 9197 if (r != null) { 9198 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 9199 } 9200 9201 N = pkg.permissionGroups.size(); 9202 r = null; 9203 for (i=0; i<N; i++) { 9204 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 9205 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 9206 final String curPackageName = cur == null ? null : cur.info.packageName; 9207 // Dont allow ephemeral apps to define new permission groups. 9208 if (pkg.applicationInfo.isEphemeralApp()) { 9209 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 9210 + pg.info.packageName 9211 + " ignored: ephemeral apps cannot define new permission groups."); 9212 continue; 9213 } 9214 final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName); 9215 if (cur == null || isPackageUpdate) { 9216 mPermissionGroups.put(pg.info.name, pg); 9217 if (chatty) { 9218 if (r == null) { 9219 r = new StringBuilder(256); 9220 } else { 9221 r.append(' '); 9222 } 9223 if (isPackageUpdate) { 9224 r.append("UPD:"); 9225 } 9226 r.append(pg.info.name); 9227 } 9228 } else { 9229 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 9230 + pg.info.packageName + " ignored: original from " 9231 + cur.info.packageName); 9232 if (chatty) { 9233 if (r == null) { 9234 r = new StringBuilder(256); 9235 } else { 9236 r.append(' '); 9237 } 9238 r.append("DUP:"); 9239 r.append(pg.info.name); 9240 } 9241 } 9242 } 9243 if (r != null) { 9244 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 9245 } 9246 9247 N = pkg.permissions.size(); 9248 r = null; 9249 for (i=0; i<N; i++) { 9250 PackageParser.Permission p = pkg.permissions.get(i); 9251 9252 // Dont allow ephemeral apps to define new permissions. 9253 if (pkg.applicationInfo.isEphemeralApp()) { 9254 Slog.w(TAG, "Permission " + p.info.name + " from package " 9255 + p.info.packageName 9256 + " ignored: ephemeral apps cannot define new permissions."); 9257 continue; 9258 } 9259 9260 // Assume by default that we did not install this permission into the system. 9261 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 9262 9263 // Now that permission groups have a special meaning, we ignore permission 9264 // groups for legacy apps to prevent unexpected behavior. In particular, 9265 // permissions for one app being granted to someone just becase they happen 9266 // to be in a group defined by another app (before this had no implications). 9267 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 9268 p.group = mPermissionGroups.get(p.info.group); 9269 // Warn for a permission in an unknown group. 9270 if (p.info.group != null && p.group == null) { 9271 Slog.w(TAG, "Permission " + p.info.name + " from package " 9272 + p.info.packageName + " in an unknown group " + p.info.group); 9273 } 9274 } 9275 9276 ArrayMap<String, BasePermission> permissionMap = 9277 p.tree ? mSettings.mPermissionTrees 9278 : mSettings.mPermissions; 9279 BasePermission bp = permissionMap.get(p.info.name); 9280 9281 // Allow system apps to redefine non-system permissions 9282 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 9283 final boolean currentOwnerIsSystem = (bp.perm != null 9284 && isSystemApp(bp.perm.owner)); 9285 if (isSystemApp(p.owner)) { 9286 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 9287 // It's a built-in permission and no owner, take ownership now 9288 bp.packageSetting = pkgSetting; 9289 bp.perm = p; 9290 bp.uid = pkg.applicationInfo.uid; 9291 bp.sourcePackage = p.info.packageName; 9292 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 9293 } else if (!currentOwnerIsSystem) { 9294 String msg = "New decl " + p.owner + " of permission " 9295 + p.info.name + " is system; overriding " + bp.sourcePackage; 9296 reportSettingsProblem(Log.WARN, msg); 9297 bp = null; 9298 } 9299 } 9300 } 9301 9302 if (bp == null) { 9303 bp = new BasePermission(p.info.name, p.info.packageName, 9304 BasePermission.TYPE_NORMAL); 9305 permissionMap.put(p.info.name, bp); 9306 } 9307 9308 if (bp.perm == null) { 9309 if (bp.sourcePackage == null 9310 || bp.sourcePackage.equals(p.info.packageName)) { 9311 BasePermission tree = findPermissionTreeLP(p.info.name); 9312 if (tree == null 9313 || tree.sourcePackage.equals(p.info.packageName)) { 9314 bp.packageSetting = pkgSetting; 9315 bp.perm = p; 9316 bp.uid = pkg.applicationInfo.uid; 9317 bp.sourcePackage = p.info.packageName; 9318 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 9319 if (chatty) { 9320 if (r == null) { 9321 r = new StringBuilder(256); 9322 } else { 9323 r.append(' '); 9324 } 9325 r.append(p.info.name); 9326 } 9327 } else { 9328 Slog.w(TAG, "Permission " + p.info.name + " from package " 9329 + p.info.packageName + " ignored: base tree " 9330 + tree.name + " is from package " 9331 + tree.sourcePackage); 9332 } 9333 } else { 9334 Slog.w(TAG, "Permission " + p.info.name + " from package " 9335 + p.info.packageName + " ignored: original from " 9336 + bp.sourcePackage); 9337 } 9338 } else if (chatty) { 9339 if (r == null) { 9340 r = new StringBuilder(256); 9341 } else { 9342 r.append(' '); 9343 } 9344 r.append("DUP:"); 9345 r.append(p.info.name); 9346 } 9347 if (bp.perm == p) { 9348 bp.protectionLevel = p.info.protectionLevel; 9349 } 9350 } 9351 9352 if (r != null) { 9353 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 9354 } 9355 9356 N = pkg.instrumentation.size(); 9357 r = null; 9358 for (i=0; i<N; i++) { 9359 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9360 a.info.packageName = pkg.applicationInfo.packageName; 9361 a.info.sourceDir = pkg.applicationInfo.sourceDir; 9362 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 9363 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 9364 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 9365 a.info.dataDir = pkg.applicationInfo.dataDir; 9366 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 9367 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 9368 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 9369 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 9370 mInstrumentation.put(a.getComponentName(), a); 9371 if (chatty) { 9372 if (r == null) { 9373 r = new StringBuilder(256); 9374 } else { 9375 r.append(' '); 9376 } 9377 r.append(a.info.name); 9378 } 9379 } 9380 if (r != null) { 9381 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 9382 } 9383 9384 if (pkg.protectedBroadcasts != null) { 9385 N = pkg.protectedBroadcasts.size(); 9386 for (i=0; i<N; i++) { 9387 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 9388 } 9389 } 9390 9391 // Create idmap files for pairs of (packages, overlay packages). 9392 // Note: "android", ie framework-res.apk, is handled by native layers. 9393 if (pkg.mOverlayTarget != null) { 9394 // This is an overlay package. 9395 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 9396 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 9397 mOverlays.put(pkg.mOverlayTarget, 9398 new ArrayMap<String, PackageParser.Package>()); 9399 } 9400 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 9401 map.put(pkg.packageName, pkg); 9402 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 9403 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 9404 createIdmapFailed = true; 9405 } 9406 } 9407 } else if (mOverlays.containsKey(pkg.packageName) && 9408 !pkg.packageName.equals("android")) { 9409 // This is a regular package, with one or more known overlay packages. 9410 createIdmapsForPackageLI(pkg); 9411 } 9412 } 9413 9414 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9415 9416 if (createIdmapFailed) { 9417 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 9418 "scanPackageLI failed to createIdmap"); 9419 } 9420 } 9421 9422 private static void maybeRenameForeignDexMarkers(PackageParser.Package existing, 9423 PackageParser.Package update, int[] userIds) { 9424 if (existing.applicationInfo == null || update.applicationInfo == null) { 9425 // This isn't due to an app installation. 9426 return; 9427 } 9428 9429 final File oldCodePath = new File(existing.applicationInfo.getCodePath()); 9430 final File newCodePath = new File(update.applicationInfo.getCodePath()); 9431 9432 // The codePath hasn't changed, so there's nothing for us to do. 9433 if (Objects.equals(oldCodePath, newCodePath)) { 9434 return; 9435 } 9436 9437 File canonicalNewCodePath; 9438 try { 9439 canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath)); 9440 } catch (IOException e) { 9441 Slog.w(TAG, "Failed to get canonical path.", e); 9442 return; 9443 } 9444 9445 // This is a bit of a hack. The oldCodePath doesn't exist at this point (because 9446 // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume 9447 // that the last component of the path (i.e, the name) doesn't need canonicalization 9448 // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now 9449 // but may change in the future. Hopefully this function won't exist at that point. 9450 final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(), 9451 oldCodePath.getName()); 9452 9453 // Calculate the prefixes of the markers. These are just the paths with "/" replaced 9454 // with "@". 9455 String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@'); 9456 if (!oldMarkerPrefix.endsWith("@")) { 9457 oldMarkerPrefix += "@"; 9458 } 9459 String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@'); 9460 if (!newMarkerPrefix.endsWith("@")) { 9461 newMarkerPrefix += "@"; 9462 } 9463 9464 List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly(); 9465 List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size()); 9466 for (String updatedPath : updatedPaths) { 9467 String updatedPathName = new File(updatedPath).getName(); 9468 markerSuffixes.add(updatedPathName.replace('/', '@')); 9469 } 9470 9471 for (int userId : userIds) { 9472 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId); 9473 9474 for (String markerSuffix : markerSuffixes) { 9475 File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix); 9476 File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix); 9477 if (oldForeignUseMark.exists()) { 9478 try { 9479 Os.rename(oldForeignUseMark.getAbsolutePath(), 9480 newForeignUseMark.getAbsolutePath()); 9481 } catch (ErrnoException e) { 9482 Slog.w(TAG, "Failed to rename foreign use marker", e); 9483 oldForeignUseMark.delete(); 9484 } 9485 } 9486 } 9487 } 9488 } 9489 9490 /** 9491 * Derive the ABI of a non-system package located at {@code scanFile}. This information 9492 * is derived purely on the basis of the contents of {@code scanFile} and 9493 * {@code cpuAbiOverride}. 9494 * 9495 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 9496 */ 9497 private static void derivePackageAbi(PackageParser.Package pkg, File scanFile, 9498 String cpuAbiOverride, boolean extractLibs, 9499 File appLib32InstallDir) 9500 throws PackageManagerException { 9501 // Give ourselves some initial paths; we'll come back for another 9502 // pass once we've determined ABI below. 9503 setNativeLibraryPaths(pkg, appLib32InstallDir); 9504 9505 // We would never need to extract libs for forward-locked and external packages, 9506 // since the container service will do it for us. We shouldn't attempt to 9507 // extract libs from system app when it was not updated. 9508 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 9509 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 9510 extractLibs = false; 9511 } 9512 9513 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 9514 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 9515 9516 NativeLibraryHelper.Handle handle = null; 9517 try { 9518 handle = NativeLibraryHelper.Handle.create(pkg); 9519 // TODO(multiArch): This can be null for apps that didn't go through the 9520 // usual installation process. We can calculate it again, like we 9521 // do during install time. 9522 // 9523 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 9524 // unnecessary. 9525 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 9526 9527 // Null out the abis so that they can be recalculated. 9528 pkg.applicationInfo.primaryCpuAbi = null; 9529 pkg.applicationInfo.secondaryCpuAbi = null; 9530 if (isMultiArch(pkg.applicationInfo)) { 9531 // Warn if we've set an abiOverride for multi-lib packages.. 9532 // By definition, we need to copy both 32 and 64 bit libraries for 9533 // such packages. 9534 if (pkg.cpuAbiOverride != null 9535 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 9536 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 9537 } 9538 9539 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 9540 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 9541 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 9542 if (extractLibs) { 9543 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 9544 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9545 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 9546 useIsaSpecificSubdirs); 9547 } else { 9548 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 9549 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 9550 } 9551 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9552 } 9553 9554 maybeThrowExceptionForMultiArchCopy( 9555 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 9556 9557 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 9558 if (extractLibs) { 9559 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 9560 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9561 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 9562 useIsaSpecificSubdirs); 9563 } else { 9564 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 9565 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 9566 } 9567 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9568 } 9569 9570 maybeThrowExceptionForMultiArchCopy( 9571 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 9572 9573 if (abi64 >= 0) { 9574 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 9575 } 9576 9577 if (abi32 >= 0) { 9578 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 9579 if (abi64 >= 0) { 9580 if (pkg.use32bitAbi) { 9581 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 9582 pkg.applicationInfo.primaryCpuAbi = abi; 9583 } else { 9584 pkg.applicationInfo.secondaryCpuAbi = abi; 9585 } 9586 } else { 9587 pkg.applicationInfo.primaryCpuAbi = abi; 9588 } 9589 } 9590 9591 } else { 9592 String[] abiList = (cpuAbiOverride != null) ? 9593 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 9594 9595 // Enable gross and lame hacks for apps that are built with old 9596 // SDK tools. We must scan their APKs for renderscript bitcode and 9597 // not launch them if it's present. Don't bother checking on devices 9598 // that don't have 64 bit support. 9599 boolean needsRenderScriptOverride = false; 9600 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 9601 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 9602 abiList = Build.SUPPORTED_32_BIT_ABIS; 9603 needsRenderScriptOverride = true; 9604 } 9605 9606 final int copyRet; 9607 if (extractLibs) { 9608 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 9609 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9610 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 9611 } else { 9612 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 9613 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 9614 } 9615 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9616 9617 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 9618 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 9619 "Error unpackaging native libs for app, errorCode=" + copyRet); 9620 } 9621 9622 if (copyRet >= 0) { 9623 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 9624 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 9625 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 9626 } else if (needsRenderScriptOverride) { 9627 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 9628 } 9629 } 9630 } catch (IOException ioe) { 9631 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 9632 } finally { 9633 IoUtils.closeQuietly(handle); 9634 } 9635 9636 // Now that we've calculated the ABIs and determined if it's an internal app, 9637 // we will go ahead and populate the nativeLibraryPath. 9638 setNativeLibraryPaths(pkg, appLib32InstallDir); 9639 } 9640 9641 /** 9642 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 9643 * i.e, so that all packages can be run inside a single process if required. 9644 * 9645 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 9646 * this function will either try and make the ABI for all packages in {@code packagesForUser} 9647 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 9648 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 9649 * updating a package that belongs to a shared user. 9650 * 9651 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 9652 * adds unnecessary complexity. 9653 */ 9654 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 9655 PackageParser.Package scannedPackage) { 9656 String requiredInstructionSet = null; 9657 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 9658 requiredInstructionSet = VMRuntime.getInstructionSet( 9659 scannedPackage.applicationInfo.primaryCpuAbi); 9660 } 9661 9662 PackageSetting requirer = null; 9663 for (PackageSetting ps : packagesForUser) { 9664 // If packagesForUser contains scannedPackage, we skip it. This will happen 9665 // when scannedPackage is an update of an existing package. Without this check, 9666 // we will never be able to change the ABI of any package belonging to a shared 9667 // user, even if it's compatible with other packages. 9668 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9669 if (ps.primaryCpuAbiString == null) { 9670 continue; 9671 } 9672 9673 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 9674 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 9675 // We have a mismatch between instruction sets (say arm vs arm64) warn about 9676 // this but there's not much we can do. 9677 String errorMessage = "Instruction set mismatch, " 9678 + ((requirer == null) ? "[caller]" : requirer) 9679 + " requires " + requiredInstructionSet + " whereas " + ps 9680 + " requires " + instructionSet; 9681 Slog.w(TAG, errorMessage); 9682 } 9683 9684 if (requiredInstructionSet == null) { 9685 requiredInstructionSet = instructionSet; 9686 requirer = ps; 9687 } 9688 } 9689 } 9690 9691 if (requiredInstructionSet != null) { 9692 String adjustedAbi; 9693 if (requirer != null) { 9694 // requirer != null implies that either scannedPackage was null or that scannedPackage 9695 // did not require an ABI, in which case we have to adjust scannedPackage to match 9696 // the ABI of the set (which is the same as requirer's ABI) 9697 adjustedAbi = requirer.primaryCpuAbiString; 9698 if (scannedPackage != null) { 9699 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 9700 } 9701 } else { 9702 // requirer == null implies that we're updating all ABIs in the set to 9703 // match scannedPackage. 9704 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 9705 } 9706 9707 for (PackageSetting ps : packagesForUser) { 9708 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9709 if (ps.primaryCpuAbiString != null) { 9710 continue; 9711 } 9712 9713 ps.primaryCpuAbiString = adjustedAbi; 9714 if (ps.pkg != null && ps.pkg.applicationInfo != null && 9715 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 9716 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 9717 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 9718 + " (requirer=" 9719 + (requirer == null ? "null" : requirer.pkg.packageName) 9720 + ", scannedPackage=" 9721 + (scannedPackage != null ? scannedPackage.packageName : "null") 9722 + ")"); 9723 try { 9724 mInstaller.rmdex(ps.codePathString, 9725 getDexCodeInstructionSet(getPreferredInstructionSet())); 9726 } catch (InstallerException ignored) { 9727 } 9728 } 9729 } 9730 } 9731 } 9732 } 9733 9734 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 9735 synchronized (mPackages) { 9736 mResolverReplaced = true; 9737 // Set up information for custom user intent resolution activity. 9738 mResolveActivity.applicationInfo = pkg.applicationInfo; 9739 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 9740 mResolveActivity.packageName = pkg.applicationInfo.packageName; 9741 mResolveActivity.processName = pkg.applicationInfo.packageName; 9742 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9743 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9744 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9745 mResolveActivity.theme = 0; 9746 mResolveActivity.exported = true; 9747 mResolveActivity.enabled = true; 9748 mResolveInfo.activityInfo = mResolveActivity; 9749 mResolveInfo.priority = 0; 9750 mResolveInfo.preferredOrder = 0; 9751 mResolveInfo.match = 0; 9752 mResolveComponentName = mCustomResolverComponentName; 9753 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 9754 mResolveComponentName); 9755 } 9756 } 9757 9758 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 9759 if (installerComponent == null) { 9760 if (DEBUG_EPHEMERAL) { 9761 Slog.d(TAG, "Clear ephemeral installer activity"); 9762 } 9763 mEphemeralInstallerActivity.applicationInfo = null; 9764 return; 9765 } 9766 9767 if (DEBUG_EPHEMERAL) { 9768 Slog.d(TAG, "Set ephemeral installer activity: " + installerComponent); 9769 } 9770 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 9771 // Set up information for ephemeral installer activity 9772 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 9773 mEphemeralInstallerActivity.name = installerComponent.getClassName(); 9774 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 9775 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 9776 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9777 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS 9778 | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9779 mEphemeralInstallerActivity.theme = 0; 9780 mEphemeralInstallerActivity.exported = true; 9781 mEphemeralInstallerActivity.enabled = true; 9782 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 9783 mEphemeralInstallerInfo.priority = 0; 9784 mEphemeralInstallerInfo.preferredOrder = 1; 9785 mEphemeralInstallerInfo.isDefault = true; 9786 mEphemeralInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 9787 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 9788 } 9789 9790 private static String calculateBundledApkRoot(final String codePathString) { 9791 final File codePath = new File(codePathString); 9792 final File codeRoot; 9793 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 9794 codeRoot = Environment.getRootDirectory(); 9795 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 9796 codeRoot = Environment.getOemDirectory(); 9797 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 9798 codeRoot = Environment.getVendorDirectory(); 9799 } else { 9800 // Unrecognized code path; take its top real segment as the apk root: 9801 // e.g. /something/app/blah.apk => /something 9802 try { 9803 File f = codePath.getCanonicalFile(); 9804 File parent = f.getParentFile(); // non-null because codePath is a file 9805 File tmp; 9806 while ((tmp = parent.getParentFile()) != null) { 9807 f = parent; 9808 parent = tmp; 9809 } 9810 codeRoot = f; 9811 Slog.w(TAG, "Unrecognized code path " 9812 + codePath + " - using " + codeRoot); 9813 } catch (IOException e) { 9814 // Can't canonicalize the code path -- shenanigans? 9815 Slog.w(TAG, "Can't canonicalize code path " + codePath); 9816 return Environment.getRootDirectory().getPath(); 9817 } 9818 } 9819 return codeRoot.getPath(); 9820 } 9821 9822 /** 9823 * Derive and set the location of native libraries for the given package, 9824 * which varies depending on where and how the package was installed. 9825 */ 9826 private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) { 9827 final ApplicationInfo info = pkg.applicationInfo; 9828 final String codePath = pkg.codePath; 9829 final File codeFile = new File(codePath); 9830 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 9831 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 9832 9833 info.nativeLibraryRootDir = null; 9834 info.nativeLibraryRootRequiresIsa = false; 9835 info.nativeLibraryDir = null; 9836 info.secondaryNativeLibraryDir = null; 9837 9838 if (isApkFile(codeFile)) { 9839 // Monolithic install 9840 if (bundledApp) { 9841 // If "/system/lib64/apkname" exists, assume that is the per-package 9842 // native library directory to use; otherwise use "/system/lib/apkname". 9843 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 9844 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 9845 getPrimaryInstructionSet(info)); 9846 9847 // This is a bundled system app so choose the path based on the ABI. 9848 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 9849 // is just the default path. 9850 final String apkName = deriveCodePathName(codePath); 9851 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 9852 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 9853 apkName).getAbsolutePath(); 9854 9855 if (info.secondaryCpuAbi != null) { 9856 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 9857 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 9858 secondaryLibDir, apkName).getAbsolutePath(); 9859 } 9860 } else if (asecApp) { 9861 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 9862 .getAbsolutePath(); 9863 } else { 9864 final String apkName = deriveCodePathName(codePath); 9865 info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName) 9866 .getAbsolutePath(); 9867 } 9868 9869 info.nativeLibraryRootRequiresIsa = false; 9870 info.nativeLibraryDir = info.nativeLibraryRootDir; 9871 } else { 9872 // Cluster install 9873 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 9874 info.nativeLibraryRootRequiresIsa = true; 9875 9876 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 9877 getPrimaryInstructionSet(info)).getAbsolutePath(); 9878 9879 if (info.secondaryCpuAbi != null) { 9880 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 9881 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 9882 } 9883 } 9884 } 9885 9886 /** 9887 * Calculate the abis and roots for a bundled app. These can uniquely 9888 * be determined from the contents of the system partition, i.e whether 9889 * it contains 64 or 32 bit shared libraries etc. We do not validate any 9890 * of this information, and instead assume that the system was built 9891 * sensibly. 9892 */ 9893 private static void setBundledAppAbisAndRoots(PackageParser.Package pkg, 9894 PackageSetting pkgSetting) { 9895 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 9896 9897 // If "/system/lib64/apkname" exists, assume that is the per-package 9898 // native library directory to use; otherwise use "/system/lib/apkname". 9899 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 9900 setBundledAppAbi(pkg, apkRoot, apkName); 9901 // pkgSetting might be null during rescan following uninstall of updates 9902 // to a bundled app, so accommodate that possibility. The settings in 9903 // that case will be established later from the parsed package. 9904 // 9905 // If the settings aren't null, sync them up with what we've just derived. 9906 // note that apkRoot isn't stored in the package settings. 9907 if (pkgSetting != null) { 9908 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9909 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9910 } 9911 } 9912 9913 /** 9914 * Deduces the ABI of a bundled app and sets the relevant fields on the 9915 * parsed pkg object. 9916 * 9917 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 9918 * under which system libraries are installed. 9919 * @param apkName the name of the installed package. 9920 */ 9921 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 9922 final File codeFile = new File(pkg.codePath); 9923 9924 final boolean has64BitLibs; 9925 final boolean has32BitLibs; 9926 if (isApkFile(codeFile)) { 9927 // Monolithic install 9928 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 9929 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 9930 } else { 9931 // Cluster install 9932 final File rootDir = new File(codeFile, LIB_DIR_NAME); 9933 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 9934 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 9935 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 9936 has64BitLibs = (new File(rootDir, isa)).exists(); 9937 } else { 9938 has64BitLibs = false; 9939 } 9940 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 9941 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 9942 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 9943 has32BitLibs = (new File(rootDir, isa)).exists(); 9944 } else { 9945 has32BitLibs = false; 9946 } 9947 } 9948 9949 if (has64BitLibs && !has32BitLibs) { 9950 // The package has 64 bit libs, but not 32 bit libs. Its primary 9951 // ABI should be 64 bit. We can safely assume here that the bundled 9952 // native libraries correspond to the most preferred ABI in the list. 9953 9954 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9955 pkg.applicationInfo.secondaryCpuAbi = null; 9956 } else if (has32BitLibs && !has64BitLibs) { 9957 // The package has 32 bit libs but not 64 bit libs. Its primary 9958 // ABI should be 32 bit. 9959 9960 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9961 pkg.applicationInfo.secondaryCpuAbi = null; 9962 } else if (has32BitLibs && has64BitLibs) { 9963 // The application has both 64 and 32 bit bundled libraries. We check 9964 // here that the app declares multiArch support, and warn if it doesn't. 9965 // 9966 // We will be lenient here and record both ABIs. The primary will be the 9967 // ABI that's higher on the list, i.e, a device that's configured to prefer 9968 // 64 bit apps will see a 64 bit primary ABI, 9969 9970 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 9971 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 9972 } 9973 9974 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 9975 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9976 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9977 } else { 9978 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9979 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9980 } 9981 } else { 9982 pkg.applicationInfo.primaryCpuAbi = null; 9983 pkg.applicationInfo.secondaryCpuAbi = null; 9984 } 9985 } 9986 9987 private void killApplication(String pkgName, int appId, String reason) { 9988 killApplication(pkgName, appId, UserHandle.USER_ALL, reason); 9989 } 9990 9991 private void killApplication(String pkgName, int appId, int userId, String reason) { 9992 // Request the ActivityManager to kill the process(only for existing packages) 9993 // so that we do not end up in a confused state while the user is still using the older 9994 // version of the application while the new one gets installed. 9995 final long token = Binder.clearCallingIdentity(); 9996 try { 9997 IActivityManager am = ActivityManager.getService(); 9998 if (am != null) { 9999 try { 10000 am.killApplication(pkgName, appId, userId, reason); 10001 } catch (RemoteException e) { 10002 } 10003 } 10004 } finally { 10005 Binder.restoreCallingIdentity(token); 10006 } 10007 } 10008 10009 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 10010 // Remove the parent package setting 10011 PackageSetting ps = (PackageSetting) pkg.mExtras; 10012 if (ps != null) { 10013 removePackageLI(ps, chatty); 10014 } 10015 // Remove the child package setting 10016 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 10017 for (int i = 0; i < childCount; i++) { 10018 PackageParser.Package childPkg = pkg.childPackages.get(i); 10019 ps = (PackageSetting) childPkg.mExtras; 10020 if (ps != null) { 10021 removePackageLI(ps, chatty); 10022 } 10023 } 10024 } 10025 10026 void removePackageLI(PackageSetting ps, boolean chatty) { 10027 if (DEBUG_INSTALL) { 10028 if (chatty) 10029 Log.d(TAG, "Removing package " + ps.name); 10030 } 10031 10032 // writer 10033 synchronized (mPackages) { 10034 mPackages.remove(ps.name); 10035 final PackageParser.Package pkg = ps.pkg; 10036 if (pkg != null) { 10037 cleanPackageDataStructuresLILPw(pkg, chatty); 10038 } 10039 } 10040 } 10041 10042 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 10043 if (DEBUG_INSTALL) { 10044 if (chatty) 10045 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 10046 } 10047 10048 // writer 10049 synchronized (mPackages) { 10050 // Remove the parent package 10051 mPackages.remove(pkg.applicationInfo.packageName); 10052 cleanPackageDataStructuresLILPw(pkg, chatty); 10053 10054 // Remove the child packages 10055 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 10056 for (int i = 0; i < childCount; i++) { 10057 PackageParser.Package childPkg = pkg.childPackages.get(i); 10058 mPackages.remove(childPkg.applicationInfo.packageName); 10059 cleanPackageDataStructuresLILPw(childPkg, chatty); 10060 } 10061 } 10062 } 10063 10064 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 10065 int N = pkg.providers.size(); 10066 StringBuilder r = null; 10067 int i; 10068 for (i=0; i<N; i++) { 10069 PackageParser.Provider p = pkg.providers.get(i); 10070 mProviders.removeProvider(p); 10071 if (p.info.authority == null) { 10072 10073 /* There was another ContentProvider with this authority when 10074 * this app was installed so this authority is null, 10075 * Ignore it as we don't have to unregister the provider. 10076 */ 10077 continue; 10078 } 10079 String names[] = p.info.authority.split(";"); 10080 for (int j = 0; j < names.length; j++) { 10081 if (mProvidersByAuthority.get(names[j]) == p) { 10082 mProvidersByAuthority.remove(names[j]); 10083 if (DEBUG_REMOVE) { 10084 if (chatty) 10085 Log.d(TAG, "Unregistered content provider: " + names[j] 10086 + ", className = " + p.info.name + ", isSyncable = " 10087 + p.info.isSyncable); 10088 } 10089 } 10090 } 10091 if (DEBUG_REMOVE && chatty) { 10092 if (r == null) { 10093 r = new StringBuilder(256); 10094 } else { 10095 r.append(' '); 10096 } 10097 r.append(p.info.name); 10098 } 10099 } 10100 if (r != null) { 10101 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 10102 } 10103 10104 N = pkg.services.size(); 10105 r = null; 10106 for (i=0; i<N; i++) { 10107 PackageParser.Service s = pkg.services.get(i); 10108 mServices.removeService(s); 10109 if (chatty) { 10110 if (r == null) { 10111 r = new StringBuilder(256); 10112 } else { 10113 r.append(' '); 10114 } 10115 r.append(s.info.name); 10116 } 10117 } 10118 if (r != null) { 10119 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 10120 } 10121 10122 N = pkg.receivers.size(); 10123 r = null; 10124 for (i=0; i<N; i++) { 10125 PackageParser.Activity a = pkg.receivers.get(i); 10126 mReceivers.removeActivity(a, "receiver"); 10127 if (DEBUG_REMOVE && chatty) { 10128 if (r == null) { 10129 r = new StringBuilder(256); 10130 } else { 10131 r.append(' '); 10132 } 10133 r.append(a.info.name); 10134 } 10135 } 10136 if (r != null) { 10137 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 10138 } 10139 10140 N = pkg.activities.size(); 10141 r = null; 10142 for (i=0; i<N; i++) { 10143 PackageParser.Activity a = pkg.activities.get(i); 10144 mActivities.removeActivity(a, "activity"); 10145 if (DEBUG_REMOVE && chatty) { 10146 if (r == null) { 10147 r = new StringBuilder(256); 10148 } else { 10149 r.append(' '); 10150 } 10151 r.append(a.info.name); 10152 } 10153 } 10154 if (r != null) { 10155 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 10156 } 10157 10158 N = pkg.permissions.size(); 10159 r = null; 10160 for (i=0; i<N; i++) { 10161 PackageParser.Permission p = pkg.permissions.get(i); 10162 BasePermission bp = mSettings.mPermissions.get(p.info.name); 10163 if (bp == null) { 10164 bp = mSettings.mPermissionTrees.get(p.info.name); 10165 } 10166 if (bp != null && bp.perm == p) { 10167 bp.perm = null; 10168 if (DEBUG_REMOVE && chatty) { 10169 if (r == null) { 10170 r = new StringBuilder(256); 10171 } else { 10172 r.append(' '); 10173 } 10174 r.append(p.info.name); 10175 } 10176 } 10177 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 10178 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 10179 if (appOpPkgs != null) { 10180 appOpPkgs.remove(pkg.packageName); 10181 } 10182 } 10183 } 10184 if (r != null) { 10185 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 10186 } 10187 10188 N = pkg.requestedPermissions.size(); 10189 r = null; 10190 for (i=0; i<N; i++) { 10191 String perm = pkg.requestedPermissions.get(i); 10192 BasePermission bp = mSettings.mPermissions.get(perm); 10193 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 10194 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 10195 if (appOpPkgs != null) { 10196 appOpPkgs.remove(pkg.packageName); 10197 if (appOpPkgs.isEmpty()) { 10198 mAppOpPermissionPackages.remove(perm); 10199 } 10200 } 10201 } 10202 } 10203 if (r != null) { 10204 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 10205 } 10206 10207 N = pkg.instrumentation.size(); 10208 r = null; 10209 for (i=0; i<N; i++) { 10210 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 10211 mInstrumentation.remove(a.getComponentName()); 10212 if (DEBUG_REMOVE && chatty) { 10213 if (r == null) { 10214 r = new StringBuilder(256); 10215 } else { 10216 r.append(' '); 10217 } 10218 r.append(a.info.name); 10219 } 10220 } 10221 if (r != null) { 10222 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 10223 } 10224 10225 r = null; 10226 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 10227 // Only system apps can hold shared libraries. 10228 if (pkg.libraryNames != null) { 10229 for (i=0; i<pkg.libraryNames.size(); i++) { 10230 String name = pkg.libraryNames.get(i); 10231 SharedLibraryEntry cur = mSharedLibraries.get(name); 10232 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 10233 mSharedLibraries.remove(name); 10234 if (DEBUG_REMOVE && chatty) { 10235 if (r == null) { 10236 r = new StringBuilder(256); 10237 } else { 10238 r.append(' '); 10239 } 10240 r.append(name); 10241 } 10242 } 10243 } 10244 } 10245 } 10246 if (r != null) { 10247 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 10248 } 10249 } 10250 10251 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 10252 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 10253 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 10254 return true; 10255 } 10256 } 10257 return false; 10258 } 10259 10260 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 10261 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 10262 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 10263 10264 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 10265 // Update the parent permissions 10266 updatePermissionsLPw(pkg.packageName, pkg, flags); 10267 // Update the child permissions 10268 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 10269 for (int i = 0; i < childCount; i++) { 10270 PackageParser.Package childPkg = pkg.childPackages.get(i); 10271 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 10272 } 10273 } 10274 10275 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 10276 int flags) { 10277 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 10278 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 10279 } 10280 10281 private void updatePermissionsLPw(String changingPkg, 10282 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 10283 // Make sure there are no dangling permission trees. 10284 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 10285 while (it.hasNext()) { 10286 final BasePermission bp = it.next(); 10287 if (bp.packageSetting == null) { 10288 // We may not yet have parsed the package, so just see if 10289 // we still know about its settings. 10290 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 10291 } 10292 if (bp.packageSetting == null) { 10293 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 10294 + " from package " + bp.sourcePackage); 10295 it.remove(); 10296 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 10297 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 10298 Slog.i(TAG, "Removing old permission tree: " + bp.name 10299 + " from package " + bp.sourcePackage); 10300 flags |= UPDATE_PERMISSIONS_ALL; 10301 it.remove(); 10302 } 10303 } 10304 } 10305 10306 // Make sure all dynamic permissions have been assigned to a package, 10307 // and make sure there are no dangling permissions. 10308 it = mSettings.mPermissions.values().iterator(); 10309 while (it.hasNext()) { 10310 final BasePermission bp = it.next(); 10311 if (bp.type == BasePermission.TYPE_DYNAMIC) { 10312 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 10313 + bp.name + " pkg=" + bp.sourcePackage 10314 + " info=" + bp.pendingInfo); 10315 if (bp.packageSetting == null && bp.pendingInfo != null) { 10316 final BasePermission tree = findPermissionTreeLP(bp.name); 10317 if (tree != null && tree.perm != null) { 10318 bp.packageSetting = tree.packageSetting; 10319 bp.perm = new PackageParser.Permission(tree.perm.owner, 10320 new PermissionInfo(bp.pendingInfo)); 10321 bp.perm.info.packageName = tree.perm.info.packageName; 10322 bp.perm.info.name = bp.name; 10323 bp.uid = tree.uid; 10324 } 10325 } 10326 } 10327 if (bp.packageSetting == null) { 10328 // We may not yet have parsed the package, so just see if 10329 // we still know about its settings. 10330 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 10331 } 10332 if (bp.packageSetting == null) { 10333 Slog.w(TAG, "Removing dangling permission: " + bp.name 10334 + " from package " + bp.sourcePackage); 10335 it.remove(); 10336 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 10337 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 10338 Slog.i(TAG, "Removing old permission: " + bp.name 10339 + " from package " + bp.sourcePackage); 10340 flags |= UPDATE_PERMISSIONS_ALL; 10341 it.remove(); 10342 } 10343 } 10344 } 10345 10346 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 10347 // Now update the permissions for all packages, in particular 10348 // replace the granted permissions of the system packages. 10349 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 10350 for (PackageParser.Package pkg : mPackages.values()) { 10351 if (pkg != pkgInfo) { 10352 // Only replace for packages on requested volume 10353 final String volumeUuid = getVolumeUuidForPackage(pkg); 10354 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 10355 && Objects.equals(replaceVolumeUuid, volumeUuid); 10356 grantPermissionsLPw(pkg, replace, changingPkg); 10357 } 10358 } 10359 } 10360 10361 if (pkgInfo != null) { 10362 // Only replace for packages on requested volume 10363 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 10364 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 10365 && Objects.equals(replaceVolumeUuid, volumeUuid); 10366 grantPermissionsLPw(pkgInfo, replace, changingPkg); 10367 } 10368 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10369 } 10370 10371 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 10372 String packageOfInterest) { 10373 // IMPORTANT: There are two types of permissions: install and runtime. 10374 // Install time permissions are granted when the app is installed to 10375 // all device users and users added in the future. Runtime permissions 10376 // are granted at runtime explicitly to specific users. Normal and signature 10377 // protected permissions are install time permissions. Dangerous permissions 10378 // are install permissions if the app's target SDK is Lollipop MR1 or older, 10379 // otherwise they are runtime permissions. This function does not manage 10380 // runtime permissions except for the case an app targeting Lollipop MR1 10381 // being upgraded to target a newer SDK, in which case dangerous permissions 10382 // are transformed from install time to runtime ones. 10383 10384 final PackageSetting ps = (PackageSetting) pkg.mExtras; 10385 if (ps == null) { 10386 return; 10387 } 10388 10389 PermissionsState permissionsState = ps.getPermissionsState(); 10390 PermissionsState origPermissions = permissionsState; 10391 10392 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 10393 10394 boolean runtimePermissionsRevoked = false; 10395 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 10396 10397 boolean changedInstallPermission = false; 10398 10399 if (replace) { 10400 ps.installPermissionsFixed = false; 10401 if (!ps.isSharedUser()) { 10402 origPermissions = new PermissionsState(permissionsState); 10403 permissionsState.reset(); 10404 } else { 10405 // We need to know only about runtime permission changes since the 10406 // calling code always writes the install permissions state but 10407 // the runtime ones are written only if changed. The only cases of 10408 // changed runtime permissions here are promotion of an install to 10409 // runtime and revocation of a runtime from a shared user. 10410 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 10411 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 10412 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 10413 runtimePermissionsRevoked = true; 10414 } 10415 } 10416 } 10417 10418 permissionsState.setGlobalGids(mGlobalGids); 10419 10420 final int N = pkg.requestedPermissions.size(); 10421 for (int i=0; i<N; i++) { 10422 final String name = pkg.requestedPermissions.get(i); 10423 final BasePermission bp = mSettings.mPermissions.get(name); 10424 10425 if (DEBUG_INSTALL) { 10426 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 10427 } 10428 10429 if (bp == null || bp.packageSetting == null) { 10430 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 10431 Slog.w(TAG, "Unknown permission " + name 10432 + " in package " + pkg.packageName); 10433 } 10434 continue; 10435 } 10436 10437 10438 // Limit ephemeral apps to ephemeral allowed permissions. 10439 if (pkg.applicationInfo.isEphemeralApp() && !bp.isEphemeral()) { 10440 Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package " 10441 + pkg.packageName); 10442 continue; 10443 } 10444 10445 final String perm = bp.name; 10446 boolean allowedSig = false; 10447 int grant = GRANT_DENIED; 10448 10449 // Keep track of app op permissions. 10450 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 10451 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 10452 if (pkgs == null) { 10453 pkgs = new ArraySet<>(); 10454 mAppOpPermissionPackages.put(bp.name, pkgs); 10455 } 10456 pkgs.add(pkg.packageName); 10457 } 10458 10459 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 10460 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 10461 >= Build.VERSION_CODES.M; 10462 switch (level) { 10463 case PermissionInfo.PROTECTION_NORMAL: { 10464 // For all apps normal permissions are install time ones. 10465 grant = GRANT_INSTALL; 10466 } break; 10467 10468 case PermissionInfo.PROTECTION_DANGEROUS: { 10469 // If a permission review is required for legacy apps we represent 10470 // their permissions as always granted runtime ones since we need 10471 // to keep the review required permission flag per user while an 10472 // install permission's state is shared across all users. 10473 if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) { 10474 // For legacy apps dangerous permissions are install time ones. 10475 grant = GRANT_INSTALL; 10476 } else if (origPermissions.hasInstallPermission(bp.name)) { 10477 // For legacy apps that became modern, install becomes runtime. 10478 grant = GRANT_UPGRADE; 10479 } else if (mPromoteSystemApps 10480 && isSystemApp(ps) 10481 && mExistingSystemPackages.contains(ps.name)) { 10482 // For legacy system apps, install becomes runtime. 10483 // We cannot check hasInstallPermission() for system apps since those 10484 // permissions were granted implicitly and not persisted pre-M. 10485 grant = GRANT_UPGRADE; 10486 } else { 10487 // For modern apps keep runtime permissions unchanged. 10488 grant = GRANT_RUNTIME; 10489 } 10490 } break; 10491 10492 case PermissionInfo.PROTECTION_SIGNATURE: { 10493 // For all apps signature permissions are install time ones. 10494 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 10495 if (allowedSig) { 10496 grant = GRANT_INSTALL; 10497 } 10498 } break; 10499 } 10500 10501 if (DEBUG_INSTALL) { 10502 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 10503 } 10504 10505 if (grant != GRANT_DENIED) { 10506 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 10507 // If this is an existing, non-system package, then 10508 // we can't add any new permissions to it. 10509 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 10510 // Except... if this is a permission that was added 10511 // to the platform (note: need to only do this when 10512 // updating the platform). 10513 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 10514 grant = GRANT_DENIED; 10515 } 10516 } 10517 } 10518 10519 switch (grant) { 10520 case GRANT_INSTALL: { 10521 // Revoke this as runtime permission to handle the case of 10522 // a runtime permission being downgraded to an install one. 10523 // Also in permission review mode we keep dangerous permissions 10524 // for legacy apps 10525 for (int userId : UserManagerService.getInstance().getUserIds()) { 10526 if (origPermissions.getRuntimePermissionState( 10527 bp.name, userId) != null) { 10528 // Revoke the runtime permission and clear the flags. 10529 origPermissions.revokeRuntimePermission(bp, userId); 10530 origPermissions.updatePermissionFlags(bp, userId, 10531 PackageManager.MASK_PERMISSION_FLAGS, 0); 10532 // If we revoked a permission permission, we have to write. 10533 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10534 changedRuntimePermissionUserIds, userId); 10535 } 10536 } 10537 // Grant an install permission. 10538 if (permissionsState.grantInstallPermission(bp) != 10539 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10540 changedInstallPermission = true; 10541 } 10542 } break; 10543 10544 case GRANT_RUNTIME: { 10545 // Grant previously granted runtime permissions. 10546 for (int userId : UserManagerService.getInstance().getUserIds()) { 10547 PermissionState permissionState = origPermissions 10548 .getRuntimePermissionState(bp.name, userId); 10549 int flags = permissionState != null 10550 ? permissionState.getFlags() : 0; 10551 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 10552 if (permissionsState.grantRuntimePermission(bp, userId) == 10553 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10554 // If we cannot put the permission as it was, we have to write. 10555 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10556 changedRuntimePermissionUserIds, userId); 10557 } 10558 // If the app supports runtime permissions no need for a review. 10559 if (mPermissionReviewRequired 10560 && appSupportsRuntimePermissions 10561 && (flags & PackageManager 10562 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 10563 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 10564 // Since we changed the flags, we have to write. 10565 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10566 changedRuntimePermissionUserIds, userId); 10567 } 10568 } else if (mPermissionReviewRequired 10569 && !appSupportsRuntimePermissions) { 10570 // For legacy apps that need a permission review, every new 10571 // runtime permission is granted but it is pending a review. 10572 // We also need to review only platform defined runtime 10573 // permissions as these are the only ones the platform knows 10574 // how to disable the API to simulate revocation as legacy 10575 // apps don't expect to run with revoked permissions. 10576 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 10577 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 10578 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 10579 // We changed the flags, hence have to write. 10580 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10581 changedRuntimePermissionUserIds, userId); 10582 } 10583 } 10584 if (permissionsState.grantRuntimePermission(bp, userId) 10585 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 10586 // We changed the permission, hence have to write. 10587 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10588 changedRuntimePermissionUserIds, userId); 10589 } 10590 } 10591 // Propagate the permission flags. 10592 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 10593 } 10594 } break; 10595 10596 case GRANT_UPGRADE: { 10597 // Grant runtime permissions for a previously held install permission. 10598 PermissionState permissionState = origPermissions 10599 .getInstallPermissionState(bp.name); 10600 final int flags = permissionState != null ? permissionState.getFlags() : 0; 10601 10602 if (origPermissions.revokeInstallPermission(bp) 10603 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 10604 // We will be transferring the permission flags, so clear them. 10605 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 10606 PackageManager.MASK_PERMISSION_FLAGS, 0); 10607 changedInstallPermission = true; 10608 } 10609 10610 // If the permission is not to be promoted to runtime we ignore it and 10611 // also its other flags as they are not applicable to install permissions. 10612 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 10613 for (int userId : currentUserIds) { 10614 if (permissionsState.grantRuntimePermission(bp, userId) != 10615 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10616 // Transfer the permission flags. 10617 permissionsState.updatePermissionFlags(bp, userId, 10618 flags, flags); 10619 // If we granted the permission, we have to write. 10620 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10621 changedRuntimePermissionUserIds, userId); 10622 } 10623 } 10624 } 10625 } break; 10626 10627 default: { 10628 if (packageOfInterest == null 10629 || packageOfInterest.equals(pkg.packageName)) { 10630 Slog.w(TAG, "Not granting permission " + perm 10631 + " to package " + pkg.packageName 10632 + " because it was previously installed without"); 10633 } 10634 } break; 10635 } 10636 } else { 10637 if (permissionsState.revokeInstallPermission(bp) != 10638 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10639 // Also drop the permission flags. 10640 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 10641 PackageManager.MASK_PERMISSION_FLAGS, 0); 10642 changedInstallPermission = true; 10643 Slog.i(TAG, "Un-granting permission " + perm 10644 + " from package " + pkg.packageName 10645 + " (protectionLevel=" + bp.protectionLevel 10646 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10647 + ")"); 10648 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 10649 // Don't print warning for app op permissions, since it is fine for them 10650 // not to be granted, there is a UI for the user to decide. 10651 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 10652 Slog.w(TAG, "Not granting permission " + perm 10653 + " to package " + pkg.packageName 10654 + " (protectionLevel=" + bp.protectionLevel 10655 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10656 + ")"); 10657 } 10658 } 10659 } 10660 } 10661 10662 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 10663 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 10664 // This is the first that we have heard about this package, so the 10665 // permissions we have now selected are fixed until explicitly 10666 // changed. 10667 ps.installPermissionsFixed = true; 10668 } 10669 10670 // Persist the runtime permissions state for users with changes. If permissions 10671 // were revoked because no app in the shared user declares them we have to 10672 // write synchronously to avoid losing runtime permissions state. 10673 for (int userId : changedRuntimePermissionUserIds) { 10674 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 10675 } 10676 } 10677 10678 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 10679 boolean allowed = false; 10680 final int NP = PackageParser.NEW_PERMISSIONS.length; 10681 for (int ip=0; ip<NP; ip++) { 10682 final PackageParser.NewPermissionInfo npi 10683 = PackageParser.NEW_PERMISSIONS[ip]; 10684 if (npi.name.equals(perm) 10685 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 10686 allowed = true; 10687 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 10688 + pkg.packageName); 10689 break; 10690 } 10691 } 10692 return allowed; 10693 } 10694 10695 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 10696 BasePermission bp, PermissionsState origPermissions) { 10697 boolean privilegedPermission = (bp.protectionLevel 10698 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0; 10699 boolean privappPermissionsDisable = 10700 RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE; 10701 boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage); 10702 boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName); 10703 if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp() 10704 && !platformPackage && platformPermission) { 10705 ArraySet<String> wlPermissions = SystemConfig.getInstance() 10706 .getPrivAppPermissions(pkg.packageName); 10707 boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm); 10708 if (!whitelisted) { 10709 Slog.w(TAG, "Privileged permission " + perm + " for package " 10710 + pkg.packageName + " - not in privapp-permissions whitelist"); 10711 if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) { 10712 return false; 10713 } 10714 } 10715 } 10716 boolean allowed = (compareSignatures( 10717 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 10718 == PackageManager.SIGNATURE_MATCH) 10719 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 10720 == PackageManager.SIGNATURE_MATCH); 10721 if (!allowed && privilegedPermission) { 10722 if (isSystemApp(pkg)) { 10723 // For updated system applications, a system permission 10724 // is granted only if it had been defined by the original application. 10725 if (pkg.isUpdatedSystemApp()) { 10726 final PackageSetting sysPs = mSettings 10727 .getDisabledSystemPkgLPr(pkg.packageName); 10728 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 10729 // If the original was granted this permission, we take 10730 // that grant decision as read and propagate it to the 10731 // update. 10732 if (sysPs.isPrivileged()) { 10733 allowed = true; 10734 } 10735 } else { 10736 // The system apk may have been updated with an older 10737 // version of the one on the data partition, but which 10738 // granted a new system permission that it didn't have 10739 // before. In this case we do want to allow the app to 10740 // now get the new permission if the ancestral apk is 10741 // privileged to get it. 10742 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 10743 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 10744 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 10745 allowed = true; 10746 break; 10747 } 10748 } 10749 } 10750 // Also if a privileged parent package on the system image or any of 10751 // its children requested a privileged permission, the updated child 10752 // packages can also get the permission. 10753 if (pkg.parentPackage != null) { 10754 final PackageSetting disabledSysParentPs = mSettings 10755 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 10756 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 10757 && disabledSysParentPs.isPrivileged()) { 10758 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 10759 allowed = true; 10760 } else if (disabledSysParentPs.pkg.childPackages != null) { 10761 final int count = disabledSysParentPs.pkg.childPackages.size(); 10762 for (int i = 0; i < count; i++) { 10763 PackageParser.Package disabledSysChildPkg = 10764 disabledSysParentPs.pkg.childPackages.get(i); 10765 if (isPackageRequestingPermission(disabledSysChildPkg, 10766 perm)) { 10767 allowed = true; 10768 break; 10769 } 10770 } 10771 } 10772 } 10773 } 10774 } 10775 } else { 10776 allowed = isPrivilegedApp(pkg); 10777 } 10778 } 10779 } 10780 if (!allowed) { 10781 if (!allowed && (bp.protectionLevel 10782 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 10783 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 10784 // If this was a previously normal/dangerous permission that got moved 10785 // to a system permission as part of the runtime permission redesign, then 10786 // we still want to blindly grant it to old apps. 10787 allowed = true; 10788 } 10789 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 10790 && pkg.packageName.equals(mRequiredInstallerPackage)) { 10791 // If this permission is to be granted to the system installer and 10792 // this app is an installer, then it gets the permission. 10793 allowed = true; 10794 } 10795 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 10796 && pkg.packageName.equals(mRequiredVerifierPackage)) { 10797 // If this permission is to be granted to the system verifier and 10798 // this app is a verifier, then it gets the permission. 10799 allowed = true; 10800 } 10801 if (!allowed && (bp.protectionLevel 10802 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 10803 && isSystemApp(pkg)) { 10804 // Any pre-installed system app is allowed to get this permission. 10805 allowed = true; 10806 } 10807 if (!allowed && (bp.protectionLevel 10808 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 10809 // For development permissions, a development permission 10810 // is granted only if it was already granted. 10811 allowed = origPermissions.hasInstallPermission(perm); 10812 } 10813 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 10814 && pkg.packageName.equals(mSetupWizardPackage)) { 10815 // If this permission is to be granted to the system setup wizard and 10816 // this app is a setup wizard, then it gets the permission. 10817 allowed = true; 10818 } 10819 } 10820 return allowed; 10821 } 10822 10823 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 10824 final int permCount = pkg.requestedPermissions.size(); 10825 for (int j = 0; j < permCount; j++) { 10826 String requestedPermission = pkg.requestedPermissions.get(j); 10827 if (permission.equals(requestedPermission)) { 10828 return true; 10829 } 10830 } 10831 return false; 10832 } 10833 10834 final class ActivityIntentResolver 10835 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 10836 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10837 boolean defaultOnly, boolean visibleToEphemeral, boolean isEphemeral, int userId) { 10838 if (!sUserManager.exists(userId)) return null; 10839 mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0) 10840 | (visibleToEphemeral ? PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY : 0) 10841 | (isEphemeral ? PackageManager.MATCH_EPHEMERAL : 0); 10842 return super.queryIntent(intent, resolvedType, defaultOnly, visibleToEphemeral, 10843 isEphemeral, userId); 10844 } 10845 10846 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10847 int userId) { 10848 if (!sUserManager.exists(userId)) return null; 10849 mFlags = flags; 10850 return super.queryIntent(intent, resolvedType, 10851 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 10852 (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0, 10853 (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId); 10854 } 10855 10856 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10857 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 10858 if (!sUserManager.exists(userId)) return null; 10859 if (packageActivities == null) { 10860 return null; 10861 } 10862 mFlags = flags; 10863 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 10864 final boolean vislbleToEphemeral = 10865 (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0; 10866 final boolean isEphemeral = (flags & PackageManager.MATCH_EPHEMERAL) != 0; 10867 final int N = packageActivities.size(); 10868 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 10869 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 10870 10871 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 10872 for (int i = 0; i < N; ++i) { 10873 intentFilters = packageActivities.get(i).intents; 10874 if (intentFilters != null && intentFilters.size() > 0) { 10875 PackageParser.ActivityIntentInfo[] array = 10876 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 10877 intentFilters.toArray(array); 10878 listCut.add(array); 10879 } 10880 } 10881 return super.queryIntentFromList(intent, resolvedType, defaultOnly, 10882 vislbleToEphemeral, isEphemeral, listCut, userId); 10883 } 10884 10885 /** 10886 * Finds a privileged activity that matches the specified activity names. 10887 */ 10888 private PackageParser.Activity findMatchingActivity( 10889 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 10890 for (PackageParser.Activity sysActivity : activityList) { 10891 if (sysActivity.info.name.equals(activityInfo.name)) { 10892 return sysActivity; 10893 } 10894 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 10895 return sysActivity; 10896 } 10897 if (sysActivity.info.targetActivity != null) { 10898 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 10899 return sysActivity; 10900 } 10901 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 10902 return sysActivity; 10903 } 10904 } 10905 } 10906 return null; 10907 } 10908 10909 public class IterGenerator<E> { 10910 public Iterator<E> generate(ActivityIntentInfo info) { 10911 return null; 10912 } 10913 } 10914 10915 public class ActionIterGenerator extends IterGenerator<String> { 10916 @Override 10917 public Iterator<String> generate(ActivityIntentInfo info) { 10918 return info.actionsIterator(); 10919 } 10920 } 10921 10922 public class CategoriesIterGenerator extends IterGenerator<String> { 10923 @Override 10924 public Iterator<String> generate(ActivityIntentInfo info) { 10925 return info.categoriesIterator(); 10926 } 10927 } 10928 10929 public class SchemesIterGenerator extends IterGenerator<String> { 10930 @Override 10931 public Iterator<String> generate(ActivityIntentInfo info) { 10932 return info.schemesIterator(); 10933 } 10934 } 10935 10936 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 10937 @Override 10938 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 10939 return info.authoritiesIterator(); 10940 } 10941 } 10942 10943 /** 10944 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 10945 * MODIFIED. Do not pass in a list that should not be changed. 10946 */ 10947 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 10948 IterGenerator<T> generator, Iterator<T> searchIterator) { 10949 // loop through the set of actions; every one must be found in the intent filter 10950 while (searchIterator.hasNext()) { 10951 // we must have at least one filter in the list to consider a match 10952 if (intentList.size() == 0) { 10953 break; 10954 } 10955 10956 final T searchAction = searchIterator.next(); 10957 10958 // loop through the set of intent filters 10959 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 10960 while (intentIter.hasNext()) { 10961 final ActivityIntentInfo intentInfo = intentIter.next(); 10962 boolean selectionFound = false; 10963 10964 // loop through the intent filter's selection criteria; at least one 10965 // of them must match the searched criteria 10966 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 10967 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 10968 final T intentSelection = intentSelectionIter.next(); 10969 if (intentSelection != null && intentSelection.equals(searchAction)) { 10970 selectionFound = true; 10971 break; 10972 } 10973 } 10974 10975 // the selection criteria wasn't found in this filter's set; this filter 10976 // is not a potential match 10977 if (!selectionFound) { 10978 intentIter.remove(); 10979 } 10980 } 10981 } 10982 } 10983 10984 private boolean isProtectedAction(ActivityIntentInfo filter) { 10985 final Iterator<String> actionsIter = filter.actionsIterator(); 10986 while (actionsIter != null && actionsIter.hasNext()) { 10987 final String filterAction = actionsIter.next(); 10988 if (PROTECTED_ACTIONS.contains(filterAction)) { 10989 return true; 10990 } 10991 } 10992 return false; 10993 } 10994 10995 /** 10996 * Adjusts the priority of the given intent filter according to policy. 10997 * <p> 10998 * <ul> 10999 * <li>The priority for non privileged applications is capped to '0'</li> 11000 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 11001 * <li>The priority for unbundled updates to privileged applications is capped to the 11002 * priority defined on the system partition</li> 11003 * </ul> 11004 * <p> 11005 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 11006 * allowed to obtain any priority on any action. 11007 */ 11008 private void adjustPriority( 11009 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 11010 // nothing to do; priority is fine as-is 11011 if (intent.getPriority() <= 0) { 11012 return; 11013 } 11014 11015 final ActivityInfo activityInfo = intent.activity.info; 11016 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 11017 11018 final boolean privilegedApp = 11019 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 11020 if (!privilegedApp) { 11021 // non-privileged applications can never define a priority >0 11022 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 11023 + " package: " + applicationInfo.packageName 11024 + " activity: " + intent.activity.className 11025 + " origPrio: " + intent.getPriority()); 11026 intent.setPriority(0); 11027 return; 11028 } 11029 11030 if (systemActivities == null) { 11031 // the system package is not disabled; we're parsing the system partition 11032 if (isProtectedAction(intent)) { 11033 if (mDeferProtectedFilters) { 11034 // We can't deal with these just yet. No component should ever obtain a 11035 // >0 priority for a protected actions, with ONE exception -- the setup 11036 // wizard. The setup wizard, however, cannot be known until we're able to 11037 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 11038 // until all intent filters have been processed. Chicken, meet egg. 11039 // Let the filter temporarily have a high priority and rectify the 11040 // priorities after all system packages have been scanned. 11041 mProtectedFilters.add(intent); 11042 if (DEBUG_FILTERS) { 11043 Slog.i(TAG, "Protected action; save for later;" 11044 + " package: " + applicationInfo.packageName 11045 + " activity: " + intent.activity.className 11046 + " origPrio: " + intent.getPriority()); 11047 } 11048 return; 11049 } else { 11050 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 11051 Slog.i(TAG, "No setup wizard;" 11052 + " All protected intents capped to priority 0"); 11053 } 11054 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 11055 if (DEBUG_FILTERS) { 11056 Slog.i(TAG, "Found setup wizard;" 11057 + " allow priority " + intent.getPriority() + ";" 11058 + " package: " + intent.activity.info.packageName 11059 + " activity: " + intent.activity.className 11060 + " priority: " + intent.getPriority()); 11061 } 11062 // setup wizard gets whatever it wants 11063 return; 11064 } 11065 Slog.w(TAG, "Protected action; cap priority to 0;" 11066 + " package: " + intent.activity.info.packageName 11067 + " activity: " + intent.activity.className 11068 + " origPrio: " + intent.getPriority()); 11069 intent.setPriority(0); 11070 return; 11071 } 11072 } 11073 // privileged apps on the system image get whatever priority they request 11074 return; 11075 } 11076 11077 // privileged app unbundled update ... try to find the same activity 11078 final PackageParser.Activity foundActivity = 11079 findMatchingActivity(systemActivities, activityInfo); 11080 if (foundActivity == null) { 11081 // this is a new activity; it cannot obtain >0 priority 11082 if (DEBUG_FILTERS) { 11083 Slog.i(TAG, "New activity; cap priority to 0;" 11084 + " package: " + applicationInfo.packageName 11085 + " activity: " + intent.activity.className 11086 + " origPrio: " + intent.getPriority()); 11087 } 11088 intent.setPriority(0); 11089 return; 11090 } 11091 11092 // found activity, now check for filter equivalence 11093 11094 // a shallow copy is enough; we modify the list, not its contents 11095 final List<ActivityIntentInfo> intentListCopy = 11096 new ArrayList<>(foundActivity.intents); 11097 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 11098 11099 // find matching action subsets 11100 final Iterator<String> actionsIterator = intent.actionsIterator(); 11101 if (actionsIterator != null) { 11102 getIntentListSubset( 11103 intentListCopy, new ActionIterGenerator(), actionsIterator); 11104 if (intentListCopy.size() == 0) { 11105 // no more intents to match; we're not equivalent 11106 if (DEBUG_FILTERS) { 11107 Slog.i(TAG, "Mismatched action; cap priority to 0;" 11108 + " package: " + applicationInfo.packageName 11109 + " activity: " + intent.activity.className 11110 + " origPrio: " + intent.getPriority()); 11111 } 11112 intent.setPriority(0); 11113 return; 11114 } 11115 } 11116 11117 // find matching category subsets 11118 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 11119 if (categoriesIterator != null) { 11120 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 11121 categoriesIterator); 11122 if (intentListCopy.size() == 0) { 11123 // no more intents to match; we're not equivalent 11124 if (DEBUG_FILTERS) { 11125 Slog.i(TAG, "Mismatched category; cap priority to 0;" 11126 + " package: " + applicationInfo.packageName 11127 + " activity: " + intent.activity.className 11128 + " origPrio: " + intent.getPriority()); 11129 } 11130 intent.setPriority(0); 11131 return; 11132 } 11133 } 11134 11135 // find matching schemes subsets 11136 final Iterator<String> schemesIterator = intent.schemesIterator(); 11137 if (schemesIterator != null) { 11138 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 11139 schemesIterator); 11140 if (intentListCopy.size() == 0) { 11141 // no more intents to match; we're not equivalent 11142 if (DEBUG_FILTERS) { 11143 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 11144 + " package: " + applicationInfo.packageName 11145 + " activity: " + intent.activity.className 11146 + " origPrio: " + intent.getPriority()); 11147 } 11148 intent.setPriority(0); 11149 return; 11150 } 11151 } 11152 11153 // find matching authorities subsets 11154 final Iterator<IntentFilter.AuthorityEntry> 11155 authoritiesIterator = intent.authoritiesIterator(); 11156 if (authoritiesIterator != null) { 11157 getIntentListSubset(intentListCopy, 11158 new AuthoritiesIterGenerator(), 11159 authoritiesIterator); 11160 if (intentListCopy.size() == 0) { 11161 // no more intents to match; we're not equivalent 11162 if (DEBUG_FILTERS) { 11163 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 11164 + " package: " + applicationInfo.packageName 11165 + " activity: " + intent.activity.className 11166 + " origPrio: " + intent.getPriority()); 11167 } 11168 intent.setPriority(0); 11169 return; 11170 } 11171 } 11172 11173 // we found matching filter(s); app gets the max priority of all intents 11174 int cappedPriority = 0; 11175 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 11176 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 11177 } 11178 if (intent.getPriority() > cappedPriority) { 11179 if (DEBUG_FILTERS) { 11180 Slog.i(TAG, "Found matching filter(s);" 11181 + " cap priority to " + cappedPriority + ";" 11182 + " package: " + applicationInfo.packageName 11183 + " activity: " + intent.activity.className 11184 + " origPrio: " + intent.getPriority()); 11185 } 11186 intent.setPriority(cappedPriority); 11187 return; 11188 } 11189 // all this for nothing; the requested priority was <= what was on the system 11190 } 11191 11192 public final void addActivity(PackageParser.Activity a, String type) { 11193 mActivities.put(a.getComponentName(), a); 11194 if (DEBUG_SHOW_INFO) 11195 Log.v( 11196 TAG, " " + type + " " + 11197 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 11198 if (DEBUG_SHOW_INFO) 11199 Log.v(TAG, " Class=" + a.info.name); 11200 final int NI = a.intents.size(); 11201 for (int j=0; j<NI; j++) { 11202 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 11203 if ("activity".equals(type)) { 11204 final PackageSetting ps = 11205 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 11206 final List<PackageParser.Activity> systemActivities = 11207 ps != null && ps.pkg != null ? ps.pkg.activities : null; 11208 adjustPriority(systemActivities, intent); 11209 } 11210 if (DEBUG_SHOW_INFO) { 11211 Log.v(TAG, " IntentFilter:"); 11212 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11213 } 11214 if (!intent.debugCheck()) { 11215 Log.w(TAG, "==> For Activity " + a.info.name); 11216 } 11217 addFilter(intent); 11218 } 11219 } 11220 11221 public final void removeActivity(PackageParser.Activity a, String type) { 11222 mActivities.remove(a.getComponentName()); 11223 if (DEBUG_SHOW_INFO) { 11224 Log.v(TAG, " " + type + " " 11225 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 11226 : a.info.name) + ":"); 11227 Log.v(TAG, " Class=" + a.info.name); 11228 } 11229 final int NI = a.intents.size(); 11230 for (int j=0; j<NI; j++) { 11231 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 11232 if (DEBUG_SHOW_INFO) { 11233 Log.v(TAG, " IntentFilter:"); 11234 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11235 } 11236 removeFilter(intent); 11237 } 11238 } 11239 11240 @Override 11241 protected boolean allowFilterResult( 11242 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 11243 ActivityInfo filterAi = filter.activity.info; 11244 for (int i=dest.size()-1; i>=0; i--) { 11245 ActivityInfo destAi = dest.get(i).activityInfo; 11246 if (destAi.name == filterAi.name 11247 && destAi.packageName == filterAi.packageName) { 11248 return false; 11249 } 11250 } 11251 return true; 11252 } 11253 11254 @Override 11255 protected ActivityIntentInfo[] newArray(int size) { 11256 return new ActivityIntentInfo[size]; 11257 } 11258 11259 @Override 11260 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 11261 if (!sUserManager.exists(userId)) return true; 11262 PackageParser.Package p = filter.activity.owner; 11263 if (p != null) { 11264 PackageSetting ps = (PackageSetting)p.mExtras; 11265 if (ps != null) { 11266 // System apps are never considered stopped for purposes of 11267 // filtering, because there may be no way for the user to 11268 // actually re-launch them. 11269 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 11270 && ps.getStopped(userId); 11271 } 11272 } 11273 return false; 11274 } 11275 11276 @Override 11277 protected boolean isPackageForFilter(String packageName, 11278 PackageParser.ActivityIntentInfo info) { 11279 return packageName.equals(info.activity.owner.packageName); 11280 } 11281 11282 @Override 11283 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 11284 int match, int userId) { 11285 if (!sUserManager.exists(userId)) return null; 11286 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 11287 return null; 11288 } 11289 final PackageParser.Activity activity = info.activity; 11290 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 11291 if (ps == null) { 11292 return null; 11293 } 11294 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 11295 ps.readUserState(userId), userId); 11296 if (ai == null) { 11297 return null; 11298 } 11299 final ResolveInfo res = new ResolveInfo(); 11300 res.activityInfo = ai; 11301 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 11302 res.filter = info; 11303 } 11304 if (info != null) { 11305 res.handleAllWebDataURI = info.handleAllWebDataURI(); 11306 } 11307 res.priority = info.getPriority(); 11308 res.preferredOrder = activity.owner.mPreferredOrder; 11309 //System.out.println("Result: " + res.activityInfo.className + 11310 // " = " + res.priority); 11311 res.match = match; 11312 res.isDefault = info.hasDefault; 11313 res.labelRes = info.labelRes; 11314 res.nonLocalizedLabel = info.nonLocalizedLabel; 11315 if (userNeedsBadging(userId)) { 11316 res.noResourceId = true; 11317 } else { 11318 res.icon = info.icon; 11319 } 11320 res.iconResourceId = info.icon; 11321 res.system = res.activityInfo.applicationInfo.isSystemApp(); 11322 return res; 11323 } 11324 11325 @Override 11326 protected void sortResults(List<ResolveInfo> results) { 11327 Collections.sort(results, mResolvePrioritySorter); 11328 } 11329 11330 @Override 11331 protected void dumpFilter(PrintWriter out, String prefix, 11332 PackageParser.ActivityIntentInfo filter) { 11333 out.print(prefix); out.print( 11334 Integer.toHexString(System.identityHashCode(filter.activity))); 11335 out.print(' '); 11336 filter.activity.printComponentShortName(out); 11337 out.print(" filter "); 11338 out.println(Integer.toHexString(System.identityHashCode(filter))); 11339 } 11340 11341 @Override 11342 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 11343 return filter.activity; 11344 } 11345 11346 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11347 PackageParser.Activity activity = (PackageParser.Activity)label; 11348 out.print(prefix); out.print( 11349 Integer.toHexString(System.identityHashCode(activity))); 11350 out.print(' '); 11351 activity.printComponentShortName(out); 11352 if (count > 1) { 11353 out.print(" ("); out.print(count); out.print(" filters)"); 11354 } 11355 out.println(); 11356 } 11357 11358 // Keys are String (activity class name), values are Activity. 11359 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 11360 = new ArrayMap<ComponentName, PackageParser.Activity>(); 11361 private int mFlags; 11362 } 11363 11364 private final class ServiceIntentResolver 11365 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 11366 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 11367 boolean defaultOnly, boolean visibleToEphemeral, boolean isEphemeral, int userId) { 11368 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 11369 return super.queryIntent(intent, resolvedType, defaultOnly, visibleToEphemeral, 11370 isEphemeral, userId); 11371 } 11372 11373 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 11374 int userId) { 11375 if (!sUserManager.exists(userId)) return null; 11376 mFlags = flags; 11377 return super.queryIntent(intent, resolvedType, 11378 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 11379 (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0, 11380 (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId); 11381 } 11382 11383 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 11384 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 11385 if (!sUserManager.exists(userId)) return null; 11386 if (packageServices == null) { 11387 return null; 11388 } 11389 mFlags = flags; 11390 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 11391 final boolean vislbleToEphemeral = 11392 (flags&PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0; 11393 final boolean isEphemeral = (flags&PackageManager.MATCH_EPHEMERAL) != 0; 11394 final int N = packageServices.size(); 11395 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 11396 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 11397 11398 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 11399 for (int i = 0; i < N; ++i) { 11400 intentFilters = packageServices.get(i).intents; 11401 if (intentFilters != null && intentFilters.size() > 0) { 11402 PackageParser.ServiceIntentInfo[] array = 11403 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 11404 intentFilters.toArray(array); 11405 listCut.add(array); 11406 } 11407 } 11408 return super.queryIntentFromList(intent, resolvedType, defaultOnly, 11409 vislbleToEphemeral, isEphemeral, listCut, userId); 11410 } 11411 11412 public final void addService(PackageParser.Service s) { 11413 mServices.put(s.getComponentName(), s); 11414 if (DEBUG_SHOW_INFO) { 11415 Log.v(TAG, " " 11416 + (s.info.nonLocalizedLabel != null 11417 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 11418 Log.v(TAG, " Class=" + s.info.name); 11419 } 11420 final int NI = s.intents.size(); 11421 int j; 11422 for (j=0; j<NI; j++) { 11423 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 11424 if (DEBUG_SHOW_INFO) { 11425 Log.v(TAG, " IntentFilter:"); 11426 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11427 } 11428 if (!intent.debugCheck()) { 11429 Log.w(TAG, "==> For Service " + s.info.name); 11430 } 11431 addFilter(intent); 11432 } 11433 } 11434 11435 public final void removeService(PackageParser.Service s) { 11436 mServices.remove(s.getComponentName()); 11437 if (DEBUG_SHOW_INFO) { 11438 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 11439 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 11440 Log.v(TAG, " Class=" + s.info.name); 11441 } 11442 final int NI = s.intents.size(); 11443 int j; 11444 for (j=0; j<NI; j++) { 11445 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 11446 if (DEBUG_SHOW_INFO) { 11447 Log.v(TAG, " IntentFilter:"); 11448 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11449 } 11450 removeFilter(intent); 11451 } 11452 } 11453 11454 @Override 11455 protected boolean allowFilterResult( 11456 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 11457 ServiceInfo filterSi = filter.service.info; 11458 for (int i=dest.size()-1; i>=0; i--) { 11459 ServiceInfo destAi = dest.get(i).serviceInfo; 11460 if (destAi.name == filterSi.name 11461 && destAi.packageName == filterSi.packageName) { 11462 return false; 11463 } 11464 } 11465 return true; 11466 } 11467 11468 @Override 11469 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 11470 return new PackageParser.ServiceIntentInfo[size]; 11471 } 11472 11473 @Override 11474 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 11475 if (!sUserManager.exists(userId)) return true; 11476 PackageParser.Package p = filter.service.owner; 11477 if (p != null) { 11478 PackageSetting ps = (PackageSetting)p.mExtras; 11479 if (ps != null) { 11480 // System apps are never considered stopped for purposes of 11481 // filtering, because there may be no way for the user to 11482 // actually re-launch them. 11483 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 11484 && ps.getStopped(userId); 11485 } 11486 } 11487 return false; 11488 } 11489 11490 @Override 11491 protected boolean isPackageForFilter(String packageName, 11492 PackageParser.ServiceIntentInfo info) { 11493 return packageName.equals(info.service.owner.packageName); 11494 } 11495 11496 @Override 11497 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 11498 int match, int userId) { 11499 if (!sUserManager.exists(userId)) return null; 11500 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 11501 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 11502 return null; 11503 } 11504 final PackageParser.Service service = info.service; 11505 PackageSetting ps = (PackageSetting) service.owner.mExtras; 11506 if (ps == null) { 11507 return null; 11508 } 11509 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 11510 ps.readUserState(userId), userId); 11511 if (si == null) { 11512 return null; 11513 } 11514 final ResolveInfo res = new ResolveInfo(); 11515 res.serviceInfo = si; 11516 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 11517 res.filter = filter; 11518 } 11519 res.priority = info.getPriority(); 11520 res.preferredOrder = service.owner.mPreferredOrder; 11521 res.match = match; 11522 res.isDefault = info.hasDefault; 11523 res.labelRes = info.labelRes; 11524 res.nonLocalizedLabel = info.nonLocalizedLabel; 11525 res.icon = info.icon; 11526 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 11527 return res; 11528 } 11529 11530 @Override 11531 protected void sortResults(List<ResolveInfo> results) { 11532 Collections.sort(results, mResolvePrioritySorter); 11533 } 11534 11535 @Override 11536 protected void dumpFilter(PrintWriter out, String prefix, 11537 PackageParser.ServiceIntentInfo filter) { 11538 out.print(prefix); out.print( 11539 Integer.toHexString(System.identityHashCode(filter.service))); 11540 out.print(' '); 11541 filter.service.printComponentShortName(out); 11542 out.print(" filter "); 11543 out.println(Integer.toHexString(System.identityHashCode(filter))); 11544 } 11545 11546 @Override 11547 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 11548 return filter.service; 11549 } 11550 11551 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11552 PackageParser.Service service = (PackageParser.Service)label; 11553 out.print(prefix); out.print( 11554 Integer.toHexString(System.identityHashCode(service))); 11555 out.print(' '); 11556 service.printComponentShortName(out); 11557 if (count > 1) { 11558 out.print(" ("); out.print(count); out.print(" filters)"); 11559 } 11560 out.println(); 11561 } 11562 11563// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 11564// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 11565// final List<ResolveInfo> retList = Lists.newArrayList(); 11566// while (i.hasNext()) { 11567// final ResolveInfo resolveInfo = (ResolveInfo) i; 11568// if (isEnabledLP(resolveInfo.serviceInfo)) { 11569// retList.add(resolveInfo); 11570// } 11571// } 11572// return retList; 11573// } 11574 11575 // Keys are String (activity class name), values are Activity. 11576 private final ArrayMap<ComponentName, PackageParser.Service> mServices 11577 = new ArrayMap<ComponentName, PackageParser.Service>(); 11578 private int mFlags; 11579 } 11580 11581 private final class ProviderIntentResolver 11582 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 11583 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 11584 boolean defaultOnly, boolean visibleToEphemeral, boolean isEphemeral, int userId) { 11585 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 11586 return super.queryIntent(intent, resolvedType, defaultOnly, visibleToEphemeral, 11587 isEphemeral, userId); 11588 } 11589 11590 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 11591 int userId) { 11592 if (!sUserManager.exists(userId)) 11593 return null; 11594 mFlags = flags; 11595 return super.queryIntent(intent, resolvedType, 11596 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 11597 (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0, 11598 (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId); 11599 } 11600 11601 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 11602 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 11603 if (!sUserManager.exists(userId)) 11604 return null; 11605 if (packageProviders == null) { 11606 return null; 11607 } 11608 mFlags = flags; 11609 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 11610 final boolean isEphemeral = (flags&PackageManager.MATCH_EPHEMERAL) != 0; 11611 final boolean vislbleToEphemeral = 11612 (flags&PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0; 11613 final int N = packageProviders.size(); 11614 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 11615 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 11616 11617 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 11618 for (int i = 0; i < N; ++i) { 11619 intentFilters = packageProviders.get(i).intents; 11620 if (intentFilters != null && intentFilters.size() > 0) { 11621 PackageParser.ProviderIntentInfo[] array = 11622 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 11623 intentFilters.toArray(array); 11624 listCut.add(array); 11625 } 11626 } 11627 return super.queryIntentFromList(intent, resolvedType, defaultOnly, 11628 vislbleToEphemeral, isEphemeral, listCut, userId); 11629 } 11630 11631 public final void addProvider(PackageParser.Provider p) { 11632 if (mProviders.containsKey(p.getComponentName())) { 11633 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 11634 return; 11635 } 11636 11637 mProviders.put(p.getComponentName(), p); 11638 if (DEBUG_SHOW_INFO) { 11639 Log.v(TAG, " " 11640 + (p.info.nonLocalizedLabel != null 11641 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 11642 Log.v(TAG, " Class=" + p.info.name); 11643 } 11644 final int NI = p.intents.size(); 11645 int j; 11646 for (j = 0; j < NI; j++) { 11647 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11648 if (DEBUG_SHOW_INFO) { 11649 Log.v(TAG, " IntentFilter:"); 11650 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11651 } 11652 if (!intent.debugCheck()) { 11653 Log.w(TAG, "==> For Provider " + p.info.name); 11654 } 11655 addFilter(intent); 11656 } 11657 } 11658 11659 public final void removeProvider(PackageParser.Provider p) { 11660 mProviders.remove(p.getComponentName()); 11661 if (DEBUG_SHOW_INFO) { 11662 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 11663 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 11664 Log.v(TAG, " Class=" + p.info.name); 11665 } 11666 final int NI = p.intents.size(); 11667 int j; 11668 for (j = 0; j < NI; j++) { 11669 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11670 if (DEBUG_SHOW_INFO) { 11671 Log.v(TAG, " IntentFilter:"); 11672 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11673 } 11674 removeFilter(intent); 11675 } 11676 } 11677 11678 @Override 11679 protected boolean allowFilterResult( 11680 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 11681 ProviderInfo filterPi = filter.provider.info; 11682 for (int i = dest.size() - 1; i >= 0; i--) { 11683 ProviderInfo destPi = dest.get(i).providerInfo; 11684 if (destPi.name == filterPi.name 11685 && destPi.packageName == filterPi.packageName) { 11686 return false; 11687 } 11688 } 11689 return true; 11690 } 11691 11692 @Override 11693 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 11694 return new PackageParser.ProviderIntentInfo[size]; 11695 } 11696 11697 @Override 11698 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 11699 if (!sUserManager.exists(userId)) 11700 return true; 11701 PackageParser.Package p = filter.provider.owner; 11702 if (p != null) { 11703 PackageSetting ps = (PackageSetting) p.mExtras; 11704 if (ps != null) { 11705 // System apps are never considered stopped for purposes of 11706 // filtering, because there may be no way for the user to 11707 // actually re-launch them. 11708 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 11709 && ps.getStopped(userId); 11710 } 11711 } 11712 return false; 11713 } 11714 11715 @Override 11716 protected boolean isPackageForFilter(String packageName, 11717 PackageParser.ProviderIntentInfo info) { 11718 return packageName.equals(info.provider.owner.packageName); 11719 } 11720 11721 @Override 11722 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 11723 int match, int userId) { 11724 if (!sUserManager.exists(userId)) 11725 return null; 11726 final PackageParser.ProviderIntentInfo info = filter; 11727 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 11728 return null; 11729 } 11730 final PackageParser.Provider provider = info.provider; 11731 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 11732 if (ps == null) { 11733 return null; 11734 } 11735 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 11736 ps.readUserState(userId), userId); 11737 if (pi == null) { 11738 return null; 11739 } 11740 final ResolveInfo res = new ResolveInfo(); 11741 res.providerInfo = pi; 11742 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 11743 res.filter = filter; 11744 } 11745 res.priority = info.getPriority(); 11746 res.preferredOrder = provider.owner.mPreferredOrder; 11747 res.match = match; 11748 res.isDefault = info.hasDefault; 11749 res.labelRes = info.labelRes; 11750 res.nonLocalizedLabel = info.nonLocalizedLabel; 11751 res.icon = info.icon; 11752 res.system = res.providerInfo.applicationInfo.isSystemApp(); 11753 return res; 11754 } 11755 11756 @Override 11757 protected void sortResults(List<ResolveInfo> results) { 11758 Collections.sort(results, mResolvePrioritySorter); 11759 } 11760 11761 @Override 11762 protected void dumpFilter(PrintWriter out, String prefix, 11763 PackageParser.ProviderIntentInfo filter) { 11764 out.print(prefix); 11765 out.print( 11766 Integer.toHexString(System.identityHashCode(filter.provider))); 11767 out.print(' '); 11768 filter.provider.printComponentShortName(out); 11769 out.print(" filter "); 11770 out.println(Integer.toHexString(System.identityHashCode(filter))); 11771 } 11772 11773 @Override 11774 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 11775 return filter.provider; 11776 } 11777 11778 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11779 PackageParser.Provider provider = (PackageParser.Provider)label; 11780 out.print(prefix); out.print( 11781 Integer.toHexString(System.identityHashCode(provider))); 11782 out.print(' '); 11783 provider.printComponentShortName(out); 11784 if (count > 1) { 11785 out.print(" ("); out.print(count); out.print(" filters)"); 11786 } 11787 out.println(); 11788 } 11789 11790 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 11791 = new ArrayMap<ComponentName, PackageParser.Provider>(); 11792 private int mFlags; 11793 } 11794 11795 static final class EphemeralIntentResolver 11796 extends IntentResolver<EphemeralResponse, EphemeralResponse> { 11797 /** 11798 * The result that has the highest defined order. Ordering applies on a 11799 * per-package basis. Mapping is from package name to Pair of order and 11800 * EphemeralResolveInfo. 11801 * <p> 11802 * NOTE: This is implemented as a field variable for convenience and efficiency. 11803 * By having a field variable, we're able to track filter ordering as soon as 11804 * a non-zero order is defined. Otherwise, multiple loops across the result set 11805 * would be needed to apply ordering. If the intent resolver becomes re-entrant, 11806 * this needs to be contained entirely within {@link #filterResults()}. 11807 */ 11808 final ArrayMap<String, Pair<Integer, EphemeralResolveInfo>> mOrderResult = new ArrayMap<>(); 11809 11810 @Override 11811 protected EphemeralResponse[] newArray(int size) { 11812 return new EphemeralResponse[size]; 11813 } 11814 11815 @Override 11816 protected boolean isPackageForFilter(String packageName, EphemeralResponse responseObj) { 11817 return true; 11818 } 11819 11820 @Override 11821 protected EphemeralResponse newResult(EphemeralResponse responseObj, int match, 11822 int userId) { 11823 if (!sUserManager.exists(userId)) { 11824 return null; 11825 } 11826 final String packageName = responseObj.resolveInfo.getPackageName(); 11827 final Integer order = responseObj.getOrder(); 11828 final Pair<Integer, EphemeralResolveInfo> lastOrderResult = 11829 mOrderResult.get(packageName); 11830 // ordering is enabled and this item's order isn't high enough 11831 if (lastOrderResult != null && lastOrderResult.first >= order) { 11832 return null; 11833 } 11834 final EphemeralResolveInfo res = responseObj.resolveInfo; 11835 if (order > 0) { 11836 // non-zero order, enable ordering 11837 mOrderResult.put(packageName, new Pair<>(order, res)); 11838 } 11839 return responseObj; 11840 } 11841 11842 @Override 11843 protected void filterResults(List<EphemeralResponse> results) { 11844 // only do work if ordering is enabled [most of the time it won't be] 11845 if (mOrderResult.size() == 0) { 11846 return; 11847 } 11848 int resultSize = results.size(); 11849 for (int i = 0; i < resultSize; i++) { 11850 final EphemeralResolveInfo info = results.get(i).resolveInfo; 11851 final String packageName = info.getPackageName(); 11852 final Pair<Integer, EphemeralResolveInfo> savedInfo = mOrderResult.get(packageName); 11853 if (savedInfo == null) { 11854 // package doesn't having ordering 11855 continue; 11856 } 11857 if (savedInfo.second == info) { 11858 // circled back to the highest ordered item; remove from order list 11859 mOrderResult.remove(savedInfo); 11860 if (mOrderResult.size() == 0) { 11861 // no more ordered items 11862 break; 11863 } 11864 continue; 11865 } 11866 // item has a worse order, remove it from the result list 11867 results.remove(i); 11868 resultSize--; 11869 i--; 11870 } 11871 } 11872 } 11873 11874 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 11875 new Comparator<ResolveInfo>() { 11876 public int compare(ResolveInfo r1, ResolveInfo r2) { 11877 int v1 = r1.priority; 11878 int v2 = r2.priority; 11879 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 11880 if (v1 != v2) { 11881 return (v1 > v2) ? -1 : 1; 11882 } 11883 v1 = r1.preferredOrder; 11884 v2 = r2.preferredOrder; 11885 if (v1 != v2) { 11886 return (v1 > v2) ? -1 : 1; 11887 } 11888 if (r1.isDefault != r2.isDefault) { 11889 return r1.isDefault ? -1 : 1; 11890 } 11891 v1 = r1.match; 11892 v2 = r2.match; 11893 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 11894 if (v1 != v2) { 11895 return (v1 > v2) ? -1 : 1; 11896 } 11897 if (r1.system != r2.system) { 11898 return r1.system ? -1 : 1; 11899 } 11900 if (r1.activityInfo != null) { 11901 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 11902 } 11903 if (r1.serviceInfo != null) { 11904 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 11905 } 11906 if (r1.providerInfo != null) { 11907 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 11908 } 11909 return 0; 11910 } 11911 }; 11912 11913 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 11914 new Comparator<ProviderInfo>() { 11915 public int compare(ProviderInfo p1, ProviderInfo p2) { 11916 final int v1 = p1.initOrder; 11917 final int v2 = p2.initOrder; 11918 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 11919 } 11920 }; 11921 11922 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 11923 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 11924 final int[] userIds) { 11925 mHandler.post(new Runnable() { 11926 @Override 11927 public void run() { 11928 try { 11929 final IActivityManager am = ActivityManager.getService(); 11930 if (am == null) return; 11931 final int[] resolvedUserIds; 11932 if (userIds == null) { 11933 resolvedUserIds = am.getRunningUserIds(); 11934 } else { 11935 resolvedUserIds = userIds; 11936 } 11937 for (int id : resolvedUserIds) { 11938 final Intent intent = new Intent(action, 11939 pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null); 11940 if (extras != null) { 11941 intent.putExtras(extras); 11942 } 11943 if (targetPkg != null) { 11944 intent.setPackage(targetPkg); 11945 } 11946 // Modify the UID when posting to other users 11947 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 11948 if (uid > 0 && UserHandle.getUserId(uid) != id) { 11949 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 11950 intent.putExtra(Intent.EXTRA_UID, uid); 11951 } 11952 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 11953 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 11954 if (DEBUG_BROADCASTS) { 11955 RuntimeException here = new RuntimeException("here"); 11956 here.fillInStackTrace(); 11957 Slog.d(TAG, "Sending to user " + id + ": " 11958 + intent.toShortString(false, true, false, false) 11959 + " " + intent.getExtras(), here); 11960 } 11961 am.broadcastIntent(null, intent, null, finishedReceiver, 11962 0, null, null, null, android.app.AppOpsManager.OP_NONE, 11963 null, finishedReceiver != null, false, id); 11964 } 11965 } catch (RemoteException ex) { 11966 } 11967 } 11968 }); 11969 } 11970 11971 /** 11972 * Check if the external storage media is available. This is true if there 11973 * is a mounted external storage medium or if the external storage is 11974 * emulated. 11975 */ 11976 private boolean isExternalMediaAvailable() { 11977 return mMediaMounted || Environment.isExternalStorageEmulated(); 11978 } 11979 11980 @Override 11981 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 11982 // writer 11983 synchronized (mPackages) { 11984 if (!isExternalMediaAvailable()) { 11985 // If the external storage is no longer mounted at this point, 11986 // the caller may not have been able to delete all of this 11987 // packages files and can not delete any more. Bail. 11988 return null; 11989 } 11990 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 11991 if (lastPackage != null) { 11992 pkgs.remove(lastPackage); 11993 } 11994 if (pkgs.size() > 0) { 11995 return pkgs.get(0); 11996 } 11997 } 11998 return null; 11999 } 12000 12001 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 12002 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 12003 userId, andCode ? 1 : 0, packageName); 12004 if (mSystemReady) { 12005 msg.sendToTarget(); 12006 } else { 12007 if (mPostSystemReadyMessages == null) { 12008 mPostSystemReadyMessages = new ArrayList<>(); 12009 } 12010 mPostSystemReadyMessages.add(msg); 12011 } 12012 } 12013 12014 void startCleaningPackages() { 12015 // reader 12016 if (!isExternalMediaAvailable()) { 12017 return; 12018 } 12019 synchronized (mPackages) { 12020 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 12021 return; 12022 } 12023 } 12024 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 12025 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 12026 IActivityManager am = ActivityManager.getService(); 12027 if (am != null) { 12028 try { 12029 am.startService(null, intent, null, mContext.getOpPackageName(), 12030 UserHandle.USER_SYSTEM); 12031 } catch (RemoteException e) { 12032 } 12033 } 12034 } 12035 12036 @Override 12037 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 12038 int installFlags, String installerPackageName, int userId) { 12039 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 12040 12041 final int callingUid = Binder.getCallingUid(); 12042 enforceCrossUserPermission(callingUid, userId, 12043 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 12044 12045 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 12046 try { 12047 if (observer != null) { 12048 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 12049 } 12050 } catch (RemoteException re) { 12051 } 12052 return; 12053 } 12054 12055 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 12056 installFlags |= PackageManager.INSTALL_FROM_ADB; 12057 12058 } else { 12059 // Caller holds INSTALL_PACKAGES permission, so we're less strict 12060 // about installerPackageName. 12061 12062 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 12063 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 12064 } 12065 12066 UserHandle user; 12067 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 12068 user = UserHandle.ALL; 12069 } else { 12070 user = new UserHandle(userId); 12071 } 12072 12073 // Only system components can circumvent runtime permissions when installing. 12074 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 12075 && mContext.checkCallingOrSelfPermission(Manifest.permission 12076 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 12077 throw new SecurityException("You need the " 12078 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 12079 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 12080 } 12081 12082 final File originFile = new File(originPath); 12083 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 12084 12085 final Message msg = mHandler.obtainMessage(INIT_COPY); 12086 final VerificationInfo verificationInfo = new VerificationInfo( 12087 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 12088 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 12089 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 12090 null /*packageAbiOverride*/, null /*grantedPermissions*/, 12091 null /*certificates*/); 12092 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 12093 msg.obj = params; 12094 12095 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 12096 System.identityHashCode(msg.obj)); 12097 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 12098 System.identityHashCode(msg.obj)); 12099 12100 mHandler.sendMessage(msg); 12101 } 12102 12103 void installStage(String packageName, File stagedDir, String stagedCid, 12104 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 12105 String installerPackageName, int installerUid, UserHandle user, 12106 Certificate[][] certificates) { 12107 if (DEBUG_EPHEMERAL) { 12108 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 12109 Slog.d(TAG, "Ephemeral install of " + packageName); 12110 } 12111 } 12112 final VerificationInfo verificationInfo = new VerificationInfo( 12113 sessionParams.originatingUri, sessionParams.referrerUri, 12114 sessionParams.originatingUid, installerUid); 12115 12116 final OriginInfo origin; 12117 if (stagedDir != null) { 12118 origin = OriginInfo.fromStagedFile(stagedDir); 12119 } else { 12120 origin = OriginInfo.fromStagedContainer(stagedCid); 12121 } 12122 12123 final Message msg = mHandler.obtainMessage(INIT_COPY); 12124 final InstallParams params = new InstallParams(origin, null, observer, 12125 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 12126 verificationInfo, user, sessionParams.abiOverride, 12127 sessionParams.grantedRuntimePermissions, certificates); 12128 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 12129 msg.obj = params; 12130 12131 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 12132 System.identityHashCode(msg.obj)); 12133 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 12134 System.identityHashCode(msg.obj)); 12135 12136 mHandler.sendMessage(msg); 12137 } 12138 12139 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 12140 int userId) { 12141 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 12142 sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId); 12143 } 12144 12145 private void sendPackageAddedForNewUsers(String packageName, boolean isSystem, 12146 int appId, int... userIds) { 12147 if (ArrayUtils.isEmpty(userIds)) { 12148 return; 12149 } 12150 Bundle extras = new Bundle(1); 12151 // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast 12152 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId)); 12153 12154 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 12155 packageName, extras, 0, null, null, userIds); 12156 if (isSystem) { 12157 mHandler.post(() -> { 12158 for (int userId : userIds) { 12159 sendBootCompletedBroadcastToSystemApp(packageName, userId); 12160 } 12161 } 12162 ); 12163 } 12164 } 12165 12166 /** 12167 * The just-installed/enabled app is bundled on the system, so presumed to be able to run 12168 * automatically without needing an explicit launch. 12169 * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones. 12170 */ 12171 private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) { 12172 // If user is not running, the app didn't miss any broadcast 12173 if (!mUserManagerInternal.isUserRunning(userId)) { 12174 return; 12175 } 12176 final IActivityManager am = ActivityManager.getService(); 12177 try { 12178 // Deliver LOCKED_BOOT_COMPLETED first 12179 Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED) 12180 .setPackage(packageName); 12181 final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED}; 12182 am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions, 12183 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 12184 12185 // Deliver BOOT_COMPLETED only if user is unlocked 12186 if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) { 12187 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName); 12188 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions, 12189 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 12190 } 12191 } catch (RemoteException e) { 12192 throw e.rethrowFromSystemServer(); 12193 } 12194 } 12195 12196 @Override 12197 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 12198 int userId) { 12199 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 12200 PackageSetting pkgSetting; 12201 final int uid = Binder.getCallingUid(); 12202 enforceCrossUserPermission(uid, userId, 12203 true /* requireFullPermission */, true /* checkShell */, 12204 "setApplicationHiddenSetting for user " + userId); 12205 12206 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 12207 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 12208 return false; 12209 } 12210 12211 long callingId = Binder.clearCallingIdentity(); 12212 try { 12213 boolean sendAdded = false; 12214 boolean sendRemoved = false; 12215 // writer 12216 synchronized (mPackages) { 12217 pkgSetting = mSettings.mPackages.get(packageName); 12218 if (pkgSetting == null) { 12219 return false; 12220 } 12221 // Do not allow "android" is being disabled 12222 if ("android".equals(packageName)) { 12223 Slog.w(TAG, "Cannot hide package: android"); 12224 return false; 12225 } 12226 // Only allow protected packages to hide themselves. 12227 if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId) 12228 && mProtectedPackages.isPackageStateProtected(userId, packageName)) { 12229 Slog.w(TAG, "Not hiding protected package: " + packageName); 12230 return false; 12231 } 12232 12233 if (pkgSetting.getHidden(userId) != hidden) { 12234 pkgSetting.setHidden(hidden, userId); 12235 mSettings.writePackageRestrictionsLPr(userId); 12236 if (hidden) { 12237 sendRemoved = true; 12238 } else { 12239 sendAdded = true; 12240 } 12241 } 12242 } 12243 if (sendAdded) { 12244 sendPackageAddedForUser(packageName, pkgSetting, userId); 12245 return true; 12246 } 12247 if (sendRemoved) { 12248 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 12249 "hiding pkg"); 12250 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 12251 return true; 12252 } 12253 } finally { 12254 Binder.restoreCallingIdentity(callingId); 12255 } 12256 return false; 12257 } 12258 12259 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 12260 int userId) { 12261 final PackageRemovedInfo info = new PackageRemovedInfo(); 12262 info.removedPackage = packageName; 12263 info.removedUsers = new int[] {userId}; 12264 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 12265 info.sendPackageRemovedBroadcasts(true /*killApp*/); 12266 } 12267 12268 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 12269 if (pkgList.length > 0) { 12270 Bundle extras = new Bundle(1); 12271 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 12272 12273 sendPackageBroadcast( 12274 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 12275 : Intent.ACTION_PACKAGES_UNSUSPENDED, 12276 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 12277 new int[] {userId}); 12278 } 12279 } 12280 12281 /** 12282 * Returns true if application is not found or there was an error. Otherwise it returns 12283 * the hidden state of the package for the given user. 12284 */ 12285 @Override 12286 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 12287 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 12288 enforceCrossUserPermission(Binder.getCallingUid(), userId, 12289 true /* requireFullPermission */, false /* checkShell */, 12290 "getApplicationHidden for user " + userId); 12291 PackageSetting pkgSetting; 12292 long callingId = Binder.clearCallingIdentity(); 12293 try { 12294 // writer 12295 synchronized (mPackages) { 12296 pkgSetting = mSettings.mPackages.get(packageName); 12297 if (pkgSetting == null) { 12298 return true; 12299 } 12300 return pkgSetting.getHidden(userId); 12301 } 12302 } finally { 12303 Binder.restoreCallingIdentity(callingId); 12304 } 12305 } 12306 12307 /** 12308 * @hide 12309 */ 12310 @Override 12311 public int installExistingPackageAsUser(String packageName, int userId) { 12312 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 12313 null); 12314 PackageSetting pkgSetting; 12315 final int uid = Binder.getCallingUid(); 12316 enforceCrossUserPermission(uid, userId, 12317 true /* requireFullPermission */, true /* checkShell */, 12318 "installExistingPackage for user " + userId); 12319 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 12320 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 12321 } 12322 12323 long callingId = Binder.clearCallingIdentity(); 12324 try { 12325 boolean installed = false; 12326 12327 // writer 12328 synchronized (mPackages) { 12329 pkgSetting = mSettings.mPackages.get(packageName); 12330 if (pkgSetting == null) { 12331 return PackageManager.INSTALL_FAILED_INVALID_URI; 12332 } 12333 if (!pkgSetting.getInstalled(userId)) { 12334 pkgSetting.setInstalled(true, userId); 12335 pkgSetting.setHidden(false, userId); 12336 mSettings.writePackageRestrictionsLPr(userId); 12337 installed = true; 12338 } 12339 } 12340 12341 if (installed) { 12342 if (pkgSetting.pkg != null) { 12343 synchronized (mInstallLock) { 12344 // We don't need to freeze for a brand new install 12345 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 12346 } 12347 } 12348 sendPackageAddedForUser(packageName, pkgSetting, userId); 12349 } 12350 } finally { 12351 Binder.restoreCallingIdentity(callingId); 12352 } 12353 12354 return PackageManager.INSTALL_SUCCEEDED; 12355 } 12356 12357 boolean isUserRestricted(int userId, String restrictionKey) { 12358 Bundle restrictions = sUserManager.getUserRestrictions(userId); 12359 if (restrictions.getBoolean(restrictionKey, false)) { 12360 Log.w(TAG, "User is restricted: " + restrictionKey); 12361 return true; 12362 } 12363 return false; 12364 } 12365 12366 @Override 12367 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 12368 int userId) { 12369 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 12370 enforceCrossUserPermission(Binder.getCallingUid(), userId, 12371 true /* requireFullPermission */, true /* checkShell */, 12372 "setPackagesSuspended for user " + userId); 12373 12374 if (ArrayUtils.isEmpty(packageNames)) { 12375 return packageNames; 12376 } 12377 12378 // List of package names for whom the suspended state has changed. 12379 List<String> changedPackages = new ArrayList<>(packageNames.length); 12380 // List of package names for whom the suspended state is not set as requested in this 12381 // method. 12382 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 12383 long callingId = Binder.clearCallingIdentity(); 12384 try { 12385 for (int i = 0; i < packageNames.length; i++) { 12386 String packageName = packageNames[i]; 12387 boolean changed = false; 12388 final int appId; 12389 synchronized (mPackages) { 12390 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 12391 if (pkgSetting == null) { 12392 Slog.w(TAG, "Could not find package setting for package \"" + packageName 12393 + "\". Skipping suspending/un-suspending."); 12394 unactionedPackages.add(packageName); 12395 continue; 12396 } 12397 appId = pkgSetting.appId; 12398 if (pkgSetting.getSuspended(userId) != suspended) { 12399 if (!canSuspendPackageForUserLocked(packageName, userId)) { 12400 unactionedPackages.add(packageName); 12401 continue; 12402 } 12403 pkgSetting.setSuspended(suspended, userId); 12404 mSettings.writePackageRestrictionsLPr(userId); 12405 changed = true; 12406 changedPackages.add(packageName); 12407 } 12408 } 12409 12410 if (changed && suspended) { 12411 killApplication(packageName, UserHandle.getUid(userId, appId), 12412 "suspending package"); 12413 } 12414 } 12415 } finally { 12416 Binder.restoreCallingIdentity(callingId); 12417 } 12418 12419 if (!changedPackages.isEmpty()) { 12420 sendPackagesSuspendedForUser(changedPackages.toArray( 12421 new String[changedPackages.size()]), userId, suspended); 12422 } 12423 12424 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 12425 } 12426 12427 @Override 12428 public boolean isPackageSuspendedForUser(String packageName, int userId) { 12429 enforceCrossUserPermission(Binder.getCallingUid(), userId, 12430 true /* requireFullPermission */, false /* checkShell */, 12431 "isPackageSuspendedForUser for user " + userId); 12432 synchronized (mPackages) { 12433 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 12434 if (pkgSetting == null) { 12435 throw new IllegalArgumentException("Unknown target package: " + packageName); 12436 } 12437 return pkgSetting.getSuspended(userId); 12438 } 12439 } 12440 12441 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 12442 if (isPackageDeviceAdmin(packageName, userId)) { 12443 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12444 + "\": has an active device admin"); 12445 return false; 12446 } 12447 12448 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 12449 if (packageName.equals(activeLauncherPackageName)) { 12450 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12451 + "\": contains the active launcher"); 12452 return false; 12453 } 12454 12455 if (packageName.equals(mRequiredInstallerPackage)) { 12456 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12457 + "\": required for package installation"); 12458 return false; 12459 } 12460 12461 if (packageName.equals(mRequiredUninstallerPackage)) { 12462 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12463 + "\": required for package uninstallation"); 12464 return false; 12465 } 12466 12467 if (packageName.equals(mRequiredVerifierPackage)) { 12468 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12469 + "\": required for package verification"); 12470 return false; 12471 } 12472 12473 if (packageName.equals(getDefaultDialerPackageName(userId))) { 12474 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12475 + "\": is the default dialer"); 12476 return false; 12477 } 12478 12479 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 12480 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12481 + "\": protected package"); 12482 return false; 12483 } 12484 12485 return true; 12486 } 12487 12488 private String getActiveLauncherPackageName(int userId) { 12489 Intent intent = new Intent(Intent.ACTION_MAIN); 12490 intent.addCategory(Intent.CATEGORY_HOME); 12491 ResolveInfo resolveInfo = resolveIntent( 12492 intent, 12493 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 12494 PackageManager.MATCH_DEFAULT_ONLY, 12495 userId); 12496 12497 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 12498 } 12499 12500 private String getDefaultDialerPackageName(int userId) { 12501 synchronized (mPackages) { 12502 return mSettings.getDefaultDialerPackageNameLPw(userId); 12503 } 12504 } 12505 12506 @Override 12507 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 12508 mContext.enforceCallingOrSelfPermission( 12509 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12510 "Only package verification agents can verify applications"); 12511 12512 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 12513 final PackageVerificationResponse response = new PackageVerificationResponse( 12514 verificationCode, Binder.getCallingUid()); 12515 msg.arg1 = id; 12516 msg.obj = response; 12517 mHandler.sendMessage(msg); 12518 } 12519 12520 @Override 12521 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 12522 long millisecondsToDelay) { 12523 mContext.enforceCallingOrSelfPermission( 12524 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12525 "Only package verification agents can extend verification timeouts"); 12526 12527 final PackageVerificationState state = mPendingVerification.get(id); 12528 final PackageVerificationResponse response = new PackageVerificationResponse( 12529 verificationCodeAtTimeout, Binder.getCallingUid()); 12530 12531 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 12532 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 12533 } 12534 if (millisecondsToDelay < 0) { 12535 millisecondsToDelay = 0; 12536 } 12537 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 12538 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 12539 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 12540 } 12541 12542 if ((state != null) && !state.timeoutExtended()) { 12543 state.extendTimeout(); 12544 12545 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 12546 msg.arg1 = id; 12547 msg.obj = response; 12548 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 12549 } 12550 } 12551 12552 private void broadcastPackageVerified(int verificationId, Uri packageUri, 12553 int verificationCode, UserHandle user) { 12554 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 12555 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 12556 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 12557 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 12558 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 12559 12560 mContext.sendBroadcastAsUser(intent, user, 12561 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 12562 } 12563 12564 private ComponentName matchComponentForVerifier(String packageName, 12565 List<ResolveInfo> receivers) { 12566 ActivityInfo targetReceiver = null; 12567 12568 final int NR = receivers.size(); 12569 for (int i = 0; i < NR; i++) { 12570 final ResolveInfo info = receivers.get(i); 12571 if (info.activityInfo == null) { 12572 continue; 12573 } 12574 12575 if (packageName.equals(info.activityInfo.packageName)) { 12576 targetReceiver = info.activityInfo; 12577 break; 12578 } 12579 } 12580 12581 if (targetReceiver == null) { 12582 return null; 12583 } 12584 12585 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 12586 } 12587 12588 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 12589 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 12590 if (pkgInfo.verifiers.length == 0) { 12591 return null; 12592 } 12593 12594 final int N = pkgInfo.verifiers.length; 12595 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 12596 for (int i = 0; i < N; i++) { 12597 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 12598 12599 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 12600 receivers); 12601 if (comp == null) { 12602 continue; 12603 } 12604 12605 final int verifierUid = getUidForVerifier(verifierInfo); 12606 if (verifierUid == -1) { 12607 continue; 12608 } 12609 12610 if (DEBUG_VERIFY) { 12611 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 12612 + " with the correct signature"); 12613 } 12614 sufficientVerifiers.add(comp); 12615 verificationState.addSufficientVerifier(verifierUid); 12616 } 12617 12618 return sufficientVerifiers; 12619 } 12620 12621 private int getUidForVerifier(VerifierInfo verifierInfo) { 12622 synchronized (mPackages) { 12623 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 12624 if (pkg == null) { 12625 return -1; 12626 } else if (pkg.mSignatures.length != 1) { 12627 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 12628 + " has more than one signature; ignoring"); 12629 return -1; 12630 } 12631 12632 /* 12633 * If the public key of the package's signature does not match 12634 * our expected public key, then this is a different package and 12635 * we should skip. 12636 */ 12637 12638 final byte[] expectedPublicKey; 12639 try { 12640 final Signature verifierSig = pkg.mSignatures[0]; 12641 final PublicKey publicKey = verifierSig.getPublicKey(); 12642 expectedPublicKey = publicKey.getEncoded(); 12643 } catch (CertificateException e) { 12644 return -1; 12645 } 12646 12647 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 12648 12649 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 12650 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 12651 + " does not have the expected public key; ignoring"); 12652 return -1; 12653 } 12654 12655 return pkg.applicationInfo.uid; 12656 } 12657 } 12658 12659 @Override 12660 public void finishPackageInstall(int token, boolean didLaunch) { 12661 enforceSystemOrRoot("Only the system is allowed to finish installs"); 12662 12663 if (DEBUG_INSTALL) { 12664 Slog.v(TAG, "BM finishing package install for " + token); 12665 } 12666 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12667 12668 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 12669 mHandler.sendMessage(msg); 12670 } 12671 12672 /** 12673 * Get the verification agent timeout. 12674 * 12675 * @return verification timeout in milliseconds 12676 */ 12677 private long getVerificationTimeout() { 12678 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 12679 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 12680 DEFAULT_VERIFICATION_TIMEOUT); 12681 } 12682 12683 /** 12684 * Get the default verification agent response code. 12685 * 12686 * @return default verification response code 12687 */ 12688 private int getDefaultVerificationResponse() { 12689 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12690 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 12691 DEFAULT_VERIFICATION_RESPONSE); 12692 } 12693 12694 /** 12695 * Check whether or not package verification has been enabled. 12696 * 12697 * @return true if verification should be performed 12698 */ 12699 private boolean isVerificationEnabled(int userId, int installFlags) { 12700 if (!DEFAULT_VERIFY_ENABLE) { 12701 return false; 12702 } 12703 // Ephemeral apps don't get the full verification treatment 12704 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 12705 if (DEBUG_EPHEMERAL) { 12706 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 12707 } 12708 return false; 12709 } 12710 12711 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 12712 12713 // Check if installing from ADB 12714 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 12715 // Do not run verification in a test harness environment 12716 if (ActivityManager.isRunningInTestHarness()) { 12717 return false; 12718 } 12719 if (ensureVerifyAppsEnabled) { 12720 return true; 12721 } 12722 // Check if the developer does not want package verification for ADB installs 12723 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12724 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 12725 return false; 12726 } 12727 } 12728 12729 if (ensureVerifyAppsEnabled) { 12730 return true; 12731 } 12732 12733 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12734 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 12735 } 12736 12737 @Override 12738 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 12739 throws RemoteException { 12740 mContext.enforceCallingOrSelfPermission( 12741 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 12742 "Only intentfilter verification agents can verify applications"); 12743 12744 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 12745 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 12746 Binder.getCallingUid(), verificationCode, failedDomains); 12747 msg.arg1 = id; 12748 msg.obj = response; 12749 mHandler.sendMessage(msg); 12750 } 12751 12752 @Override 12753 public int getIntentVerificationStatus(String packageName, int userId) { 12754 synchronized (mPackages) { 12755 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 12756 } 12757 } 12758 12759 @Override 12760 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 12761 mContext.enforceCallingOrSelfPermission( 12762 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12763 12764 boolean result = false; 12765 synchronized (mPackages) { 12766 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 12767 } 12768 if (result) { 12769 scheduleWritePackageRestrictionsLocked(userId); 12770 } 12771 return result; 12772 } 12773 12774 @Override 12775 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 12776 String packageName) { 12777 synchronized (mPackages) { 12778 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 12779 } 12780 } 12781 12782 @Override 12783 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 12784 if (TextUtils.isEmpty(packageName)) { 12785 return ParceledListSlice.emptyList(); 12786 } 12787 synchronized (mPackages) { 12788 PackageParser.Package pkg = mPackages.get(packageName); 12789 if (pkg == null || pkg.activities == null) { 12790 return ParceledListSlice.emptyList(); 12791 } 12792 final int count = pkg.activities.size(); 12793 ArrayList<IntentFilter> result = new ArrayList<>(); 12794 for (int n=0; n<count; n++) { 12795 PackageParser.Activity activity = pkg.activities.get(n); 12796 if (activity.intents != null && activity.intents.size() > 0) { 12797 result.addAll(activity.intents); 12798 } 12799 } 12800 return new ParceledListSlice<>(result); 12801 } 12802 } 12803 12804 @Override 12805 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 12806 mContext.enforceCallingOrSelfPermission( 12807 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12808 12809 synchronized (mPackages) { 12810 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 12811 if (packageName != null) { 12812 result |= updateIntentVerificationStatus(packageName, 12813 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 12814 userId); 12815 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 12816 packageName, userId); 12817 } 12818 return result; 12819 } 12820 } 12821 12822 @Override 12823 public String getDefaultBrowserPackageName(int userId) { 12824 synchronized (mPackages) { 12825 return mSettings.getDefaultBrowserPackageNameLPw(userId); 12826 } 12827 } 12828 12829 /** 12830 * Get the "allow unknown sources" setting. 12831 * 12832 * @return the current "allow unknown sources" setting 12833 */ 12834 private int getUnknownSourcesSettings() { 12835 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 12836 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 12837 -1); 12838 } 12839 12840 @Override 12841 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 12842 final int uid = Binder.getCallingUid(); 12843 // writer 12844 synchronized (mPackages) { 12845 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 12846 if (targetPackageSetting == null) { 12847 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 12848 } 12849 12850 PackageSetting installerPackageSetting; 12851 if (installerPackageName != null) { 12852 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 12853 if (installerPackageSetting == null) { 12854 throw new IllegalArgumentException("Unknown installer package: " 12855 + installerPackageName); 12856 } 12857 } else { 12858 installerPackageSetting = null; 12859 } 12860 12861 Signature[] callerSignature; 12862 Object obj = mSettings.getUserIdLPr(uid); 12863 if (obj != null) { 12864 if (obj instanceof SharedUserSetting) { 12865 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 12866 } else if (obj instanceof PackageSetting) { 12867 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 12868 } else { 12869 throw new SecurityException("Bad object " + obj + " for uid " + uid); 12870 } 12871 } else { 12872 throw new SecurityException("Unknown calling UID: " + uid); 12873 } 12874 12875 // Verify: can't set installerPackageName to a package that is 12876 // not signed with the same cert as the caller. 12877 if (installerPackageSetting != null) { 12878 if (compareSignatures(callerSignature, 12879 installerPackageSetting.signatures.mSignatures) 12880 != PackageManager.SIGNATURE_MATCH) { 12881 throw new SecurityException( 12882 "Caller does not have same cert as new installer package " 12883 + installerPackageName); 12884 } 12885 } 12886 12887 // Verify: if target already has an installer package, it must 12888 // be signed with the same cert as the caller. 12889 if (targetPackageSetting.installerPackageName != null) { 12890 PackageSetting setting = mSettings.mPackages.get( 12891 targetPackageSetting.installerPackageName); 12892 // If the currently set package isn't valid, then it's always 12893 // okay to change it. 12894 if (setting != null) { 12895 if (compareSignatures(callerSignature, 12896 setting.signatures.mSignatures) 12897 != PackageManager.SIGNATURE_MATCH) { 12898 throw new SecurityException( 12899 "Caller does not have same cert as old installer package " 12900 + targetPackageSetting.installerPackageName); 12901 } 12902 } 12903 } 12904 12905 // Okay! 12906 targetPackageSetting.installerPackageName = installerPackageName; 12907 if (installerPackageName != null) { 12908 mSettings.mInstallerPackages.add(installerPackageName); 12909 } 12910 scheduleWriteSettingsLocked(); 12911 } 12912 } 12913 12914 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 12915 // Queue up an async operation since the package installation may take a little while. 12916 mHandler.post(new Runnable() { 12917 public void run() { 12918 mHandler.removeCallbacks(this); 12919 // Result object to be returned 12920 PackageInstalledInfo res = new PackageInstalledInfo(); 12921 res.setReturnCode(currentStatus); 12922 res.uid = -1; 12923 res.pkg = null; 12924 res.removedInfo = null; 12925 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12926 args.doPreInstall(res.returnCode); 12927 synchronized (mInstallLock) { 12928 installPackageTracedLI(args, res); 12929 } 12930 args.doPostInstall(res.returnCode, res.uid); 12931 } 12932 12933 // A restore should be performed at this point if (a) the install 12934 // succeeded, (b) the operation is not an update, and (c) the new 12935 // package has not opted out of backup participation. 12936 final boolean update = res.removedInfo != null 12937 && res.removedInfo.removedPackage != null; 12938 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 12939 boolean doRestore = !update 12940 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 12941 12942 // Set up the post-install work request bookkeeping. This will be used 12943 // and cleaned up by the post-install event handling regardless of whether 12944 // there's a restore pass performed. Token values are >= 1. 12945 int token; 12946 if (mNextInstallToken < 0) mNextInstallToken = 1; 12947 token = mNextInstallToken++; 12948 12949 PostInstallData data = new PostInstallData(args, res); 12950 mRunningInstalls.put(token, data); 12951 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 12952 12953 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 12954 // Pass responsibility to the Backup Manager. It will perform a 12955 // restore if appropriate, then pass responsibility back to the 12956 // Package Manager to run the post-install observer callbacks 12957 // and broadcasts. 12958 IBackupManager bm = IBackupManager.Stub.asInterface( 12959 ServiceManager.getService(Context.BACKUP_SERVICE)); 12960 if (bm != null) { 12961 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 12962 + " to BM for possible restore"); 12963 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12964 try { 12965 // TODO: http://b/22388012 12966 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 12967 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 12968 } else { 12969 doRestore = false; 12970 } 12971 } catch (RemoteException e) { 12972 // can't happen; the backup manager is local 12973 } catch (Exception e) { 12974 Slog.e(TAG, "Exception trying to enqueue restore", e); 12975 doRestore = false; 12976 } 12977 } else { 12978 Slog.e(TAG, "Backup Manager not found!"); 12979 doRestore = false; 12980 } 12981 } 12982 12983 if (!doRestore) { 12984 // No restore possible, or the Backup Manager was mysteriously not 12985 // available -- just fire the post-install work request directly. 12986 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 12987 12988 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 12989 12990 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 12991 mHandler.sendMessage(msg); 12992 } 12993 } 12994 }); 12995 } 12996 12997 /** 12998 * Callback from PackageSettings whenever an app is first transitioned out of the 12999 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 13000 * the app was "launched" for a restoreAtInstall operation. Therefore we check 13001 * here whether the app is the target of an ongoing install, and only send the 13002 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 13003 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 13004 * handling. 13005 */ 13006 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 13007 // Serialize this with the rest of the install-process message chain. In the 13008 // restore-at-install case, this Runnable will necessarily run before the 13009 // POST_INSTALL message is processed, so the contents of mRunningInstalls 13010 // are coherent. In the non-restore case, the app has already completed install 13011 // and been launched through some other means, so it is not in a problematic 13012 // state for observers to see the FIRST_LAUNCH signal. 13013 mHandler.post(new Runnable() { 13014 @Override 13015 public void run() { 13016 for (int i = 0; i < mRunningInstalls.size(); i++) { 13017 final PostInstallData data = mRunningInstalls.valueAt(i); 13018 if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 13019 continue; 13020 } 13021 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 13022 // right package; but is it for the right user? 13023 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 13024 if (userId == data.res.newUsers[uIndex]) { 13025 if (DEBUG_BACKUP) { 13026 Slog.i(TAG, "Package " + pkgName 13027 + " being restored so deferring FIRST_LAUNCH"); 13028 } 13029 return; 13030 } 13031 } 13032 } 13033 } 13034 // didn't find it, so not being restored 13035 if (DEBUG_BACKUP) { 13036 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 13037 } 13038 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 13039 } 13040 }); 13041 } 13042 13043 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 13044 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 13045 installerPkg, null, userIds); 13046 } 13047 13048 private abstract class HandlerParams { 13049 private static final int MAX_RETRIES = 4; 13050 13051 /** 13052 * Number of times startCopy() has been attempted and had a non-fatal 13053 * error. 13054 */ 13055 private int mRetries = 0; 13056 13057 /** User handle for the user requesting the information or installation. */ 13058 private final UserHandle mUser; 13059 String traceMethod; 13060 int traceCookie; 13061 13062 HandlerParams(UserHandle user) { 13063 mUser = user; 13064 } 13065 13066 UserHandle getUser() { 13067 return mUser; 13068 } 13069 13070 HandlerParams setTraceMethod(String traceMethod) { 13071 this.traceMethod = traceMethod; 13072 return this; 13073 } 13074 13075 HandlerParams setTraceCookie(int traceCookie) { 13076 this.traceCookie = traceCookie; 13077 return this; 13078 } 13079 13080 final boolean startCopy() { 13081 boolean res; 13082 try { 13083 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 13084 13085 if (++mRetries > MAX_RETRIES) { 13086 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 13087 mHandler.sendEmptyMessage(MCS_GIVE_UP); 13088 handleServiceError(); 13089 return false; 13090 } else { 13091 handleStartCopy(); 13092 res = true; 13093 } 13094 } catch (RemoteException e) { 13095 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 13096 mHandler.sendEmptyMessage(MCS_RECONNECT); 13097 res = false; 13098 } 13099 handleReturnCode(); 13100 return res; 13101 } 13102 13103 final void serviceError() { 13104 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 13105 handleServiceError(); 13106 handleReturnCode(); 13107 } 13108 13109 abstract void handleStartCopy() throws RemoteException; 13110 abstract void handleServiceError(); 13111 abstract void handleReturnCode(); 13112 } 13113 13114 class MeasureParams extends HandlerParams { 13115 private final PackageStats mStats; 13116 private boolean mSuccess; 13117 13118 private final IPackageStatsObserver mObserver; 13119 13120 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 13121 super(new UserHandle(stats.userHandle)); 13122 mObserver = observer; 13123 mStats = stats; 13124 } 13125 13126 @Override 13127 public String toString() { 13128 return "MeasureParams{" 13129 + Integer.toHexString(System.identityHashCode(this)) 13130 + " " + mStats.packageName + "}"; 13131 } 13132 13133 @Override 13134 void handleStartCopy() throws RemoteException { 13135 synchronized (mInstallLock) { 13136 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 13137 } 13138 13139 if (mSuccess) { 13140 boolean mounted = false; 13141 try { 13142 final String status = Environment.getExternalStorageState(); 13143 mounted = (Environment.MEDIA_MOUNTED.equals(status) 13144 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 13145 } catch (Exception e) { 13146 } 13147 13148 if (mounted) { 13149 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 13150 13151 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 13152 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 13153 13154 mStats.externalDataSize = calculateDirectorySize(mContainerService, 13155 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 13156 13157 // Always subtract cache size, since it's a subdirectory 13158 mStats.externalDataSize -= mStats.externalCacheSize; 13159 13160 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 13161 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 13162 13163 mStats.externalObbSize = calculateDirectorySize(mContainerService, 13164 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 13165 } 13166 } 13167 } 13168 13169 @Override 13170 void handleReturnCode() { 13171 if (mObserver != null) { 13172 try { 13173 mObserver.onGetStatsCompleted(mStats, mSuccess); 13174 } catch (RemoteException e) { 13175 Slog.i(TAG, "Observer no longer exists."); 13176 } 13177 } 13178 } 13179 13180 @Override 13181 void handleServiceError() { 13182 Slog.e(TAG, "Could not measure application " + mStats.packageName 13183 + " external storage"); 13184 } 13185 } 13186 13187 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 13188 throws RemoteException { 13189 long result = 0; 13190 for (File path : paths) { 13191 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 13192 } 13193 return result; 13194 } 13195 13196 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 13197 for (File path : paths) { 13198 try { 13199 mcs.clearDirectory(path.getAbsolutePath()); 13200 } catch (RemoteException e) { 13201 } 13202 } 13203 } 13204 13205 static class OriginInfo { 13206 /** 13207 * Location where install is coming from, before it has been 13208 * copied/renamed into place. This could be a single monolithic APK 13209 * file, or a cluster directory. This location may be untrusted. 13210 */ 13211 final File file; 13212 final String cid; 13213 13214 /** 13215 * Flag indicating that {@link #file} or {@link #cid} has already been 13216 * staged, meaning downstream users don't need to defensively copy the 13217 * contents. 13218 */ 13219 final boolean staged; 13220 13221 /** 13222 * Flag indicating that {@link #file} or {@link #cid} is an already 13223 * installed app that is being moved. 13224 */ 13225 final boolean existing; 13226 13227 final String resolvedPath; 13228 final File resolvedFile; 13229 13230 static OriginInfo fromNothing() { 13231 return new OriginInfo(null, null, false, false); 13232 } 13233 13234 static OriginInfo fromUntrustedFile(File file) { 13235 return new OriginInfo(file, null, false, false); 13236 } 13237 13238 static OriginInfo fromExistingFile(File file) { 13239 return new OriginInfo(file, null, false, true); 13240 } 13241 13242 static OriginInfo fromStagedFile(File file) { 13243 return new OriginInfo(file, null, true, false); 13244 } 13245 13246 static OriginInfo fromStagedContainer(String cid) { 13247 return new OriginInfo(null, cid, true, false); 13248 } 13249 13250 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 13251 this.file = file; 13252 this.cid = cid; 13253 this.staged = staged; 13254 this.existing = existing; 13255 13256 if (cid != null) { 13257 resolvedPath = PackageHelper.getSdDir(cid); 13258 resolvedFile = new File(resolvedPath); 13259 } else if (file != null) { 13260 resolvedPath = file.getAbsolutePath(); 13261 resolvedFile = file; 13262 } else { 13263 resolvedPath = null; 13264 resolvedFile = null; 13265 } 13266 } 13267 } 13268 13269 static class MoveInfo { 13270 final int moveId; 13271 final String fromUuid; 13272 final String toUuid; 13273 final String packageName; 13274 final String dataAppName; 13275 final int appId; 13276 final String seinfo; 13277 final int targetSdkVersion; 13278 13279 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 13280 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 13281 this.moveId = moveId; 13282 this.fromUuid = fromUuid; 13283 this.toUuid = toUuid; 13284 this.packageName = packageName; 13285 this.dataAppName = dataAppName; 13286 this.appId = appId; 13287 this.seinfo = seinfo; 13288 this.targetSdkVersion = targetSdkVersion; 13289 } 13290 } 13291 13292 static class VerificationInfo { 13293 /** A constant used to indicate that a uid value is not present. */ 13294 public static final int NO_UID = -1; 13295 13296 /** URI referencing where the package was downloaded from. */ 13297 final Uri originatingUri; 13298 13299 /** HTTP referrer URI associated with the originatingURI. */ 13300 final Uri referrer; 13301 13302 /** UID of the application that the install request originated from. */ 13303 final int originatingUid; 13304 13305 /** UID of application requesting the install */ 13306 final int installerUid; 13307 13308 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 13309 this.originatingUri = originatingUri; 13310 this.referrer = referrer; 13311 this.originatingUid = originatingUid; 13312 this.installerUid = installerUid; 13313 } 13314 } 13315 13316 class InstallParams extends HandlerParams { 13317 final OriginInfo origin; 13318 final MoveInfo move; 13319 final IPackageInstallObserver2 observer; 13320 int installFlags; 13321 final String installerPackageName; 13322 final String volumeUuid; 13323 private InstallArgs mArgs; 13324 private int mRet; 13325 final String packageAbiOverride; 13326 final String[] grantedRuntimePermissions; 13327 final VerificationInfo verificationInfo; 13328 final Certificate[][] certificates; 13329 13330 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 13331 int installFlags, String installerPackageName, String volumeUuid, 13332 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 13333 String[] grantedPermissions, Certificate[][] certificates) { 13334 super(user); 13335 this.origin = origin; 13336 this.move = move; 13337 this.observer = observer; 13338 this.installFlags = installFlags; 13339 this.installerPackageName = installerPackageName; 13340 this.volumeUuid = volumeUuid; 13341 this.verificationInfo = verificationInfo; 13342 this.packageAbiOverride = packageAbiOverride; 13343 this.grantedRuntimePermissions = grantedPermissions; 13344 this.certificates = certificates; 13345 } 13346 13347 @Override 13348 public String toString() { 13349 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 13350 + " file=" + origin.file + " cid=" + origin.cid + "}"; 13351 } 13352 13353 private int installLocationPolicy(PackageInfoLite pkgLite) { 13354 String packageName = pkgLite.packageName; 13355 int installLocation = pkgLite.installLocation; 13356 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 13357 // reader 13358 synchronized (mPackages) { 13359 // Currently installed package which the new package is attempting to replace or 13360 // null if no such package is installed. 13361 PackageParser.Package installedPkg = mPackages.get(packageName); 13362 // Package which currently owns the data which the new package will own if installed. 13363 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 13364 // will be null whereas dataOwnerPkg will contain information about the package 13365 // which was uninstalled while keeping its data. 13366 PackageParser.Package dataOwnerPkg = installedPkg; 13367 if (dataOwnerPkg == null) { 13368 PackageSetting ps = mSettings.mPackages.get(packageName); 13369 if (ps != null) { 13370 dataOwnerPkg = ps.pkg; 13371 } 13372 } 13373 13374 if (dataOwnerPkg != null) { 13375 // If installed, the package will get access to data left on the device by its 13376 // predecessor. As a security measure, this is permited only if this is not a 13377 // version downgrade or if the predecessor package is marked as debuggable and 13378 // a downgrade is explicitly requested. 13379 // 13380 // On debuggable platform builds, downgrades are permitted even for 13381 // non-debuggable packages to make testing easier. Debuggable platform builds do 13382 // not offer security guarantees and thus it's OK to disable some security 13383 // mechanisms to make debugging/testing easier on those builds. However, even on 13384 // debuggable builds downgrades of packages are permitted only if requested via 13385 // installFlags. This is because we aim to keep the behavior of debuggable 13386 // platform builds as close as possible to the behavior of non-debuggable 13387 // platform builds. 13388 final boolean downgradeRequested = 13389 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 13390 final boolean packageDebuggable = 13391 (dataOwnerPkg.applicationInfo.flags 13392 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 13393 final boolean downgradePermitted = 13394 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 13395 if (!downgradePermitted) { 13396 try { 13397 checkDowngrade(dataOwnerPkg, pkgLite); 13398 } catch (PackageManagerException e) { 13399 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 13400 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 13401 } 13402 } 13403 } 13404 13405 if (installedPkg != null) { 13406 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 13407 // Check for updated system application. 13408 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 13409 if (onSd) { 13410 Slog.w(TAG, "Cannot install update to system app on sdcard"); 13411 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 13412 } 13413 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 13414 } else { 13415 if (onSd) { 13416 // Install flag overrides everything. 13417 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 13418 } 13419 // If current upgrade specifies particular preference 13420 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 13421 // Application explicitly specified internal. 13422 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 13423 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 13424 // App explictly prefers external. Let policy decide 13425 } else { 13426 // Prefer previous location 13427 if (isExternal(installedPkg)) { 13428 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 13429 } 13430 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 13431 } 13432 } 13433 } else { 13434 // Invalid install. Return error code 13435 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 13436 } 13437 } 13438 } 13439 // All the special cases have been taken care of. 13440 // Return result based on recommended install location. 13441 if (onSd) { 13442 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 13443 } 13444 return pkgLite.recommendedInstallLocation; 13445 } 13446 13447 /* 13448 * Invoke remote method to get package information and install 13449 * location values. Override install location based on default 13450 * policy if needed and then create install arguments based 13451 * on the install location. 13452 */ 13453 public void handleStartCopy() throws RemoteException { 13454 int ret = PackageManager.INSTALL_SUCCEEDED; 13455 13456 // If we're already staged, we've firmly committed to an install location 13457 if (origin.staged) { 13458 if (origin.file != null) { 13459 installFlags |= PackageManager.INSTALL_INTERNAL; 13460 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 13461 } else if (origin.cid != null) { 13462 installFlags |= PackageManager.INSTALL_EXTERNAL; 13463 installFlags &= ~PackageManager.INSTALL_INTERNAL; 13464 } else { 13465 throw new IllegalStateException("Invalid stage location"); 13466 } 13467 } 13468 13469 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 13470 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 13471 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13472 PackageInfoLite pkgLite = null; 13473 13474 if (onInt && onSd) { 13475 // Check if both bits are set. 13476 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 13477 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 13478 } else if (onSd && ephemeral) { 13479 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 13480 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 13481 } else { 13482 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 13483 packageAbiOverride); 13484 13485 if (DEBUG_EPHEMERAL && ephemeral) { 13486 Slog.v(TAG, "pkgLite for install: " + pkgLite); 13487 } 13488 13489 /* 13490 * If we have too little free space, try to free cache 13491 * before giving up. 13492 */ 13493 if (!origin.staged && pkgLite.recommendedInstallLocation 13494 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 13495 // TODO: focus freeing disk space on the target device 13496 final StorageManager storage = StorageManager.from(mContext); 13497 final long lowThreshold = storage.getStorageLowBytes( 13498 Environment.getDataDirectory()); 13499 13500 final long sizeBytes = mContainerService.calculateInstalledSize( 13501 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 13502 13503 try { 13504 mInstaller.freeCache(null, sizeBytes + lowThreshold); 13505 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 13506 installFlags, packageAbiOverride); 13507 } catch (InstallerException e) { 13508 Slog.w(TAG, "Failed to free cache", e); 13509 } 13510 13511 /* 13512 * The cache free must have deleted the file we 13513 * downloaded to install. 13514 * 13515 * TODO: fix the "freeCache" call to not delete 13516 * the file we care about. 13517 */ 13518 if (pkgLite.recommendedInstallLocation 13519 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 13520 pkgLite.recommendedInstallLocation 13521 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 13522 } 13523 } 13524 } 13525 13526 if (ret == PackageManager.INSTALL_SUCCEEDED) { 13527 int loc = pkgLite.recommendedInstallLocation; 13528 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 13529 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 13530 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 13531 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 13532 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 13533 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 13534 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 13535 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 13536 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 13537 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 13538 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 13539 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 13540 } else { 13541 // Override with defaults if needed. 13542 loc = installLocationPolicy(pkgLite); 13543 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 13544 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 13545 } else if (!onSd && !onInt) { 13546 // Override install location with flags 13547 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 13548 // Set the flag to install on external media. 13549 installFlags |= PackageManager.INSTALL_EXTERNAL; 13550 installFlags &= ~PackageManager.INSTALL_INTERNAL; 13551 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 13552 if (DEBUG_EPHEMERAL) { 13553 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 13554 } 13555 installFlags |= PackageManager.INSTALL_EPHEMERAL; 13556 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 13557 |PackageManager.INSTALL_INTERNAL); 13558 } else { 13559 // Make sure the flag for installing on external 13560 // media is unset 13561 installFlags |= PackageManager.INSTALL_INTERNAL; 13562 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 13563 } 13564 } 13565 } 13566 } 13567 13568 final InstallArgs args = createInstallArgs(this); 13569 mArgs = args; 13570 13571 if (ret == PackageManager.INSTALL_SUCCEEDED) { 13572 // TODO: http://b/22976637 13573 // Apps installed for "all" users use the device owner to verify the app 13574 UserHandle verifierUser = getUser(); 13575 if (verifierUser == UserHandle.ALL) { 13576 verifierUser = UserHandle.SYSTEM; 13577 } 13578 13579 /* 13580 * Determine if we have any installed package verifiers. If we 13581 * do, then we'll defer to them to verify the packages. 13582 */ 13583 final int requiredUid = mRequiredVerifierPackage == null ? -1 13584 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 13585 verifierUser.getIdentifier()); 13586 if (!origin.existing && requiredUid != -1 13587 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 13588 final Intent verification = new Intent( 13589 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 13590 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 13591 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 13592 PACKAGE_MIME_TYPE); 13593 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 13594 13595 // Query all live verifiers based on current user state 13596 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 13597 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 13598 13599 if (DEBUG_VERIFY) { 13600 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 13601 + verification.toString() + " with " + pkgLite.verifiers.length 13602 + " optional verifiers"); 13603 } 13604 13605 final int verificationId = mPendingVerificationToken++; 13606 13607 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 13608 13609 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 13610 installerPackageName); 13611 13612 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 13613 installFlags); 13614 13615 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 13616 pkgLite.packageName); 13617 13618 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 13619 pkgLite.versionCode); 13620 13621 if (verificationInfo != null) { 13622 if (verificationInfo.originatingUri != null) { 13623 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 13624 verificationInfo.originatingUri); 13625 } 13626 if (verificationInfo.referrer != null) { 13627 verification.putExtra(Intent.EXTRA_REFERRER, 13628 verificationInfo.referrer); 13629 } 13630 if (verificationInfo.originatingUid >= 0) { 13631 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 13632 verificationInfo.originatingUid); 13633 } 13634 if (verificationInfo.installerUid >= 0) { 13635 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 13636 verificationInfo.installerUid); 13637 } 13638 } 13639 13640 final PackageVerificationState verificationState = new PackageVerificationState( 13641 requiredUid, args); 13642 13643 mPendingVerification.append(verificationId, verificationState); 13644 13645 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 13646 receivers, verificationState); 13647 13648 /* 13649 * If any sufficient verifiers were listed in the package 13650 * manifest, attempt to ask them. 13651 */ 13652 if (sufficientVerifiers != null) { 13653 final int N = sufficientVerifiers.size(); 13654 if (N == 0) { 13655 Slog.i(TAG, "Additional verifiers required, but none installed."); 13656 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 13657 } else { 13658 for (int i = 0; i < N; i++) { 13659 final ComponentName verifierComponent = sufficientVerifiers.get(i); 13660 13661 final Intent sufficientIntent = new Intent(verification); 13662 sufficientIntent.setComponent(verifierComponent); 13663 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 13664 } 13665 } 13666 } 13667 13668 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 13669 mRequiredVerifierPackage, receivers); 13670 if (ret == PackageManager.INSTALL_SUCCEEDED 13671 && mRequiredVerifierPackage != null) { 13672 Trace.asyncTraceBegin( 13673 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 13674 /* 13675 * Send the intent to the required verification agent, 13676 * but only start the verification timeout after the 13677 * target BroadcastReceivers have run. 13678 */ 13679 verification.setComponent(requiredVerifierComponent); 13680 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 13681 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13682 new BroadcastReceiver() { 13683 @Override 13684 public void onReceive(Context context, Intent intent) { 13685 final Message msg = mHandler 13686 .obtainMessage(CHECK_PENDING_VERIFICATION); 13687 msg.arg1 = verificationId; 13688 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 13689 } 13690 }, null, 0, null, null); 13691 13692 /* 13693 * We don't want the copy to proceed until verification 13694 * succeeds, so null out this field. 13695 */ 13696 mArgs = null; 13697 } 13698 } else { 13699 /* 13700 * No package verification is enabled, so immediately start 13701 * the remote call to initiate copy using temporary file. 13702 */ 13703 ret = args.copyApk(mContainerService, true); 13704 } 13705 } 13706 13707 mRet = ret; 13708 } 13709 13710 @Override 13711 void handleReturnCode() { 13712 // If mArgs is null, then MCS couldn't be reached. When it 13713 // reconnects, it will try again to install. At that point, this 13714 // will succeed. 13715 if (mArgs != null) { 13716 processPendingInstall(mArgs, mRet); 13717 } 13718 } 13719 13720 @Override 13721 void handleServiceError() { 13722 mArgs = createInstallArgs(this); 13723 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13724 } 13725 13726 public boolean isForwardLocked() { 13727 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13728 } 13729 } 13730 13731 /** 13732 * Used during creation of InstallArgs 13733 * 13734 * @param installFlags package installation flags 13735 * @return true if should be installed on external storage 13736 */ 13737 private static boolean installOnExternalAsec(int installFlags) { 13738 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 13739 return false; 13740 } 13741 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 13742 return true; 13743 } 13744 return false; 13745 } 13746 13747 /** 13748 * Used during creation of InstallArgs 13749 * 13750 * @param installFlags package installation flags 13751 * @return true if should be installed as forward locked 13752 */ 13753 private static boolean installForwardLocked(int installFlags) { 13754 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13755 } 13756 13757 private InstallArgs createInstallArgs(InstallParams params) { 13758 if (params.move != null) { 13759 return new MoveInstallArgs(params); 13760 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 13761 return new AsecInstallArgs(params); 13762 } else { 13763 return new FileInstallArgs(params); 13764 } 13765 } 13766 13767 /** 13768 * Create args that describe an existing installed package. Typically used 13769 * when cleaning up old installs, or used as a move source. 13770 */ 13771 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 13772 String resourcePath, String[] instructionSets) { 13773 final boolean isInAsec; 13774 if (installOnExternalAsec(installFlags)) { 13775 /* Apps on SD card are always in ASEC containers. */ 13776 isInAsec = true; 13777 } else if (installForwardLocked(installFlags) 13778 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 13779 /* 13780 * Forward-locked apps are only in ASEC containers if they're the 13781 * new style 13782 */ 13783 isInAsec = true; 13784 } else { 13785 isInAsec = false; 13786 } 13787 13788 if (isInAsec) { 13789 return new AsecInstallArgs(codePath, instructionSets, 13790 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 13791 } else { 13792 return new FileInstallArgs(codePath, resourcePath, instructionSets); 13793 } 13794 } 13795 13796 static abstract class InstallArgs { 13797 /** @see InstallParams#origin */ 13798 final OriginInfo origin; 13799 /** @see InstallParams#move */ 13800 final MoveInfo move; 13801 13802 final IPackageInstallObserver2 observer; 13803 // Always refers to PackageManager flags only 13804 final int installFlags; 13805 final String installerPackageName; 13806 final String volumeUuid; 13807 final UserHandle user; 13808 final String abiOverride; 13809 final String[] installGrantPermissions; 13810 /** If non-null, drop an async trace when the install completes */ 13811 final String traceMethod; 13812 final int traceCookie; 13813 final Certificate[][] certificates; 13814 13815 // The list of instruction sets supported by this app. This is currently 13816 // only used during the rmdex() phase to clean up resources. We can get rid of this 13817 // if we move dex files under the common app path. 13818 /* nullable */ String[] instructionSets; 13819 13820 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 13821 int installFlags, String installerPackageName, String volumeUuid, 13822 UserHandle user, String[] instructionSets, 13823 String abiOverride, String[] installGrantPermissions, 13824 String traceMethod, int traceCookie, Certificate[][] certificates) { 13825 this.origin = origin; 13826 this.move = move; 13827 this.installFlags = installFlags; 13828 this.observer = observer; 13829 this.installerPackageName = installerPackageName; 13830 this.volumeUuid = volumeUuid; 13831 this.user = user; 13832 this.instructionSets = instructionSets; 13833 this.abiOverride = abiOverride; 13834 this.installGrantPermissions = installGrantPermissions; 13835 this.traceMethod = traceMethod; 13836 this.traceCookie = traceCookie; 13837 this.certificates = certificates; 13838 } 13839 13840 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 13841 abstract int doPreInstall(int status); 13842 13843 /** 13844 * Rename package into final resting place. All paths on the given 13845 * scanned package should be updated to reflect the rename. 13846 */ 13847 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 13848 abstract int doPostInstall(int status, int uid); 13849 13850 /** @see PackageSettingBase#codePathString */ 13851 abstract String getCodePath(); 13852 /** @see PackageSettingBase#resourcePathString */ 13853 abstract String getResourcePath(); 13854 13855 // Need installer lock especially for dex file removal. 13856 abstract void cleanUpResourcesLI(); 13857 abstract boolean doPostDeleteLI(boolean delete); 13858 13859 /** 13860 * Called before the source arguments are copied. This is used mostly 13861 * for MoveParams when it needs to read the source file to put it in the 13862 * destination. 13863 */ 13864 int doPreCopy() { 13865 return PackageManager.INSTALL_SUCCEEDED; 13866 } 13867 13868 /** 13869 * Called after the source arguments are copied. This is used mostly for 13870 * MoveParams when it needs to read the source file to put it in the 13871 * destination. 13872 */ 13873 int doPostCopy(int uid) { 13874 return PackageManager.INSTALL_SUCCEEDED; 13875 } 13876 13877 protected boolean isFwdLocked() { 13878 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13879 } 13880 13881 protected boolean isExternalAsec() { 13882 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 13883 } 13884 13885 protected boolean isEphemeral() { 13886 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13887 } 13888 13889 UserHandle getUser() { 13890 return user; 13891 } 13892 } 13893 13894 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 13895 if (!allCodePaths.isEmpty()) { 13896 if (instructionSets == null) { 13897 throw new IllegalStateException("instructionSet == null"); 13898 } 13899 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 13900 for (String codePath : allCodePaths) { 13901 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 13902 try { 13903 mInstaller.rmdex(codePath, dexCodeInstructionSet); 13904 } catch (InstallerException ignored) { 13905 } 13906 } 13907 } 13908 } 13909 } 13910 13911 /** 13912 * Logic to handle installation of non-ASEC applications, including copying 13913 * and renaming logic. 13914 */ 13915 class FileInstallArgs extends InstallArgs { 13916 private File codeFile; 13917 private File resourceFile; 13918 13919 // Example topology: 13920 // /data/app/com.example/base.apk 13921 // /data/app/com.example/split_foo.apk 13922 // /data/app/com.example/lib/arm/libfoo.so 13923 // /data/app/com.example/lib/arm64/libfoo.so 13924 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 13925 13926 /** New install */ 13927 FileInstallArgs(InstallParams params) { 13928 super(params.origin, params.move, params.observer, params.installFlags, 13929 params.installerPackageName, params.volumeUuid, 13930 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 13931 params.grantedRuntimePermissions, 13932 params.traceMethod, params.traceCookie, params.certificates); 13933 if (isFwdLocked()) { 13934 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 13935 } 13936 } 13937 13938 /** Existing install */ 13939 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 13940 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 13941 null, null, null, 0, null /*certificates*/); 13942 this.codeFile = (codePath != null) ? new File(codePath) : null; 13943 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 13944 } 13945 13946 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13947 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 13948 try { 13949 return doCopyApk(imcs, temp); 13950 } finally { 13951 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13952 } 13953 } 13954 13955 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13956 if (origin.staged) { 13957 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 13958 codeFile = origin.file; 13959 resourceFile = origin.file; 13960 return PackageManager.INSTALL_SUCCEEDED; 13961 } 13962 13963 try { 13964 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13965 final File tempDir = 13966 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 13967 codeFile = tempDir; 13968 resourceFile = tempDir; 13969 } catch (IOException e) { 13970 Slog.w(TAG, "Failed to create copy file: " + e); 13971 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 13972 } 13973 13974 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 13975 @Override 13976 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 13977 if (!FileUtils.isValidExtFilename(name)) { 13978 throw new IllegalArgumentException("Invalid filename: " + name); 13979 } 13980 try { 13981 final File file = new File(codeFile, name); 13982 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 13983 O_RDWR | O_CREAT, 0644); 13984 Os.chmod(file.getAbsolutePath(), 0644); 13985 return new ParcelFileDescriptor(fd); 13986 } catch (ErrnoException e) { 13987 throw new RemoteException("Failed to open: " + e.getMessage()); 13988 } 13989 } 13990 }; 13991 13992 int ret = PackageManager.INSTALL_SUCCEEDED; 13993 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 13994 if (ret != PackageManager.INSTALL_SUCCEEDED) { 13995 Slog.e(TAG, "Failed to copy package"); 13996 return ret; 13997 } 13998 13999 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 14000 NativeLibraryHelper.Handle handle = null; 14001 try { 14002 handle = NativeLibraryHelper.Handle.create(codeFile); 14003 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 14004 abiOverride); 14005 } catch (IOException e) { 14006 Slog.e(TAG, "Copying native libraries failed", e); 14007 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 14008 } finally { 14009 IoUtils.closeQuietly(handle); 14010 } 14011 14012 return ret; 14013 } 14014 14015 int doPreInstall(int status) { 14016 if (status != PackageManager.INSTALL_SUCCEEDED) { 14017 cleanUp(); 14018 } 14019 return status; 14020 } 14021 14022 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 14023 if (status != PackageManager.INSTALL_SUCCEEDED) { 14024 cleanUp(); 14025 return false; 14026 } 14027 14028 final File targetDir = codeFile.getParentFile(); 14029 final File beforeCodeFile = codeFile; 14030 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 14031 14032 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 14033 try { 14034 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 14035 } catch (ErrnoException e) { 14036 Slog.w(TAG, "Failed to rename", e); 14037 return false; 14038 } 14039 14040 if (!SELinux.restoreconRecursive(afterCodeFile)) { 14041 Slog.w(TAG, "Failed to restorecon"); 14042 return false; 14043 } 14044 14045 // Reflect the rename internally 14046 codeFile = afterCodeFile; 14047 resourceFile = afterCodeFile; 14048 14049 // Reflect the rename in scanned details 14050 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 14051 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 14052 afterCodeFile, pkg.baseCodePath)); 14053 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 14054 afterCodeFile, pkg.splitCodePaths)); 14055 14056 // Reflect the rename in app info 14057 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 14058 pkg.setApplicationInfoCodePath(pkg.codePath); 14059 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 14060 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 14061 pkg.setApplicationInfoResourcePath(pkg.codePath); 14062 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 14063 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 14064 14065 return true; 14066 } 14067 14068 int doPostInstall(int status, int uid) { 14069 if (status != PackageManager.INSTALL_SUCCEEDED) { 14070 cleanUp(); 14071 } 14072 return status; 14073 } 14074 14075 @Override 14076 String getCodePath() { 14077 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 14078 } 14079 14080 @Override 14081 String getResourcePath() { 14082 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 14083 } 14084 14085 private boolean cleanUp() { 14086 if (codeFile == null || !codeFile.exists()) { 14087 return false; 14088 } 14089 14090 removeCodePathLI(codeFile); 14091 14092 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 14093 resourceFile.delete(); 14094 } 14095 14096 return true; 14097 } 14098 14099 void cleanUpResourcesLI() { 14100 // Try enumerating all code paths before deleting 14101 List<String> allCodePaths = Collections.EMPTY_LIST; 14102 if (codeFile != null && codeFile.exists()) { 14103 try { 14104 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 14105 allCodePaths = pkg.getAllCodePaths(); 14106 } catch (PackageParserException e) { 14107 // Ignored; we tried our best 14108 } 14109 } 14110 14111 cleanUp(); 14112 removeDexFiles(allCodePaths, instructionSets); 14113 } 14114 14115 boolean doPostDeleteLI(boolean delete) { 14116 // XXX err, shouldn't we respect the delete flag? 14117 cleanUpResourcesLI(); 14118 return true; 14119 } 14120 } 14121 14122 private boolean isAsecExternal(String cid) { 14123 final String asecPath = PackageHelper.getSdFilesystem(cid); 14124 return !asecPath.startsWith(mAsecInternalPath); 14125 } 14126 14127 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 14128 PackageManagerException { 14129 if (copyRet < 0) { 14130 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 14131 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 14132 throw new PackageManagerException(copyRet, message); 14133 } 14134 } 14135 } 14136 14137 /** 14138 * Extract the StorageManagerService "container ID" from the full code path of an 14139 * .apk. 14140 */ 14141 static String cidFromCodePath(String fullCodePath) { 14142 int eidx = fullCodePath.lastIndexOf("/"); 14143 String subStr1 = fullCodePath.substring(0, eidx); 14144 int sidx = subStr1.lastIndexOf("/"); 14145 return subStr1.substring(sidx+1, eidx); 14146 } 14147 14148 /** 14149 * Logic to handle installation of ASEC applications, including copying and 14150 * renaming logic. 14151 */ 14152 class AsecInstallArgs extends InstallArgs { 14153 static final String RES_FILE_NAME = "pkg.apk"; 14154 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 14155 14156 String cid; 14157 String packagePath; 14158 String resourcePath; 14159 14160 /** New install */ 14161 AsecInstallArgs(InstallParams params) { 14162 super(params.origin, params.move, params.observer, params.installFlags, 14163 params.installerPackageName, params.volumeUuid, 14164 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 14165 params.grantedRuntimePermissions, 14166 params.traceMethod, params.traceCookie, params.certificates); 14167 } 14168 14169 /** Existing install */ 14170 AsecInstallArgs(String fullCodePath, String[] instructionSets, 14171 boolean isExternal, boolean isForwardLocked) { 14172 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 14173 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 14174 instructionSets, null, null, null, 0, null /*certificates*/); 14175 // Hackily pretend we're still looking at a full code path 14176 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 14177 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 14178 } 14179 14180 // Extract cid from fullCodePath 14181 int eidx = fullCodePath.lastIndexOf("/"); 14182 String subStr1 = fullCodePath.substring(0, eidx); 14183 int sidx = subStr1.lastIndexOf("/"); 14184 cid = subStr1.substring(sidx+1, eidx); 14185 setMountPath(subStr1); 14186 } 14187 14188 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 14189 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 14190 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 14191 instructionSets, null, null, null, 0, null /*certificates*/); 14192 this.cid = cid; 14193 setMountPath(PackageHelper.getSdDir(cid)); 14194 } 14195 14196 void createCopyFile() { 14197 cid = mInstallerService.allocateExternalStageCidLegacy(); 14198 } 14199 14200 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 14201 if (origin.staged && origin.cid != null) { 14202 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 14203 cid = origin.cid; 14204 setMountPath(PackageHelper.getSdDir(cid)); 14205 return PackageManager.INSTALL_SUCCEEDED; 14206 } 14207 14208 if (temp) { 14209 createCopyFile(); 14210 } else { 14211 /* 14212 * Pre-emptively destroy the container since it's destroyed if 14213 * copying fails due to it existing anyway. 14214 */ 14215 PackageHelper.destroySdDir(cid); 14216 } 14217 14218 final String newMountPath = imcs.copyPackageToContainer( 14219 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 14220 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 14221 14222 if (newMountPath != null) { 14223 setMountPath(newMountPath); 14224 return PackageManager.INSTALL_SUCCEEDED; 14225 } else { 14226 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 14227 } 14228 } 14229 14230 @Override 14231 String getCodePath() { 14232 return packagePath; 14233 } 14234 14235 @Override 14236 String getResourcePath() { 14237 return resourcePath; 14238 } 14239 14240 int doPreInstall(int status) { 14241 if (status != PackageManager.INSTALL_SUCCEEDED) { 14242 // Destroy container 14243 PackageHelper.destroySdDir(cid); 14244 } else { 14245 boolean mounted = PackageHelper.isContainerMounted(cid); 14246 if (!mounted) { 14247 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 14248 Process.SYSTEM_UID); 14249 if (newMountPath != null) { 14250 setMountPath(newMountPath); 14251 } else { 14252 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 14253 } 14254 } 14255 } 14256 return status; 14257 } 14258 14259 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 14260 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 14261 String newMountPath = null; 14262 if (PackageHelper.isContainerMounted(cid)) { 14263 // Unmount the container 14264 if (!PackageHelper.unMountSdDir(cid)) { 14265 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 14266 return false; 14267 } 14268 } 14269 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 14270 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 14271 " which might be stale. Will try to clean up."); 14272 // Clean up the stale container and proceed to recreate. 14273 if (!PackageHelper.destroySdDir(newCacheId)) { 14274 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 14275 return false; 14276 } 14277 // Successfully cleaned up stale container. Try to rename again. 14278 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 14279 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 14280 + " inspite of cleaning it up."); 14281 return false; 14282 } 14283 } 14284 if (!PackageHelper.isContainerMounted(newCacheId)) { 14285 Slog.w(TAG, "Mounting container " + newCacheId); 14286 newMountPath = PackageHelper.mountSdDir(newCacheId, 14287 getEncryptKey(), Process.SYSTEM_UID); 14288 } else { 14289 newMountPath = PackageHelper.getSdDir(newCacheId); 14290 } 14291 if (newMountPath == null) { 14292 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 14293 return false; 14294 } 14295 Log.i(TAG, "Succesfully renamed " + cid + 14296 " to " + newCacheId + 14297 " at new path: " + newMountPath); 14298 cid = newCacheId; 14299 14300 final File beforeCodeFile = new File(packagePath); 14301 setMountPath(newMountPath); 14302 final File afterCodeFile = new File(packagePath); 14303 14304 // Reflect the rename in scanned details 14305 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 14306 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 14307 afterCodeFile, pkg.baseCodePath)); 14308 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 14309 afterCodeFile, pkg.splitCodePaths)); 14310 14311 // Reflect the rename in app info 14312 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 14313 pkg.setApplicationInfoCodePath(pkg.codePath); 14314 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 14315 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 14316 pkg.setApplicationInfoResourcePath(pkg.codePath); 14317 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 14318 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 14319 14320 return true; 14321 } 14322 14323 private void setMountPath(String mountPath) { 14324 final File mountFile = new File(mountPath); 14325 14326 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 14327 if (monolithicFile.exists()) { 14328 packagePath = monolithicFile.getAbsolutePath(); 14329 if (isFwdLocked()) { 14330 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 14331 } else { 14332 resourcePath = packagePath; 14333 } 14334 } else { 14335 packagePath = mountFile.getAbsolutePath(); 14336 resourcePath = packagePath; 14337 } 14338 } 14339 14340 int doPostInstall(int status, int uid) { 14341 if (status != PackageManager.INSTALL_SUCCEEDED) { 14342 cleanUp(); 14343 } else { 14344 final int groupOwner; 14345 final String protectedFile; 14346 if (isFwdLocked()) { 14347 groupOwner = UserHandle.getSharedAppGid(uid); 14348 protectedFile = RES_FILE_NAME; 14349 } else { 14350 groupOwner = -1; 14351 protectedFile = null; 14352 } 14353 14354 if (uid < Process.FIRST_APPLICATION_UID 14355 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 14356 Slog.e(TAG, "Failed to finalize " + cid); 14357 PackageHelper.destroySdDir(cid); 14358 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 14359 } 14360 14361 boolean mounted = PackageHelper.isContainerMounted(cid); 14362 if (!mounted) { 14363 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 14364 } 14365 } 14366 return status; 14367 } 14368 14369 private void cleanUp() { 14370 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 14371 14372 // Destroy secure container 14373 PackageHelper.destroySdDir(cid); 14374 } 14375 14376 private List<String> getAllCodePaths() { 14377 final File codeFile = new File(getCodePath()); 14378 if (codeFile != null && codeFile.exists()) { 14379 try { 14380 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 14381 return pkg.getAllCodePaths(); 14382 } catch (PackageParserException e) { 14383 // Ignored; we tried our best 14384 } 14385 } 14386 return Collections.EMPTY_LIST; 14387 } 14388 14389 void cleanUpResourcesLI() { 14390 // Enumerate all code paths before deleting 14391 cleanUpResourcesLI(getAllCodePaths()); 14392 } 14393 14394 private void cleanUpResourcesLI(List<String> allCodePaths) { 14395 cleanUp(); 14396 removeDexFiles(allCodePaths, instructionSets); 14397 } 14398 14399 String getPackageName() { 14400 return getAsecPackageName(cid); 14401 } 14402 14403 boolean doPostDeleteLI(boolean delete) { 14404 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 14405 final List<String> allCodePaths = getAllCodePaths(); 14406 boolean mounted = PackageHelper.isContainerMounted(cid); 14407 if (mounted) { 14408 // Unmount first 14409 if (PackageHelper.unMountSdDir(cid)) { 14410 mounted = false; 14411 } 14412 } 14413 if (!mounted && delete) { 14414 cleanUpResourcesLI(allCodePaths); 14415 } 14416 return !mounted; 14417 } 14418 14419 @Override 14420 int doPreCopy() { 14421 if (isFwdLocked()) { 14422 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 14423 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 14424 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 14425 } 14426 } 14427 14428 return PackageManager.INSTALL_SUCCEEDED; 14429 } 14430 14431 @Override 14432 int doPostCopy(int uid) { 14433 if (isFwdLocked()) { 14434 if (uid < Process.FIRST_APPLICATION_UID 14435 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 14436 RES_FILE_NAME)) { 14437 Slog.e(TAG, "Failed to finalize " + cid); 14438 PackageHelper.destroySdDir(cid); 14439 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 14440 } 14441 } 14442 14443 return PackageManager.INSTALL_SUCCEEDED; 14444 } 14445 } 14446 14447 /** 14448 * Logic to handle movement of existing installed applications. 14449 */ 14450 class MoveInstallArgs extends InstallArgs { 14451 private File codeFile; 14452 private File resourceFile; 14453 14454 /** New install */ 14455 MoveInstallArgs(InstallParams params) { 14456 super(params.origin, params.move, params.observer, params.installFlags, 14457 params.installerPackageName, params.volumeUuid, 14458 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 14459 params.grantedRuntimePermissions, 14460 params.traceMethod, params.traceCookie, params.certificates); 14461 } 14462 14463 int copyApk(IMediaContainerService imcs, boolean temp) { 14464 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 14465 + move.fromUuid + " to " + move.toUuid); 14466 synchronized (mInstaller) { 14467 try { 14468 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 14469 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 14470 } catch (InstallerException e) { 14471 Slog.w(TAG, "Failed to move app", e); 14472 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 14473 } 14474 } 14475 14476 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 14477 resourceFile = codeFile; 14478 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 14479 14480 return PackageManager.INSTALL_SUCCEEDED; 14481 } 14482 14483 int doPreInstall(int status) { 14484 if (status != PackageManager.INSTALL_SUCCEEDED) { 14485 cleanUp(move.toUuid); 14486 } 14487 return status; 14488 } 14489 14490 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 14491 if (status != PackageManager.INSTALL_SUCCEEDED) { 14492 cleanUp(move.toUuid); 14493 return false; 14494 } 14495 14496 // Reflect the move in app info 14497 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 14498 pkg.setApplicationInfoCodePath(pkg.codePath); 14499 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 14500 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 14501 pkg.setApplicationInfoResourcePath(pkg.codePath); 14502 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 14503 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 14504 14505 return true; 14506 } 14507 14508 int doPostInstall(int status, int uid) { 14509 if (status == PackageManager.INSTALL_SUCCEEDED) { 14510 cleanUp(move.fromUuid); 14511 } else { 14512 cleanUp(move.toUuid); 14513 } 14514 return status; 14515 } 14516 14517 @Override 14518 String getCodePath() { 14519 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 14520 } 14521 14522 @Override 14523 String getResourcePath() { 14524 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 14525 } 14526 14527 private boolean cleanUp(String volumeUuid) { 14528 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 14529 move.dataAppName); 14530 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 14531 final int[] userIds = sUserManager.getUserIds(); 14532 synchronized (mInstallLock) { 14533 // Clean up both app data and code 14534 // All package moves are frozen until finished 14535 for (int userId : userIds) { 14536 try { 14537 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 14538 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 14539 } catch (InstallerException e) { 14540 Slog.w(TAG, String.valueOf(e)); 14541 } 14542 } 14543 removeCodePathLI(codeFile); 14544 } 14545 return true; 14546 } 14547 14548 void cleanUpResourcesLI() { 14549 throw new UnsupportedOperationException(); 14550 } 14551 14552 boolean doPostDeleteLI(boolean delete) { 14553 throw new UnsupportedOperationException(); 14554 } 14555 } 14556 14557 static String getAsecPackageName(String packageCid) { 14558 int idx = packageCid.lastIndexOf("-"); 14559 if (idx == -1) { 14560 return packageCid; 14561 } 14562 return packageCid.substring(0, idx); 14563 } 14564 14565 // Utility method used to create code paths based on package name and available index. 14566 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 14567 String idxStr = ""; 14568 int idx = 1; 14569 // Fall back to default value of idx=1 if prefix is not 14570 // part of oldCodePath 14571 if (oldCodePath != null) { 14572 String subStr = oldCodePath; 14573 // Drop the suffix right away 14574 if (suffix != null && subStr.endsWith(suffix)) { 14575 subStr = subStr.substring(0, subStr.length() - suffix.length()); 14576 } 14577 // If oldCodePath already contains prefix find out the 14578 // ending index to either increment or decrement. 14579 int sidx = subStr.lastIndexOf(prefix); 14580 if (sidx != -1) { 14581 subStr = subStr.substring(sidx + prefix.length()); 14582 if (subStr != null) { 14583 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 14584 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 14585 } 14586 try { 14587 idx = Integer.parseInt(subStr); 14588 if (idx <= 1) { 14589 idx++; 14590 } else { 14591 idx--; 14592 } 14593 } catch(NumberFormatException e) { 14594 } 14595 } 14596 } 14597 } 14598 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 14599 return prefix + idxStr; 14600 } 14601 14602 private File getNextCodePath(File targetDir, String packageName) { 14603 File result; 14604 SecureRandom random = new SecureRandom(); 14605 byte[] bytes = new byte[16]; 14606 do { 14607 random.nextBytes(bytes); 14608 String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP); 14609 result = new File(targetDir, packageName + "-" + suffix); 14610 } while (result.exists()); 14611 return result; 14612 } 14613 14614 // Utility method that returns the relative package path with respect 14615 // to the installation directory. Like say for /data/data/com.test-1.apk 14616 // string com.test-1 is returned. 14617 static String deriveCodePathName(String codePath) { 14618 if (codePath == null) { 14619 return null; 14620 } 14621 final File codeFile = new File(codePath); 14622 final String name = codeFile.getName(); 14623 if (codeFile.isDirectory()) { 14624 return name; 14625 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 14626 final int lastDot = name.lastIndexOf('.'); 14627 return name.substring(0, lastDot); 14628 } else { 14629 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 14630 return null; 14631 } 14632 } 14633 14634 static class PackageInstalledInfo { 14635 String name; 14636 int uid; 14637 // The set of users that originally had this package installed. 14638 int[] origUsers; 14639 // The set of users that now have this package installed. 14640 int[] newUsers; 14641 PackageParser.Package pkg; 14642 int returnCode; 14643 String returnMsg; 14644 PackageRemovedInfo removedInfo; 14645 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 14646 14647 public void setError(int code, String msg) { 14648 setReturnCode(code); 14649 setReturnMessage(msg); 14650 Slog.w(TAG, msg); 14651 } 14652 14653 public void setError(String msg, PackageParserException e) { 14654 setReturnCode(e.error); 14655 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 14656 Slog.w(TAG, msg, e); 14657 } 14658 14659 public void setError(String msg, PackageManagerException e) { 14660 returnCode = e.error; 14661 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 14662 Slog.w(TAG, msg, e); 14663 } 14664 14665 public void setReturnCode(int returnCode) { 14666 this.returnCode = returnCode; 14667 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 14668 for (int i = 0; i < childCount; i++) { 14669 addedChildPackages.valueAt(i).returnCode = returnCode; 14670 } 14671 } 14672 14673 private void setReturnMessage(String returnMsg) { 14674 this.returnMsg = returnMsg; 14675 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 14676 for (int i = 0; i < childCount; i++) { 14677 addedChildPackages.valueAt(i).returnMsg = returnMsg; 14678 } 14679 } 14680 14681 // In some error cases we want to convey more info back to the observer 14682 String origPackage; 14683 String origPermission; 14684 } 14685 14686 /* 14687 * Install a non-existing package. 14688 */ 14689 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 14690 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 14691 PackageInstalledInfo res) { 14692 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 14693 14694 // Remember this for later, in case we need to rollback this install 14695 String pkgName = pkg.packageName; 14696 14697 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 14698 14699 synchronized(mPackages) { 14700 final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName); 14701 if (renamedPackage != null) { 14702 // A package with the same name is already installed, though 14703 // it has been renamed to an older name. The package we 14704 // are trying to install should be installed as an update to 14705 // the existing one, but that has not been requested, so bail. 14706 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 14707 + " without first uninstalling package running as " 14708 + renamedPackage); 14709 return; 14710 } 14711 if (mPackages.containsKey(pkgName)) { 14712 // Don't allow installation over an existing package with the same name. 14713 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 14714 + " without first uninstalling."); 14715 return; 14716 } 14717 } 14718 14719 try { 14720 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 14721 System.currentTimeMillis(), user); 14722 14723 updateSettingsLI(newPackage, installerPackageName, null, res, user); 14724 14725 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14726 prepareAppDataAfterInstallLIF(newPackage); 14727 14728 } else { 14729 // Remove package from internal structures, but keep around any 14730 // data that might have already existed 14731 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 14732 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 14733 } 14734 } catch (PackageManagerException e) { 14735 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14736 } 14737 14738 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14739 } 14740 14741 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 14742 // Can't rotate keys during boot or if sharedUser. 14743 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 14744 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 14745 return false; 14746 } 14747 // app is using upgradeKeySets; make sure all are valid 14748 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14749 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 14750 for (int i = 0; i < upgradeKeySets.length; i++) { 14751 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 14752 Slog.wtf(TAG, "Package " 14753 + (oldPs.name != null ? oldPs.name : "<null>") 14754 + " contains upgrade-key-set reference to unknown key-set: " 14755 + upgradeKeySets[i] 14756 + " reverting to signatures check."); 14757 return false; 14758 } 14759 } 14760 return true; 14761 } 14762 14763 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 14764 // Upgrade keysets are being used. Determine if new package has a superset of the 14765 // required keys. 14766 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 14767 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14768 for (int i = 0; i < upgradeKeySets.length; i++) { 14769 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 14770 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 14771 return true; 14772 } 14773 } 14774 return false; 14775 } 14776 14777 private static void updateDigest(MessageDigest digest, File file) throws IOException { 14778 try (DigestInputStream digestStream = 14779 new DigestInputStream(new FileInputStream(file), digest)) { 14780 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 14781 } 14782 } 14783 14784 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 14785 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 14786 final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 14787 14788 final PackageParser.Package oldPackage; 14789 final String pkgName = pkg.packageName; 14790 final int[] allUsers; 14791 final int[] installedUsers; 14792 14793 synchronized(mPackages) { 14794 oldPackage = mPackages.get(pkgName); 14795 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 14796 14797 // don't allow upgrade to target a release SDK from a pre-release SDK 14798 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 14799 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14800 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 14801 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14802 if (oldTargetsPreRelease 14803 && !newTargetsPreRelease 14804 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 14805 Slog.w(TAG, "Can't install package targeting released sdk"); 14806 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 14807 return; 14808 } 14809 14810 // don't allow an upgrade from full to ephemeral 14811 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 14812 if (isEphemeral && !oldIsEphemeral) { 14813 // can't downgrade from full to ephemeral 14814 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 14815 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14816 return; 14817 } 14818 14819 // verify signatures are valid 14820 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14821 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14822 if (!checkUpgradeKeySetLP(ps, pkg)) { 14823 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14824 "New package not signed by keys specified by upgrade-keysets: " 14825 + pkgName); 14826 return; 14827 } 14828 } else { 14829 // default to original signature matching 14830 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 14831 != PackageManager.SIGNATURE_MATCH) { 14832 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14833 "New package has a different signature: " + pkgName); 14834 return; 14835 } 14836 } 14837 14838 // don't allow a system upgrade unless the upgrade hash matches 14839 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 14840 byte[] digestBytes = null; 14841 try { 14842 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 14843 updateDigest(digest, new File(pkg.baseCodePath)); 14844 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 14845 for (String path : pkg.splitCodePaths) { 14846 updateDigest(digest, new File(path)); 14847 } 14848 } 14849 digestBytes = digest.digest(); 14850 } catch (NoSuchAlgorithmException | IOException e) { 14851 res.setError(INSTALL_FAILED_INVALID_APK, 14852 "Could not compute hash: " + pkgName); 14853 return; 14854 } 14855 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 14856 res.setError(INSTALL_FAILED_INVALID_APK, 14857 "New package fails restrict-update check: " + pkgName); 14858 return; 14859 } 14860 // retain upgrade restriction 14861 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 14862 } 14863 14864 // Check for shared user id changes 14865 String invalidPackageName = 14866 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 14867 if (invalidPackageName != null) { 14868 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 14869 "Package " + invalidPackageName + " tried to change user " 14870 + oldPackage.mSharedUserId); 14871 return; 14872 } 14873 14874 // In case of rollback, remember per-user/profile install state 14875 allUsers = sUserManager.getUserIds(); 14876 installedUsers = ps.queryInstalledUsers(allUsers, true); 14877 } 14878 14879 // Update what is removed 14880 res.removedInfo = new PackageRemovedInfo(); 14881 res.removedInfo.uid = oldPackage.applicationInfo.uid; 14882 res.removedInfo.removedPackage = oldPackage.packageName; 14883 res.removedInfo.isUpdate = true; 14884 res.removedInfo.origUsers = installedUsers; 14885 final int childCount = (oldPackage.childPackages != null) 14886 ? oldPackage.childPackages.size() : 0; 14887 for (int i = 0; i < childCount; i++) { 14888 boolean childPackageUpdated = false; 14889 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 14890 if (res.addedChildPackages != null) { 14891 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14892 if (childRes != null) { 14893 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 14894 childRes.removedInfo.removedPackage = childPkg.packageName; 14895 childRes.removedInfo.isUpdate = true; 14896 childPackageUpdated = true; 14897 } 14898 } 14899 if (!childPackageUpdated) { 14900 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 14901 childRemovedRes.removedPackage = childPkg.packageName; 14902 childRemovedRes.isUpdate = false; 14903 childRemovedRes.dataRemoved = true; 14904 synchronized (mPackages) { 14905 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 14906 if (childPs != null) { 14907 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 14908 } 14909 } 14910 if (res.removedInfo.removedChildPackages == null) { 14911 res.removedInfo.removedChildPackages = new ArrayMap<>(); 14912 } 14913 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 14914 } 14915 } 14916 14917 boolean sysPkg = (isSystemApp(oldPackage)); 14918 if (sysPkg) { 14919 // Set the system/privileged flags as needed 14920 final boolean privileged = 14921 (oldPackage.applicationInfo.privateFlags 14922 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14923 final int systemPolicyFlags = policyFlags 14924 | PackageParser.PARSE_IS_SYSTEM 14925 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 14926 14927 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 14928 user, allUsers, installerPackageName, res); 14929 } else { 14930 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 14931 user, allUsers, installerPackageName, res); 14932 } 14933 } 14934 14935 public List<String> getPreviousCodePaths(String packageName) { 14936 final PackageSetting ps = mSettings.mPackages.get(packageName); 14937 final List<String> result = new ArrayList<String>(); 14938 if (ps != null && ps.oldCodePaths != null) { 14939 result.addAll(ps.oldCodePaths); 14940 } 14941 return result; 14942 } 14943 14944 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 14945 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14946 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14947 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 14948 + deletedPackage); 14949 14950 String pkgName = deletedPackage.packageName; 14951 boolean deletedPkg = true; 14952 boolean addedPkg = false; 14953 boolean updatedSettings = false; 14954 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 14955 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 14956 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 14957 14958 final long origUpdateTime = (pkg.mExtras != null) 14959 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 14960 14961 // First delete the existing package while retaining the data directory 14962 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14963 res.removedInfo, true, pkg)) { 14964 // If the existing package wasn't successfully deleted 14965 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 14966 deletedPkg = false; 14967 } else { 14968 // Successfully deleted the old package; proceed with replace. 14969 14970 // If deleted package lived in a container, give users a chance to 14971 // relinquish resources before killing. 14972 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 14973 if (DEBUG_INSTALL) { 14974 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 14975 } 14976 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 14977 final ArrayList<String> pkgList = new ArrayList<String>(1); 14978 pkgList.add(deletedPackage.applicationInfo.packageName); 14979 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 14980 } 14981 14982 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14983 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14984 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 14985 14986 try { 14987 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 14988 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 14989 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14990 14991 // Update the in-memory copy of the previous code paths. 14992 PackageSetting ps = mSettings.mPackages.get(pkgName); 14993 if (!killApp) { 14994 if (ps.oldCodePaths == null) { 14995 ps.oldCodePaths = new ArraySet<>(); 14996 } 14997 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 14998 if (deletedPackage.splitCodePaths != null) { 14999 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 15000 } 15001 } else { 15002 ps.oldCodePaths = null; 15003 } 15004 if (ps.childPackageNames != null) { 15005 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 15006 final String childPkgName = ps.childPackageNames.get(i); 15007 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 15008 childPs.oldCodePaths = ps.oldCodePaths; 15009 } 15010 } 15011 prepareAppDataAfterInstallLIF(newPackage); 15012 addedPkg = true; 15013 } catch (PackageManagerException e) { 15014 res.setError("Package couldn't be installed in " + pkg.codePath, e); 15015 } 15016 } 15017 15018 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 15019 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 15020 15021 // Revert all internal state mutations and added folders for the failed install 15022 if (addedPkg) { 15023 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 15024 res.removedInfo, true, null); 15025 } 15026 15027 // Restore the old package 15028 if (deletedPkg) { 15029 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 15030 File restoreFile = new File(deletedPackage.codePath); 15031 // Parse old package 15032 boolean oldExternal = isExternal(deletedPackage); 15033 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 15034 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 15035 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 15036 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 15037 try { 15038 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 15039 null); 15040 } catch (PackageManagerException e) { 15041 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 15042 + e.getMessage()); 15043 return; 15044 } 15045 15046 synchronized (mPackages) { 15047 // Ensure the installer package name up to date 15048 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 15049 15050 // Update permissions for restored package 15051 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 15052 15053 mSettings.writeLPr(); 15054 } 15055 15056 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 15057 } 15058 } else { 15059 synchronized (mPackages) { 15060 PackageSetting ps = mSettings.getPackageLPr(pkg.packageName); 15061 if (ps != null) { 15062 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 15063 if (res.removedInfo.removedChildPackages != null) { 15064 final int childCount = res.removedInfo.removedChildPackages.size(); 15065 // Iterate in reverse as we may modify the collection 15066 for (int i = childCount - 1; i >= 0; i--) { 15067 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 15068 if (res.addedChildPackages.containsKey(childPackageName)) { 15069 res.removedInfo.removedChildPackages.removeAt(i); 15070 } else { 15071 PackageRemovedInfo childInfo = res.removedInfo 15072 .removedChildPackages.valueAt(i); 15073 childInfo.removedForAllUsers = mPackages.get( 15074 childInfo.removedPackage) == null; 15075 } 15076 } 15077 } 15078 } 15079 } 15080 } 15081 } 15082 15083 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 15084 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 15085 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 15086 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 15087 + ", old=" + deletedPackage); 15088 15089 final boolean disabledSystem; 15090 15091 // Remove existing system package 15092 removePackageLI(deletedPackage, true); 15093 15094 synchronized (mPackages) { 15095 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 15096 } 15097 if (!disabledSystem) { 15098 // We didn't need to disable the .apk as a current system package, 15099 // which means we are replacing another update that is already 15100 // installed. We need to make sure to delete the older one's .apk. 15101 res.removedInfo.args = createInstallArgsForExisting(0, 15102 deletedPackage.applicationInfo.getCodePath(), 15103 deletedPackage.applicationInfo.getResourcePath(), 15104 getAppDexInstructionSets(deletedPackage.applicationInfo)); 15105 } else { 15106 res.removedInfo.args = null; 15107 } 15108 15109 // Successfully disabled the old package. Now proceed with re-installation 15110 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 15111 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 15112 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 15113 15114 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 15115 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 15116 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 15117 15118 PackageParser.Package newPackage = null; 15119 try { 15120 // Add the package to the internal data structures 15121 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 15122 15123 // Set the update and install times 15124 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 15125 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 15126 System.currentTimeMillis()); 15127 15128 // Update the package dynamic state if succeeded 15129 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 15130 // Now that the install succeeded make sure we remove data 15131 // directories for any child package the update removed. 15132 final int deletedChildCount = (deletedPackage.childPackages != null) 15133 ? deletedPackage.childPackages.size() : 0; 15134 final int newChildCount = (newPackage.childPackages != null) 15135 ? newPackage.childPackages.size() : 0; 15136 for (int i = 0; i < deletedChildCount; i++) { 15137 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 15138 boolean childPackageDeleted = true; 15139 for (int j = 0; j < newChildCount; j++) { 15140 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 15141 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 15142 childPackageDeleted = false; 15143 break; 15144 } 15145 } 15146 if (childPackageDeleted) { 15147 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 15148 deletedChildPkg.packageName); 15149 if (ps != null && res.removedInfo.removedChildPackages != null) { 15150 PackageRemovedInfo removedChildRes = res.removedInfo 15151 .removedChildPackages.get(deletedChildPkg.packageName); 15152 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 15153 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 15154 } 15155 } 15156 } 15157 15158 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 15159 prepareAppDataAfterInstallLIF(newPackage); 15160 } 15161 } catch (PackageManagerException e) { 15162 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 15163 res.setError("Package couldn't be installed in " + pkg.codePath, e); 15164 } 15165 15166 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 15167 // Re installation failed. Restore old information 15168 // Remove new pkg information 15169 if (newPackage != null) { 15170 removeInstalledPackageLI(newPackage, true); 15171 } 15172 // Add back the old system package 15173 try { 15174 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 15175 } catch (PackageManagerException e) { 15176 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 15177 } 15178 15179 synchronized (mPackages) { 15180 if (disabledSystem) { 15181 enableSystemPackageLPw(deletedPackage); 15182 } 15183 15184 // Ensure the installer package name up to date 15185 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 15186 15187 // Update permissions for restored package 15188 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 15189 15190 mSettings.writeLPr(); 15191 } 15192 15193 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 15194 + " after failed upgrade"); 15195 } 15196 } 15197 15198 /** 15199 * Checks whether the parent or any of the child packages have a change shared 15200 * user. For a package to be a valid update the shred users of the parent and 15201 * the children should match. We may later support changing child shared users. 15202 * @param oldPkg The updated package. 15203 * @param newPkg The update package. 15204 * @return The shared user that change between the versions. 15205 */ 15206 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 15207 PackageParser.Package newPkg) { 15208 // Check parent shared user 15209 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 15210 return newPkg.packageName; 15211 } 15212 // Check child shared users 15213 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 15214 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 15215 for (int i = 0; i < newChildCount; i++) { 15216 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 15217 // If this child was present, did it have the same shared user? 15218 for (int j = 0; j < oldChildCount; j++) { 15219 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 15220 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 15221 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 15222 return newChildPkg.packageName; 15223 } 15224 } 15225 } 15226 return null; 15227 } 15228 15229 private void removeNativeBinariesLI(PackageSetting ps) { 15230 // Remove the lib path for the parent package 15231 if (ps != null) { 15232 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 15233 // Remove the lib path for the child packages 15234 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 15235 for (int i = 0; i < childCount; i++) { 15236 PackageSetting childPs = null; 15237 synchronized (mPackages) { 15238 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 15239 } 15240 if (childPs != null) { 15241 NativeLibraryHelper.removeNativeBinariesLI(childPs 15242 .legacyNativeLibraryPathString); 15243 } 15244 } 15245 } 15246 } 15247 15248 private void enableSystemPackageLPw(PackageParser.Package pkg) { 15249 // Enable the parent package 15250 mSettings.enableSystemPackageLPw(pkg.packageName); 15251 // Enable the child packages 15252 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15253 for (int i = 0; i < childCount; i++) { 15254 PackageParser.Package childPkg = pkg.childPackages.get(i); 15255 mSettings.enableSystemPackageLPw(childPkg.packageName); 15256 } 15257 } 15258 15259 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 15260 PackageParser.Package newPkg) { 15261 // Disable the parent package (parent always replaced) 15262 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 15263 // Disable the child packages 15264 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 15265 for (int i = 0; i < childCount; i++) { 15266 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 15267 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 15268 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 15269 } 15270 return disabled; 15271 } 15272 15273 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 15274 String installerPackageName) { 15275 // Enable the parent package 15276 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 15277 // Enable the child packages 15278 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15279 for (int i = 0; i < childCount; i++) { 15280 PackageParser.Package childPkg = pkg.childPackages.get(i); 15281 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 15282 } 15283 } 15284 15285 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 15286 // Collect all used permissions in the UID 15287 ArraySet<String> usedPermissions = new ArraySet<>(); 15288 final int packageCount = su.packages.size(); 15289 for (int i = 0; i < packageCount; i++) { 15290 PackageSetting ps = su.packages.valueAt(i); 15291 if (ps.pkg == null) { 15292 continue; 15293 } 15294 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 15295 for (int j = 0; j < requestedPermCount; j++) { 15296 String permission = ps.pkg.requestedPermissions.get(j); 15297 BasePermission bp = mSettings.mPermissions.get(permission); 15298 if (bp != null) { 15299 usedPermissions.add(permission); 15300 } 15301 } 15302 } 15303 15304 PermissionsState permissionsState = su.getPermissionsState(); 15305 // Prune install permissions 15306 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 15307 final int installPermCount = installPermStates.size(); 15308 for (int i = installPermCount - 1; i >= 0; i--) { 15309 PermissionState permissionState = installPermStates.get(i); 15310 if (!usedPermissions.contains(permissionState.getName())) { 15311 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 15312 if (bp != null) { 15313 permissionsState.revokeInstallPermission(bp); 15314 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 15315 PackageManager.MASK_PERMISSION_FLAGS, 0); 15316 } 15317 } 15318 } 15319 15320 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 15321 15322 // Prune runtime permissions 15323 for (int userId : allUserIds) { 15324 List<PermissionState> runtimePermStates = permissionsState 15325 .getRuntimePermissionStates(userId); 15326 final int runtimePermCount = runtimePermStates.size(); 15327 for (int i = runtimePermCount - 1; i >= 0; i--) { 15328 PermissionState permissionState = runtimePermStates.get(i); 15329 if (!usedPermissions.contains(permissionState.getName())) { 15330 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 15331 if (bp != null) { 15332 permissionsState.revokeRuntimePermission(bp, userId); 15333 permissionsState.updatePermissionFlags(bp, userId, 15334 PackageManager.MASK_PERMISSION_FLAGS, 0); 15335 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 15336 runtimePermissionChangedUserIds, userId); 15337 } 15338 } 15339 } 15340 } 15341 15342 return runtimePermissionChangedUserIds; 15343 } 15344 15345 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 15346 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 15347 // Update the parent package setting 15348 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 15349 res, user); 15350 // Update the child packages setting 15351 final int childCount = (newPackage.childPackages != null) 15352 ? newPackage.childPackages.size() : 0; 15353 for (int i = 0; i < childCount; i++) { 15354 PackageParser.Package childPackage = newPackage.childPackages.get(i); 15355 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 15356 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 15357 childRes.origUsers, childRes, user); 15358 } 15359 } 15360 15361 private void updateSettingsInternalLI(PackageParser.Package newPackage, 15362 String installerPackageName, int[] allUsers, int[] installedForUsers, 15363 PackageInstalledInfo res, UserHandle user) { 15364 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 15365 15366 String pkgName = newPackage.packageName; 15367 synchronized (mPackages) { 15368 //write settings. the installStatus will be incomplete at this stage. 15369 //note that the new package setting would have already been 15370 //added to mPackages. It hasn't been persisted yet. 15371 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 15372 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 15373 mSettings.writeLPr(); 15374 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15375 } 15376 15377 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 15378 synchronized (mPackages) { 15379 updatePermissionsLPw(newPackage.packageName, newPackage, 15380 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 15381 ? UPDATE_PERMISSIONS_ALL : 0)); 15382 // For system-bundled packages, we assume that installing an upgraded version 15383 // of the package implies that the user actually wants to run that new code, 15384 // so we enable the package. 15385 PackageSetting ps = mSettings.mPackages.get(pkgName); 15386 final int userId = user.getIdentifier(); 15387 if (ps != null) { 15388 if (isSystemApp(newPackage)) { 15389 if (DEBUG_INSTALL) { 15390 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 15391 } 15392 // Enable system package for requested users 15393 if (res.origUsers != null) { 15394 for (int origUserId : res.origUsers) { 15395 if (userId == UserHandle.USER_ALL || userId == origUserId) { 15396 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 15397 origUserId, installerPackageName); 15398 } 15399 } 15400 } 15401 // Also convey the prior install/uninstall state 15402 if (allUsers != null && installedForUsers != null) { 15403 for (int currentUserId : allUsers) { 15404 final boolean installed = ArrayUtils.contains( 15405 installedForUsers, currentUserId); 15406 if (DEBUG_INSTALL) { 15407 Slog.d(TAG, " user " + currentUserId + " => " + installed); 15408 } 15409 ps.setInstalled(installed, currentUserId); 15410 } 15411 // these install state changes will be persisted in the 15412 // upcoming call to mSettings.writeLPr(). 15413 } 15414 } 15415 // It's implied that when a user requests installation, they want the app to be 15416 // installed and enabled. 15417 if (userId != UserHandle.USER_ALL) { 15418 ps.setInstalled(true, userId); 15419 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 15420 } 15421 } 15422 res.name = pkgName; 15423 res.uid = newPackage.applicationInfo.uid; 15424 res.pkg = newPackage; 15425 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 15426 mSettings.setInstallerPackageName(pkgName, installerPackageName); 15427 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 15428 //to update install status 15429 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 15430 mSettings.writeLPr(); 15431 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15432 } 15433 15434 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15435 } 15436 15437 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 15438 try { 15439 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 15440 installPackageLI(args, res); 15441 } finally { 15442 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15443 } 15444 } 15445 15446 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 15447 final int installFlags = args.installFlags; 15448 final String installerPackageName = args.installerPackageName; 15449 final String volumeUuid = args.volumeUuid; 15450 final File tmpPackageFile = new File(args.getCodePath()); 15451 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 15452 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 15453 || (args.volumeUuid != null)); 15454 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 15455 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 15456 boolean replace = false; 15457 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 15458 if (args.move != null) { 15459 // moving a complete application; perform an initial scan on the new install location 15460 scanFlags |= SCAN_INITIAL; 15461 } 15462 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 15463 scanFlags |= SCAN_DONT_KILL_APP; 15464 } 15465 15466 // Result object to be returned 15467 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 15468 15469 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 15470 15471 // Sanity check 15472 if (ephemeral && (forwardLocked || onExternal)) { 15473 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 15474 + " external=" + onExternal); 15475 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 15476 return; 15477 } 15478 15479 // Retrieve PackageSettings and parse package 15480 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 15481 | PackageParser.PARSE_ENFORCE_CODE 15482 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 15483 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 15484 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0) 15485 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 15486 PackageParser pp = new PackageParser(); 15487 pp.setSeparateProcesses(mSeparateProcesses); 15488 pp.setDisplayMetrics(mMetrics); 15489 15490 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 15491 final PackageParser.Package pkg; 15492 try { 15493 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 15494 } catch (PackageParserException e) { 15495 res.setError("Failed parse during installPackageLI", e); 15496 return; 15497 } finally { 15498 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15499 } 15500 15501 // Ephemeral apps must have target SDK >= O. 15502 // TODO: Update conditional and error message when O gets locked down 15503 if (ephemeral && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) { 15504 res.setError(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID, 15505 "Ephemeral apps must have target SDK version of at least O"); 15506 return; 15507 } 15508 15509 // If we are installing a clustered package add results for the children 15510 if (pkg.childPackages != null) { 15511 synchronized (mPackages) { 15512 final int childCount = pkg.childPackages.size(); 15513 for (int i = 0; i < childCount; i++) { 15514 PackageParser.Package childPkg = pkg.childPackages.get(i); 15515 PackageInstalledInfo childRes = new PackageInstalledInfo(); 15516 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 15517 childRes.pkg = childPkg; 15518 childRes.name = childPkg.packageName; 15519 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 15520 if (childPs != null) { 15521 childRes.origUsers = childPs.queryInstalledUsers( 15522 sUserManager.getUserIds(), true); 15523 } 15524 if ((mPackages.containsKey(childPkg.packageName))) { 15525 childRes.removedInfo = new PackageRemovedInfo(); 15526 childRes.removedInfo.removedPackage = childPkg.packageName; 15527 } 15528 if (res.addedChildPackages == null) { 15529 res.addedChildPackages = new ArrayMap<>(); 15530 } 15531 res.addedChildPackages.put(childPkg.packageName, childRes); 15532 } 15533 } 15534 } 15535 15536 // If package doesn't declare API override, mark that we have an install 15537 // time CPU ABI override. 15538 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 15539 pkg.cpuAbiOverride = args.abiOverride; 15540 } 15541 15542 String pkgName = res.name = pkg.packageName; 15543 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 15544 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 15545 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 15546 return; 15547 } 15548 } 15549 15550 try { 15551 // either use what we've been given or parse directly from the APK 15552 if (args.certificates != null) { 15553 try { 15554 PackageParser.populateCertificates(pkg, args.certificates); 15555 } catch (PackageParserException e) { 15556 // there was something wrong with the certificates we were given; 15557 // try to pull them from the APK 15558 PackageParser.collectCertificates(pkg, parseFlags); 15559 } 15560 } else { 15561 PackageParser.collectCertificates(pkg, parseFlags); 15562 } 15563 } catch (PackageParserException e) { 15564 res.setError("Failed collect during installPackageLI", e); 15565 return; 15566 } 15567 15568 // Get rid of all references to package scan path via parser. 15569 pp = null; 15570 String oldCodePath = null; 15571 boolean systemApp = false; 15572 synchronized (mPackages) { 15573 // Check if installing already existing package 15574 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 15575 String oldName = mSettings.getRenamedPackageLPr(pkgName); 15576 if (pkg.mOriginalPackages != null 15577 && pkg.mOriginalPackages.contains(oldName) 15578 && mPackages.containsKey(oldName)) { 15579 // This package is derived from an original package, 15580 // and this device has been updating from that original 15581 // name. We must continue using the original name, so 15582 // rename the new package here. 15583 pkg.setPackageName(oldName); 15584 pkgName = pkg.packageName; 15585 replace = true; 15586 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 15587 + oldName + " pkgName=" + pkgName); 15588 } else if (mPackages.containsKey(pkgName)) { 15589 // This package, under its official name, already exists 15590 // on the device; we should replace it. 15591 replace = true; 15592 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 15593 } 15594 15595 // Child packages are installed through the parent package 15596 if (pkg.parentPackage != null) { 15597 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 15598 "Package " + pkg.packageName + " is child of package " 15599 + pkg.parentPackage.parentPackage + ". Child packages " 15600 + "can be updated only through the parent package."); 15601 return; 15602 } 15603 15604 if (replace) { 15605 // Prevent apps opting out from runtime permissions 15606 PackageParser.Package oldPackage = mPackages.get(pkgName); 15607 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 15608 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 15609 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 15610 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 15611 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 15612 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 15613 + " doesn't support runtime permissions but the old" 15614 + " target SDK " + oldTargetSdk + " does."); 15615 return; 15616 } 15617 15618 // Prevent installing of child packages 15619 if (oldPackage.parentPackage != null) { 15620 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 15621 "Package " + pkg.packageName + " is child of package " 15622 + oldPackage.parentPackage + ". Child packages " 15623 + "can be updated only through the parent package."); 15624 return; 15625 } 15626 } 15627 } 15628 15629 PackageSetting ps = mSettings.mPackages.get(pkgName); 15630 if (ps != null) { 15631 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 15632 15633 // Quick sanity check that we're signed correctly if updating; 15634 // we'll check this again later when scanning, but we want to 15635 // bail early here before tripping over redefined permissions. 15636 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 15637 if (!checkUpgradeKeySetLP(ps, pkg)) { 15638 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 15639 + pkg.packageName + " upgrade keys do not match the " 15640 + "previously installed version"); 15641 return; 15642 } 15643 } else { 15644 try { 15645 verifySignaturesLP(ps, pkg); 15646 } catch (PackageManagerException e) { 15647 res.setError(e.error, e.getMessage()); 15648 return; 15649 } 15650 } 15651 15652 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 15653 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 15654 systemApp = (ps.pkg.applicationInfo.flags & 15655 ApplicationInfo.FLAG_SYSTEM) != 0; 15656 } 15657 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 15658 } 15659 15660 // Check whether the newly-scanned package wants to define an already-defined perm 15661 int N = pkg.permissions.size(); 15662 for (int i = N-1; i >= 0; i--) { 15663 PackageParser.Permission perm = pkg.permissions.get(i); 15664 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 15665 if (bp != null) { 15666 // If the defining package is signed with our cert, it's okay. This 15667 // also includes the "updating the same package" case, of course. 15668 // "updating same package" could also involve key-rotation. 15669 final boolean sigsOk; 15670 if (bp.sourcePackage.equals(pkg.packageName) 15671 && (bp.packageSetting instanceof PackageSetting) 15672 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 15673 scanFlags))) { 15674 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 15675 } else { 15676 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 15677 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 15678 } 15679 if (!sigsOk) { 15680 // If the owning package is the system itself, we log but allow 15681 // install to proceed; we fail the install on all other permission 15682 // redefinitions. 15683 if (!bp.sourcePackage.equals("android")) { 15684 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 15685 + pkg.packageName + " attempting to redeclare permission " 15686 + perm.info.name + " already owned by " + bp.sourcePackage); 15687 res.origPermission = perm.info.name; 15688 res.origPackage = bp.sourcePackage; 15689 return; 15690 } else { 15691 Slog.w(TAG, "Package " + pkg.packageName 15692 + " attempting to redeclare system permission " 15693 + perm.info.name + "; ignoring new declaration"); 15694 pkg.permissions.remove(i); 15695 } 15696 } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) { 15697 // Prevent apps to change protection level to dangerous from any other 15698 // type as this would allow a privilege escalation where an app adds a 15699 // normal/signature permission in other app's group and later redefines 15700 // it as dangerous leading to the group auto-grant. 15701 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE) 15702 == PermissionInfo.PROTECTION_DANGEROUS) { 15703 if (bp != null && !bp.isRuntime()) { 15704 Slog.w(TAG, "Package " + pkg.packageName + " trying to change a " 15705 + "non-runtime permission " + perm.info.name 15706 + " to runtime; keeping old protection level"); 15707 perm.info.protectionLevel = bp.protectionLevel; 15708 } 15709 } 15710 } 15711 } 15712 } 15713 } 15714 15715 if (systemApp) { 15716 if (onExternal) { 15717 // Abort update; system app can't be replaced with app on sdcard 15718 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 15719 "Cannot install updates to system apps on sdcard"); 15720 return; 15721 } else if (ephemeral) { 15722 // Abort update; system app can't be replaced with an ephemeral app 15723 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 15724 "Cannot update a system app with an ephemeral app"); 15725 return; 15726 } 15727 } 15728 15729 if (args.move != null) { 15730 // We did an in-place move, so dex is ready to roll 15731 scanFlags |= SCAN_NO_DEX; 15732 scanFlags |= SCAN_MOVE; 15733 15734 synchronized (mPackages) { 15735 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15736 if (ps == null) { 15737 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 15738 "Missing settings for moved package " + pkgName); 15739 } 15740 15741 // We moved the entire application as-is, so bring over the 15742 // previously derived ABI information. 15743 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 15744 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 15745 } 15746 15747 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 15748 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 15749 scanFlags |= SCAN_NO_DEX; 15750 15751 try { 15752 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 15753 args.abiOverride : pkg.cpuAbiOverride); 15754 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 15755 true /*extractLibs*/, mAppLib32InstallDir); 15756 } catch (PackageManagerException pme) { 15757 Slog.e(TAG, "Error deriving application ABI", pme); 15758 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 15759 return; 15760 } 15761 15762 // Shared libraries for the package need to be updated. 15763 synchronized (mPackages) { 15764 try { 15765 updateSharedLibrariesLPr(pkg, null); 15766 } catch (PackageManagerException e) { 15767 Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage()); 15768 } 15769 } 15770 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 15771 // Do not run PackageDexOptimizer through the local performDexOpt 15772 // method because `pkg` may not be in `mPackages` yet. 15773 // 15774 // Also, don't fail application installs if the dexopt step fails. 15775 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 15776 null /* instructionSets */, false /* checkProfiles */, 15777 getCompilerFilterForReason(REASON_INSTALL), 15778 getOrCreateCompilerPackageStats(pkg)); 15779 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15780 15781 // Notify BackgroundDexOptService that the package has been changed. 15782 // If this is an update of a package which used to fail to compile, 15783 // BDOS will remove it from its blacklist. 15784 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 15785 } 15786 15787 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 15788 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 15789 return; 15790 } 15791 15792 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 15793 15794 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 15795 "installPackageLI")) { 15796 if (replace) { 15797 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 15798 installerPackageName, res); 15799 } else { 15800 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 15801 args.user, installerPackageName, volumeUuid, res); 15802 } 15803 } 15804 synchronized (mPackages) { 15805 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15806 if (ps != null) { 15807 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 15808 } 15809 15810 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15811 for (int i = 0; i < childCount; i++) { 15812 PackageParser.Package childPkg = pkg.childPackages.get(i); 15813 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 15814 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 15815 if (childPs != null) { 15816 childRes.newUsers = childPs.queryInstalledUsers( 15817 sUserManager.getUserIds(), true); 15818 } 15819 } 15820 } 15821 } 15822 15823 private void startIntentFilterVerifications(int userId, boolean replacing, 15824 PackageParser.Package pkg) { 15825 if (mIntentFilterVerifierComponent == null) { 15826 Slog.w(TAG, "No IntentFilter verification will not be done as " 15827 + "there is no IntentFilterVerifier available!"); 15828 return; 15829 } 15830 15831 final int verifierUid = getPackageUid( 15832 mIntentFilterVerifierComponent.getPackageName(), 15833 MATCH_DEBUG_TRIAGED_MISSING, 15834 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 15835 15836 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15837 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 15838 mHandler.sendMessage(msg); 15839 15840 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15841 for (int i = 0; i < childCount; i++) { 15842 PackageParser.Package childPkg = pkg.childPackages.get(i); 15843 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15844 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 15845 mHandler.sendMessage(msg); 15846 } 15847 } 15848 15849 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 15850 PackageParser.Package pkg) { 15851 int size = pkg.activities.size(); 15852 if (size == 0) { 15853 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15854 "No activity, so no need to verify any IntentFilter!"); 15855 return; 15856 } 15857 15858 final boolean hasDomainURLs = hasDomainURLs(pkg); 15859 if (!hasDomainURLs) { 15860 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15861 "No domain URLs, so no need to verify any IntentFilter!"); 15862 return; 15863 } 15864 15865 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 15866 + " if any IntentFilter from the " + size 15867 + " Activities needs verification ..."); 15868 15869 int count = 0; 15870 final String packageName = pkg.packageName; 15871 15872 synchronized (mPackages) { 15873 // If this is a new install and we see that we've already run verification for this 15874 // package, we have nothing to do: it means the state was restored from backup. 15875 if (!replacing) { 15876 IntentFilterVerificationInfo ivi = 15877 mSettings.getIntentFilterVerificationLPr(packageName); 15878 if (ivi != null) { 15879 if (DEBUG_DOMAIN_VERIFICATION) { 15880 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 15881 + ivi.getStatusString()); 15882 } 15883 return; 15884 } 15885 } 15886 15887 // If any filters need to be verified, then all need to be. 15888 boolean needToVerify = false; 15889 for (PackageParser.Activity a : pkg.activities) { 15890 for (ActivityIntentInfo filter : a.intents) { 15891 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 15892 if (DEBUG_DOMAIN_VERIFICATION) { 15893 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 15894 } 15895 needToVerify = true; 15896 break; 15897 } 15898 } 15899 } 15900 15901 if (needToVerify) { 15902 final int verificationId = mIntentFilterVerificationToken++; 15903 for (PackageParser.Activity a : pkg.activities) { 15904 for (ActivityIntentInfo filter : a.intents) { 15905 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 15906 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15907 "Verification needed for IntentFilter:" + filter.toString()); 15908 mIntentFilterVerifier.addOneIntentFilterVerification( 15909 verifierUid, userId, verificationId, filter, packageName); 15910 count++; 15911 } 15912 } 15913 } 15914 } 15915 } 15916 15917 if (count > 0) { 15918 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 15919 + " IntentFilter verification" + (count > 1 ? "s" : "") 15920 + " for userId:" + userId); 15921 mIntentFilterVerifier.startVerifications(userId); 15922 } else { 15923 if (DEBUG_DOMAIN_VERIFICATION) { 15924 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 15925 } 15926 } 15927 } 15928 15929 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 15930 final ComponentName cn = filter.activity.getComponentName(); 15931 final String packageName = cn.getPackageName(); 15932 15933 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 15934 packageName); 15935 if (ivi == null) { 15936 return true; 15937 } 15938 int status = ivi.getStatus(); 15939 switch (status) { 15940 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 15941 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 15942 return true; 15943 15944 default: 15945 // Nothing to do 15946 return false; 15947 } 15948 } 15949 15950 private static boolean isMultiArch(ApplicationInfo info) { 15951 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 15952 } 15953 15954 private static boolean isExternal(PackageParser.Package pkg) { 15955 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15956 } 15957 15958 private static boolean isExternal(PackageSetting ps) { 15959 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15960 } 15961 15962 private static boolean isEphemeral(PackageParser.Package pkg) { 15963 return pkg.applicationInfo.isEphemeralApp(); 15964 } 15965 15966 private static boolean isEphemeral(PackageSetting ps) { 15967 return ps.pkg != null && isEphemeral(ps.pkg); 15968 } 15969 15970 private static boolean isSystemApp(PackageParser.Package pkg) { 15971 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 15972 } 15973 15974 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 15975 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 15976 } 15977 15978 private static boolean hasDomainURLs(PackageParser.Package pkg) { 15979 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 15980 } 15981 15982 private static boolean isSystemApp(PackageSetting ps) { 15983 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 15984 } 15985 15986 private static boolean isUpdatedSystemApp(PackageSetting ps) { 15987 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 15988 } 15989 15990 private int packageFlagsToInstallFlags(PackageSetting ps) { 15991 int installFlags = 0; 15992 if (isEphemeral(ps)) { 15993 installFlags |= PackageManager.INSTALL_EPHEMERAL; 15994 } 15995 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 15996 // This existing package was an external ASEC install when we have 15997 // the external flag without a UUID 15998 installFlags |= PackageManager.INSTALL_EXTERNAL; 15999 } 16000 if (ps.isForwardLocked()) { 16001 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 16002 } 16003 return installFlags; 16004 } 16005 16006 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 16007 if (isExternal(pkg)) { 16008 if (TextUtils.isEmpty(pkg.volumeUuid)) { 16009 return StorageManager.UUID_PRIMARY_PHYSICAL; 16010 } else { 16011 return pkg.volumeUuid; 16012 } 16013 } else { 16014 return StorageManager.UUID_PRIVATE_INTERNAL; 16015 } 16016 } 16017 16018 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 16019 if (isExternal(pkg)) { 16020 if (TextUtils.isEmpty(pkg.volumeUuid)) { 16021 return mSettings.getExternalVersion(); 16022 } else { 16023 return mSettings.findOrCreateVersion(pkg.volumeUuid); 16024 } 16025 } else { 16026 return mSettings.getInternalVersion(); 16027 } 16028 } 16029 16030 private void deleteTempPackageFiles() { 16031 final FilenameFilter filter = new FilenameFilter() { 16032 public boolean accept(File dir, String name) { 16033 return name.startsWith("vmdl") && name.endsWith(".tmp"); 16034 } 16035 }; 16036 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 16037 file.delete(); 16038 } 16039 } 16040 16041 @Override 16042 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 16043 int flags) { 16044 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 16045 flags); 16046 } 16047 16048 @Override 16049 public void deletePackage(final String packageName, 16050 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 16051 mContext.enforceCallingOrSelfPermission( 16052 android.Manifest.permission.DELETE_PACKAGES, null); 16053 Preconditions.checkNotNull(packageName); 16054 Preconditions.checkNotNull(observer); 16055 final int uid = Binder.getCallingUid(); 16056 if (!isOrphaned(packageName) 16057 && !isCallerAllowedToSilentlyUninstall(uid, packageName)) { 16058 try { 16059 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 16060 intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null)); 16061 intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder()); 16062 observer.onUserActionRequired(intent); 16063 } catch (RemoteException re) { 16064 } 16065 return; 16066 } 16067 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 16068 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 16069 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 16070 mContext.enforceCallingOrSelfPermission( 16071 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 16072 "deletePackage for user " + userId); 16073 } 16074 16075 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 16076 try { 16077 observer.onPackageDeleted(packageName, 16078 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 16079 } catch (RemoteException re) { 16080 } 16081 return; 16082 } 16083 16084 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 16085 try { 16086 observer.onPackageDeleted(packageName, 16087 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 16088 } catch (RemoteException re) { 16089 } 16090 return; 16091 } 16092 16093 if (DEBUG_REMOVE) { 16094 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 16095 + " deleteAllUsers: " + deleteAllUsers ); 16096 } 16097 // Queue up an async operation since the package deletion may take a little while. 16098 mHandler.post(new Runnable() { 16099 public void run() { 16100 mHandler.removeCallbacks(this); 16101 int returnCode; 16102 if (!deleteAllUsers) { 16103 returnCode = deletePackageX(packageName, userId, deleteFlags); 16104 } else { 16105 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 16106 // If nobody is blocking uninstall, proceed with delete for all users 16107 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 16108 returnCode = deletePackageX(packageName, userId, deleteFlags); 16109 } else { 16110 // Otherwise uninstall individually for users with blockUninstalls=false 16111 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 16112 for (int userId : users) { 16113 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 16114 returnCode = deletePackageX(packageName, userId, userFlags); 16115 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 16116 Slog.w(TAG, "Package delete failed for user " + userId 16117 + ", returnCode " + returnCode); 16118 } 16119 } 16120 } 16121 // The app has only been marked uninstalled for certain users. 16122 // We still need to report that delete was blocked 16123 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 16124 } 16125 } 16126 try { 16127 observer.onPackageDeleted(packageName, returnCode, null); 16128 } catch (RemoteException e) { 16129 Log.i(TAG, "Observer no longer exists."); 16130 } //end catch 16131 } //end run 16132 }); 16133 } 16134 16135 private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) { 16136 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID 16137 || callingUid == Process.SYSTEM_UID) { 16138 return true; 16139 } 16140 final int callingUserId = UserHandle.getUserId(callingUid); 16141 // If the caller installed the pkgName, then allow it to silently uninstall. 16142 if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) { 16143 return true; 16144 } 16145 16146 // Allow package verifier to silently uninstall. 16147 if (mRequiredVerifierPackage != null && 16148 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) { 16149 return true; 16150 } 16151 16152 // Allow package uninstaller to silently uninstall. 16153 if (mRequiredUninstallerPackage != null && 16154 callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) { 16155 return true; 16156 } 16157 16158 // Allow storage manager to silently uninstall. 16159 if (mStorageManagerPackage != null && 16160 callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) { 16161 return true; 16162 } 16163 return false; 16164 } 16165 16166 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 16167 int[] result = EMPTY_INT_ARRAY; 16168 for (int userId : userIds) { 16169 if (getBlockUninstallForUser(packageName, userId)) { 16170 result = ArrayUtils.appendInt(result, userId); 16171 } 16172 } 16173 return result; 16174 } 16175 16176 @Override 16177 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 16178 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 16179 } 16180 16181 private boolean isPackageDeviceAdmin(String packageName, int userId) { 16182 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 16183 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 16184 try { 16185 if (dpm != null) { 16186 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 16187 /* callingUserOnly =*/ false); 16188 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 16189 : deviceOwnerComponentName.getPackageName(); 16190 // Does the package contains the device owner? 16191 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 16192 // this check is probably not needed, since DO should be registered as a device 16193 // admin on some user too. (Original bug for this: b/17657954) 16194 if (packageName.equals(deviceOwnerPackageName)) { 16195 return true; 16196 } 16197 // Does it contain a device admin for any user? 16198 int[] users; 16199 if (userId == UserHandle.USER_ALL) { 16200 users = sUserManager.getUserIds(); 16201 } else { 16202 users = new int[]{userId}; 16203 } 16204 for (int i = 0; i < users.length; ++i) { 16205 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 16206 return true; 16207 } 16208 } 16209 } 16210 } catch (RemoteException e) { 16211 } 16212 return false; 16213 } 16214 16215 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 16216 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 16217 } 16218 16219 /** 16220 * This method is an internal method that could be get invoked either 16221 * to delete an installed package or to clean up a failed installation. 16222 * After deleting an installed package, a broadcast is sent to notify any 16223 * listeners that the package has been removed. For cleaning up a failed 16224 * installation, the broadcast is not necessary since the package's 16225 * installation wouldn't have sent the initial broadcast either 16226 * The key steps in deleting a package are 16227 * deleting the package information in internal structures like mPackages, 16228 * deleting the packages base directories through installd 16229 * updating mSettings to reflect current status 16230 * persisting settings for later use 16231 * sending a broadcast if necessary 16232 */ 16233 private int deletePackageX(String packageName, int userId, int deleteFlags) { 16234 final PackageRemovedInfo info = new PackageRemovedInfo(); 16235 final boolean res; 16236 16237 final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 16238 ? UserHandle.USER_ALL : userId; 16239 16240 if (isPackageDeviceAdmin(packageName, removeUser)) { 16241 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 16242 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 16243 } 16244 16245 PackageSetting uninstalledPs = null; 16246 16247 // for the uninstall-updates case and restricted profiles, remember the per- 16248 // user handle installed state 16249 int[] allUsers; 16250 synchronized (mPackages) { 16251 uninstalledPs = mSettings.mPackages.get(packageName); 16252 if (uninstalledPs == null) { 16253 Slog.w(TAG, "Not removing non-existent package " + packageName); 16254 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 16255 } 16256 allUsers = sUserManager.getUserIds(); 16257 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 16258 } 16259 16260 final int freezeUser; 16261 if (isUpdatedSystemApp(uninstalledPs) 16262 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) { 16263 // We're downgrading a system app, which will apply to all users, so 16264 // freeze them all during the downgrade 16265 freezeUser = UserHandle.USER_ALL; 16266 } else { 16267 freezeUser = removeUser; 16268 } 16269 16270 synchronized (mInstallLock) { 16271 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 16272 try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser, 16273 deleteFlags, "deletePackageX")) { 16274 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers, 16275 deleteFlags | REMOVE_CHATTY, info, true, null); 16276 } 16277 synchronized (mPackages) { 16278 if (res) { 16279 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 16280 } 16281 } 16282 } 16283 16284 if (res) { 16285 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 16286 info.sendPackageRemovedBroadcasts(killApp); 16287 info.sendSystemPackageUpdatedBroadcasts(); 16288 info.sendSystemPackageAppearedBroadcasts(); 16289 } 16290 // Force a gc here. 16291 Runtime.getRuntime().gc(); 16292 // Delete the resources here after sending the broadcast to let 16293 // other processes clean up before deleting resources. 16294 if (info.args != null) { 16295 synchronized (mInstallLock) { 16296 info.args.doPostDeleteLI(true); 16297 } 16298 } 16299 16300 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 16301 } 16302 16303 class PackageRemovedInfo { 16304 String removedPackage; 16305 int uid = -1; 16306 int removedAppId = -1; 16307 int[] origUsers; 16308 int[] removedUsers = null; 16309 boolean isRemovedPackageSystemUpdate = false; 16310 boolean isUpdate; 16311 boolean dataRemoved; 16312 boolean removedForAllUsers; 16313 // Clean up resources deleted packages. 16314 InstallArgs args = null; 16315 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 16316 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 16317 16318 void sendPackageRemovedBroadcasts(boolean killApp) { 16319 sendPackageRemovedBroadcastInternal(killApp); 16320 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 16321 for (int i = 0; i < childCount; i++) { 16322 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 16323 childInfo.sendPackageRemovedBroadcastInternal(killApp); 16324 } 16325 } 16326 16327 void sendSystemPackageUpdatedBroadcasts() { 16328 if (isRemovedPackageSystemUpdate) { 16329 sendSystemPackageUpdatedBroadcastsInternal(); 16330 final int childCount = (removedChildPackages != null) 16331 ? removedChildPackages.size() : 0; 16332 for (int i = 0; i < childCount; i++) { 16333 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 16334 if (childInfo.isRemovedPackageSystemUpdate) { 16335 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 16336 } 16337 } 16338 } 16339 } 16340 16341 void sendSystemPackageAppearedBroadcasts() { 16342 final int packageCount = (appearedChildPackages != null) 16343 ? appearedChildPackages.size() : 0; 16344 for (int i = 0; i < packageCount; i++) { 16345 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 16346 sendPackageAddedForNewUsers(installedInfo.name, true, 16347 UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers); 16348 } 16349 } 16350 16351 private void sendSystemPackageUpdatedBroadcastsInternal() { 16352 Bundle extras = new Bundle(2); 16353 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 16354 extras.putBoolean(Intent.EXTRA_REPLACING, true); 16355 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 16356 extras, 0, null, null, null); 16357 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 16358 extras, 0, null, null, null); 16359 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 16360 null, 0, removedPackage, null, null); 16361 } 16362 16363 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 16364 Bundle extras = new Bundle(2); 16365 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 16366 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 16367 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 16368 if (isUpdate || isRemovedPackageSystemUpdate) { 16369 extras.putBoolean(Intent.EXTRA_REPLACING, true); 16370 } 16371 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 16372 if (removedPackage != null) { 16373 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 16374 extras, 0, null, null, removedUsers); 16375 if (dataRemoved && !isRemovedPackageSystemUpdate) { 16376 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 16377 removedPackage, extras, 0, null, null, removedUsers); 16378 } 16379 } 16380 if (removedAppId >= 0) { 16381 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 16382 removedUsers); 16383 } 16384 } 16385 } 16386 16387 /* 16388 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 16389 * flag is not set, the data directory is removed as well. 16390 * make sure this flag is set for partially installed apps. If not its meaningless to 16391 * delete a partially installed application. 16392 */ 16393 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 16394 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 16395 String packageName = ps.name; 16396 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 16397 // Retrieve object to delete permissions for shared user later on 16398 final PackageParser.Package deletedPkg; 16399 final PackageSetting deletedPs; 16400 // reader 16401 synchronized (mPackages) { 16402 deletedPkg = mPackages.get(packageName); 16403 deletedPs = mSettings.mPackages.get(packageName); 16404 if (outInfo != null) { 16405 outInfo.removedPackage = packageName; 16406 outInfo.removedUsers = deletedPs != null 16407 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 16408 : null; 16409 } 16410 } 16411 16412 removePackageLI(ps, (flags & REMOVE_CHATTY) != 0); 16413 16414 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 16415 final PackageParser.Package resolvedPkg; 16416 if (deletedPkg != null) { 16417 resolvedPkg = deletedPkg; 16418 } else { 16419 // We don't have a parsed package when it lives on an ejected 16420 // adopted storage device, so fake something together 16421 resolvedPkg = new PackageParser.Package(ps.name); 16422 resolvedPkg.setVolumeUuid(ps.volumeUuid); 16423 } 16424 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 16425 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16426 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 16427 if (outInfo != null) { 16428 outInfo.dataRemoved = true; 16429 } 16430 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 16431 } 16432 16433 // writer 16434 synchronized (mPackages) { 16435 if (deletedPs != null) { 16436 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 16437 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 16438 clearDefaultBrowserIfNeeded(packageName); 16439 if (outInfo != null) { 16440 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 16441 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 16442 } 16443 updatePermissionsLPw(deletedPs.name, null, 0); 16444 if (deletedPs.sharedUser != null) { 16445 // Remove permissions associated with package. Since runtime 16446 // permissions are per user we have to kill the removed package 16447 // or packages running under the shared user of the removed 16448 // package if revoking the permissions requested only by the removed 16449 // package is successful and this causes a change in gids. 16450 for (int userId : UserManagerService.getInstance().getUserIds()) { 16451 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 16452 userId); 16453 if (userIdToKill == UserHandle.USER_ALL 16454 || userIdToKill >= UserHandle.USER_SYSTEM) { 16455 // If gids changed for this user, kill all affected packages. 16456 mHandler.post(new Runnable() { 16457 @Override 16458 public void run() { 16459 // This has to happen with no lock held. 16460 killApplication(deletedPs.name, deletedPs.appId, 16461 KILL_APP_REASON_GIDS_CHANGED); 16462 } 16463 }); 16464 break; 16465 } 16466 } 16467 } 16468 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 16469 } 16470 // make sure to preserve per-user disabled state if this removal was just 16471 // a downgrade of a system app to the factory package 16472 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 16473 if (DEBUG_REMOVE) { 16474 Slog.d(TAG, "Propagating install state across downgrade"); 16475 } 16476 for (int userId : allUserHandles) { 16477 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 16478 if (DEBUG_REMOVE) { 16479 Slog.d(TAG, " user " + userId + " => " + installed); 16480 } 16481 ps.setInstalled(installed, userId); 16482 } 16483 } 16484 } 16485 // can downgrade to reader 16486 if (writeSettings) { 16487 // Save settings now 16488 mSettings.writeLPr(); 16489 } 16490 } 16491 if (outInfo != null) { 16492 // A user ID was deleted here. Go through all users and remove it 16493 // from KeyStore. 16494 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 16495 } 16496 } 16497 16498 static boolean locationIsPrivileged(File path) { 16499 try { 16500 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 16501 .getCanonicalPath(); 16502 return path.getCanonicalPath().startsWith(privilegedAppDir); 16503 } catch (IOException e) { 16504 Slog.e(TAG, "Unable to access code path " + path); 16505 } 16506 return false; 16507 } 16508 16509 /* 16510 * Tries to delete system package. 16511 */ 16512 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 16513 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 16514 boolean writeSettings) { 16515 if (deletedPs.parentPackageName != null) { 16516 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 16517 return false; 16518 } 16519 16520 final boolean applyUserRestrictions 16521 = (allUserHandles != null) && (outInfo.origUsers != null); 16522 final PackageSetting disabledPs; 16523 // Confirm if the system package has been updated 16524 // An updated system app can be deleted. This will also have to restore 16525 // the system pkg from system partition 16526 // reader 16527 synchronized (mPackages) { 16528 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 16529 } 16530 16531 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 16532 + " disabledPs=" + disabledPs); 16533 16534 if (disabledPs == null) { 16535 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 16536 return false; 16537 } else if (DEBUG_REMOVE) { 16538 Slog.d(TAG, "Deleting system pkg from data partition"); 16539 } 16540 16541 if (DEBUG_REMOVE) { 16542 if (applyUserRestrictions) { 16543 Slog.d(TAG, "Remembering install states:"); 16544 for (int userId : allUserHandles) { 16545 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 16546 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 16547 } 16548 } 16549 } 16550 16551 // Delete the updated package 16552 outInfo.isRemovedPackageSystemUpdate = true; 16553 if (outInfo.removedChildPackages != null) { 16554 final int childCount = (deletedPs.childPackageNames != null) 16555 ? deletedPs.childPackageNames.size() : 0; 16556 for (int i = 0; i < childCount; i++) { 16557 String childPackageName = deletedPs.childPackageNames.get(i); 16558 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 16559 .contains(childPackageName)) { 16560 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 16561 childPackageName); 16562 if (childInfo != null) { 16563 childInfo.isRemovedPackageSystemUpdate = true; 16564 } 16565 } 16566 } 16567 } 16568 16569 if (disabledPs.versionCode < deletedPs.versionCode) { 16570 // Delete data for downgrades 16571 flags &= ~PackageManager.DELETE_KEEP_DATA; 16572 } else { 16573 // Preserve data by setting flag 16574 flags |= PackageManager.DELETE_KEEP_DATA; 16575 } 16576 16577 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 16578 outInfo, writeSettings, disabledPs.pkg); 16579 if (!ret) { 16580 return false; 16581 } 16582 16583 // writer 16584 synchronized (mPackages) { 16585 // Reinstate the old system package 16586 enableSystemPackageLPw(disabledPs.pkg); 16587 // Remove any native libraries from the upgraded package. 16588 removeNativeBinariesLI(deletedPs); 16589 } 16590 16591 // Install the system package 16592 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 16593 int parseFlags = mDefParseFlags 16594 | PackageParser.PARSE_MUST_BE_APK 16595 | PackageParser.PARSE_IS_SYSTEM 16596 | PackageParser.PARSE_IS_SYSTEM_DIR; 16597 if (locationIsPrivileged(disabledPs.codePath)) { 16598 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 16599 } 16600 16601 final PackageParser.Package newPkg; 16602 try { 16603 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */, 16604 0 /* currentTime */, null); 16605 } catch (PackageManagerException e) { 16606 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 16607 + e.getMessage()); 16608 return false; 16609 } 16610 try { 16611 // update shared libraries for the newly re-installed system package 16612 updateSharedLibrariesLPr(newPkg, null); 16613 } catch (PackageManagerException e) { 16614 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 16615 } 16616 16617 prepareAppDataAfterInstallLIF(newPkg); 16618 16619 // writer 16620 synchronized (mPackages) { 16621 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 16622 16623 // Propagate the permissions state as we do not want to drop on the floor 16624 // runtime permissions. The update permissions method below will take 16625 // care of removing obsolete permissions and grant install permissions. 16626 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 16627 updatePermissionsLPw(newPkg.packageName, newPkg, 16628 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 16629 16630 if (applyUserRestrictions) { 16631 if (DEBUG_REMOVE) { 16632 Slog.d(TAG, "Propagating install state across reinstall"); 16633 } 16634 for (int userId : allUserHandles) { 16635 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 16636 if (DEBUG_REMOVE) { 16637 Slog.d(TAG, " user " + userId + " => " + installed); 16638 } 16639 ps.setInstalled(installed, userId); 16640 16641 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 16642 } 16643 // Regardless of writeSettings we need to ensure that this restriction 16644 // state propagation is persisted 16645 mSettings.writeAllUsersPackageRestrictionsLPr(); 16646 } 16647 // can downgrade to reader here 16648 if (writeSettings) { 16649 mSettings.writeLPr(); 16650 } 16651 } 16652 return true; 16653 } 16654 16655 private boolean deleteInstalledPackageLIF(PackageSetting ps, 16656 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 16657 PackageRemovedInfo outInfo, boolean writeSettings, 16658 PackageParser.Package replacingPackage) { 16659 synchronized (mPackages) { 16660 if (outInfo != null) { 16661 outInfo.uid = ps.appId; 16662 } 16663 16664 if (outInfo != null && outInfo.removedChildPackages != null) { 16665 final int childCount = (ps.childPackageNames != null) 16666 ? ps.childPackageNames.size() : 0; 16667 for (int i = 0; i < childCount; i++) { 16668 String childPackageName = ps.childPackageNames.get(i); 16669 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 16670 if (childPs == null) { 16671 return false; 16672 } 16673 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 16674 childPackageName); 16675 if (childInfo != null) { 16676 childInfo.uid = childPs.appId; 16677 } 16678 } 16679 } 16680 } 16681 16682 // Delete package data from internal structures and also remove data if flag is set 16683 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 16684 16685 // Delete the child packages data 16686 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 16687 for (int i = 0; i < childCount; i++) { 16688 PackageSetting childPs; 16689 synchronized (mPackages) { 16690 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 16691 } 16692 if (childPs != null) { 16693 PackageRemovedInfo childOutInfo = (outInfo != null 16694 && outInfo.removedChildPackages != null) 16695 ? outInfo.removedChildPackages.get(childPs.name) : null; 16696 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 16697 && (replacingPackage != null 16698 && !replacingPackage.hasChildPackage(childPs.name)) 16699 ? flags & ~DELETE_KEEP_DATA : flags; 16700 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 16701 deleteFlags, writeSettings); 16702 } 16703 } 16704 16705 // Delete application code and resources only for parent packages 16706 if (ps.parentPackageName == null) { 16707 if (deleteCodeAndResources && (outInfo != null)) { 16708 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 16709 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 16710 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 16711 } 16712 } 16713 16714 return true; 16715 } 16716 16717 @Override 16718 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 16719 int userId) { 16720 mContext.enforceCallingOrSelfPermission( 16721 android.Manifest.permission.DELETE_PACKAGES, null); 16722 synchronized (mPackages) { 16723 PackageSetting ps = mSettings.mPackages.get(packageName); 16724 if (ps == null) { 16725 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 16726 return false; 16727 } 16728 if (!ps.getInstalled(userId)) { 16729 // Can't block uninstall for an app that is not installed or enabled. 16730 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 16731 return false; 16732 } 16733 ps.setBlockUninstall(blockUninstall, userId); 16734 mSettings.writePackageRestrictionsLPr(userId); 16735 } 16736 return true; 16737 } 16738 16739 @Override 16740 public boolean getBlockUninstallForUser(String packageName, int userId) { 16741 synchronized (mPackages) { 16742 PackageSetting ps = mSettings.mPackages.get(packageName); 16743 if (ps == null) { 16744 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 16745 return false; 16746 } 16747 return ps.getBlockUninstall(userId); 16748 } 16749 } 16750 16751 @Override 16752 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 16753 int callingUid = Binder.getCallingUid(); 16754 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 16755 throw new SecurityException( 16756 "setRequiredForSystemUser can only be run by the system or root"); 16757 } 16758 synchronized (mPackages) { 16759 PackageSetting ps = mSettings.mPackages.get(packageName); 16760 if (ps == null) { 16761 Log.w(TAG, "Package doesn't exist: " + packageName); 16762 return false; 16763 } 16764 if (systemUserApp) { 16765 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 16766 } else { 16767 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 16768 } 16769 mSettings.writeLPr(); 16770 } 16771 return true; 16772 } 16773 16774 /* 16775 * This method handles package deletion in general 16776 */ 16777 private boolean deletePackageLIF(String packageName, UserHandle user, 16778 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 16779 PackageRemovedInfo outInfo, boolean writeSettings, 16780 PackageParser.Package replacingPackage) { 16781 if (packageName == null) { 16782 Slog.w(TAG, "Attempt to delete null packageName."); 16783 return false; 16784 } 16785 16786 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 16787 16788 PackageSetting ps; 16789 16790 synchronized (mPackages) { 16791 ps = mSettings.mPackages.get(packageName); 16792 if (ps == null) { 16793 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16794 return false; 16795 } 16796 16797 if (ps.parentPackageName != null && (!isSystemApp(ps) 16798 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 16799 if (DEBUG_REMOVE) { 16800 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 16801 + ((user == null) ? UserHandle.USER_ALL : user)); 16802 } 16803 final int removedUserId = (user != null) ? user.getIdentifier() 16804 : UserHandle.USER_ALL; 16805 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 16806 return false; 16807 } 16808 markPackageUninstalledForUserLPw(ps, user); 16809 scheduleWritePackageRestrictionsLocked(user); 16810 return true; 16811 } 16812 } 16813 16814 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 16815 && user.getIdentifier() != UserHandle.USER_ALL)) { 16816 // The caller is asking that the package only be deleted for a single 16817 // user. To do this, we just mark its uninstalled state and delete 16818 // its data. If this is a system app, we only allow this to happen if 16819 // they have set the special DELETE_SYSTEM_APP which requests different 16820 // semantics than normal for uninstalling system apps. 16821 markPackageUninstalledForUserLPw(ps, user); 16822 16823 if (!isSystemApp(ps)) { 16824 // Do not uninstall the APK if an app should be cached 16825 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 16826 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 16827 // Other user still have this package installed, so all 16828 // we need to do is clear this user's data and save that 16829 // it is uninstalled. 16830 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 16831 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 16832 return false; 16833 } 16834 scheduleWritePackageRestrictionsLocked(user); 16835 return true; 16836 } else { 16837 // We need to set it back to 'installed' so the uninstall 16838 // broadcasts will be sent correctly. 16839 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 16840 ps.setInstalled(true, user.getIdentifier()); 16841 } 16842 } else { 16843 // This is a system app, so we assume that the 16844 // other users still have this package installed, so all 16845 // we need to do is clear this user's data and save that 16846 // it is uninstalled. 16847 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 16848 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 16849 return false; 16850 } 16851 scheduleWritePackageRestrictionsLocked(user); 16852 return true; 16853 } 16854 } 16855 16856 // If we are deleting a composite package for all users, keep track 16857 // of result for each child. 16858 if (ps.childPackageNames != null && outInfo != null) { 16859 synchronized (mPackages) { 16860 final int childCount = ps.childPackageNames.size(); 16861 outInfo.removedChildPackages = new ArrayMap<>(childCount); 16862 for (int i = 0; i < childCount; i++) { 16863 String childPackageName = ps.childPackageNames.get(i); 16864 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 16865 childInfo.removedPackage = childPackageName; 16866 outInfo.removedChildPackages.put(childPackageName, childInfo); 16867 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 16868 if (childPs != null) { 16869 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 16870 } 16871 } 16872 } 16873 } 16874 16875 boolean ret = false; 16876 if (isSystemApp(ps)) { 16877 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 16878 // When an updated system application is deleted we delete the existing resources 16879 // as well and fall back to existing code in system partition 16880 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 16881 } else { 16882 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 16883 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 16884 outInfo, writeSettings, replacingPackage); 16885 } 16886 16887 // Take a note whether we deleted the package for all users 16888 if (outInfo != null) { 16889 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 16890 if (outInfo.removedChildPackages != null) { 16891 synchronized (mPackages) { 16892 final int childCount = outInfo.removedChildPackages.size(); 16893 for (int i = 0; i < childCount; i++) { 16894 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 16895 if (childInfo != null) { 16896 childInfo.removedForAllUsers = mPackages.get( 16897 childInfo.removedPackage) == null; 16898 } 16899 } 16900 } 16901 } 16902 // If we uninstalled an update to a system app there may be some 16903 // child packages that appeared as they are declared in the system 16904 // app but were not declared in the update. 16905 if (isSystemApp(ps)) { 16906 synchronized (mPackages) { 16907 PackageSetting updatedPs = mSettings.getPackageLPr(ps.name); 16908 final int childCount = (updatedPs.childPackageNames != null) 16909 ? updatedPs.childPackageNames.size() : 0; 16910 for (int i = 0; i < childCount; i++) { 16911 String childPackageName = updatedPs.childPackageNames.get(i); 16912 if (outInfo.removedChildPackages == null 16913 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 16914 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 16915 if (childPs == null) { 16916 continue; 16917 } 16918 PackageInstalledInfo installRes = new PackageInstalledInfo(); 16919 installRes.name = childPackageName; 16920 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 16921 installRes.pkg = mPackages.get(childPackageName); 16922 installRes.uid = childPs.pkg.applicationInfo.uid; 16923 if (outInfo.appearedChildPackages == null) { 16924 outInfo.appearedChildPackages = new ArrayMap<>(); 16925 } 16926 outInfo.appearedChildPackages.put(childPackageName, installRes); 16927 } 16928 } 16929 } 16930 } 16931 } 16932 16933 return ret; 16934 } 16935 16936 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 16937 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 16938 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 16939 for (int nextUserId : userIds) { 16940 if (DEBUG_REMOVE) { 16941 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 16942 } 16943 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 16944 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 16945 false /*hidden*/, false /*suspended*/, null, null, null, 16946 false /*blockUninstall*/, 16947 ps.readUserState(nextUserId).domainVerificationStatus, 0); 16948 } 16949 } 16950 16951 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 16952 PackageRemovedInfo outInfo) { 16953 final PackageParser.Package pkg; 16954 synchronized (mPackages) { 16955 pkg = mPackages.get(ps.name); 16956 } 16957 16958 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 16959 : new int[] {userId}; 16960 for (int nextUserId : userIds) { 16961 if (DEBUG_REMOVE) { 16962 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 16963 + nextUserId); 16964 } 16965 16966 destroyAppDataLIF(pkg, userId, 16967 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16968 destroyAppProfilesLIF(pkg, userId); 16969 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 16970 schedulePackageCleaning(ps.name, nextUserId, false); 16971 synchronized (mPackages) { 16972 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 16973 scheduleWritePackageRestrictionsLocked(nextUserId); 16974 } 16975 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 16976 } 16977 } 16978 16979 if (outInfo != null) { 16980 outInfo.removedPackage = ps.name; 16981 outInfo.removedAppId = ps.appId; 16982 outInfo.removedUsers = userIds; 16983 } 16984 16985 return true; 16986 } 16987 16988 private final class ClearStorageConnection implements ServiceConnection { 16989 IMediaContainerService mContainerService; 16990 16991 @Override 16992 public void onServiceConnected(ComponentName name, IBinder service) { 16993 synchronized (this) { 16994 mContainerService = IMediaContainerService.Stub 16995 .asInterface(Binder.allowBlocking(service)); 16996 notifyAll(); 16997 } 16998 } 16999 17000 @Override 17001 public void onServiceDisconnected(ComponentName name) { 17002 } 17003 } 17004 17005 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 17006 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 17007 17008 final boolean mounted; 17009 if (Environment.isExternalStorageEmulated()) { 17010 mounted = true; 17011 } else { 17012 final String status = Environment.getExternalStorageState(); 17013 17014 mounted = status.equals(Environment.MEDIA_MOUNTED) 17015 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 17016 } 17017 17018 if (!mounted) { 17019 return; 17020 } 17021 17022 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 17023 int[] users; 17024 if (userId == UserHandle.USER_ALL) { 17025 users = sUserManager.getUserIds(); 17026 } else { 17027 users = new int[] { userId }; 17028 } 17029 final ClearStorageConnection conn = new ClearStorageConnection(); 17030 if (mContext.bindServiceAsUser( 17031 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 17032 try { 17033 for (int curUser : users) { 17034 long timeout = SystemClock.uptimeMillis() + 5000; 17035 synchronized (conn) { 17036 long now; 17037 while (conn.mContainerService == null && 17038 (now = SystemClock.uptimeMillis()) < timeout) { 17039 try { 17040 conn.wait(timeout - now); 17041 } catch (InterruptedException e) { 17042 } 17043 } 17044 } 17045 if (conn.mContainerService == null) { 17046 return; 17047 } 17048 17049 final UserEnvironment userEnv = new UserEnvironment(curUser); 17050 clearDirectory(conn.mContainerService, 17051 userEnv.buildExternalStorageAppCacheDirs(packageName)); 17052 if (allData) { 17053 clearDirectory(conn.mContainerService, 17054 userEnv.buildExternalStorageAppDataDirs(packageName)); 17055 clearDirectory(conn.mContainerService, 17056 userEnv.buildExternalStorageAppMediaDirs(packageName)); 17057 } 17058 } 17059 } finally { 17060 mContext.unbindService(conn); 17061 } 17062 } 17063 } 17064 17065 @Override 17066 public void clearApplicationProfileData(String packageName) { 17067 enforceSystemOrRoot("Only the system can clear all profile data"); 17068 17069 final PackageParser.Package pkg; 17070 synchronized (mPackages) { 17071 pkg = mPackages.get(packageName); 17072 } 17073 17074 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 17075 synchronized (mInstallLock) { 17076 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 17077 destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL, 17078 true /* removeBaseMarker */); 17079 } 17080 } 17081 } 17082 17083 @Override 17084 public void clearApplicationUserData(final String packageName, 17085 final IPackageDataObserver observer, final int userId) { 17086 mContext.enforceCallingOrSelfPermission( 17087 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 17088 17089 enforceCrossUserPermission(Binder.getCallingUid(), userId, 17090 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 17091 17092 if (mProtectedPackages.isPackageDataProtected(userId, packageName)) { 17093 throw new SecurityException("Cannot clear data for a protected package: " 17094 + packageName); 17095 } 17096 // Queue up an async operation since the package deletion may take a little while. 17097 mHandler.post(new Runnable() { 17098 public void run() { 17099 mHandler.removeCallbacks(this); 17100 final boolean succeeded; 17101 try (PackageFreezer freezer = freezePackage(packageName, 17102 "clearApplicationUserData")) { 17103 synchronized (mInstallLock) { 17104 succeeded = clearApplicationUserDataLIF(packageName, userId); 17105 } 17106 clearExternalStorageDataSync(packageName, userId, true); 17107 } 17108 if (succeeded) { 17109 // invoke DeviceStorageMonitor's update method to clear any notifications 17110 DeviceStorageMonitorInternal dsm = LocalServices 17111 .getService(DeviceStorageMonitorInternal.class); 17112 if (dsm != null) { 17113 dsm.checkMemory(); 17114 } 17115 } 17116 if(observer != null) { 17117 try { 17118 observer.onRemoveCompleted(packageName, succeeded); 17119 } catch (RemoteException e) { 17120 Log.i(TAG, "Observer no longer exists."); 17121 } 17122 } //end if observer 17123 } //end run 17124 }); 17125 } 17126 17127 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 17128 if (packageName == null) { 17129 Slog.w(TAG, "Attempt to delete null packageName."); 17130 return false; 17131 } 17132 17133 // Try finding details about the requested package 17134 PackageParser.Package pkg; 17135 synchronized (mPackages) { 17136 pkg = mPackages.get(packageName); 17137 if (pkg == null) { 17138 final PackageSetting ps = mSettings.mPackages.get(packageName); 17139 if (ps != null) { 17140 pkg = ps.pkg; 17141 } 17142 } 17143 17144 if (pkg == null) { 17145 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 17146 return false; 17147 } 17148 17149 PackageSetting ps = (PackageSetting) pkg.mExtras; 17150 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 17151 } 17152 17153 clearAppDataLIF(pkg, userId, 17154 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 17155 17156 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 17157 removeKeystoreDataIfNeeded(userId, appId); 17158 17159 UserManagerInternal umInternal = getUserManagerInternal(); 17160 final int flags; 17161 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 17162 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 17163 } else if (umInternal.isUserRunning(userId)) { 17164 flags = StorageManager.FLAG_STORAGE_DE; 17165 } else { 17166 flags = 0; 17167 } 17168 prepareAppDataContentsLIF(pkg, userId, flags); 17169 17170 return true; 17171 } 17172 17173 /** 17174 * Reverts user permission state changes (permissions and flags) in 17175 * all packages for a given user. 17176 * 17177 * @param userId The device user for which to do a reset. 17178 */ 17179 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 17180 final int packageCount = mPackages.size(); 17181 for (int i = 0; i < packageCount; i++) { 17182 PackageParser.Package pkg = mPackages.valueAt(i); 17183 PackageSetting ps = (PackageSetting) pkg.mExtras; 17184 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 17185 } 17186 } 17187 17188 private void resetNetworkPolicies(int userId) { 17189 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 17190 } 17191 17192 /** 17193 * Reverts user permission state changes (permissions and flags). 17194 * 17195 * @param ps The package for which to reset. 17196 * @param userId The device user for which to do a reset. 17197 */ 17198 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 17199 final PackageSetting ps, final int userId) { 17200 if (ps.pkg == null) { 17201 return; 17202 } 17203 17204 // These are flags that can change base on user actions. 17205 final int userSettableMask = FLAG_PERMISSION_USER_SET 17206 | FLAG_PERMISSION_USER_FIXED 17207 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 17208 | FLAG_PERMISSION_REVIEW_REQUIRED; 17209 17210 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 17211 | FLAG_PERMISSION_POLICY_FIXED; 17212 17213 boolean writeInstallPermissions = false; 17214 boolean writeRuntimePermissions = false; 17215 17216 final int permissionCount = ps.pkg.requestedPermissions.size(); 17217 for (int i = 0; i < permissionCount; i++) { 17218 String permission = ps.pkg.requestedPermissions.get(i); 17219 17220 BasePermission bp = mSettings.mPermissions.get(permission); 17221 if (bp == null) { 17222 continue; 17223 } 17224 17225 // If shared user we just reset the state to which only this app contributed. 17226 if (ps.sharedUser != null) { 17227 boolean used = false; 17228 final int packageCount = ps.sharedUser.packages.size(); 17229 for (int j = 0; j < packageCount; j++) { 17230 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 17231 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 17232 && pkg.pkg.requestedPermissions.contains(permission)) { 17233 used = true; 17234 break; 17235 } 17236 } 17237 if (used) { 17238 continue; 17239 } 17240 } 17241 17242 PermissionsState permissionsState = ps.getPermissionsState(); 17243 17244 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 17245 17246 // Always clear the user settable flags. 17247 final boolean hasInstallState = permissionsState.getInstallPermissionState( 17248 bp.name) != null; 17249 // If permission review is enabled and this is a legacy app, mark the 17250 // permission as requiring a review as this is the initial state. 17251 int flags = 0; 17252 if (mPermissionReviewRequired 17253 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 17254 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 17255 } 17256 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 17257 if (hasInstallState) { 17258 writeInstallPermissions = true; 17259 } else { 17260 writeRuntimePermissions = true; 17261 } 17262 } 17263 17264 // Below is only runtime permission handling. 17265 if (!bp.isRuntime()) { 17266 continue; 17267 } 17268 17269 // Never clobber system or policy. 17270 if ((oldFlags & policyOrSystemFlags) != 0) { 17271 continue; 17272 } 17273 17274 // If this permission was granted by default, make sure it is. 17275 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 17276 if (permissionsState.grantRuntimePermission(bp, userId) 17277 != PERMISSION_OPERATION_FAILURE) { 17278 writeRuntimePermissions = true; 17279 } 17280 // If permission review is enabled the permissions for a legacy apps 17281 // are represented as constantly granted runtime ones, so don't revoke. 17282 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 17283 // Otherwise, reset the permission. 17284 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 17285 switch (revokeResult) { 17286 case PERMISSION_OPERATION_SUCCESS: 17287 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 17288 writeRuntimePermissions = true; 17289 final int appId = ps.appId; 17290 mHandler.post(new Runnable() { 17291 @Override 17292 public void run() { 17293 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 17294 } 17295 }); 17296 } break; 17297 } 17298 } 17299 } 17300 17301 // Synchronously write as we are taking permissions away. 17302 if (writeRuntimePermissions) { 17303 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 17304 } 17305 17306 // Synchronously write as we are taking permissions away. 17307 if (writeInstallPermissions) { 17308 mSettings.writeLPr(); 17309 } 17310 } 17311 17312 /** 17313 * Remove entries from the keystore daemon. Will only remove it if the 17314 * {@code appId} is valid. 17315 */ 17316 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 17317 if (appId < 0) { 17318 return; 17319 } 17320 17321 final KeyStore keyStore = KeyStore.getInstance(); 17322 if (keyStore != null) { 17323 if (userId == UserHandle.USER_ALL) { 17324 for (final int individual : sUserManager.getUserIds()) { 17325 keyStore.clearUid(UserHandle.getUid(individual, appId)); 17326 } 17327 } else { 17328 keyStore.clearUid(UserHandle.getUid(userId, appId)); 17329 } 17330 } else { 17331 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 17332 } 17333 } 17334 17335 @Override 17336 public void deleteApplicationCacheFiles(final String packageName, 17337 final IPackageDataObserver observer) { 17338 final int userId = UserHandle.getCallingUserId(); 17339 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 17340 } 17341 17342 @Override 17343 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 17344 final IPackageDataObserver observer) { 17345 mContext.enforceCallingOrSelfPermission( 17346 android.Manifest.permission.DELETE_CACHE_FILES, null); 17347 enforceCrossUserPermission(Binder.getCallingUid(), userId, 17348 /* requireFullPermission= */ true, /* checkShell= */ false, 17349 "delete application cache files"); 17350 17351 final PackageParser.Package pkg; 17352 synchronized (mPackages) { 17353 pkg = mPackages.get(packageName); 17354 } 17355 17356 // Queue up an async operation since the package deletion may take a little while. 17357 mHandler.post(new Runnable() { 17358 public void run() { 17359 synchronized (mInstallLock) { 17360 final int flags = StorageManager.FLAG_STORAGE_DE 17361 | StorageManager.FLAG_STORAGE_CE; 17362 // We're only clearing cache files, so we don't care if the 17363 // app is unfrozen and still able to run 17364 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 17365 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 17366 } 17367 clearExternalStorageDataSync(packageName, userId, false); 17368 if (observer != null) { 17369 try { 17370 observer.onRemoveCompleted(packageName, true); 17371 } catch (RemoteException e) { 17372 Log.i(TAG, "Observer no longer exists."); 17373 } 17374 } 17375 } 17376 }); 17377 } 17378 17379 @Override 17380 public void getPackageSizeInfo(final String packageName, int userHandle, 17381 final IPackageStatsObserver observer) { 17382 mContext.enforceCallingOrSelfPermission( 17383 android.Manifest.permission.GET_PACKAGE_SIZE, null); 17384 if (packageName == null) { 17385 throw new IllegalArgumentException("Attempt to get size of null packageName"); 17386 } 17387 17388 PackageStats stats = new PackageStats(packageName, userHandle); 17389 17390 /* 17391 * Queue up an async operation since the package measurement may take a 17392 * little while. 17393 */ 17394 Message msg = mHandler.obtainMessage(INIT_COPY); 17395 msg.obj = new MeasureParams(stats, observer); 17396 mHandler.sendMessage(msg); 17397 } 17398 17399 private boolean equals(PackageStats a, PackageStats b) { 17400 return (a.codeSize == b.codeSize) && (a.dataSize == b.dataSize) 17401 && (a.cacheSize == b.cacheSize); 17402 } 17403 17404 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 17405 final PackageSetting ps; 17406 synchronized (mPackages) { 17407 ps = mSettings.mPackages.get(packageName); 17408 if (ps == null) { 17409 Slog.w(TAG, "Failed to find settings for " + packageName); 17410 return false; 17411 } 17412 } 17413 17414 final long ceDataInode = ps.getCeDataInode(userId); 17415 final PackageStats quotaStats = new PackageStats(stats.packageName, stats.userHandle); 17416 17417 final StorageManager storage = mContext.getSystemService(StorageManager.class); 17418 final String externalUuid = storage.getPrimaryStorageUuid(); 17419 try { 17420 final long start = SystemClock.elapsedRealtimeNanos(); 17421 mInstaller.getAppSize(ps.volumeUuid, packageName, userId, 0, 17422 ps.appId, ceDataInode, ps.codePathString, externalUuid, stats); 17423 final long stopManual = SystemClock.elapsedRealtimeNanos(); 17424 if (ENABLE_QUOTA) { 17425 mInstaller.getAppSize(ps.volumeUuid, packageName, userId, Installer.FLAG_USE_QUOTA, 17426 ps.appId, ceDataInode, ps.codePathString, externalUuid, quotaStats); 17427 } 17428 final long stopQuota = SystemClock.elapsedRealtimeNanos(); 17429 17430 // For now, ignore code size of packages on system partition 17431 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 17432 stats.codeSize = 0; 17433 quotaStats.codeSize = 0; 17434 } 17435 17436 if (ENABLE_QUOTA && Build.IS_ENG && !ps.isSharedUser()) { 17437 if (!equals(stats, quotaStats)) { 17438 Log.w(TAG, "Found discrepancy between statistics:"); 17439 Log.w(TAG, "Manual: " + stats); 17440 Log.w(TAG, "Quota: " + quotaStats); 17441 } 17442 final long manualTime = stopManual - start; 17443 final long quotaTime = stopQuota - stopManual; 17444 EventLogTags.writePmPackageStats(manualTime, quotaTime, 17445 stats.dataSize, quotaStats.dataSize, 17446 stats.cacheSize, quotaStats.cacheSize); 17447 } 17448 17449 // External clients expect these to be tracked separately 17450 stats.dataSize -= stats.cacheSize; 17451 quotaStats.dataSize -= quotaStats.cacheSize; 17452 17453 } catch (InstallerException e) { 17454 Slog.w(TAG, String.valueOf(e)); 17455 return false; 17456 } 17457 17458 return true; 17459 } 17460 17461 private int getUidTargetSdkVersionLockedLPr(int uid) { 17462 Object obj = mSettings.getUserIdLPr(uid); 17463 if (obj instanceof SharedUserSetting) { 17464 final SharedUserSetting sus = (SharedUserSetting) obj; 17465 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 17466 final Iterator<PackageSetting> it = sus.packages.iterator(); 17467 while (it.hasNext()) { 17468 final PackageSetting ps = it.next(); 17469 if (ps.pkg != null) { 17470 int v = ps.pkg.applicationInfo.targetSdkVersion; 17471 if (v < vers) vers = v; 17472 } 17473 } 17474 return vers; 17475 } else if (obj instanceof PackageSetting) { 17476 final PackageSetting ps = (PackageSetting) obj; 17477 if (ps.pkg != null) { 17478 return ps.pkg.applicationInfo.targetSdkVersion; 17479 } 17480 } 17481 return Build.VERSION_CODES.CUR_DEVELOPMENT; 17482 } 17483 17484 @Override 17485 public void addPreferredActivity(IntentFilter filter, int match, 17486 ComponentName[] set, ComponentName activity, int userId) { 17487 addPreferredActivityInternal(filter, match, set, activity, true, userId, 17488 "Adding preferred"); 17489 } 17490 17491 private void addPreferredActivityInternal(IntentFilter filter, int match, 17492 ComponentName[] set, ComponentName activity, boolean always, int userId, 17493 String opname) { 17494 // writer 17495 int callingUid = Binder.getCallingUid(); 17496 enforceCrossUserPermission(callingUid, userId, 17497 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 17498 if (filter.countActions() == 0) { 17499 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 17500 return; 17501 } 17502 synchronized (mPackages) { 17503 if (mContext.checkCallingOrSelfPermission( 17504 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 17505 != PackageManager.PERMISSION_GRANTED) { 17506 if (getUidTargetSdkVersionLockedLPr(callingUid) 17507 < Build.VERSION_CODES.FROYO) { 17508 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 17509 + callingUid); 17510 return; 17511 } 17512 mContext.enforceCallingOrSelfPermission( 17513 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 17514 } 17515 17516 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 17517 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 17518 + userId + ":"); 17519 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17520 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 17521 scheduleWritePackageRestrictionsLocked(userId); 17522 postPreferredActivityChangedBroadcast(userId); 17523 } 17524 } 17525 17526 private void postPreferredActivityChangedBroadcast(int userId) { 17527 mHandler.post(() -> { 17528 final IActivityManager am = ActivityManager.getService(); 17529 if (am == null) { 17530 return; 17531 } 17532 17533 final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED); 17534 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 17535 try { 17536 am.broadcastIntent(null, intent, null, null, 17537 0, null, null, null, android.app.AppOpsManager.OP_NONE, 17538 null, false, false, userId); 17539 } catch (RemoteException e) { 17540 } 17541 }); 17542 } 17543 17544 @Override 17545 public void replacePreferredActivity(IntentFilter filter, int match, 17546 ComponentName[] set, ComponentName activity, int userId) { 17547 if (filter.countActions() != 1) { 17548 throw new IllegalArgumentException( 17549 "replacePreferredActivity expects filter to have only 1 action."); 17550 } 17551 if (filter.countDataAuthorities() != 0 17552 || filter.countDataPaths() != 0 17553 || filter.countDataSchemes() > 1 17554 || filter.countDataTypes() != 0) { 17555 throw new IllegalArgumentException( 17556 "replacePreferredActivity expects filter to have no data authorities, " + 17557 "paths, or types; and at most one scheme."); 17558 } 17559 17560 final int callingUid = Binder.getCallingUid(); 17561 enforceCrossUserPermission(callingUid, userId, 17562 true /* requireFullPermission */, false /* checkShell */, 17563 "replace preferred activity"); 17564 synchronized (mPackages) { 17565 if (mContext.checkCallingOrSelfPermission( 17566 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 17567 != PackageManager.PERMISSION_GRANTED) { 17568 if (getUidTargetSdkVersionLockedLPr(callingUid) 17569 < Build.VERSION_CODES.FROYO) { 17570 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 17571 + Binder.getCallingUid()); 17572 return; 17573 } 17574 mContext.enforceCallingOrSelfPermission( 17575 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 17576 } 17577 17578 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 17579 if (pir != null) { 17580 // Get all of the existing entries that exactly match this filter. 17581 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 17582 if (existing != null && existing.size() == 1) { 17583 PreferredActivity cur = existing.get(0); 17584 if (DEBUG_PREFERRED) { 17585 Slog.i(TAG, "Checking replace of preferred:"); 17586 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17587 if (!cur.mPref.mAlways) { 17588 Slog.i(TAG, " -- CUR; not mAlways!"); 17589 } else { 17590 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 17591 Slog.i(TAG, " -- CUR: mSet=" 17592 + Arrays.toString(cur.mPref.mSetComponents)); 17593 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 17594 Slog.i(TAG, " -- NEW: mMatch=" 17595 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 17596 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 17597 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 17598 } 17599 } 17600 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 17601 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 17602 && cur.mPref.sameSet(set)) { 17603 // Setting the preferred activity to what it happens to be already 17604 if (DEBUG_PREFERRED) { 17605 Slog.i(TAG, "Replacing with same preferred activity " 17606 + cur.mPref.mShortComponent + " for user " 17607 + userId + ":"); 17608 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17609 } 17610 return; 17611 } 17612 } 17613 17614 if (existing != null) { 17615 if (DEBUG_PREFERRED) { 17616 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 17617 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17618 } 17619 for (int i = 0; i < existing.size(); i++) { 17620 PreferredActivity pa = existing.get(i); 17621 if (DEBUG_PREFERRED) { 17622 Slog.i(TAG, "Removing existing preferred activity " 17623 + pa.mPref.mComponent + ":"); 17624 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 17625 } 17626 pir.removeFilter(pa); 17627 } 17628 } 17629 } 17630 addPreferredActivityInternal(filter, match, set, activity, true, userId, 17631 "Replacing preferred"); 17632 } 17633 } 17634 17635 @Override 17636 public void clearPackagePreferredActivities(String packageName) { 17637 final int uid = Binder.getCallingUid(); 17638 // writer 17639 synchronized (mPackages) { 17640 PackageParser.Package pkg = mPackages.get(packageName); 17641 if (pkg == null || pkg.applicationInfo.uid != uid) { 17642 if (mContext.checkCallingOrSelfPermission( 17643 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 17644 != PackageManager.PERMISSION_GRANTED) { 17645 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 17646 < Build.VERSION_CODES.FROYO) { 17647 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 17648 + Binder.getCallingUid()); 17649 return; 17650 } 17651 mContext.enforceCallingOrSelfPermission( 17652 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 17653 } 17654 } 17655 17656 int user = UserHandle.getCallingUserId(); 17657 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 17658 scheduleWritePackageRestrictionsLocked(user); 17659 } 17660 } 17661 } 17662 17663 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 17664 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 17665 ArrayList<PreferredActivity> removed = null; 17666 boolean changed = false; 17667 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17668 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 17669 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17670 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 17671 continue; 17672 } 17673 Iterator<PreferredActivity> it = pir.filterIterator(); 17674 while (it.hasNext()) { 17675 PreferredActivity pa = it.next(); 17676 // Mark entry for removal only if it matches the package name 17677 // and the entry is of type "always". 17678 if (packageName == null || 17679 (pa.mPref.mComponent.getPackageName().equals(packageName) 17680 && pa.mPref.mAlways)) { 17681 if (removed == null) { 17682 removed = new ArrayList<PreferredActivity>(); 17683 } 17684 removed.add(pa); 17685 } 17686 } 17687 if (removed != null) { 17688 for (int j=0; j<removed.size(); j++) { 17689 PreferredActivity pa = removed.get(j); 17690 pir.removeFilter(pa); 17691 } 17692 changed = true; 17693 } 17694 } 17695 if (changed) { 17696 postPreferredActivityChangedBroadcast(userId); 17697 } 17698 return changed; 17699 } 17700 17701 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 17702 private void clearIntentFilterVerificationsLPw(int userId) { 17703 final int packageCount = mPackages.size(); 17704 for (int i = 0; i < packageCount; i++) { 17705 PackageParser.Package pkg = mPackages.valueAt(i); 17706 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 17707 } 17708 } 17709 17710 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 17711 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 17712 if (userId == UserHandle.USER_ALL) { 17713 if (mSettings.removeIntentFilterVerificationLPw(packageName, 17714 sUserManager.getUserIds())) { 17715 for (int oneUserId : sUserManager.getUserIds()) { 17716 scheduleWritePackageRestrictionsLocked(oneUserId); 17717 } 17718 } 17719 } else { 17720 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 17721 scheduleWritePackageRestrictionsLocked(userId); 17722 } 17723 } 17724 } 17725 17726 void clearDefaultBrowserIfNeeded(String packageName) { 17727 for (int oneUserId : sUserManager.getUserIds()) { 17728 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 17729 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 17730 if (packageName.equals(defaultBrowserPackageName)) { 17731 setDefaultBrowserPackageName(null, oneUserId); 17732 } 17733 } 17734 } 17735 17736 @Override 17737 public void resetApplicationPreferences(int userId) { 17738 mContext.enforceCallingOrSelfPermission( 17739 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 17740 final long identity = Binder.clearCallingIdentity(); 17741 // writer 17742 try { 17743 synchronized (mPackages) { 17744 clearPackagePreferredActivitiesLPw(null, userId); 17745 mSettings.applyDefaultPreferredAppsLPw(this, userId); 17746 // TODO: We have to reset the default SMS and Phone. This requires 17747 // significant refactoring to keep all default apps in the package 17748 // manager (cleaner but more work) or have the services provide 17749 // callbacks to the package manager to request a default app reset. 17750 applyFactoryDefaultBrowserLPw(userId); 17751 clearIntentFilterVerificationsLPw(userId); 17752 primeDomainVerificationsLPw(userId); 17753 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 17754 scheduleWritePackageRestrictionsLocked(userId); 17755 } 17756 resetNetworkPolicies(userId); 17757 } finally { 17758 Binder.restoreCallingIdentity(identity); 17759 } 17760 } 17761 17762 @Override 17763 public int getPreferredActivities(List<IntentFilter> outFilters, 17764 List<ComponentName> outActivities, String packageName) { 17765 17766 int num = 0; 17767 final int userId = UserHandle.getCallingUserId(); 17768 // reader 17769 synchronized (mPackages) { 17770 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 17771 if (pir != null) { 17772 final Iterator<PreferredActivity> it = pir.filterIterator(); 17773 while (it.hasNext()) { 17774 final PreferredActivity pa = it.next(); 17775 if (packageName == null 17776 || (pa.mPref.mComponent.getPackageName().equals(packageName) 17777 && pa.mPref.mAlways)) { 17778 if (outFilters != null) { 17779 outFilters.add(new IntentFilter(pa)); 17780 } 17781 if (outActivities != null) { 17782 outActivities.add(pa.mPref.mComponent); 17783 } 17784 } 17785 } 17786 } 17787 } 17788 17789 return num; 17790 } 17791 17792 @Override 17793 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 17794 int userId) { 17795 int callingUid = Binder.getCallingUid(); 17796 if (callingUid != Process.SYSTEM_UID) { 17797 throw new SecurityException( 17798 "addPersistentPreferredActivity can only be run by the system"); 17799 } 17800 if (filter.countActions() == 0) { 17801 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 17802 return; 17803 } 17804 synchronized (mPackages) { 17805 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 17806 ":"); 17807 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17808 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 17809 new PersistentPreferredActivity(filter, activity)); 17810 scheduleWritePackageRestrictionsLocked(userId); 17811 postPreferredActivityChangedBroadcast(userId); 17812 } 17813 } 17814 17815 @Override 17816 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 17817 int callingUid = Binder.getCallingUid(); 17818 if (callingUid != Process.SYSTEM_UID) { 17819 throw new SecurityException( 17820 "clearPackagePersistentPreferredActivities can only be run by the system"); 17821 } 17822 ArrayList<PersistentPreferredActivity> removed = null; 17823 boolean changed = false; 17824 synchronized (mPackages) { 17825 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 17826 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 17827 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 17828 .valueAt(i); 17829 if (userId != thisUserId) { 17830 continue; 17831 } 17832 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 17833 while (it.hasNext()) { 17834 PersistentPreferredActivity ppa = it.next(); 17835 // Mark entry for removal only if it matches the package name. 17836 if (ppa.mComponent.getPackageName().equals(packageName)) { 17837 if (removed == null) { 17838 removed = new ArrayList<PersistentPreferredActivity>(); 17839 } 17840 removed.add(ppa); 17841 } 17842 } 17843 if (removed != null) { 17844 for (int j=0; j<removed.size(); j++) { 17845 PersistentPreferredActivity ppa = removed.get(j); 17846 ppir.removeFilter(ppa); 17847 } 17848 changed = true; 17849 } 17850 } 17851 17852 if (changed) { 17853 scheduleWritePackageRestrictionsLocked(userId); 17854 postPreferredActivityChangedBroadcast(userId); 17855 } 17856 } 17857 } 17858 17859 /** 17860 * Common machinery for picking apart a restored XML blob and passing 17861 * it to a caller-supplied functor to be applied to the running system. 17862 */ 17863 private void restoreFromXml(XmlPullParser parser, int userId, 17864 String expectedStartTag, BlobXmlRestorer functor) 17865 throws IOException, XmlPullParserException { 17866 int type; 17867 while ((type = parser.next()) != XmlPullParser.START_TAG 17868 && type != XmlPullParser.END_DOCUMENT) { 17869 } 17870 if (type != XmlPullParser.START_TAG) { 17871 // oops didn't find a start tag?! 17872 if (DEBUG_BACKUP) { 17873 Slog.e(TAG, "Didn't find start tag during restore"); 17874 } 17875 return; 17876 } 17877Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 17878 // this is supposed to be TAG_PREFERRED_BACKUP 17879 if (!expectedStartTag.equals(parser.getName())) { 17880 if (DEBUG_BACKUP) { 17881 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 17882 } 17883 return; 17884 } 17885 17886 // skip interfering stuff, then we're aligned with the backing implementation 17887 while ((type = parser.next()) == XmlPullParser.TEXT) { } 17888Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 17889 functor.apply(parser, userId); 17890 } 17891 17892 private interface BlobXmlRestorer { 17893 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 17894 } 17895 17896 /** 17897 * Non-Binder method, support for the backup/restore mechanism: write the 17898 * full set of preferred activities in its canonical XML format. Returns the 17899 * XML output as a byte array, or null if there is none. 17900 */ 17901 @Override 17902 public byte[] getPreferredActivityBackup(int userId) { 17903 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17904 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 17905 } 17906 17907 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17908 try { 17909 final XmlSerializer serializer = new FastXmlSerializer(); 17910 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17911 serializer.startDocument(null, true); 17912 serializer.startTag(null, TAG_PREFERRED_BACKUP); 17913 17914 synchronized (mPackages) { 17915 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 17916 } 17917 17918 serializer.endTag(null, TAG_PREFERRED_BACKUP); 17919 serializer.endDocument(); 17920 serializer.flush(); 17921 } catch (Exception e) { 17922 if (DEBUG_BACKUP) { 17923 Slog.e(TAG, "Unable to write preferred activities for backup", e); 17924 } 17925 return null; 17926 } 17927 17928 return dataStream.toByteArray(); 17929 } 17930 17931 @Override 17932 public void restorePreferredActivities(byte[] backup, int userId) { 17933 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17934 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17935 } 17936 17937 try { 17938 final XmlPullParser parser = Xml.newPullParser(); 17939 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17940 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 17941 new BlobXmlRestorer() { 17942 @Override 17943 public void apply(XmlPullParser parser, int userId) 17944 throws XmlPullParserException, IOException { 17945 synchronized (mPackages) { 17946 mSettings.readPreferredActivitiesLPw(parser, userId); 17947 } 17948 } 17949 } ); 17950 } catch (Exception e) { 17951 if (DEBUG_BACKUP) { 17952 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17953 } 17954 } 17955 } 17956 17957 /** 17958 * Non-Binder method, support for the backup/restore mechanism: write the 17959 * default browser (etc) settings in its canonical XML format. Returns the default 17960 * browser XML representation as a byte array, or null if there is none. 17961 */ 17962 @Override 17963 public byte[] getDefaultAppsBackup(int userId) { 17964 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17965 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 17966 } 17967 17968 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17969 try { 17970 final XmlSerializer serializer = new FastXmlSerializer(); 17971 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17972 serializer.startDocument(null, true); 17973 serializer.startTag(null, TAG_DEFAULT_APPS); 17974 17975 synchronized (mPackages) { 17976 mSettings.writeDefaultAppsLPr(serializer, userId); 17977 } 17978 17979 serializer.endTag(null, TAG_DEFAULT_APPS); 17980 serializer.endDocument(); 17981 serializer.flush(); 17982 } catch (Exception e) { 17983 if (DEBUG_BACKUP) { 17984 Slog.e(TAG, "Unable to write default apps for backup", e); 17985 } 17986 return null; 17987 } 17988 17989 return dataStream.toByteArray(); 17990 } 17991 17992 @Override 17993 public void restoreDefaultApps(byte[] backup, int userId) { 17994 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17995 throw new SecurityException("Only the system may call restoreDefaultApps()"); 17996 } 17997 17998 try { 17999 final XmlPullParser parser = Xml.newPullParser(); 18000 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 18001 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 18002 new BlobXmlRestorer() { 18003 @Override 18004 public void apply(XmlPullParser parser, int userId) 18005 throws XmlPullParserException, IOException { 18006 synchronized (mPackages) { 18007 mSettings.readDefaultAppsLPw(parser, userId); 18008 } 18009 } 18010 } ); 18011 } catch (Exception e) { 18012 if (DEBUG_BACKUP) { 18013 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 18014 } 18015 } 18016 } 18017 18018 @Override 18019 public byte[] getIntentFilterVerificationBackup(int userId) { 18020 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 18021 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 18022 } 18023 18024 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 18025 try { 18026 final XmlSerializer serializer = new FastXmlSerializer(); 18027 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 18028 serializer.startDocument(null, true); 18029 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 18030 18031 synchronized (mPackages) { 18032 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 18033 } 18034 18035 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 18036 serializer.endDocument(); 18037 serializer.flush(); 18038 } catch (Exception e) { 18039 if (DEBUG_BACKUP) { 18040 Slog.e(TAG, "Unable to write default apps for backup", e); 18041 } 18042 return null; 18043 } 18044 18045 return dataStream.toByteArray(); 18046 } 18047 18048 @Override 18049 public void restoreIntentFilterVerification(byte[] backup, int userId) { 18050 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 18051 throw new SecurityException("Only the system may call restorePreferredActivities()"); 18052 } 18053 18054 try { 18055 final XmlPullParser parser = Xml.newPullParser(); 18056 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 18057 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 18058 new BlobXmlRestorer() { 18059 @Override 18060 public void apply(XmlPullParser parser, int userId) 18061 throws XmlPullParserException, IOException { 18062 synchronized (mPackages) { 18063 mSettings.readAllDomainVerificationsLPr(parser, userId); 18064 mSettings.writeLPr(); 18065 } 18066 } 18067 } ); 18068 } catch (Exception e) { 18069 if (DEBUG_BACKUP) { 18070 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 18071 } 18072 } 18073 } 18074 18075 @Override 18076 public byte[] getPermissionGrantBackup(int userId) { 18077 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 18078 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 18079 } 18080 18081 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 18082 try { 18083 final XmlSerializer serializer = new FastXmlSerializer(); 18084 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 18085 serializer.startDocument(null, true); 18086 serializer.startTag(null, TAG_PERMISSION_BACKUP); 18087 18088 synchronized (mPackages) { 18089 serializeRuntimePermissionGrantsLPr(serializer, userId); 18090 } 18091 18092 serializer.endTag(null, TAG_PERMISSION_BACKUP); 18093 serializer.endDocument(); 18094 serializer.flush(); 18095 } catch (Exception e) { 18096 if (DEBUG_BACKUP) { 18097 Slog.e(TAG, "Unable to write default apps for backup", e); 18098 } 18099 return null; 18100 } 18101 18102 return dataStream.toByteArray(); 18103 } 18104 18105 @Override 18106 public void restorePermissionGrants(byte[] backup, int userId) { 18107 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 18108 throw new SecurityException("Only the system may call restorePermissionGrants()"); 18109 } 18110 18111 try { 18112 final XmlPullParser parser = Xml.newPullParser(); 18113 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 18114 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 18115 new BlobXmlRestorer() { 18116 @Override 18117 public void apply(XmlPullParser parser, int userId) 18118 throws XmlPullParserException, IOException { 18119 synchronized (mPackages) { 18120 processRestoredPermissionGrantsLPr(parser, userId); 18121 } 18122 } 18123 } ); 18124 } catch (Exception e) { 18125 if (DEBUG_BACKUP) { 18126 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 18127 } 18128 } 18129 } 18130 18131 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 18132 throws IOException { 18133 serializer.startTag(null, TAG_ALL_GRANTS); 18134 18135 final int N = mSettings.mPackages.size(); 18136 for (int i = 0; i < N; i++) { 18137 final PackageSetting ps = mSettings.mPackages.valueAt(i); 18138 boolean pkgGrantsKnown = false; 18139 18140 PermissionsState packagePerms = ps.getPermissionsState(); 18141 18142 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 18143 final int grantFlags = state.getFlags(); 18144 // only look at grants that are not system/policy fixed 18145 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 18146 final boolean isGranted = state.isGranted(); 18147 // And only back up the user-twiddled state bits 18148 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 18149 final String packageName = mSettings.mPackages.keyAt(i); 18150 if (!pkgGrantsKnown) { 18151 serializer.startTag(null, TAG_GRANT); 18152 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 18153 pkgGrantsKnown = true; 18154 } 18155 18156 final boolean userSet = 18157 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 18158 final boolean userFixed = 18159 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 18160 final boolean revoke = 18161 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 18162 18163 serializer.startTag(null, TAG_PERMISSION); 18164 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 18165 if (isGranted) { 18166 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 18167 } 18168 if (userSet) { 18169 serializer.attribute(null, ATTR_USER_SET, "true"); 18170 } 18171 if (userFixed) { 18172 serializer.attribute(null, ATTR_USER_FIXED, "true"); 18173 } 18174 if (revoke) { 18175 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 18176 } 18177 serializer.endTag(null, TAG_PERMISSION); 18178 } 18179 } 18180 } 18181 18182 if (pkgGrantsKnown) { 18183 serializer.endTag(null, TAG_GRANT); 18184 } 18185 } 18186 18187 serializer.endTag(null, TAG_ALL_GRANTS); 18188 } 18189 18190 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 18191 throws XmlPullParserException, IOException { 18192 String pkgName = null; 18193 int outerDepth = parser.getDepth(); 18194 int type; 18195 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 18196 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 18197 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 18198 continue; 18199 } 18200 18201 final String tagName = parser.getName(); 18202 if (tagName.equals(TAG_GRANT)) { 18203 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 18204 if (DEBUG_BACKUP) { 18205 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 18206 } 18207 } else if (tagName.equals(TAG_PERMISSION)) { 18208 18209 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 18210 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 18211 18212 int newFlagSet = 0; 18213 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 18214 newFlagSet |= FLAG_PERMISSION_USER_SET; 18215 } 18216 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 18217 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 18218 } 18219 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 18220 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 18221 } 18222 if (DEBUG_BACKUP) { 18223 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 18224 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 18225 } 18226 final PackageSetting ps = mSettings.mPackages.get(pkgName); 18227 if (ps != null) { 18228 // Already installed so we apply the grant immediately 18229 if (DEBUG_BACKUP) { 18230 Slog.v(TAG, " + already installed; applying"); 18231 } 18232 PermissionsState perms = ps.getPermissionsState(); 18233 BasePermission bp = mSettings.mPermissions.get(permName); 18234 if (bp != null) { 18235 if (isGranted) { 18236 perms.grantRuntimePermission(bp, userId); 18237 } 18238 if (newFlagSet != 0) { 18239 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 18240 } 18241 } 18242 } else { 18243 // Need to wait for post-restore install to apply the grant 18244 if (DEBUG_BACKUP) { 18245 Slog.v(TAG, " - not yet installed; saving for later"); 18246 } 18247 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 18248 isGranted, newFlagSet, userId); 18249 } 18250 } else { 18251 PackageManagerService.reportSettingsProblem(Log.WARN, 18252 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 18253 XmlUtils.skipCurrentTag(parser); 18254 } 18255 } 18256 18257 scheduleWriteSettingsLocked(); 18258 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 18259 } 18260 18261 @Override 18262 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 18263 int sourceUserId, int targetUserId, int flags) { 18264 mContext.enforceCallingOrSelfPermission( 18265 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 18266 int callingUid = Binder.getCallingUid(); 18267 enforceOwnerRights(ownerPackage, callingUid); 18268 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 18269 if (intentFilter.countActions() == 0) { 18270 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 18271 return; 18272 } 18273 synchronized (mPackages) { 18274 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 18275 ownerPackage, targetUserId, flags); 18276 CrossProfileIntentResolver resolver = 18277 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 18278 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 18279 // We have all those whose filter is equal. Now checking if the rest is equal as well. 18280 if (existing != null) { 18281 int size = existing.size(); 18282 for (int i = 0; i < size; i++) { 18283 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 18284 return; 18285 } 18286 } 18287 } 18288 resolver.addFilter(newFilter); 18289 scheduleWritePackageRestrictionsLocked(sourceUserId); 18290 } 18291 } 18292 18293 @Override 18294 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 18295 mContext.enforceCallingOrSelfPermission( 18296 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 18297 int callingUid = Binder.getCallingUid(); 18298 enforceOwnerRights(ownerPackage, callingUid); 18299 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 18300 synchronized (mPackages) { 18301 CrossProfileIntentResolver resolver = 18302 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 18303 ArraySet<CrossProfileIntentFilter> set = 18304 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 18305 for (CrossProfileIntentFilter filter : set) { 18306 if (filter.getOwnerPackage().equals(ownerPackage)) { 18307 resolver.removeFilter(filter); 18308 } 18309 } 18310 scheduleWritePackageRestrictionsLocked(sourceUserId); 18311 } 18312 } 18313 18314 // Enforcing that callingUid is owning pkg on userId 18315 private void enforceOwnerRights(String pkg, int callingUid) { 18316 // The system owns everything. 18317 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 18318 return; 18319 } 18320 int callingUserId = UserHandle.getUserId(callingUid); 18321 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 18322 if (pi == null) { 18323 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 18324 + callingUserId); 18325 } 18326 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 18327 throw new SecurityException("Calling uid " + callingUid 18328 + " does not own package " + pkg); 18329 } 18330 } 18331 18332 @Override 18333 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 18334 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 18335 } 18336 18337 private Intent getHomeIntent() { 18338 Intent intent = new Intent(Intent.ACTION_MAIN); 18339 intent.addCategory(Intent.CATEGORY_HOME); 18340 intent.addCategory(Intent.CATEGORY_DEFAULT); 18341 return intent; 18342 } 18343 18344 private IntentFilter getHomeFilter() { 18345 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 18346 filter.addCategory(Intent.CATEGORY_HOME); 18347 filter.addCategory(Intent.CATEGORY_DEFAULT); 18348 return filter; 18349 } 18350 18351 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 18352 int userId) { 18353 Intent intent = getHomeIntent(); 18354 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 18355 PackageManager.GET_META_DATA, userId); 18356 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 18357 true, false, false, userId); 18358 18359 allHomeCandidates.clear(); 18360 if (list != null) { 18361 for (ResolveInfo ri : list) { 18362 allHomeCandidates.add(ri); 18363 } 18364 } 18365 return (preferred == null || preferred.activityInfo == null) 18366 ? null 18367 : new ComponentName(preferred.activityInfo.packageName, 18368 preferred.activityInfo.name); 18369 } 18370 18371 @Override 18372 public void setHomeActivity(ComponentName comp, int userId) { 18373 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 18374 getHomeActivitiesAsUser(homeActivities, userId); 18375 18376 boolean found = false; 18377 18378 final int size = homeActivities.size(); 18379 final ComponentName[] set = new ComponentName[size]; 18380 for (int i = 0; i < size; i++) { 18381 final ResolveInfo candidate = homeActivities.get(i); 18382 final ActivityInfo info = candidate.activityInfo; 18383 final ComponentName activityName = new ComponentName(info.packageName, info.name); 18384 set[i] = activityName; 18385 if (!found && activityName.equals(comp)) { 18386 found = true; 18387 } 18388 } 18389 if (!found) { 18390 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 18391 + userId); 18392 } 18393 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 18394 set, comp, userId); 18395 } 18396 18397 private @Nullable String getSetupWizardPackageName() { 18398 final Intent intent = new Intent(Intent.ACTION_MAIN); 18399 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 18400 18401 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 18402 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 18403 | MATCH_DISABLED_COMPONENTS, 18404 UserHandle.myUserId()); 18405 if (matches.size() == 1) { 18406 return matches.get(0).getComponentInfo().packageName; 18407 } else { 18408 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 18409 + ": matches=" + matches); 18410 return null; 18411 } 18412 } 18413 18414 private @Nullable String getStorageManagerPackageName() { 18415 final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE); 18416 18417 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 18418 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 18419 | MATCH_DISABLED_COMPONENTS, 18420 UserHandle.myUserId()); 18421 if (matches.size() == 1) { 18422 return matches.get(0).getComponentInfo().packageName; 18423 } else { 18424 Slog.e(TAG, "There should probably be exactly one storage manager; found " 18425 + matches.size() + ": matches=" + matches); 18426 return null; 18427 } 18428 } 18429 18430 @Override 18431 public void setApplicationEnabledSetting(String appPackageName, 18432 int newState, int flags, int userId, String callingPackage) { 18433 if (!sUserManager.exists(userId)) return; 18434 if (callingPackage == null) { 18435 callingPackage = Integer.toString(Binder.getCallingUid()); 18436 } 18437 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 18438 } 18439 18440 @Override 18441 public void setComponentEnabledSetting(ComponentName componentName, 18442 int newState, int flags, int userId) { 18443 if (!sUserManager.exists(userId)) return; 18444 setEnabledSetting(componentName.getPackageName(), 18445 componentName.getClassName(), newState, flags, userId, null); 18446 } 18447 18448 private void setEnabledSetting(final String packageName, String className, int newState, 18449 final int flags, int userId, String callingPackage) { 18450 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 18451 || newState == COMPONENT_ENABLED_STATE_ENABLED 18452 || newState == COMPONENT_ENABLED_STATE_DISABLED 18453 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 18454 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 18455 throw new IllegalArgumentException("Invalid new component state: " 18456 + newState); 18457 } 18458 PackageSetting pkgSetting; 18459 final int uid = Binder.getCallingUid(); 18460 final int permission; 18461 if (uid == Process.SYSTEM_UID) { 18462 permission = PackageManager.PERMISSION_GRANTED; 18463 } else { 18464 permission = mContext.checkCallingOrSelfPermission( 18465 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 18466 } 18467 enforceCrossUserPermission(uid, userId, 18468 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 18469 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 18470 boolean sendNow = false; 18471 boolean isApp = (className == null); 18472 String componentName = isApp ? packageName : className; 18473 int packageUid = -1; 18474 ArrayList<String> components; 18475 18476 // writer 18477 synchronized (mPackages) { 18478 pkgSetting = mSettings.mPackages.get(packageName); 18479 if (pkgSetting == null) { 18480 if (className == null) { 18481 throw new IllegalArgumentException("Unknown package: " + packageName); 18482 } 18483 throw new IllegalArgumentException( 18484 "Unknown component: " + packageName + "/" + className); 18485 } 18486 } 18487 18488 // Limit who can change which apps 18489 if (!UserHandle.isSameApp(uid, pkgSetting.appId)) { 18490 // Don't allow apps that don't have permission to modify other apps 18491 if (!allowedByPermission) { 18492 throw new SecurityException( 18493 "Permission Denial: attempt to change component state from pid=" 18494 + Binder.getCallingPid() 18495 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 18496 } 18497 // Don't allow changing protected packages. 18498 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 18499 throw new SecurityException("Cannot disable a protected package: " + packageName); 18500 } 18501 } 18502 18503 synchronized (mPackages) { 18504 if (uid == Process.SHELL_UID 18505 && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) { 18506 // Shell can only change whole packages between ENABLED and DISABLED_USER states 18507 // unless it is a test package. 18508 int oldState = pkgSetting.getEnabled(userId); 18509 if (className == null 18510 && 18511 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 18512 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 18513 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 18514 && 18515 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 18516 || newState == COMPONENT_ENABLED_STATE_DEFAULT 18517 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 18518 // ok 18519 } else { 18520 throw new SecurityException( 18521 "Shell cannot change component state for " + packageName + "/" 18522 + className + " to " + newState); 18523 } 18524 } 18525 if (className == null) { 18526 // We're dealing with an application/package level state change 18527 if (pkgSetting.getEnabled(userId) == newState) { 18528 // Nothing to do 18529 return; 18530 } 18531 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 18532 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 18533 // Don't care about who enables an app. 18534 callingPackage = null; 18535 } 18536 pkgSetting.setEnabled(newState, userId, callingPackage); 18537 // pkgSetting.pkg.mSetEnabled = newState; 18538 } else { 18539 // We're dealing with a component level state change 18540 // First, verify that this is a valid class name. 18541 PackageParser.Package pkg = pkgSetting.pkg; 18542 if (pkg == null || !pkg.hasComponentClassName(className)) { 18543 if (pkg != null && 18544 pkg.applicationInfo.targetSdkVersion >= 18545 Build.VERSION_CODES.JELLY_BEAN) { 18546 throw new IllegalArgumentException("Component class " + className 18547 + " does not exist in " + packageName); 18548 } else { 18549 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 18550 + className + " does not exist in " + packageName); 18551 } 18552 } 18553 switch (newState) { 18554 case COMPONENT_ENABLED_STATE_ENABLED: 18555 if (!pkgSetting.enableComponentLPw(className, userId)) { 18556 return; 18557 } 18558 break; 18559 case COMPONENT_ENABLED_STATE_DISABLED: 18560 if (!pkgSetting.disableComponentLPw(className, userId)) { 18561 return; 18562 } 18563 break; 18564 case COMPONENT_ENABLED_STATE_DEFAULT: 18565 if (!pkgSetting.restoreComponentLPw(className, userId)) { 18566 return; 18567 } 18568 break; 18569 default: 18570 Slog.e(TAG, "Invalid new component state: " + newState); 18571 return; 18572 } 18573 } 18574 scheduleWritePackageRestrictionsLocked(userId); 18575 components = mPendingBroadcasts.get(userId, packageName); 18576 final boolean newPackage = components == null; 18577 if (newPackage) { 18578 components = new ArrayList<String>(); 18579 } 18580 if (!components.contains(componentName)) { 18581 components.add(componentName); 18582 } 18583 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 18584 sendNow = true; 18585 // Purge entry from pending broadcast list if another one exists already 18586 // since we are sending one right away. 18587 mPendingBroadcasts.remove(userId, packageName); 18588 } else { 18589 if (newPackage) { 18590 mPendingBroadcasts.put(userId, packageName, components); 18591 } 18592 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 18593 // Schedule a message 18594 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 18595 } 18596 } 18597 } 18598 18599 long callingId = Binder.clearCallingIdentity(); 18600 try { 18601 if (sendNow) { 18602 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 18603 sendPackageChangedBroadcast(packageName, 18604 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 18605 } 18606 } finally { 18607 Binder.restoreCallingIdentity(callingId); 18608 } 18609 } 18610 18611 @Override 18612 public void flushPackageRestrictionsAsUser(int userId) { 18613 if (!sUserManager.exists(userId)) { 18614 return; 18615 } 18616 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 18617 false /* checkShell */, "flushPackageRestrictions"); 18618 synchronized (mPackages) { 18619 mSettings.writePackageRestrictionsLPr(userId); 18620 mDirtyUsers.remove(userId); 18621 if (mDirtyUsers.isEmpty()) { 18622 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 18623 } 18624 } 18625 } 18626 18627 private void sendPackageChangedBroadcast(String packageName, 18628 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 18629 if (DEBUG_INSTALL) 18630 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 18631 + componentNames); 18632 Bundle extras = new Bundle(4); 18633 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 18634 String nameList[] = new String[componentNames.size()]; 18635 componentNames.toArray(nameList); 18636 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 18637 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 18638 extras.putInt(Intent.EXTRA_UID, packageUid); 18639 // If this is not reporting a change of the overall package, then only send it 18640 // to registered receivers. We don't want to launch a swath of apps for every 18641 // little component state change. 18642 final int flags = !componentNames.contains(packageName) 18643 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 18644 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 18645 new int[] {UserHandle.getUserId(packageUid)}); 18646 } 18647 18648 @Override 18649 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 18650 if (!sUserManager.exists(userId)) return; 18651 final int uid = Binder.getCallingUid(); 18652 final int permission = mContext.checkCallingOrSelfPermission( 18653 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 18654 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 18655 enforceCrossUserPermission(uid, userId, 18656 true /* requireFullPermission */, true /* checkShell */, "stop package"); 18657 // writer 18658 synchronized (mPackages) { 18659 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 18660 allowedByPermission, uid, userId)) { 18661 scheduleWritePackageRestrictionsLocked(userId); 18662 } 18663 } 18664 } 18665 18666 @Override 18667 public String getInstallerPackageName(String packageName) { 18668 // reader 18669 synchronized (mPackages) { 18670 return mSettings.getInstallerPackageNameLPr(packageName); 18671 } 18672 } 18673 18674 public boolean isOrphaned(String packageName) { 18675 // reader 18676 synchronized (mPackages) { 18677 return mSettings.isOrphaned(packageName); 18678 } 18679 } 18680 18681 @Override 18682 public int getApplicationEnabledSetting(String packageName, int userId) { 18683 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 18684 int uid = Binder.getCallingUid(); 18685 enforceCrossUserPermission(uid, userId, 18686 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 18687 // reader 18688 synchronized (mPackages) { 18689 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 18690 } 18691 } 18692 18693 @Override 18694 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 18695 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 18696 int uid = Binder.getCallingUid(); 18697 enforceCrossUserPermission(uid, userId, 18698 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 18699 // reader 18700 synchronized (mPackages) { 18701 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 18702 } 18703 } 18704 18705 @Override 18706 public void enterSafeMode() { 18707 enforceSystemOrRoot("Only the system can request entering safe mode"); 18708 18709 if (!mSystemReady) { 18710 mSafeMode = true; 18711 } 18712 } 18713 18714 @Override 18715 public void systemReady() { 18716 mSystemReady = true; 18717 18718 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 18719 // disabled after already being started. 18720 CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this, 18721 mContext.getContentResolver(), UserHandle.USER_SYSTEM); 18722 18723 // Read the compatibilty setting when the system is ready. 18724 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 18725 mContext.getContentResolver(), 18726 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 18727 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 18728 if (DEBUG_SETTINGS) { 18729 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 18730 } 18731 18732 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 18733 18734 synchronized (mPackages) { 18735 // Verify that all of the preferred activity components actually 18736 // exist. It is possible for applications to be updated and at 18737 // that point remove a previously declared activity component that 18738 // had been set as a preferred activity. We try to clean this up 18739 // the next time we encounter that preferred activity, but it is 18740 // possible for the user flow to never be able to return to that 18741 // situation so here we do a sanity check to make sure we haven't 18742 // left any junk around. 18743 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 18744 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18745 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18746 removed.clear(); 18747 for (PreferredActivity pa : pir.filterSet()) { 18748 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 18749 removed.add(pa); 18750 } 18751 } 18752 if (removed.size() > 0) { 18753 for (int r=0; r<removed.size(); r++) { 18754 PreferredActivity pa = removed.get(r); 18755 Slog.w(TAG, "Removing dangling preferred activity: " 18756 + pa.mPref.mComponent); 18757 pir.removeFilter(pa); 18758 } 18759 mSettings.writePackageRestrictionsLPr( 18760 mSettings.mPreferredActivities.keyAt(i)); 18761 } 18762 } 18763 18764 for (int userId : UserManagerService.getInstance().getUserIds()) { 18765 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 18766 grantPermissionsUserIds = ArrayUtils.appendInt( 18767 grantPermissionsUserIds, userId); 18768 } 18769 } 18770 } 18771 sUserManager.systemReady(); 18772 18773 // If we upgraded grant all default permissions before kicking off. 18774 for (int userId : grantPermissionsUserIds) { 18775 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 18776 } 18777 18778 // If we did not grant default permissions, we preload from this the 18779 // default permission exceptions lazily to ensure we don't hit the 18780 // disk on a new user creation. 18781 if (grantPermissionsUserIds == EMPTY_INT_ARRAY) { 18782 mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions(); 18783 } 18784 18785 // Kick off any messages waiting for system ready 18786 if (mPostSystemReadyMessages != null) { 18787 for (Message msg : mPostSystemReadyMessages) { 18788 msg.sendToTarget(); 18789 } 18790 mPostSystemReadyMessages = null; 18791 } 18792 18793 // Watch for external volumes that come and go over time 18794 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18795 storage.registerListener(mStorageListener); 18796 18797 mInstallerService.systemReady(); 18798 mPackageDexOptimizer.systemReady(); 18799 18800 StorageManagerInternal StorageManagerInternal = LocalServices.getService( 18801 StorageManagerInternal.class); 18802 StorageManagerInternal.addExternalStoragePolicy( 18803 new StorageManagerInternal.ExternalStorageMountPolicy() { 18804 @Override 18805 public int getMountMode(int uid, String packageName) { 18806 if (Process.isIsolated(uid)) { 18807 return Zygote.MOUNT_EXTERNAL_NONE; 18808 } 18809 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 18810 return Zygote.MOUNT_EXTERNAL_DEFAULT; 18811 } 18812 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 18813 return Zygote.MOUNT_EXTERNAL_DEFAULT; 18814 } 18815 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 18816 return Zygote.MOUNT_EXTERNAL_READ; 18817 } 18818 return Zygote.MOUNT_EXTERNAL_WRITE; 18819 } 18820 18821 @Override 18822 public boolean hasExternalStorage(int uid, String packageName) { 18823 return true; 18824 } 18825 }); 18826 18827 // Now that we're mostly running, clean up stale users and apps 18828 reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 18829 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 18830 } 18831 18832 @Override 18833 public boolean isSafeMode() { 18834 return mSafeMode; 18835 } 18836 18837 @Override 18838 public boolean hasSystemUidErrors() { 18839 return mHasSystemUidErrors; 18840 } 18841 18842 static String arrayToString(int[] array) { 18843 StringBuffer buf = new StringBuffer(128); 18844 buf.append('['); 18845 if (array != null) { 18846 for (int i=0; i<array.length; i++) { 18847 if (i > 0) buf.append(", "); 18848 buf.append(array[i]); 18849 } 18850 } 18851 buf.append(']'); 18852 return buf.toString(); 18853 } 18854 18855 static class DumpState { 18856 public static final int DUMP_LIBS = 1 << 0; 18857 public static final int DUMP_FEATURES = 1 << 1; 18858 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 18859 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 18860 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 18861 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 18862 public static final int DUMP_PERMISSIONS = 1 << 6; 18863 public static final int DUMP_PACKAGES = 1 << 7; 18864 public static final int DUMP_SHARED_USERS = 1 << 8; 18865 public static final int DUMP_MESSAGES = 1 << 9; 18866 public static final int DUMP_PROVIDERS = 1 << 10; 18867 public static final int DUMP_VERIFIERS = 1 << 11; 18868 public static final int DUMP_PREFERRED = 1 << 12; 18869 public static final int DUMP_PREFERRED_XML = 1 << 13; 18870 public static final int DUMP_KEYSETS = 1 << 14; 18871 public static final int DUMP_VERSION = 1 << 15; 18872 public static final int DUMP_INSTALLS = 1 << 16; 18873 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 18874 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 18875 public static final int DUMP_FROZEN = 1 << 19; 18876 public static final int DUMP_DEXOPT = 1 << 20; 18877 public static final int DUMP_COMPILER_STATS = 1 << 21; 18878 18879 public static final int OPTION_SHOW_FILTERS = 1 << 0; 18880 18881 private int mTypes; 18882 18883 private int mOptions; 18884 18885 private boolean mTitlePrinted; 18886 18887 private SharedUserSetting mSharedUser; 18888 18889 public boolean isDumping(int type) { 18890 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 18891 return true; 18892 } 18893 18894 return (mTypes & type) != 0; 18895 } 18896 18897 public void setDump(int type) { 18898 mTypes |= type; 18899 } 18900 18901 public boolean isOptionEnabled(int option) { 18902 return (mOptions & option) != 0; 18903 } 18904 18905 public void setOptionEnabled(int option) { 18906 mOptions |= option; 18907 } 18908 18909 public boolean onTitlePrinted() { 18910 final boolean printed = mTitlePrinted; 18911 mTitlePrinted = true; 18912 return printed; 18913 } 18914 18915 public boolean getTitlePrinted() { 18916 return mTitlePrinted; 18917 } 18918 18919 public void setTitlePrinted(boolean enabled) { 18920 mTitlePrinted = enabled; 18921 } 18922 18923 public SharedUserSetting getSharedUser() { 18924 return mSharedUser; 18925 } 18926 18927 public void setSharedUser(SharedUserSetting user) { 18928 mSharedUser = user; 18929 } 18930 } 18931 18932 @Override 18933 public void onShellCommand(FileDescriptor in, FileDescriptor out, 18934 FileDescriptor err, String[] args, ShellCallback callback, 18935 ResultReceiver resultReceiver) { 18936 (new PackageManagerShellCommand(this)).exec( 18937 this, in, out, err, args, callback, resultReceiver); 18938 } 18939 18940 @Override 18941 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 18942 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 18943 != PackageManager.PERMISSION_GRANTED) { 18944 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 18945 + Binder.getCallingPid() 18946 + ", uid=" + Binder.getCallingUid() 18947 + " without permission " 18948 + android.Manifest.permission.DUMP); 18949 return; 18950 } 18951 18952 DumpState dumpState = new DumpState(); 18953 boolean fullPreferred = false; 18954 boolean checkin = false; 18955 18956 String packageName = null; 18957 ArraySet<String> permissionNames = null; 18958 18959 int opti = 0; 18960 while (opti < args.length) { 18961 String opt = args[opti]; 18962 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 18963 break; 18964 } 18965 opti++; 18966 18967 if ("-a".equals(opt)) { 18968 // Right now we only know how to print all. 18969 } else if ("-h".equals(opt)) { 18970 pw.println("Package manager dump options:"); 18971 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 18972 pw.println(" --checkin: dump for a checkin"); 18973 pw.println(" -f: print details of intent filters"); 18974 pw.println(" -h: print this help"); 18975 pw.println(" cmd may be one of:"); 18976 pw.println(" l[ibraries]: list known shared libraries"); 18977 pw.println(" f[eatures]: list device features"); 18978 pw.println(" k[eysets]: print known keysets"); 18979 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 18980 pw.println(" perm[issions]: dump permissions"); 18981 pw.println(" permission [name ...]: dump declaration and use of given permission"); 18982 pw.println(" pref[erred]: print preferred package settings"); 18983 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 18984 pw.println(" prov[iders]: dump content providers"); 18985 pw.println(" p[ackages]: dump installed packages"); 18986 pw.println(" s[hared-users]: dump shared user IDs"); 18987 pw.println(" m[essages]: print collected runtime messages"); 18988 pw.println(" v[erifiers]: print package verifier info"); 18989 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 18990 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 18991 pw.println(" version: print database version info"); 18992 pw.println(" write: write current settings now"); 18993 pw.println(" installs: details about install sessions"); 18994 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 18995 pw.println(" dexopt: dump dexopt state"); 18996 pw.println(" compiler-stats: dump compiler statistics"); 18997 pw.println(" <package.name>: info about given package"); 18998 return; 18999 } else if ("--checkin".equals(opt)) { 19000 checkin = true; 19001 } else if ("-f".equals(opt)) { 19002 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 19003 } else { 19004 pw.println("Unknown argument: " + opt + "; use -h for help"); 19005 } 19006 } 19007 19008 // Is the caller requesting to dump a particular piece of data? 19009 if (opti < args.length) { 19010 String cmd = args[opti]; 19011 opti++; 19012 // Is this a package name? 19013 if ("android".equals(cmd) || cmd.contains(".")) { 19014 packageName = cmd; 19015 // When dumping a single package, we always dump all of its 19016 // filter information since the amount of data will be reasonable. 19017 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 19018 } else if ("check-permission".equals(cmd)) { 19019 if (opti >= args.length) { 19020 pw.println("Error: check-permission missing permission argument"); 19021 return; 19022 } 19023 String perm = args[opti]; 19024 opti++; 19025 if (opti >= args.length) { 19026 pw.println("Error: check-permission missing package argument"); 19027 return; 19028 } 19029 String pkg = args[opti]; 19030 opti++; 19031 int user = UserHandle.getUserId(Binder.getCallingUid()); 19032 if (opti < args.length) { 19033 try { 19034 user = Integer.parseInt(args[opti]); 19035 } catch (NumberFormatException e) { 19036 pw.println("Error: check-permission user argument is not a number: " 19037 + args[opti]); 19038 return; 19039 } 19040 } 19041 pw.println(checkPermission(perm, pkg, user)); 19042 return; 19043 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 19044 dumpState.setDump(DumpState.DUMP_LIBS); 19045 } else if ("f".equals(cmd) || "features".equals(cmd)) { 19046 dumpState.setDump(DumpState.DUMP_FEATURES); 19047 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 19048 if (opti >= args.length) { 19049 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 19050 | DumpState.DUMP_SERVICE_RESOLVERS 19051 | DumpState.DUMP_RECEIVER_RESOLVERS 19052 | DumpState.DUMP_CONTENT_RESOLVERS); 19053 } else { 19054 while (opti < args.length) { 19055 String name = args[opti]; 19056 if ("a".equals(name) || "activity".equals(name)) { 19057 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 19058 } else if ("s".equals(name) || "service".equals(name)) { 19059 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 19060 } else if ("r".equals(name) || "receiver".equals(name)) { 19061 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 19062 } else if ("c".equals(name) || "content".equals(name)) { 19063 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 19064 } else { 19065 pw.println("Error: unknown resolver table type: " + name); 19066 return; 19067 } 19068 opti++; 19069 } 19070 } 19071 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 19072 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 19073 } else if ("permission".equals(cmd)) { 19074 if (opti >= args.length) { 19075 pw.println("Error: permission requires permission name"); 19076 return; 19077 } 19078 permissionNames = new ArraySet<>(); 19079 while (opti < args.length) { 19080 permissionNames.add(args[opti]); 19081 opti++; 19082 } 19083 dumpState.setDump(DumpState.DUMP_PERMISSIONS 19084 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 19085 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 19086 dumpState.setDump(DumpState.DUMP_PREFERRED); 19087 } else if ("preferred-xml".equals(cmd)) { 19088 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 19089 if (opti < args.length && "--full".equals(args[opti])) { 19090 fullPreferred = true; 19091 opti++; 19092 } 19093 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 19094 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 19095 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 19096 dumpState.setDump(DumpState.DUMP_PACKAGES); 19097 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 19098 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 19099 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 19100 dumpState.setDump(DumpState.DUMP_PROVIDERS); 19101 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 19102 dumpState.setDump(DumpState.DUMP_MESSAGES); 19103 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 19104 dumpState.setDump(DumpState.DUMP_VERIFIERS); 19105 } else if ("i".equals(cmd) || "ifv".equals(cmd) 19106 || "intent-filter-verifiers".equals(cmd)) { 19107 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 19108 } else if ("version".equals(cmd)) { 19109 dumpState.setDump(DumpState.DUMP_VERSION); 19110 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 19111 dumpState.setDump(DumpState.DUMP_KEYSETS); 19112 } else if ("installs".equals(cmd)) { 19113 dumpState.setDump(DumpState.DUMP_INSTALLS); 19114 } else if ("frozen".equals(cmd)) { 19115 dumpState.setDump(DumpState.DUMP_FROZEN); 19116 } else if ("dexopt".equals(cmd)) { 19117 dumpState.setDump(DumpState.DUMP_DEXOPT); 19118 } else if ("compiler-stats".equals(cmd)) { 19119 dumpState.setDump(DumpState.DUMP_COMPILER_STATS); 19120 } else if ("write".equals(cmd)) { 19121 synchronized (mPackages) { 19122 mSettings.writeLPr(); 19123 pw.println("Settings written."); 19124 return; 19125 } 19126 } 19127 } 19128 19129 if (checkin) { 19130 pw.println("vers,1"); 19131 } 19132 19133 // reader 19134 synchronized (mPackages) { 19135 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 19136 if (!checkin) { 19137 if (dumpState.onTitlePrinted()) 19138 pw.println(); 19139 pw.println("Database versions:"); 19140 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 19141 } 19142 } 19143 19144 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 19145 if (!checkin) { 19146 if (dumpState.onTitlePrinted()) 19147 pw.println(); 19148 pw.println("Verifiers:"); 19149 pw.print(" Required: "); 19150 pw.print(mRequiredVerifierPackage); 19151 pw.print(" (uid="); 19152 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 19153 UserHandle.USER_SYSTEM)); 19154 pw.println(")"); 19155 } else if (mRequiredVerifierPackage != null) { 19156 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 19157 pw.print(","); 19158 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 19159 UserHandle.USER_SYSTEM)); 19160 } 19161 } 19162 19163 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 19164 packageName == null) { 19165 if (mIntentFilterVerifierComponent != null) { 19166 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 19167 if (!checkin) { 19168 if (dumpState.onTitlePrinted()) 19169 pw.println(); 19170 pw.println("Intent Filter Verifier:"); 19171 pw.print(" Using: "); 19172 pw.print(verifierPackageName); 19173 pw.print(" (uid="); 19174 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 19175 UserHandle.USER_SYSTEM)); 19176 pw.println(")"); 19177 } else if (verifierPackageName != null) { 19178 pw.print("ifv,"); pw.print(verifierPackageName); 19179 pw.print(","); 19180 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 19181 UserHandle.USER_SYSTEM)); 19182 } 19183 } else { 19184 pw.println(); 19185 pw.println("No Intent Filter Verifier available!"); 19186 } 19187 } 19188 19189 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 19190 boolean printedHeader = false; 19191 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 19192 while (it.hasNext()) { 19193 String name = it.next(); 19194 SharedLibraryEntry ent = mSharedLibraries.get(name); 19195 if (!checkin) { 19196 if (!printedHeader) { 19197 if (dumpState.onTitlePrinted()) 19198 pw.println(); 19199 pw.println("Libraries:"); 19200 printedHeader = true; 19201 } 19202 pw.print(" "); 19203 } else { 19204 pw.print("lib,"); 19205 } 19206 pw.print(name); 19207 if (!checkin) { 19208 pw.print(" -> "); 19209 } 19210 if (ent.path != null) { 19211 if (!checkin) { 19212 pw.print("(jar) "); 19213 pw.print(ent.path); 19214 } else { 19215 pw.print(",jar,"); 19216 pw.print(ent.path); 19217 } 19218 } else { 19219 if (!checkin) { 19220 pw.print("(apk) "); 19221 pw.print(ent.apk); 19222 } else { 19223 pw.print(",apk,"); 19224 pw.print(ent.apk); 19225 } 19226 } 19227 pw.println(); 19228 } 19229 } 19230 19231 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 19232 if (dumpState.onTitlePrinted()) 19233 pw.println(); 19234 if (!checkin) { 19235 pw.println("Features:"); 19236 } 19237 19238 for (FeatureInfo feat : mAvailableFeatures.values()) { 19239 if (checkin) { 19240 pw.print("feat,"); 19241 pw.print(feat.name); 19242 pw.print(","); 19243 pw.println(feat.version); 19244 } else { 19245 pw.print(" "); 19246 pw.print(feat.name); 19247 if (feat.version > 0) { 19248 pw.print(" version="); 19249 pw.print(feat.version); 19250 } 19251 pw.println(); 19252 } 19253 } 19254 } 19255 19256 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 19257 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 19258 : "Activity Resolver Table:", " ", packageName, 19259 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 19260 dumpState.setTitlePrinted(true); 19261 } 19262 } 19263 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 19264 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 19265 : "Receiver Resolver Table:", " ", packageName, 19266 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 19267 dumpState.setTitlePrinted(true); 19268 } 19269 } 19270 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 19271 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 19272 : "Service Resolver Table:", " ", packageName, 19273 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 19274 dumpState.setTitlePrinted(true); 19275 } 19276 } 19277 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 19278 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 19279 : "Provider Resolver Table:", " ", packageName, 19280 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 19281 dumpState.setTitlePrinted(true); 19282 } 19283 } 19284 19285 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 19286 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 19287 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 19288 int user = mSettings.mPreferredActivities.keyAt(i); 19289 if (pir.dump(pw, 19290 dumpState.getTitlePrinted() 19291 ? "\nPreferred Activities User " + user + ":" 19292 : "Preferred Activities User " + user + ":", " ", 19293 packageName, true, false)) { 19294 dumpState.setTitlePrinted(true); 19295 } 19296 } 19297 } 19298 19299 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 19300 pw.flush(); 19301 FileOutputStream fout = new FileOutputStream(fd); 19302 BufferedOutputStream str = new BufferedOutputStream(fout); 19303 XmlSerializer serializer = new FastXmlSerializer(); 19304 try { 19305 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 19306 serializer.startDocument(null, true); 19307 serializer.setFeature( 19308 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 19309 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 19310 serializer.endDocument(); 19311 serializer.flush(); 19312 } catch (IllegalArgumentException e) { 19313 pw.println("Failed writing: " + e); 19314 } catch (IllegalStateException e) { 19315 pw.println("Failed writing: " + e); 19316 } catch (IOException e) { 19317 pw.println("Failed writing: " + e); 19318 } 19319 } 19320 19321 if (!checkin 19322 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 19323 && packageName == null) { 19324 pw.println(); 19325 int count = mSettings.mPackages.size(); 19326 if (count == 0) { 19327 pw.println("No applications!"); 19328 pw.println(); 19329 } else { 19330 final String prefix = " "; 19331 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 19332 if (allPackageSettings.size() == 0) { 19333 pw.println("No domain preferred apps!"); 19334 pw.println(); 19335 } else { 19336 pw.println("App verification status:"); 19337 pw.println(); 19338 count = 0; 19339 for (PackageSetting ps : allPackageSettings) { 19340 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 19341 if (ivi == null || ivi.getPackageName() == null) continue; 19342 pw.println(prefix + "Package: " + ivi.getPackageName()); 19343 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 19344 pw.println(prefix + "Status: " + ivi.getStatusString()); 19345 pw.println(); 19346 count++; 19347 } 19348 if (count == 0) { 19349 pw.println(prefix + "No app verification established."); 19350 pw.println(); 19351 } 19352 for (int userId : sUserManager.getUserIds()) { 19353 pw.println("App linkages for user " + userId + ":"); 19354 pw.println(); 19355 count = 0; 19356 for (PackageSetting ps : allPackageSettings) { 19357 final long status = ps.getDomainVerificationStatusForUser(userId); 19358 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 19359 continue; 19360 } 19361 pw.println(prefix + "Package: " + ps.name); 19362 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 19363 String statusStr = IntentFilterVerificationInfo. 19364 getStatusStringFromValue(status); 19365 pw.println(prefix + "Status: " + statusStr); 19366 pw.println(); 19367 count++; 19368 } 19369 if (count == 0) { 19370 pw.println(prefix + "No configured app linkages."); 19371 pw.println(); 19372 } 19373 } 19374 } 19375 } 19376 } 19377 19378 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 19379 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 19380 if (packageName == null && permissionNames == null) { 19381 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 19382 if (iperm == 0) { 19383 if (dumpState.onTitlePrinted()) 19384 pw.println(); 19385 pw.println("AppOp Permissions:"); 19386 } 19387 pw.print(" AppOp Permission "); 19388 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 19389 pw.println(":"); 19390 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 19391 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 19392 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 19393 } 19394 } 19395 } 19396 } 19397 19398 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 19399 boolean printedSomething = false; 19400 for (PackageParser.Provider p : mProviders.mProviders.values()) { 19401 if (packageName != null && !packageName.equals(p.info.packageName)) { 19402 continue; 19403 } 19404 if (!printedSomething) { 19405 if (dumpState.onTitlePrinted()) 19406 pw.println(); 19407 pw.println("Registered ContentProviders:"); 19408 printedSomething = true; 19409 } 19410 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 19411 pw.print(" "); pw.println(p.toString()); 19412 } 19413 printedSomething = false; 19414 for (Map.Entry<String, PackageParser.Provider> entry : 19415 mProvidersByAuthority.entrySet()) { 19416 PackageParser.Provider p = entry.getValue(); 19417 if (packageName != null && !packageName.equals(p.info.packageName)) { 19418 continue; 19419 } 19420 if (!printedSomething) { 19421 if (dumpState.onTitlePrinted()) 19422 pw.println(); 19423 pw.println("ContentProvider Authorities:"); 19424 printedSomething = true; 19425 } 19426 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 19427 pw.print(" "); pw.println(p.toString()); 19428 if (p.info != null && p.info.applicationInfo != null) { 19429 final String appInfo = p.info.applicationInfo.toString(); 19430 pw.print(" applicationInfo="); pw.println(appInfo); 19431 } 19432 } 19433 } 19434 19435 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 19436 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 19437 } 19438 19439 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 19440 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 19441 } 19442 19443 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 19444 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 19445 } 19446 19447 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 19448 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 19449 } 19450 19451 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 19452 // XXX should handle packageName != null by dumping only install data that 19453 // the given package is involved with. 19454 if (dumpState.onTitlePrinted()) pw.println(); 19455 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 19456 } 19457 19458 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 19459 // XXX should handle packageName != null by dumping only install data that 19460 // the given package is involved with. 19461 if (dumpState.onTitlePrinted()) pw.println(); 19462 19463 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 19464 ipw.println(); 19465 ipw.println("Frozen packages:"); 19466 ipw.increaseIndent(); 19467 if (mFrozenPackages.size() == 0) { 19468 ipw.println("(none)"); 19469 } else { 19470 for (int i = 0; i < mFrozenPackages.size(); i++) { 19471 ipw.println(mFrozenPackages.valueAt(i)); 19472 } 19473 } 19474 ipw.decreaseIndent(); 19475 } 19476 19477 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 19478 if (dumpState.onTitlePrinted()) pw.println(); 19479 dumpDexoptStateLPr(pw, packageName); 19480 } 19481 19482 if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) { 19483 if (dumpState.onTitlePrinted()) pw.println(); 19484 dumpCompilerStatsLPr(pw, packageName); 19485 } 19486 19487 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 19488 if (dumpState.onTitlePrinted()) pw.println(); 19489 mSettings.dumpReadMessagesLPr(pw, dumpState); 19490 19491 pw.println(); 19492 pw.println("Package warning messages:"); 19493 BufferedReader in = null; 19494 String line = null; 19495 try { 19496 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 19497 while ((line = in.readLine()) != null) { 19498 if (line.contains("ignored: updated version")) continue; 19499 pw.println(line); 19500 } 19501 } catch (IOException ignored) { 19502 } finally { 19503 IoUtils.closeQuietly(in); 19504 } 19505 } 19506 19507 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 19508 BufferedReader in = null; 19509 String line = null; 19510 try { 19511 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 19512 while ((line = in.readLine()) != null) { 19513 if (line.contains("ignored: updated version")) continue; 19514 pw.print("msg,"); 19515 pw.println(line); 19516 } 19517 } catch (IOException ignored) { 19518 } finally { 19519 IoUtils.closeQuietly(in); 19520 } 19521 } 19522 } 19523 } 19524 19525 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 19526 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 19527 ipw.println(); 19528 ipw.println("Dexopt state:"); 19529 ipw.increaseIndent(); 19530 Collection<PackageParser.Package> packages = null; 19531 if (packageName != null) { 19532 PackageParser.Package targetPackage = mPackages.get(packageName); 19533 if (targetPackage != null) { 19534 packages = Collections.singletonList(targetPackage); 19535 } else { 19536 ipw.println("Unable to find package: " + packageName); 19537 return; 19538 } 19539 } else { 19540 packages = mPackages.values(); 19541 } 19542 19543 for (PackageParser.Package pkg : packages) { 19544 ipw.println("[" + pkg.packageName + "]"); 19545 ipw.increaseIndent(); 19546 mPackageDexOptimizer.dumpDexoptState(ipw, pkg); 19547 ipw.decreaseIndent(); 19548 } 19549 } 19550 19551 private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) { 19552 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 19553 ipw.println(); 19554 ipw.println("Compiler stats:"); 19555 ipw.increaseIndent(); 19556 Collection<PackageParser.Package> packages = null; 19557 if (packageName != null) { 19558 PackageParser.Package targetPackage = mPackages.get(packageName); 19559 if (targetPackage != null) { 19560 packages = Collections.singletonList(targetPackage); 19561 } else { 19562 ipw.println("Unable to find package: " + packageName); 19563 return; 19564 } 19565 } else { 19566 packages = mPackages.values(); 19567 } 19568 19569 for (PackageParser.Package pkg : packages) { 19570 ipw.println("[" + pkg.packageName + "]"); 19571 ipw.increaseIndent(); 19572 19573 CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName); 19574 if (stats == null) { 19575 ipw.println("(No recorded stats)"); 19576 } else { 19577 stats.dump(ipw); 19578 } 19579 ipw.decreaseIndent(); 19580 } 19581 } 19582 19583 private String dumpDomainString(String packageName) { 19584 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 19585 .getList(); 19586 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 19587 19588 ArraySet<String> result = new ArraySet<>(); 19589 if (iviList.size() > 0) { 19590 for (IntentFilterVerificationInfo ivi : iviList) { 19591 for (String host : ivi.getDomains()) { 19592 result.add(host); 19593 } 19594 } 19595 } 19596 if (filters != null && filters.size() > 0) { 19597 for (IntentFilter filter : filters) { 19598 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 19599 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 19600 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 19601 result.addAll(filter.getHostsList()); 19602 } 19603 } 19604 } 19605 19606 StringBuilder sb = new StringBuilder(result.size() * 16); 19607 for (String domain : result) { 19608 if (sb.length() > 0) sb.append(" "); 19609 sb.append(domain); 19610 } 19611 return sb.toString(); 19612 } 19613 19614 // ------- apps on sdcard specific code ------- 19615 static final boolean DEBUG_SD_INSTALL = false; 19616 19617 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 19618 19619 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 19620 19621 private boolean mMediaMounted = false; 19622 19623 static String getEncryptKey() { 19624 try { 19625 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 19626 SD_ENCRYPTION_KEYSTORE_NAME); 19627 if (sdEncKey == null) { 19628 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 19629 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 19630 if (sdEncKey == null) { 19631 Slog.e(TAG, "Failed to create encryption keys"); 19632 return null; 19633 } 19634 } 19635 return sdEncKey; 19636 } catch (NoSuchAlgorithmException nsae) { 19637 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 19638 return null; 19639 } catch (IOException ioe) { 19640 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 19641 return null; 19642 } 19643 } 19644 19645 /* 19646 * Update media status on PackageManager. 19647 */ 19648 @Override 19649 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 19650 int callingUid = Binder.getCallingUid(); 19651 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 19652 throw new SecurityException("Media status can only be updated by the system"); 19653 } 19654 // reader; this apparently protects mMediaMounted, but should probably 19655 // be a different lock in that case. 19656 synchronized (mPackages) { 19657 Log.i(TAG, "Updating external media status from " 19658 + (mMediaMounted ? "mounted" : "unmounted") + " to " 19659 + (mediaStatus ? "mounted" : "unmounted")); 19660 if (DEBUG_SD_INSTALL) 19661 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 19662 + ", mMediaMounted=" + mMediaMounted); 19663 if (mediaStatus == mMediaMounted) { 19664 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 19665 : 0, -1); 19666 mHandler.sendMessage(msg); 19667 return; 19668 } 19669 mMediaMounted = mediaStatus; 19670 } 19671 // Queue up an async operation since the package installation may take a 19672 // little while. 19673 mHandler.post(new Runnable() { 19674 public void run() { 19675 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 19676 } 19677 }); 19678 } 19679 19680 /** 19681 * Called by StorageManagerService when the initial ASECs to scan are available. 19682 * Should block until all the ASEC containers are finished being scanned. 19683 */ 19684 public void scanAvailableAsecs() { 19685 updateExternalMediaStatusInner(true, false, false); 19686 } 19687 19688 /* 19689 * Collect information of applications on external media, map them against 19690 * existing containers and update information based on current mount status. 19691 * Please note that we always have to report status if reportStatus has been 19692 * set to true especially when unloading packages. 19693 */ 19694 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 19695 boolean externalStorage) { 19696 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 19697 int[] uidArr = EmptyArray.INT; 19698 19699 final String[] list = PackageHelper.getSecureContainerList(); 19700 if (ArrayUtils.isEmpty(list)) { 19701 Log.i(TAG, "No secure containers found"); 19702 } else { 19703 // Process list of secure containers and categorize them 19704 // as active or stale based on their package internal state. 19705 19706 // reader 19707 synchronized (mPackages) { 19708 for (String cid : list) { 19709 // Leave stages untouched for now; installer service owns them 19710 if (PackageInstallerService.isStageName(cid)) continue; 19711 19712 if (DEBUG_SD_INSTALL) 19713 Log.i(TAG, "Processing container " + cid); 19714 String pkgName = getAsecPackageName(cid); 19715 if (pkgName == null) { 19716 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 19717 continue; 19718 } 19719 if (DEBUG_SD_INSTALL) 19720 Log.i(TAG, "Looking for pkg : " + pkgName); 19721 19722 final PackageSetting ps = mSettings.mPackages.get(pkgName); 19723 if (ps == null) { 19724 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 19725 continue; 19726 } 19727 19728 /* 19729 * Skip packages that are not external if we're unmounting 19730 * external storage. 19731 */ 19732 if (externalStorage && !isMounted && !isExternal(ps)) { 19733 continue; 19734 } 19735 19736 final AsecInstallArgs args = new AsecInstallArgs(cid, 19737 getAppDexInstructionSets(ps), ps.isForwardLocked()); 19738 // The package status is changed only if the code path 19739 // matches between settings and the container id. 19740 if (ps.codePathString != null 19741 && ps.codePathString.startsWith(args.getCodePath())) { 19742 if (DEBUG_SD_INSTALL) { 19743 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 19744 + " at code path: " + ps.codePathString); 19745 } 19746 19747 // We do have a valid package installed on sdcard 19748 processCids.put(args, ps.codePathString); 19749 final int uid = ps.appId; 19750 if (uid != -1) { 19751 uidArr = ArrayUtils.appendInt(uidArr, uid); 19752 } 19753 } else { 19754 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 19755 + ps.codePathString); 19756 } 19757 } 19758 } 19759 19760 Arrays.sort(uidArr); 19761 } 19762 19763 // Process packages with valid entries. 19764 if (isMounted) { 19765 if (DEBUG_SD_INSTALL) 19766 Log.i(TAG, "Loading packages"); 19767 loadMediaPackages(processCids, uidArr, externalStorage); 19768 startCleaningPackages(); 19769 mInstallerService.onSecureContainersAvailable(); 19770 } else { 19771 if (DEBUG_SD_INSTALL) 19772 Log.i(TAG, "Unloading packages"); 19773 unloadMediaPackages(processCids, uidArr, reportStatus); 19774 } 19775 } 19776 19777 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 19778 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 19779 final int size = infos.size(); 19780 final String[] packageNames = new String[size]; 19781 final int[] packageUids = new int[size]; 19782 for (int i = 0; i < size; i++) { 19783 final ApplicationInfo info = infos.get(i); 19784 packageNames[i] = info.packageName; 19785 packageUids[i] = info.uid; 19786 } 19787 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 19788 finishedReceiver); 19789 } 19790 19791 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 19792 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 19793 sendResourcesChangedBroadcast(mediaStatus, replacing, 19794 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 19795 } 19796 19797 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 19798 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 19799 int size = pkgList.length; 19800 if (size > 0) { 19801 // Send broadcasts here 19802 Bundle extras = new Bundle(); 19803 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 19804 if (uidArr != null) { 19805 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 19806 } 19807 if (replacing) { 19808 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 19809 } 19810 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 19811 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 19812 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 19813 } 19814 } 19815 19816 /* 19817 * Look at potentially valid container ids from processCids If package 19818 * information doesn't match the one on record or package scanning fails, 19819 * the cid is added to list of removeCids. We currently don't delete stale 19820 * containers. 19821 */ 19822 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 19823 boolean externalStorage) { 19824 ArrayList<String> pkgList = new ArrayList<String>(); 19825 Set<AsecInstallArgs> keys = processCids.keySet(); 19826 19827 for (AsecInstallArgs args : keys) { 19828 String codePath = processCids.get(args); 19829 if (DEBUG_SD_INSTALL) 19830 Log.i(TAG, "Loading container : " + args.cid); 19831 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 19832 try { 19833 // Make sure there are no container errors first. 19834 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 19835 Slog.e(TAG, "Failed to mount cid : " + args.cid 19836 + " when installing from sdcard"); 19837 continue; 19838 } 19839 // Check code path here. 19840 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 19841 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 19842 + " does not match one in settings " + codePath); 19843 continue; 19844 } 19845 // Parse package 19846 int parseFlags = mDefParseFlags; 19847 if (args.isExternalAsec()) { 19848 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 19849 } 19850 if (args.isFwdLocked()) { 19851 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 19852 } 19853 19854 synchronized (mInstallLock) { 19855 PackageParser.Package pkg = null; 19856 try { 19857 // Sadly we don't know the package name yet to freeze it 19858 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 19859 SCAN_IGNORE_FROZEN, 0, null); 19860 } catch (PackageManagerException e) { 19861 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 19862 } 19863 // Scan the package 19864 if (pkg != null) { 19865 /* 19866 * TODO why is the lock being held? doPostInstall is 19867 * called in other places without the lock. This needs 19868 * to be straightened out. 19869 */ 19870 // writer 19871 synchronized (mPackages) { 19872 retCode = PackageManager.INSTALL_SUCCEEDED; 19873 pkgList.add(pkg.packageName); 19874 // Post process args 19875 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 19876 pkg.applicationInfo.uid); 19877 } 19878 } else { 19879 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 19880 } 19881 } 19882 19883 } finally { 19884 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 19885 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 19886 } 19887 } 19888 } 19889 // writer 19890 synchronized (mPackages) { 19891 // If the platform SDK has changed since the last time we booted, 19892 // we need to re-grant app permission to catch any new ones that 19893 // appear. This is really a hack, and means that apps can in some 19894 // cases get permissions that the user didn't initially explicitly 19895 // allow... it would be nice to have some better way to handle 19896 // this situation. 19897 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 19898 : mSettings.getInternalVersion(); 19899 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 19900 : StorageManager.UUID_PRIVATE_INTERNAL; 19901 19902 int updateFlags = UPDATE_PERMISSIONS_ALL; 19903 if (ver.sdkVersion != mSdkVersion) { 19904 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 19905 + mSdkVersion + "; regranting permissions for external"); 19906 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 19907 } 19908 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 19909 19910 // Yay, everything is now upgraded 19911 ver.forceCurrent(); 19912 19913 // can downgrade to reader 19914 // Persist settings 19915 mSettings.writeLPr(); 19916 } 19917 // Send a broadcast to let everyone know we are done processing 19918 if (pkgList.size() > 0) { 19919 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 19920 } 19921 } 19922 19923 /* 19924 * Utility method to unload a list of specified containers 19925 */ 19926 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 19927 // Just unmount all valid containers. 19928 for (AsecInstallArgs arg : cidArgs) { 19929 synchronized (mInstallLock) { 19930 arg.doPostDeleteLI(false); 19931 } 19932 } 19933 } 19934 19935 /* 19936 * Unload packages mounted on external media. This involves deleting package 19937 * data from internal structures, sending broadcasts about disabled packages, 19938 * gc'ing to free up references, unmounting all secure containers 19939 * corresponding to packages on external media, and posting a 19940 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 19941 * that we always have to post this message if status has been requested no 19942 * matter what. 19943 */ 19944 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 19945 final boolean reportStatus) { 19946 if (DEBUG_SD_INSTALL) 19947 Log.i(TAG, "unloading media packages"); 19948 ArrayList<String> pkgList = new ArrayList<String>(); 19949 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 19950 final Set<AsecInstallArgs> keys = processCids.keySet(); 19951 for (AsecInstallArgs args : keys) { 19952 String pkgName = args.getPackageName(); 19953 if (DEBUG_SD_INSTALL) 19954 Log.i(TAG, "Trying to unload pkg : " + pkgName); 19955 // Delete package internally 19956 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 19957 synchronized (mInstallLock) { 19958 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 19959 final boolean res; 19960 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 19961 "unloadMediaPackages")) { 19962 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 19963 null); 19964 } 19965 if (res) { 19966 pkgList.add(pkgName); 19967 } else { 19968 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 19969 failedList.add(args); 19970 } 19971 } 19972 } 19973 19974 // reader 19975 synchronized (mPackages) { 19976 // We didn't update the settings after removing each package; 19977 // write them now for all packages. 19978 mSettings.writeLPr(); 19979 } 19980 19981 // We have to absolutely send UPDATED_MEDIA_STATUS only 19982 // after confirming that all the receivers processed the ordered 19983 // broadcast when packages get disabled, force a gc to clean things up. 19984 // and unload all the containers. 19985 if (pkgList.size() > 0) { 19986 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 19987 new IIntentReceiver.Stub() { 19988 public void performReceive(Intent intent, int resultCode, String data, 19989 Bundle extras, boolean ordered, boolean sticky, 19990 int sendingUser) throws RemoteException { 19991 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 19992 reportStatus ? 1 : 0, 1, keys); 19993 mHandler.sendMessage(msg); 19994 } 19995 }); 19996 } else { 19997 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 19998 keys); 19999 mHandler.sendMessage(msg); 20000 } 20001 } 20002 20003 private void loadPrivatePackages(final VolumeInfo vol) { 20004 mHandler.post(new Runnable() { 20005 @Override 20006 public void run() { 20007 loadPrivatePackagesInner(vol); 20008 } 20009 }); 20010 } 20011 20012 private void loadPrivatePackagesInner(VolumeInfo vol) { 20013 final String volumeUuid = vol.fsUuid; 20014 if (TextUtils.isEmpty(volumeUuid)) { 20015 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 20016 return; 20017 } 20018 20019 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 20020 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 20021 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 20022 20023 final VersionInfo ver; 20024 final List<PackageSetting> packages; 20025 synchronized (mPackages) { 20026 ver = mSettings.findOrCreateVersion(volumeUuid); 20027 packages = mSettings.getVolumePackagesLPr(volumeUuid); 20028 } 20029 20030 for (PackageSetting ps : packages) { 20031 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 20032 synchronized (mInstallLock) { 20033 final PackageParser.Package pkg; 20034 try { 20035 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 20036 loaded.add(pkg.applicationInfo); 20037 20038 } catch (PackageManagerException e) { 20039 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 20040 } 20041 20042 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 20043 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 20044 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 20045 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 20046 } 20047 } 20048 } 20049 20050 // Reconcile app data for all started/unlocked users 20051 final StorageManager sm = mContext.getSystemService(StorageManager.class); 20052 final UserManager um = mContext.getSystemService(UserManager.class); 20053 UserManagerInternal umInternal = getUserManagerInternal(); 20054 for (UserInfo user : um.getUsers()) { 20055 final int flags; 20056 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 20057 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 20058 } else if (umInternal.isUserRunning(user.id)) { 20059 flags = StorageManager.FLAG_STORAGE_DE; 20060 } else { 20061 continue; 20062 } 20063 20064 try { 20065 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 20066 synchronized (mInstallLock) { 20067 reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */); 20068 } 20069 } catch (IllegalStateException e) { 20070 // Device was probably ejected, and we'll process that event momentarily 20071 Slog.w(TAG, "Failed to prepare storage: " + e); 20072 } 20073 } 20074 20075 synchronized (mPackages) { 20076 int updateFlags = UPDATE_PERMISSIONS_ALL; 20077 if (ver.sdkVersion != mSdkVersion) { 20078 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 20079 + mSdkVersion + "; regranting permissions for " + volumeUuid); 20080 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 20081 } 20082 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 20083 20084 // Yay, everything is now upgraded 20085 ver.forceCurrent(); 20086 20087 mSettings.writeLPr(); 20088 } 20089 20090 for (PackageFreezer freezer : freezers) { 20091 freezer.close(); 20092 } 20093 20094 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 20095 sendResourcesChangedBroadcast(true, false, loaded, null); 20096 } 20097 20098 private void unloadPrivatePackages(final VolumeInfo vol) { 20099 mHandler.post(new Runnable() { 20100 @Override 20101 public void run() { 20102 unloadPrivatePackagesInner(vol); 20103 } 20104 }); 20105 } 20106 20107 private void unloadPrivatePackagesInner(VolumeInfo vol) { 20108 final String volumeUuid = vol.fsUuid; 20109 if (TextUtils.isEmpty(volumeUuid)) { 20110 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 20111 return; 20112 } 20113 20114 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 20115 synchronized (mInstallLock) { 20116 synchronized (mPackages) { 20117 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 20118 for (PackageSetting ps : packages) { 20119 if (ps.pkg == null) continue; 20120 20121 final ApplicationInfo info = ps.pkg.applicationInfo; 20122 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 20123 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 20124 20125 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 20126 "unloadPrivatePackagesInner")) { 20127 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 20128 false, null)) { 20129 unloaded.add(info); 20130 } else { 20131 Slog.w(TAG, "Failed to unload " + ps.codePath); 20132 } 20133 } 20134 20135 // Try very hard to release any references to this package 20136 // so we don't risk the system server being killed due to 20137 // open FDs 20138 AttributeCache.instance().removePackage(ps.name); 20139 } 20140 20141 mSettings.writeLPr(); 20142 } 20143 } 20144 20145 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 20146 sendResourcesChangedBroadcast(false, false, unloaded, null); 20147 20148 // Try very hard to release any references to this path so we don't risk 20149 // the system server being killed due to open FDs 20150 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 20151 20152 for (int i = 0; i < 3; i++) { 20153 System.gc(); 20154 System.runFinalization(); 20155 } 20156 } 20157 20158 /** 20159 * Prepare storage areas for given user on all mounted devices. 20160 */ 20161 void prepareUserData(int userId, int userSerial, int flags) { 20162 synchronized (mInstallLock) { 20163 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20164 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 20165 final String volumeUuid = vol.getFsUuid(); 20166 prepareUserDataLI(volumeUuid, userId, userSerial, flags, true); 20167 } 20168 } 20169 } 20170 20171 private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags, 20172 boolean allowRecover) { 20173 // Prepare storage and verify that serial numbers are consistent; if 20174 // there's a mismatch we need to destroy to avoid leaking data 20175 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20176 try { 20177 storage.prepareUserStorage(volumeUuid, userId, userSerial, flags); 20178 20179 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) { 20180 UserManagerService.enforceSerialNumber( 20181 Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial); 20182 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 20183 UserManagerService.enforceSerialNumber( 20184 Environment.getDataSystemDeDirectory(userId), userSerial); 20185 } 20186 } 20187 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) { 20188 UserManagerService.enforceSerialNumber( 20189 Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial); 20190 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 20191 UserManagerService.enforceSerialNumber( 20192 Environment.getDataSystemCeDirectory(userId), userSerial); 20193 } 20194 } 20195 20196 synchronized (mInstallLock) { 20197 mInstaller.createUserData(volumeUuid, userId, userSerial, flags); 20198 } 20199 } catch (Exception e) { 20200 logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid 20201 + " because we failed to prepare: " + e); 20202 destroyUserDataLI(volumeUuid, userId, 20203 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 20204 20205 if (allowRecover) { 20206 // Try one last time; if we fail again we're really in trouble 20207 prepareUserDataLI(volumeUuid, userId, userSerial, flags, false); 20208 } 20209 } 20210 } 20211 20212 /** 20213 * Destroy storage areas for given user on all mounted devices. 20214 */ 20215 void destroyUserData(int userId, int flags) { 20216 synchronized (mInstallLock) { 20217 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20218 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 20219 final String volumeUuid = vol.getFsUuid(); 20220 destroyUserDataLI(volumeUuid, userId, flags); 20221 } 20222 } 20223 } 20224 20225 private void destroyUserDataLI(String volumeUuid, int userId, int flags) { 20226 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20227 try { 20228 // Clean up app data, profile data, and media data 20229 mInstaller.destroyUserData(volumeUuid, userId, flags); 20230 20231 // Clean up system data 20232 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 20233 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 20234 FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId)); 20235 FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId)); 20236 } 20237 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 20238 FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId)); 20239 } 20240 } 20241 20242 // Data with special labels is now gone, so finish the job 20243 storage.destroyUserStorage(volumeUuid, userId, flags); 20244 20245 } catch (Exception e) { 20246 logCriticalInfo(Log.WARN, 20247 "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e); 20248 } 20249 } 20250 20251 /** 20252 * Examine all users present on given mounted volume, and destroy data 20253 * belonging to users that are no longer valid, or whose user ID has been 20254 * recycled. 20255 */ 20256 private void reconcileUsers(String volumeUuid) { 20257 final List<File> files = new ArrayList<>(); 20258 Collections.addAll(files, FileUtils 20259 .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid))); 20260 Collections.addAll(files, FileUtils 20261 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid))); 20262 Collections.addAll(files, FileUtils 20263 .listFilesOrEmpty(Environment.getDataSystemDeDirectory())); 20264 Collections.addAll(files, FileUtils 20265 .listFilesOrEmpty(Environment.getDataSystemCeDirectory())); 20266 for (File file : files) { 20267 if (!file.isDirectory()) continue; 20268 20269 final int userId; 20270 final UserInfo info; 20271 try { 20272 userId = Integer.parseInt(file.getName()); 20273 info = sUserManager.getUserInfo(userId); 20274 } catch (NumberFormatException e) { 20275 Slog.w(TAG, "Invalid user directory " + file); 20276 continue; 20277 } 20278 20279 boolean destroyUser = false; 20280 if (info == null) { 20281 logCriticalInfo(Log.WARN, "Destroying user directory " + file 20282 + " because no matching user was found"); 20283 destroyUser = true; 20284 } else if (!mOnlyCore) { 20285 try { 20286 UserManagerService.enforceSerialNumber(file, info.serialNumber); 20287 } catch (IOException e) { 20288 logCriticalInfo(Log.WARN, "Destroying user directory " + file 20289 + " because we failed to enforce serial number: " + e); 20290 destroyUser = true; 20291 } 20292 } 20293 20294 if (destroyUser) { 20295 synchronized (mInstallLock) { 20296 destroyUserDataLI(volumeUuid, userId, 20297 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 20298 } 20299 } 20300 } 20301 } 20302 20303 private void assertPackageKnown(String volumeUuid, String packageName) 20304 throws PackageManagerException { 20305 synchronized (mPackages) { 20306 // Normalize package name to handle renamed packages 20307 packageName = normalizePackageNameLPr(packageName); 20308 20309 final PackageSetting ps = mSettings.mPackages.get(packageName); 20310 if (ps == null) { 20311 throw new PackageManagerException("Package " + packageName + " is unknown"); 20312 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 20313 throw new PackageManagerException( 20314 "Package " + packageName + " found on unknown volume " + volumeUuid 20315 + "; expected volume " + ps.volumeUuid); 20316 } 20317 } 20318 } 20319 20320 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 20321 throws PackageManagerException { 20322 synchronized (mPackages) { 20323 // Normalize package name to handle renamed packages 20324 packageName = normalizePackageNameLPr(packageName); 20325 20326 final PackageSetting ps = mSettings.mPackages.get(packageName); 20327 if (ps == null) { 20328 throw new PackageManagerException("Package " + packageName + " is unknown"); 20329 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 20330 throw new PackageManagerException( 20331 "Package " + packageName + " found on unknown volume " + volumeUuid 20332 + "; expected volume " + ps.volumeUuid); 20333 } else if (!ps.getInstalled(userId)) { 20334 throw new PackageManagerException( 20335 "Package " + packageName + " not installed for user " + userId); 20336 } 20337 } 20338 } 20339 20340 /** 20341 * Examine all apps present on given mounted volume, and destroy apps that 20342 * aren't expected, either due to uninstallation or reinstallation on 20343 * another volume. 20344 */ 20345 private void reconcileApps(String volumeUuid) { 20346 final File[] files = FileUtils 20347 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 20348 for (File file : files) { 20349 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 20350 && !PackageInstallerService.isStageName(file.getName()); 20351 if (!isPackage) { 20352 // Ignore entries which are not packages 20353 continue; 20354 } 20355 20356 try { 20357 final PackageLite pkg = PackageParser.parsePackageLite(file, 20358 PackageParser.PARSE_MUST_BE_APK); 20359 assertPackageKnown(volumeUuid, pkg.packageName); 20360 20361 } catch (PackageParserException | PackageManagerException e) { 20362 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 20363 synchronized (mInstallLock) { 20364 removeCodePathLI(file); 20365 } 20366 } 20367 } 20368 } 20369 20370 /** 20371 * Reconcile all app data for the given user. 20372 * <p> 20373 * Verifies that directories exist and that ownership and labeling is 20374 * correct for all installed apps on all mounted volumes. 20375 */ 20376 void reconcileAppsData(int userId, int flags, boolean migrateAppsData) { 20377 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20378 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 20379 final String volumeUuid = vol.getFsUuid(); 20380 synchronized (mInstallLock) { 20381 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData); 20382 } 20383 } 20384 } 20385 20386 /** 20387 * Reconcile all app data on given mounted volume. 20388 * <p> 20389 * Destroys app data that isn't expected, either due to uninstallation or 20390 * reinstallation on another volume. 20391 * <p> 20392 * Verifies that directories exist and that ownership and labeling is 20393 * correct for all installed apps. 20394 */ 20395 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags, 20396 boolean migrateAppData) { 20397 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 20398 + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData); 20399 20400 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 20401 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 20402 20403 // First look for stale data that doesn't belong, and check if things 20404 // have changed since we did our last restorecon 20405 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 20406 if (StorageManager.isFileEncryptedNativeOrEmulated() 20407 && !StorageManager.isUserKeyUnlocked(userId)) { 20408 throw new RuntimeException( 20409 "Yikes, someone asked us to reconcile CE storage while " + userId 20410 + " was still locked; this would have caused massive data loss!"); 20411 } 20412 20413 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 20414 for (File file : files) { 20415 final String packageName = file.getName(); 20416 try { 20417 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 20418 } catch (PackageManagerException e) { 20419 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 20420 try { 20421 mInstaller.destroyAppData(volumeUuid, packageName, userId, 20422 StorageManager.FLAG_STORAGE_CE, 0); 20423 } catch (InstallerException e2) { 20424 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 20425 } 20426 } 20427 } 20428 } 20429 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 20430 final File[] files = FileUtils.listFilesOrEmpty(deDir); 20431 for (File file : files) { 20432 final String packageName = file.getName(); 20433 try { 20434 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 20435 } catch (PackageManagerException e) { 20436 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 20437 try { 20438 mInstaller.destroyAppData(volumeUuid, packageName, userId, 20439 StorageManager.FLAG_STORAGE_DE, 0); 20440 } catch (InstallerException e2) { 20441 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 20442 } 20443 } 20444 } 20445 } 20446 20447 // Ensure that data directories are ready to roll for all packages 20448 // installed for this volume and user 20449 final List<PackageSetting> packages; 20450 synchronized (mPackages) { 20451 packages = mSettings.getVolumePackagesLPr(volumeUuid); 20452 } 20453 int preparedCount = 0; 20454 for (PackageSetting ps : packages) { 20455 final String packageName = ps.name; 20456 if (ps.pkg == null) { 20457 Slog.w(TAG, "Odd, missing scanned package " + packageName); 20458 // TODO: might be due to legacy ASEC apps; we should circle back 20459 // and reconcile again once they're scanned 20460 continue; 20461 } 20462 20463 if (ps.getInstalled(userId)) { 20464 prepareAppDataLIF(ps.pkg, userId, flags); 20465 20466 if (migrateAppData && maybeMigrateAppDataLIF(ps.pkg, userId)) { 20467 // We may have just shuffled around app data directories, so 20468 // prepare them one more time 20469 prepareAppDataLIF(ps.pkg, userId, flags); 20470 } 20471 20472 preparedCount++; 20473 } 20474 } 20475 20476 Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages"); 20477 } 20478 20479 /** 20480 * Prepare app data for the given app just after it was installed or 20481 * upgraded. This method carefully only touches users that it's installed 20482 * for, and it forces a restorecon to handle any seinfo changes. 20483 * <p> 20484 * Verifies that directories exist and that ownership and labeling is 20485 * correct for all installed apps. If there is an ownership mismatch, it 20486 * will try recovering system apps by wiping data; third-party app data is 20487 * left intact. 20488 * <p> 20489 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 20490 */ 20491 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 20492 final PackageSetting ps; 20493 synchronized (mPackages) { 20494 ps = mSettings.mPackages.get(pkg.packageName); 20495 mSettings.writeKernelMappingLPr(ps); 20496 } 20497 20498 final UserManager um = mContext.getSystemService(UserManager.class); 20499 UserManagerInternal umInternal = getUserManagerInternal(); 20500 for (UserInfo user : um.getUsers()) { 20501 final int flags; 20502 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 20503 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 20504 } else if (umInternal.isUserRunning(user.id)) { 20505 flags = StorageManager.FLAG_STORAGE_DE; 20506 } else { 20507 continue; 20508 } 20509 20510 if (ps.getInstalled(user.id)) { 20511 // TODO: when user data is locked, mark that we're still dirty 20512 prepareAppDataLIF(pkg, user.id, flags); 20513 } 20514 } 20515 } 20516 20517 /** 20518 * Prepare app data for the given app. 20519 * <p> 20520 * Verifies that directories exist and that ownership and labeling is 20521 * correct for all installed apps. If there is an ownership mismatch, this 20522 * will try recovering system apps by wiping data; third-party app data is 20523 * left intact. 20524 */ 20525 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 20526 if (pkg == null) { 20527 Slog.wtf(TAG, "Package was null!", new Throwable()); 20528 return; 20529 } 20530 prepareAppDataLeafLIF(pkg, userId, flags); 20531 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 20532 for (int i = 0; i < childCount; i++) { 20533 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 20534 } 20535 } 20536 20537 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 20538 if (DEBUG_APP_DATA) { 20539 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 20540 + Integer.toHexString(flags)); 20541 } 20542 20543 final String volumeUuid = pkg.volumeUuid; 20544 final String packageName = pkg.packageName; 20545 final ApplicationInfo app = pkg.applicationInfo; 20546 final int appId = UserHandle.getAppId(app.uid); 20547 20548 Preconditions.checkNotNull(app.seinfo); 20549 20550 long ceDataInode = -1; 20551 try { 20552 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 20553 appId, app.seinfo, app.targetSdkVersion); 20554 } catch (InstallerException e) { 20555 if (app.isSystemApp()) { 20556 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 20557 + ", but trying to recover: " + e); 20558 destroyAppDataLeafLIF(pkg, userId, flags); 20559 try { 20560 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 20561 appId, app.seinfo, app.targetSdkVersion); 20562 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 20563 } catch (InstallerException e2) { 20564 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 20565 } 20566 } else { 20567 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 20568 } 20569 } 20570 20571 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) { 20572 // TODO: mark this structure as dirty so we persist it! 20573 synchronized (mPackages) { 20574 final PackageSetting ps = mSettings.mPackages.get(packageName); 20575 if (ps != null) { 20576 ps.setCeDataInode(ceDataInode, userId); 20577 } 20578 } 20579 } 20580 20581 prepareAppDataContentsLeafLIF(pkg, userId, flags); 20582 } 20583 20584 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 20585 if (pkg == null) { 20586 Slog.wtf(TAG, "Package was null!", new Throwable()); 20587 return; 20588 } 20589 prepareAppDataContentsLeafLIF(pkg, userId, flags); 20590 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 20591 for (int i = 0; i < childCount; i++) { 20592 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 20593 } 20594 } 20595 20596 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 20597 final String volumeUuid = pkg.volumeUuid; 20598 final String packageName = pkg.packageName; 20599 final ApplicationInfo app = pkg.applicationInfo; 20600 20601 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 20602 // Create a native library symlink only if we have native libraries 20603 // and if the native libraries are 32 bit libraries. We do not provide 20604 // this symlink for 64 bit libraries. 20605 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 20606 final String nativeLibPath = app.nativeLibraryDir; 20607 try { 20608 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 20609 nativeLibPath, userId); 20610 } catch (InstallerException e) { 20611 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 20612 } 20613 } 20614 } 20615 } 20616 20617 /** 20618 * For system apps on non-FBE devices, this method migrates any existing 20619 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 20620 * requested by the app. 20621 */ 20622 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 20623 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 20624 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 20625 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 20626 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 20627 try { 20628 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 20629 storageTarget); 20630 } catch (InstallerException e) { 20631 logCriticalInfo(Log.WARN, 20632 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 20633 } 20634 return true; 20635 } else { 20636 return false; 20637 } 20638 } 20639 20640 public PackageFreezer freezePackage(String packageName, String killReason) { 20641 return freezePackage(packageName, UserHandle.USER_ALL, killReason); 20642 } 20643 20644 public PackageFreezer freezePackage(String packageName, int userId, String killReason) { 20645 return new PackageFreezer(packageName, userId, killReason); 20646 } 20647 20648 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 20649 String killReason) { 20650 return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason); 20651 } 20652 20653 public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags, 20654 String killReason) { 20655 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 20656 return new PackageFreezer(); 20657 } else { 20658 return freezePackage(packageName, userId, killReason); 20659 } 20660 } 20661 20662 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 20663 String killReason) { 20664 return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason); 20665 } 20666 20667 public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags, 20668 String killReason) { 20669 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 20670 return new PackageFreezer(); 20671 } else { 20672 return freezePackage(packageName, userId, killReason); 20673 } 20674 } 20675 20676 /** 20677 * Class that freezes and kills the given package upon creation, and 20678 * unfreezes it upon closing. This is typically used when doing surgery on 20679 * app code/data to prevent the app from running while you're working. 20680 */ 20681 private class PackageFreezer implements AutoCloseable { 20682 private final String mPackageName; 20683 private final PackageFreezer[] mChildren; 20684 20685 private final boolean mWeFroze; 20686 20687 private final AtomicBoolean mClosed = new AtomicBoolean(); 20688 private final CloseGuard mCloseGuard = CloseGuard.get(); 20689 20690 /** 20691 * Create and return a stub freezer that doesn't actually do anything, 20692 * typically used when someone requested 20693 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 20694 * {@link PackageManager#DELETE_DONT_KILL_APP}. 20695 */ 20696 public PackageFreezer() { 20697 mPackageName = null; 20698 mChildren = null; 20699 mWeFroze = false; 20700 mCloseGuard.open("close"); 20701 } 20702 20703 public PackageFreezer(String packageName, int userId, String killReason) { 20704 synchronized (mPackages) { 20705 mPackageName = packageName; 20706 mWeFroze = mFrozenPackages.add(mPackageName); 20707 20708 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 20709 if (ps != null) { 20710 killApplication(ps.name, ps.appId, userId, killReason); 20711 } 20712 20713 final PackageParser.Package p = mPackages.get(packageName); 20714 if (p != null && p.childPackages != null) { 20715 final int N = p.childPackages.size(); 20716 mChildren = new PackageFreezer[N]; 20717 for (int i = 0; i < N; i++) { 20718 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 20719 userId, killReason); 20720 } 20721 } else { 20722 mChildren = null; 20723 } 20724 } 20725 mCloseGuard.open("close"); 20726 } 20727 20728 @Override 20729 protected void finalize() throws Throwable { 20730 try { 20731 mCloseGuard.warnIfOpen(); 20732 close(); 20733 } finally { 20734 super.finalize(); 20735 } 20736 } 20737 20738 @Override 20739 public void close() { 20740 mCloseGuard.close(); 20741 if (mClosed.compareAndSet(false, true)) { 20742 synchronized (mPackages) { 20743 if (mWeFroze) { 20744 mFrozenPackages.remove(mPackageName); 20745 } 20746 20747 if (mChildren != null) { 20748 for (PackageFreezer freezer : mChildren) { 20749 freezer.close(); 20750 } 20751 } 20752 } 20753 } 20754 } 20755 } 20756 20757 /** 20758 * Verify that given package is currently frozen. 20759 */ 20760 private void checkPackageFrozen(String packageName) { 20761 synchronized (mPackages) { 20762 if (!mFrozenPackages.contains(packageName)) { 20763 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 20764 } 20765 } 20766 } 20767 20768 @Override 20769 public int movePackage(final String packageName, final String volumeUuid) { 20770 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 20771 20772 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 20773 final int moveId = mNextMoveId.getAndIncrement(); 20774 mHandler.post(new Runnable() { 20775 @Override 20776 public void run() { 20777 try { 20778 movePackageInternal(packageName, volumeUuid, moveId, user); 20779 } catch (PackageManagerException e) { 20780 Slog.w(TAG, "Failed to move " + packageName, e); 20781 mMoveCallbacks.notifyStatusChanged(moveId, 20782 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 20783 } 20784 } 20785 }); 20786 return moveId; 20787 } 20788 20789 private void movePackageInternal(final String packageName, final String volumeUuid, 20790 final int moveId, UserHandle user) throws PackageManagerException { 20791 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20792 final PackageManager pm = mContext.getPackageManager(); 20793 20794 final boolean currentAsec; 20795 final String currentVolumeUuid; 20796 final File codeFile; 20797 final String installerPackageName; 20798 final String packageAbiOverride; 20799 final int appId; 20800 final String seinfo; 20801 final String label; 20802 final int targetSdkVersion; 20803 final PackageFreezer freezer; 20804 final int[] installedUserIds; 20805 20806 // reader 20807 synchronized (mPackages) { 20808 final PackageParser.Package pkg = mPackages.get(packageName); 20809 final PackageSetting ps = mSettings.mPackages.get(packageName); 20810 if (pkg == null || ps == null) { 20811 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 20812 } 20813 20814 if (pkg.applicationInfo.isSystemApp()) { 20815 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 20816 "Cannot move system application"); 20817 } 20818 20819 final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid); 20820 final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean( 20821 com.android.internal.R.bool.config_allow3rdPartyAppOnInternal); 20822 if (isInternalStorage && !allow3rdPartyOnInternal) { 20823 throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL, 20824 "3rd party apps are not allowed on internal storage"); 20825 } 20826 20827 if (pkg.applicationInfo.isExternalAsec()) { 20828 currentAsec = true; 20829 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 20830 } else if (pkg.applicationInfo.isForwardLocked()) { 20831 currentAsec = true; 20832 currentVolumeUuid = "forward_locked"; 20833 } else { 20834 currentAsec = false; 20835 currentVolumeUuid = ps.volumeUuid; 20836 20837 final File probe = new File(pkg.codePath); 20838 final File probeOat = new File(probe, "oat"); 20839 if (!probe.isDirectory() || !probeOat.isDirectory()) { 20840 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20841 "Move only supported for modern cluster style installs"); 20842 } 20843 } 20844 20845 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 20846 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20847 "Package already moved to " + volumeUuid); 20848 } 20849 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 20850 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 20851 "Device admin cannot be moved"); 20852 } 20853 20854 if (mFrozenPackages.contains(packageName)) { 20855 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 20856 "Failed to move already frozen package"); 20857 } 20858 20859 codeFile = new File(pkg.codePath); 20860 installerPackageName = ps.installerPackageName; 20861 packageAbiOverride = ps.cpuAbiOverrideString; 20862 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 20863 seinfo = pkg.applicationInfo.seinfo; 20864 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 20865 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 20866 freezer = freezePackage(packageName, "movePackageInternal"); 20867 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 20868 } 20869 20870 final Bundle extras = new Bundle(); 20871 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 20872 extras.putString(Intent.EXTRA_TITLE, label); 20873 mMoveCallbacks.notifyCreated(moveId, extras); 20874 20875 int installFlags; 20876 final boolean moveCompleteApp; 20877 final File measurePath; 20878 20879 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 20880 installFlags = INSTALL_INTERNAL; 20881 moveCompleteApp = !currentAsec; 20882 measurePath = Environment.getDataAppDirectory(volumeUuid); 20883 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 20884 installFlags = INSTALL_EXTERNAL; 20885 moveCompleteApp = false; 20886 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 20887 } else { 20888 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 20889 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 20890 || !volume.isMountedWritable()) { 20891 freezer.close(); 20892 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20893 "Move location not mounted private volume"); 20894 } 20895 20896 Preconditions.checkState(!currentAsec); 20897 20898 installFlags = INSTALL_INTERNAL; 20899 moveCompleteApp = true; 20900 measurePath = Environment.getDataAppDirectory(volumeUuid); 20901 } 20902 20903 final PackageStats stats = new PackageStats(null, -1); 20904 synchronized (mInstaller) { 20905 for (int userId : installedUserIds) { 20906 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 20907 freezer.close(); 20908 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20909 "Failed to measure package size"); 20910 } 20911 } 20912 } 20913 20914 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 20915 + stats.dataSize); 20916 20917 final long startFreeBytes = measurePath.getFreeSpace(); 20918 final long sizeBytes; 20919 if (moveCompleteApp) { 20920 sizeBytes = stats.codeSize + stats.dataSize; 20921 } else { 20922 sizeBytes = stats.codeSize; 20923 } 20924 20925 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 20926 freezer.close(); 20927 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20928 "Not enough free space to move"); 20929 } 20930 20931 mMoveCallbacks.notifyStatusChanged(moveId, 10); 20932 20933 final CountDownLatch installedLatch = new CountDownLatch(1); 20934 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 20935 @Override 20936 public void onUserActionRequired(Intent intent) throws RemoteException { 20937 throw new IllegalStateException(); 20938 } 20939 20940 @Override 20941 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 20942 Bundle extras) throws RemoteException { 20943 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 20944 + PackageManager.installStatusToString(returnCode, msg)); 20945 20946 installedLatch.countDown(); 20947 freezer.close(); 20948 20949 final int status = PackageManager.installStatusToPublicStatus(returnCode); 20950 switch (status) { 20951 case PackageInstaller.STATUS_SUCCESS: 20952 mMoveCallbacks.notifyStatusChanged(moveId, 20953 PackageManager.MOVE_SUCCEEDED); 20954 break; 20955 case PackageInstaller.STATUS_FAILURE_STORAGE: 20956 mMoveCallbacks.notifyStatusChanged(moveId, 20957 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 20958 break; 20959 default: 20960 mMoveCallbacks.notifyStatusChanged(moveId, 20961 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 20962 break; 20963 } 20964 } 20965 }; 20966 20967 final MoveInfo move; 20968 if (moveCompleteApp) { 20969 // Kick off a thread to report progress estimates 20970 new Thread() { 20971 @Override 20972 public void run() { 20973 while (true) { 20974 try { 20975 if (installedLatch.await(1, TimeUnit.SECONDS)) { 20976 break; 20977 } 20978 } catch (InterruptedException ignored) { 20979 } 20980 20981 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 20982 final int progress = 10 + (int) MathUtils.constrain( 20983 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 20984 mMoveCallbacks.notifyStatusChanged(moveId, progress); 20985 } 20986 } 20987 }.start(); 20988 20989 final String dataAppName = codeFile.getName(); 20990 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 20991 dataAppName, appId, seinfo, targetSdkVersion); 20992 } else { 20993 move = null; 20994 } 20995 20996 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 20997 20998 final Message msg = mHandler.obtainMessage(INIT_COPY); 20999 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 21000 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 21001 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 21002 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/); 21003 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 21004 msg.obj = params; 21005 21006 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 21007 System.identityHashCode(msg.obj)); 21008 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 21009 System.identityHashCode(msg.obj)); 21010 21011 mHandler.sendMessage(msg); 21012 } 21013 21014 @Override 21015 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 21016 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 21017 21018 final int realMoveId = mNextMoveId.getAndIncrement(); 21019 final Bundle extras = new Bundle(); 21020 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 21021 mMoveCallbacks.notifyCreated(realMoveId, extras); 21022 21023 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 21024 @Override 21025 public void onCreated(int moveId, Bundle extras) { 21026 // Ignored 21027 } 21028 21029 @Override 21030 public void onStatusChanged(int moveId, int status, long estMillis) { 21031 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 21032 } 21033 }; 21034 21035 final StorageManager storage = mContext.getSystemService(StorageManager.class); 21036 storage.setPrimaryStorageUuid(volumeUuid, callback); 21037 return realMoveId; 21038 } 21039 21040 @Override 21041 public int getMoveStatus(int moveId) { 21042 mContext.enforceCallingOrSelfPermission( 21043 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 21044 return mMoveCallbacks.mLastStatus.get(moveId); 21045 } 21046 21047 @Override 21048 public void registerMoveCallback(IPackageMoveObserver callback) { 21049 mContext.enforceCallingOrSelfPermission( 21050 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 21051 mMoveCallbacks.register(callback); 21052 } 21053 21054 @Override 21055 public void unregisterMoveCallback(IPackageMoveObserver callback) { 21056 mContext.enforceCallingOrSelfPermission( 21057 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 21058 mMoveCallbacks.unregister(callback); 21059 } 21060 21061 @Override 21062 public boolean setInstallLocation(int loc) { 21063 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 21064 null); 21065 if (getInstallLocation() == loc) { 21066 return true; 21067 } 21068 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 21069 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 21070 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 21071 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 21072 return true; 21073 } 21074 return false; 21075 } 21076 21077 @Override 21078 public int getInstallLocation() { 21079 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 21080 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 21081 PackageHelper.APP_INSTALL_AUTO); 21082 } 21083 21084 /** Called by UserManagerService */ 21085 void cleanUpUser(UserManagerService userManager, int userHandle) { 21086 synchronized (mPackages) { 21087 mDirtyUsers.remove(userHandle); 21088 mUserNeedsBadging.delete(userHandle); 21089 mSettings.removeUserLPw(userHandle); 21090 mPendingBroadcasts.remove(userHandle); 21091 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 21092 removeUnusedPackagesLPw(userManager, userHandle); 21093 } 21094 } 21095 21096 /** 21097 * We're removing userHandle and would like to remove any downloaded packages 21098 * that are no longer in use by any other user. 21099 * @param userHandle the user being removed 21100 */ 21101 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 21102 final boolean DEBUG_CLEAN_APKS = false; 21103 int [] users = userManager.getUserIds(); 21104 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 21105 while (psit.hasNext()) { 21106 PackageSetting ps = psit.next(); 21107 if (ps.pkg == null) { 21108 continue; 21109 } 21110 final String packageName = ps.pkg.packageName; 21111 // Skip over if system app 21112 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 21113 continue; 21114 } 21115 if (DEBUG_CLEAN_APKS) { 21116 Slog.i(TAG, "Checking package " + packageName); 21117 } 21118 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 21119 if (keep) { 21120 if (DEBUG_CLEAN_APKS) { 21121 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 21122 } 21123 } else { 21124 for (int i = 0; i < users.length; i++) { 21125 if (users[i] != userHandle && ps.getInstalled(users[i])) { 21126 keep = true; 21127 if (DEBUG_CLEAN_APKS) { 21128 Slog.i(TAG, " Keeping package " + packageName + " for user " 21129 + users[i]); 21130 } 21131 break; 21132 } 21133 } 21134 } 21135 if (!keep) { 21136 if (DEBUG_CLEAN_APKS) { 21137 Slog.i(TAG, " Removing package " + packageName); 21138 } 21139 mHandler.post(new Runnable() { 21140 public void run() { 21141 deletePackageX(packageName, userHandle, 0); 21142 } //end run 21143 }); 21144 } 21145 } 21146 } 21147 21148 /** Called by UserManagerService */ 21149 void createNewUser(int userId, String[] disallowedPackages) { 21150 synchronized (mInstallLock) { 21151 mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages); 21152 } 21153 synchronized (mPackages) { 21154 scheduleWritePackageRestrictionsLocked(userId); 21155 scheduleWritePackageListLocked(userId); 21156 applyFactoryDefaultBrowserLPw(userId); 21157 primeDomainVerificationsLPw(userId); 21158 } 21159 } 21160 21161 void onNewUserCreated(final int userId) { 21162 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 21163 // If permission review for legacy apps is required, we represent 21164 // dagerous permissions for such apps as always granted runtime 21165 // permissions to keep per user flag state whether review is needed. 21166 // Hence, if a new user is added we have to propagate dangerous 21167 // permission grants for these legacy apps. 21168 if (mPermissionReviewRequired) { 21169 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 21170 | UPDATE_PERMISSIONS_REPLACE_ALL); 21171 } 21172 } 21173 21174 @Override 21175 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 21176 mContext.enforceCallingOrSelfPermission( 21177 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 21178 "Only package verification agents can read the verifier device identity"); 21179 21180 synchronized (mPackages) { 21181 return mSettings.getVerifierDeviceIdentityLPw(); 21182 } 21183 } 21184 21185 @Override 21186 public void setPermissionEnforced(String permission, boolean enforced) { 21187 // TODO: Now that we no longer change GID for storage, this should to away. 21188 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 21189 "setPermissionEnforced"); 21190 if (READ_EXTERNAL_STORAGE.equals(permission)) { 21191 synchronized (mPackages) { 21192 if (mSettings.mReadExternalStorageEnforced == null 21193 || mSettings.mReadExternalStorageEnforced != enforced) { 21194 mSettings.mReadExternalStorageEnforced = enforced; 21195 mSettings.writeLPr(); 21196 } 21197 } 21198 // kill any non-foreground processes so we restart them and 21199 // grant/revoke the GID. 21200 final IActivityManager am = ActivityManager.getService(); 21201 if (am != null) { 21202 final long token = Binder.clearCallingIdentity(); 21203 try { 21204 am.killProcessesBelowForeground("setPermissionEnforcement"); 21205 } catch (RemoteException e) { 21206 } finally { 21207 Binder.restoreCallingIdentity(token); 21208 } 21209 } 21210 } else { 21211 throw new IllegalArgumentException("No selective enforcement for " + permission); 21212 } 21213 } 21214 21215 @Override 21216 @Deprecated 21217 public boolean isPermissionEnforced(String permission) { 21218 return true; 21219 } 21220 21221 @Override 21222 public boolean isStorageLow() { 21223 final long token = Binder.clearCallingIdentity(); 21224 try { 21225 final DeviceStorageMonitorInternal 21226 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 21227 if (dsm != null) { 21228 return dsm.isMemoryLow(); 21229 } else { 21230 return false; 21231 } 21232 } finally { 21233 Binder.restoreCallingIdentity(token); 21234 } 21235 } 21236 21237 @Override 21238 public IPackageInstaller getPackageInstaller() { 21239 return mInstallerService; 21240 } 21241 21242 private boolean userNeedsBadging(int userId) { 21243 int index = mUserNeedsBadging.indexOfKey(userId); 21244 if (index < 0) { 21245 final UserInfo userInfo; 21246 final long token = Binder.clearCallingIdentity(); 21247 try { 21248 userInfo = sUserManager.getUserInfo(userId); 21249 } finally { 21250 Binder.restoreCallingIdentity(token); 21251 } 21252 final boolean b; 21253 if (userInfo != null && userInfo.isManagedProfile()) { 21254 b = true; 21255 } else { 21256 b = false; 21257 } 21258 mUserNeedsBadging.put(userId, b); 21259 return b; 21260 } 21261 return mUserNeedsBadging.valueAt(index); 21262 } 21263 21264 @Override 21265 public KeySet getKeySetByAlias(String packageName, String alias) { 21266 if (packageName == null || alias == null) { 21267 return null; 21268 } 21269 synchronized(mPackages) { 21270 final PackageParser.Package pkg = mPackages.get(packageName); 21271 if (pkg == null) { 21272 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 21273 throw new IllegalArgumentException("Unknown package: " + packageName); 21274 } 21275 KeySetManagerService ksms = mSettings.mKeySetManagerService; 21276 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 21277 } 21278 } 21279 21280 @Override 21281 public KeySet getSigningKeySet(String packageName) { 21282 if (packageName == null) { 21283 return null; 21284 } 21285 synchronized(mPackages) { 21286 final PackageParser.Package pkg = mPackages.get(packageName); 21287 if (pkg == null) { 21288 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 21289 throw new IllegalArgumentException("Unknown package: " + packageName); 21290 } 21291 if (pkg.applicationInfo.uid != Binder.getCallingUid() 21292 && Process.SYSTEM_UID != Binder.getCallingUid()) { 21293 throw new SecurityException("May not access signing KeySet of other apps."); 21294 } 21295 KeySetManagerService ksms = mSettings.mKeySetManagerService; 21296 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 21297 } 21298 } 21299 21300 @Override 21301 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 21302 if (packageName == null || ks == null) { 21303 return false; 21304 } 21305 synchronized(mPackages) { 21306 final PackageParser.Package pkg = mPackages.get(packageName); 21307 if (pkg == null) { 21308 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 21309 throw new IllegalArgumentException("Unknown package: " + packageName); 21310 } 21311 IBinder ksh = ks.getToken(); 21312 if (ksh instanceof KeySetHandle) { 21313 KeySetManagerService ksms = mSettings.mKeySetManagerService; 21314 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 21315 } 21316 return false; 21317 } 21318 } 21319 21320 @Override 21321 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 21322 if (packageName == null || ks == null) { 21323 return false; 21324 } 21325 synchronized(mPackages) { 21326 final PackageParser.Package pkg = mPackages.get(packageName); 21327 if (pkg == null) { 21328 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 21329 throw new IllegalArgumentException("Unknown package: " + packageName); 21330 } 21331 IBinder ksh = ks.getToken(); 21332 if (ksh instanceof KeySetHandle) { 21333 KeySetManagerService ksms = mSettings.mKeySetManagerService; 21334 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 21335 } 21336 return false; 21337 } 21338 } 21339 21340 private void deletePackageIfUnusedLPr(final String packageName) { 21341 PackageSetting ps = mSettings.mPackages.get(packageName); 21342 if (ps == null) { 21343 return; 21344 } 21345 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 21346 // TODO Implement atomic delete if package is unused 21347 // It is currently possible that the package will be deleted even if it is installed 21348 // after this method returns. 21349 mHandler.post(new Runnable() { 21350 public void run() { 21351 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 21352 } 21353 }); 21354 } 21355 } 21356 21357 /** 21358 * Check and throw if the given before/after packages would be considered a 21359 * downgrade. 21360 */ 21361 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 21362 throws PackageManagerException { 21363 if (after.versionCode < before.mVersionCode) { 21364 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 21365 "Update version code " + after.versionCode + " is older than current " 21366 + before.mVersionCode); 21367 } else if (after.versionCode == before.mVersionCode) { 21368 if (after.baseRevisionCode < before.baseRevisionCode) { 21369 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 21370 "Update base revision code " + after.baseRevisionCode 21371 + " is older than current " + before.baseRevisionCode); 21372 } 21373 21374 if (!ArrayUtils.isEmpty(after.splitNames)) { 21375 for (int i = 0; i < after.splitNames.length; i++) { 21376 final String splitName = after.splitNames[i]; 21377 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 21378 if (j != -1) { 21379 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 21380 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 21381 "Update split " + splitName + " revision code " 21382 + after.splitRevisionCodes[i] + " is older than current " 21383 + before.splitRevisionCodes[j]); 21384 } 21385 } 21386 } 21387 } 21388 } 21389 } 21390 21391 private static class MoveCallbacks extends Handler { 21392 private static final int MSG_CREATED = 1; 21393 private static final int MSG_STATUS_CHANGED = 2; 21394 21395 private final RemoteCallbackList<IPackageMoveObserver> 21396 mCallbacks = new RemoteCallbackList<>(); 21397 21398 private final SparseIntArray mLastStatus = new SparseIntArray(); 21399 21400 public MoveCallbacks(Looper looper) { 21401 super(looper); 21402 } 21403 21404 public void register(IPackageMoveObserver callback) { 21405 mCallbacks.register(callback); 21406 } 21407 21408 public void unregister(IPackageMoveObserver callback) { 21409 mCallbacks.unregister(callback); 21410 } 21411 21412 @Override 21413 public void handleMessage(Message msg) { 21414 final SomeArgs args = (SomeArgs) msg.obj; 21415 final int n = mCallbacks.beginBroadcast(); 21416 for (int i = 0; i < n; i++) { 21417 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 21418 try { 21419 invokeCallback(callback, msg.what, args); 21420 } catch (RemoteException ignored) { 21421 } 21422 } 21423 mCallbacks.finishBroadcast(); 21424 args.recycle(); 21425 } 21426 21427 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 21428 throws RemoteException { 21429 switch (what) { 21430 case MSG_CREATED: { 21431 callback.onCreated(args.argi1, (Bundle) args.arg2); 21432 break; 21433 } 21434 case MSG_STATUS_CHANGED: { 21435 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 21436 break; 21437 } 21438 } 21439 } 21440 21441 private void notifyCreated(int moveId, Bundle extras) { 21442 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 21443 21444 final SomeArgs args = SomeArgs.obtain(); 21445 args.argi1 = moveId; 21446 args.arg2 = extras; 21447 obtainMessage(MSG_CREATED, args).sendToTarget(); 21448 } 21449 21450 private void notifyStatusChanged(int moveId, int status) { 21451 notifyStatusChanged(moveId, status, -1); 21452 } 21453 21454 private void notifyStatusChanged(int moveId, int status, long estMillis) { 21455 Slog.v(TAG, "Move " + moveId + " status " + status); 21456 21457 final SomeArgs args = SomeArgs.obtain(); 21458 args.argi1 = moveId; 21459 args.argi2 = status; 21460 args.arg3 = estMillis; 21461 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 21462 21463 synchronized (mLastStatus) { 21464 mLastStatus.put(moveId, status); 21465 } 21466 } 21467 } 21468 21469 private final static class OnPermissionChangeListeners extends Handler { 21470 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 21471 21472 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 21473 new RemoteCallbackList<>(); 21474 21475 public OnPermissionChangeListeners(Looper looper) { 21476 super(looper); 21477 } 21478 21479 @Override 21480 public void handleMessage(Message msg) { 21481 switch (msg.what) { 21482 case MSG_ON_PERMISSIONS_CHANGED: { 21483 final int uid = msg.arg1; 21484 handleOnPermissionsChanged(uid); 21485 } break; 21486 } 21487 } 21488 21489 public void addListenerLocked(IOnPermissionsChangeListener listener) { 21490 mPermissionListeners.register(listener); 21491 21492 } 21493 21494 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 21495 mPermissionListeners.unregister(listener); 21496 } 21497 21498 public void onPermissionsChanged(int uid) { 21499 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 21500 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 21501 } 21502 } 21503 21504 private void handleOnPermissionsChanged(int uid) { 21505 final int count = mPermissionListeners.beginBroadcast(); 21506 try { 21507 for (int i = 0; i < count; i++) { 21508 IOnPermissionsChangeListener callback = mPermissionListeners 21509 .getBroadcastItem(i); 21510 try { 21511 callback.onPermissionsChanged(uid); 21512 } catch (RemoteException e) { 21513 Log.e(TAG, "Permission listener is dead", e); 21514 } 21515 } 21516 } finally { 21517 mPermissionListeners.finishBroadcast(); 21518 } 21519 } 21520 } 21521 21522 private class PackageManagerInternalImpl extends PackageManagerInternal { 21523 @Override 21524 public void setLocationPackagesProvider(PackagesProvider provider) { 21525 synchronized (mPackages) { 21526 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 21527 } 21528 } 21529 21530 @Override 21531 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 21532 synchronized (mPackages) { 21533 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 21534 } 21535 } 21536 21537 @Override 21538 public void setSmsAppPackagesProvider(PackagesProvider provider) { 21539 synchronized (mPackages) { 21540 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 21541 } 21542 } 21543 21544 @Override 21545 public void setDialerAppPackagesProvider(PackagesProvider provider) { 21546 synchronized (mPackages) { 21547 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 21548 } 21549 } 21550 21551 @Override 21552 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 21553 synchronized (mPackages) { 21554 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 21555 } 21556 } 21557 21558 @Override 21559 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 21560 synchronized (mPackages) { 21561 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 21562 } 21563 } 21564 21565 @Override 21566 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 21567 synchronized (mPackages) { 21568 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 21569 packageName, userId); 21570 } 21571 } 21572 21573 @Override 21574 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 21575 synchronized (mPackages) { 21576 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 21577 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 21578 packageName, userId); 21579 } 21580 } 21581 21582 @Override 21583 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 21584 synchronized (mPackages) { 21585 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 21586 packageName, userId); 21587 } 21588 } 21589 21590 @Override 21591 public void setKeepUninstalledPackages(final List<String> packageList) { 21592 Preconditions.checkNotNull(packageList); 21593 List<String> removedFromList = null; 21594 synchronized (mPackages) { 21595 if (mKeepUninstalledPackages != null) { 21596 final int packagesCount = mKeepUninstalledPackages.size(); 21597 for (int i = 0; i < packagesCount; i++) { 21598 String oldPackage = mKeepUninstalledPackages.get(i); 21599 if (packageList != null && packageList.contains(oldPackage)) { 21600 continue; 21601 } 21602 if (removedFromList == null) { 21603 removedFromList = new ArrayList<>(); 21604 } 21605 removedFromList.add(oldPackage); 21606 } 21607 } 21608 mKeepUninstalledPackages = new ArrayList<>(packageList); 21609 if (removedFromList != null) { 21610 final int removedCount = removedFromList.size(); 21611 for (int i = 0; i < removedCount; i++) { 21612 deletePackageIfUnusedLPr(removedFromList.get(i)); 21613 } 21614 } 21615 } 21616 } 21617 21618 @Override 21619 public boolean isPermissionsReviewRequired(String packageName, int userId) { 21620 synchronized (mPackages) { 21621 // If we do not support permission review, done. 21622 if (!mPermissionReviewRequired) { 21623 return false; 21624 } 21625 21626 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 21627 if (packageSetting == null) { 21628 return false; 21629 } 21630 21631 // Permission review applies only to apps not supporting the new permission model. 21632 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 21633 return false; 21634 } 21635 21636 // Legacy apps have the permission and get user consent on launch. 21637 PermissionsState permissionsState = packageSetting.getPermissionsState(); 21638 return permissionsState.isPermissionReviewRequired(userId); 21639 } 21640 } 21641 21642 @Override 21643 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 21644 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 21645 } 21646 21647 @Override 21648 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 21649 int userId) { 21650 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 21651 } 21652 21653 @Override 21654 public void setDeviceAndProfileOwnerPackages( 21655 int deviceOwnerUserId, String deviceOwnerPackage, 21656 SparseArray<String> profileOwnerPackages) { 21657 mProtectedPackages.setDeviceAndProfileOwnerPackages( 21658 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages); 21659 } 21660 21661 @Override 21662 public boolean isPackageDataProtected(int userId, String packageName) { 21663 return mProtectedPackages.isPackageDataProtected(userId, packageName); 21664 } 21665 21666 @Override 21667 public boolean isPackageEphemeral(int userId, String packageName) { 21668 synchronized (mPackages) { 21669 PackageParser.Package p = mPackages.get(packageName); 21670 return p != null ? p.applicationInfo.isEphemeralApp() : false; 21671 } 21672 } 21673 21674 @Override 21675 public boolean wasPackageEverLaunched(String packageName, int userId) { 21676 synchronized (mPackages) { 21677 return mSettings.wasPackageEverLaunchedLPr(packageName, userId); 21678 } 21679 } 21680 21681 @Override 21682 public void grantRuntimePermission(String packageName, String name, int userId, 21683 boolean overridePolicy) { 21684 PackageManagerService.this.grantRuntimePermission(packageName, name, userId, 21685 overridePolicy); 21686 } 21687 21688 @Override 21689 public void revokeRuntimePermission(String packageName, String name, int userId, 21690 boolean overridePolicy) { 21691 PackageManagerService.this.revokeRuntimePermission(packageName, name, userId, 21692 overridePolicy); 21693 } 21694 21695 @Override 21696 public String getNameForUid(int uid) { 21697 return PackageManagerService.this.getNameForUid(uid); 21698 } 21699 21700 @Override 21701 public void requestEphemeralResolutionPhaseTwo(EphemeralResponse responseObj, 21702 Intent origIntent, String resolvedType, Intent launchIntent, 21703 String callingPackage, int userId) { 21704 PackageManagerService.this.requestEphemeralResolutionPhaseTwo( 21705 responseObj, origIntent, resolvedType, launchIntent, callingPackage, userId); 21706 } 21707 21708 public String getSetupWizardPackageName() { 21709 return mSetupWizardPackage; 21710 } 21711 } 21712 21713 @Override 21714 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 21715 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 21716 synchronized (mPackages) { 21717 final long identity = Binder.clearCallingIdentity(); 21718 try { 21719 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 21720 packageNames, userId); 21721 } finally { 21722 Binder.restoreCallingIdentity(identity); 21723 } 21724 } 21725 } 21726 21727 private static void enforceSystemOrPhoneCaller(String tag) { 21728 int callingUid = Binder.getCallingUid(); 21729 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 21730 throw new SecurityException( 21731 "Cannot call " + tag + " from UID " + callingUid); 21732 } 21733 } 21734 21735 boolean isHistoricalPackageUsageAvailable() { 21736 return mPackageUsage.isHistoricalPackageUsageAvailable(); 21737 } 21738 21739 /** 21740 * Return a <b>copy</b> of the collection of packages known to the package manager. 21741 * @return A copy of the values of mPackages. 21742 */ 21743 Collection<PackageParser.Package> getPackages() { 21744 synchronized (mPackages) { 21745 return new ArrayList<>(mPackages.values()); 21746 } 21747 } 21748 21749 /** 21750 * Logs process start information (including base APK hash) to the security log. 21751 * @hide 21752 */ 21753 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 21754 String apkFile, int pid) { 21755 if (!SecurityLog.isLoggingEnabled()) { 21756 return; 21757 } 21758 Bundle data = new Bundle(); 21759 data.putLong("startTimestamp", System.currentTimeMillis()); 21760 data.putString("processName", processName); 21761 data.putInt("uid", uid); 21762 data.putString("seinfo", seinfo); 21763 data.putString("apkFile", apkFile); 21764 data.putInt("pid", pid); 21765 Message msg = mProcessLoggingHandler.obtainMessage( 21766 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 21767 msg.setData(data); 21768 mProcessLoggingHandler.sendMessage(msg); 21769 } 21770 21771 public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) { 21772 return mCompilerStats.getPackageStats(pkgName); 21773 } 21774 21775 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) { 21776 return getOrCreateCompilerPackageStats(pkg.packageName); 21777 } 21778 21779 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) { 21780 return mCompilerStats.getOrCreatePackageStats(pkgName); 21781 } 21782 21783 public void deleteCompilerPackageStats(String pkgName) { 21784 mCompilerStats.deletePackageStats(pkgName); 21785 } 21786} 21787